一键导入
cli-claude-code
Claude Code CLI executor for Anthropic-backed reasoning, edits, reviews, and structured cross-AI handoff.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Claude Code CLI executor for Anthropic-backed reasoning, edits, reviews, and structured cross-AI handoff.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Routes non-trivial requests to matching skills through standalone MCP metadata and stable advisor tool ids.
Unified spec-folder workflow + context preservation: Levels 1-3+, validation, Spec Kit Memory. Required for file modifications.
OpenCode CLI orchestrator: external dispatch, in-OpenCode parallel sessions, cross-AI handback with full runtime context.
Shared deep-loop runtime: executor + prompt-pack + validation + atomic state + coverage-graph + Bayesian scoring + fallback routing.
Iterative codebase-context-gathering deep loop. Runs a configurable pool over a shared scope in parallel (native-only by default; optional heterogeneous CLI seats) and synthesizes a reuse-first Context Report for planning/implementation. Use before /speckit:plan or /speckit:implement to map existing code, integration points, and conventions.
Unified deep-loop workflow skill: routes a request to one of five modes (context, research, review, ai-council, improvement) over the shared deep-loop-runtime backend. Holds no per-mode logic — it dispatches by workflowMode through mode-registry.json. Use for codebase-context gathering, autonomous research, iterative code review, multi-seat AI Council planning, and evaluator-first agent/model/skill/non-dev-system improvement.
| name | cli-claude-code |
| description | Claude Code CLI executor for Anthropic-backed reasoning, edits, reviews, and structured cross-AI handoff. |
| allowed-tools | ["Bash","Read","Glob","Grep"] |
| version | 1.1.13.0 |
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 §2), the skill MUST refuse to load and return the documented error message instead of generating anyclaudeinvocation.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 (Codex CLI, 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.
--json-schema-validated output, machine-readable analysis, guaranteed-structure data extraction, pipeline integration..claude/agents/*.md matches, --permission-mode plan read-only exploration, @ai-council planning, session continuity (--continue, --resume).--max-budget-usd cost control.$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.claude directly instead).--search flag — use Codex).# Verify Claude Code CLI is available before routing
command -v claude || echo "Not installed. Run: npm install -g @anthropic-ai/claude-code"
# SELF-INVOCATION GUARD: If you ARE Claude Code, do not use this skill — use native capabilities
[ -n "$CLAUDECODE" ] && echo "ERROR: Already inside Claude Code session. Do not self-invoke."
def detect_self_invocation():
"""Returns a non-None signal when the orchestrator is already running inside Claude Code."""
# Layer 1: env var lookup — Claude Code sets CLAUDECODE on session start
if os.environ.get('CLAUDECODE'):
return ('env', 'CLAUDECODE')
# Layer 2: process ancestry — claude in parent tree
try:
ancestry = subprocess.check_output(['ps', '-o', 'command=', '-p', str(os.getppid())]).decode()
if '/claude' in ancestry or 'claude ' in ancestry:
return ('ancestry', 'claude')
except subprocess.SubprocessError:
pass
# Layer 3: state lock-file probe
state_dir = os.path.expanduser('~/.claude/state')
if os.path.isdir(state_dir):
for entry in os.listdir(state_dir):
if os.path.exists(os.path.join(state_dir, entry, 'lock')):
return ('lockfile', entry)
return None
if detect_self_invocation():
refuse(
"Self-invocation refused: this agent is already running inside Claude Code. "
"Use a sibling cli-* skill or a fresh shell session in a different runtime to dispatch a different model."
)
| Level | When to Load | Resources |
|---|---|---|
| ALWAYS | Every skill invocation | references/cli_reference.md, assets/prompt_quality_card.md |
| CONDITIONAL | If intent signals match | Intent-mapped reference docs |
| ON_DEMAND | Only on explicit request | Extended templates and patterns |
Provider-specific dictionaries (used by the shared helper functions in system-spec-kit/references/cli/shared_smart_router.md):
INTENT_SIGNALS = {
"DEEP_REASONING": {"weight": 4, "keywords": ["reason", "think", "analyze", "trade-off", "architecture", "extended thinking", "chain-of-thought"]},
"CODE_EDITING": {"weight": 4, "keywords": ["edit", "refactor", "modify", "fix", "change code", "surgical edit", "diff-based"]},
"STRUCTURED_OUTPUT": {"weight": 4, "keywords": ["json", "schema", "structured", "extract", "parse", "validate output", "--json-schema"]},
"REVIEW": {"weight": 4, "keywords": ["review", "audit", "security", "quality", "second opinion", "cross-validate"]},
"AGENT_DELEGATION": {"weight": 4, "keywords": ["delegate", "agent", "background", "parallel", "offload", "claude agent"]},
"TEMPLATES": {"weight": 3, "keywords": ["template", "prompt", "how to ask", "claude prompt"]},
"PATTERNS": {"weight": 3, "keywords": ["pattern", "workflow", "orchestrate", "session", "continue", "resume"]},
}
RESOURCE_MAP = {
"DEEP_REASONING": ["references/cli_reference.md", "references/claude_tools.md"],
"CODE_EDITING": ["references/cli_reference.md", "assets/prompt_templates.md"],
"STRUCTURED_OUTPUT": ["references/cli_reference.md", "references/claude_tools.md"],
"REVIEW": ["references/integration_patterns.md", "references/agent_delegation.md"],
"AGENT_DELEGATION": ["references/agent_delegation.md", "references/integration_patterns.md"],
"TEMPLATES": ["assets/prompt_templates.md", "references/cli_reference.md"],
"PATTERNS": ["references/integration_patterns.md", "references/cli_reference.md"],
}
LOADING_LEVELS = {
"ALWAYS": ["references/cli_reference.md", "assets/prompt_quality_card.md"],
"ON_DEMAND_KEYWORDS": ["full reference", "all templates", "deep dive", "complete guide", "extended thinking", "json schema", "claude agent", "claude prompt", "diff-based edit"],
"ON_DEMAND": ["references/claude_tools.md", "assets/prompt_templates.md"],
}
UNKNOWN_FALLBACK_CHECKLIST = [
"Is the user asking about Claude Code CLI specifically?",
"Does the task benefit from deep reasoning or extended thinking?",
"Is structured JSON output needed (--json-schema)?",
"Would surgical code editing or agent delegation help?",
]
Call sequence (using shared helpers from shared_smart_router.md):
discover_markdown_resources() — recursively enumerate current .md files under existing references/ and assets/ folders at routing time._guard_in_skill() + load_if_available() — sandbox paths to this skill, reject non-markdown loads, skip missing files, and suppress duplicates.score_intents(task) and select_intents(scores, ambiguity_delta=1.0) — preserve provider-specific weighted intent scoring and top-2 ambiguity handling.get_routing_key(task, intents) — derive the provider routing key from task/provider context, then fall back to claude_code.LOADING_LEVELS["ALWAYS"], then return UNKNOWN_FALLBACK with UNKNOWN_FALLBACK_CHECKLIST when max score is 0.RESOURCE_MAP[intent], ON_DEMAND-load keyword matches, and return a notice when no provider-specific knowledge base is available beyond always-load resources.The route_claude_code_resources(task) function body lives in shared_smart_router.md — substitute <PROVIDER> = claude_code.
# 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 — API key OR setup-token (CI/CD)
export ANTHROPIC_API_KEY=your-key-here
claude setup-token
Authentication options: ANTHROPIC_API_KEY env var (direct API), claude auth login (interactive OAuth), or claude setup-token (non-interactive CI/CD).
MANDATORY before any first dispatch in a session. The default Anthropic auth (API key OR OAuth OR setup-token) may not be configured on this machine — silently failing with 401 Unauthorized mid-dispatch wastes a round-trip. Run this check once per session, cache the result, and re-run it only if a dispatch fails with an auth error.
# One-shot pre-flight: capture auth status for routing
[ -n "$ANTHROPIC_API_KEY" ] && ANTHROPIC_KEY_OK=1 || ANTHROPIC_KEY_OK=0
CLAUDE_AUTH=$(claude config list 2>&1)
echo "$CLAUDE_AUTH" | grep -qi "oauth\|setup-token" && CLAUDE_OAUTH_OK=1 || CLAUDE_OAUTH_OK=0
Decision tree (apply in order — first match wins):
| State | ANTHROPIC_KEY_OK | CLAUDE_OAUTH_OK | Action |
|---|---|---|---|
| Default available | 1 | * | Proceed with claude -p "<prompt>" --model claude-sonnet-4-6 --output-format text |
| API key missing, OAuth ready | 0 | 1 | ASK user before substituting — never auto-fall-back silently. Surface options A/B/C below. |
| Both missing | 0 | 0 | ASK user to configure auth — surface the login commands, do NOT dispatch. |
User prompt template — API key missing, OAuth configured:
`$ANTHROPIC_API_KEY` is not set, but `claude auth login` OAuth is configured.
Pick one:
A) Use the existing OAuth session (works for interactive `claude` calls; non-interactive `-p` may need an env var)
B) Run `export ANTHROPIC_API_KEY=sk-ant-...` first, then retry the original dispatch
C) Name a different model — paste the `--model <id>` you want to use
User prompt template — both missing:
No Anthropic auth is configured on this machine. Run one:
- `export ANTHROPIC_API_KEY=sk-ant-...` (recommended for direct API calls)
- `claude auth login` (interactive OAuth flow)
- `claude setup-token` (non-interactive CI/CD)
Which would you like to set up? Confirm when login finishes; the skill will retry the original dispatch.
Error-recovery contract. If a dispatch returns an auth error after pre-flight passed (key revoked or OAuth expired), invalidate the cache, rerun the pre-flight, and apply the same decision tree before retrying. Never substitute a model the user didn't approve.
Default model + flags + agent: claude-sonnet-4-6 · --output-format text · no --agent (general-purpose). For deep-reasoning work, override with --model claude-opus-4-6 --effort high. The pinned shape:
claude -p "<prompt>" \
--model claude-sonnet-4-6 \
--output-format text \
2>&1
User override (honor explicit user phrasing verbatim):
| User says | Resolve to |
|---|---|
| (nothing specified) | --model claude-sonnet-4-6 --output-format text |
| "Use Opus extended thinking" | --model claude-opus-4-6 --effort high |
| "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) |
All non-interactive Claude Code CLI calls use the -p (print) flag:
claude -p "prompt" --output-format text 2>&1
| Flag / Option | Purpose |
|---|---|
-p "prompt" | Non-interactive mode — send prompt, get response, exit |
--output-format text | Plain text output (default for human consumption) |
--output-format json | JSON output with metadata (role, content, cost) |
--output-format stream-json | Streaming JSON for real-time processing |
--model claude-sonnet-4-6 | Model selection (default: sonnet) |
--permission-mode plan | Read-only safe exploration — no file writes |
--permission-mode bypassPermissions | Auto-approve all operations — requires explicit user approval |
--json-schema '{"type":"object",...}' | Schema-validated structured output |
--max-budget-usd 1.00 | Cost cap for the session |
--agent review | Route to a specialized agent |
--continue | Continue the most recent conversation |
--resume SESSION_ID | Resume a specific session |
| Model | ID | Use Case |
|---|---|---|
| Opus | claude-opus-4-6 | Deep reasoning, complex architecture, extended thinking |
| Sonnet | claude-sonnet-4-6 | Balanced performance/cost — default for most tasks |
| Haiku | claude-haiku-4-5-20251001 | Optional-unverified; use only when explicitly requested or after adoption for fast, lightweight tasks |
Selection guidance: Default to Sonnet unless the task specifically needs deep reasoning (Opus + --effort high). Use Haiku only when explicitly requested or after adoption.
The calling AI is the conductor; Claude Code agents in .claude/agents/*.md shape HOW Claude Code processes the task.
| Task Type | Agent | Invocation Pattern |
|---|---|---|
| Codebase exploration | context | claude -p "Analyze the architecture of src/" --agent context --permission-mode plan --output-format text 2>&1 |
| Systematic debugging | debug | claude -p "Debug this error: [error]" --agent debug --output-format text 2>&1 |
| Session state capture | handover | claude -p "Create handover for current work" --agent handover --output-format text 2>&1 |
| Multi-agent coordination | orchestrate | claude -p "Coordinate review and testing of auth module" --agent orchestrate --output-format text 2>&1 |
| Evidence gathering | research | claude -p "Research best practices for [topic]" --agent research --output-format text 2>&1 |
| Code review / audit | review | claude -p "Review @src/auth.ts for security issues" --agent review --permission-mode plan --output-format text 2>&1 |
| Spec documentation | speckit | claude -p "Create spec folder for [feature]" --agent speckit --output-format text 2>&1 |
| Multi-strategy planning | ai-council | claude -p "Plan the authentication redesign" --agent ai-council --permission-mode plan --output-format text 2>&1 |
| Documentation generation | write | claude -p "Generate README for this project" --agent write --output-format text 2>&1 |
See agent_delegation.md for complete agent roster.
| Capability | Purpose | Invocation |
|---|---|---|
| Extended Thinking | Deep chain-of-thought reasoning | claude -p "..." --effort high --model claude-opus-4-6 |
| Edit Tool | Surgical diff-based code editing | Built-in — Claude Code edits files directly |
| Agent Tool | Spawn focused subagents within a session | Built-in — agents defined in .claude/agents/ |
--json-schema | Schema-validated structured output | claude -p "..." --json-schema '{"type":"object",...}' |
--permission-mode plan | Read-only safe exploration | claude -p "..." --permission-mode plan |
--max-budget-usd | Cost-controlled execution | claude -p "..." --max-budget-usd 1.00 |
| Skills System | On-demand specialized workflows | Loaded via SKILL.md files |
| Spec Kit Memory | Persistent structured context across sessions | Via MCP tools |
| Hooks | Pre/post tool-call automation | Configured in settings |
| Session continuity | Continue or resume conversations | --continue or --resume SESSION_ID |
# Deep reasoning with extended thinking (Opus)
claude -p "Analyze the trade-offs between microservices and monolith for this project." \
--model claude-opus-4-6 --effort high --output-format text 2>&1
# Code review (read-only — safe exploration)
claude -p "Review @src/auth.ts for security vulnerabilities" \
--permission-mode plan --output-format text 2>&1
# Structured JSON output with schema validation
claude -p "Analyze src/utils.ts and return function signatures" \
--json-schema '{"type":"object","properties":{"functions":{"type":"array"}}}' \
--output-format json 2>&1
# Agent-delegated architecture analysis
claude -p "Map the dependency graph for src/" \
--agent context --permission-mode plan --output-format text 2>&1
# Cost-controlled background execution
claude -p "Generate comprehensive tests for src/utils.ts" \
--max-budget-usd 0.50 --output-format text 2>&1 &
# Continue previous conversation
claude -p "Now refactor the auth module based on the review" --continue --output-format text 2>&1
| Issue | Solution |
|---|---|
| CLI not installed | npm install -g @anthropic-ai/claude-code |
ANTHROPIC_API_KEY not set | export ANTHROPIC_API_KEY=your-key or run claude auth login |
| Nested session detected | Cannot run claude inside Claude Code — use a different terminal or exit first |
| Rate limit exceeded | Wait for auto-retry or reduce request frequency |
| Budget exceeded | Increase --max-budget-usd or reduce prompt complexity |
| Permission denied | Match --permission-mode to task requirements |
| Context too large | Specify files explicitly with @./path rather than broad prompts |
Verify Claude Code CLI is installed before first invocation (command -v claude); check $CLAUDECODE for nesting.
Use --permission-mode plan for review/analysis/exploration (no file writes); --output-format text unless JSON is specifically needed.
Validate output before applying — correctness, completeness, alignment, syntax checks if code generated.
Capture stderr (2>&1) to catch errors and warnings.
Specify --model explicitly: default claude-sonnet-4-6 unless task needs Opus (deep reasoning). Use Haiku only when explicitly requested or after adoption.
Route to the appropriate --agent <name> when the task matches a specialization (see Section 3 routing table).
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.
Prompt construction & model-craft (cli- family precedence).* Compose every dispatch prompt via the 3-tier rule canonical in ../sk-prompt-small-model/assets/cli_prompt_quality_card.md:
assets/prompt_quality_card.md, which delegates the framework table + CLEAR check to the canonical card.../sk-prompt-small-model/references/models/<id>.md, that profile OVERRIDES the cross-model default. The sk-prompt-small-model hub owns per-model prompt-craft (framework + scaffold + gotchas, mirroring sk-prompt-small-model/assets/model_profiles.json recommended_frameworks); consult it before composing for any small model.@prompt-improver via the Task tool (never load full sk-prompt inline) when any canonical Tier 3 trigger applies — the trigger list lives in ../sk-prompt-small-model/assets/cli_prompt_quality_card.md under "Tier 3 — 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.
Code Standards Loading (surface-aware contract) — When dispatching for code review or code generation, instruct the dispatched session to: (1) load sk-code; (2) let sk-code emit a surface tag matching the detected stack from markers and target files; (3) load the selected surface resources and run its verification commands; (4) add sk-code-review only for formal findings-first review output. Fallback: 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.
Single-dispatch discipline (operator-gated, session-scoped) — Default: launch ONE cli-* dispatch at a time across the cli-* family (cli-codex, cli-opencode, cli-claude-code). Wait for the dispatched agent's work to return, verify outputs exist, then SIGKILL the dispatcher process + any orphan children (pkill -9 -f "claude -p" for this skill, plus gtimeout / positional_scoring_fallback:app cleanup). Only launch the next dispatch (this skill OR a sibling) after the prior one is dead and RSS has dropped. Within 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 (cross-skill parallel): when the operator explicitly authorizes N parallel dispatches, run N concurrently — but still SIGKILL each as its work returns.
Set AI_SESSION_CHILD=1 in the dispatched child's env when sessions may be launched through the per-session worktree wrapper (.opencode/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 .... Harmless when the wrapper is not in use. See .opencode/bin/README.md → "Worktree session isolation".
--permission-mode bypassPermissions without explicit user approval (auto-approves all writes/tool calls).--max-budget-usd for cost control.npm install -g @anthropic-ai/claude-code).--max-budget-usd or checking quota).--permission-mode bypassPermissions (describe risks; get explicit user approval).When the calling AI needs to preserve session context from a Claude Code CLI delegation, run the canonical 7-step procedure (extract MEMORY_HANDBACK section → build structured JSON → scrub secrets → invoke generate-context.js via --stdin/--json/temp-file → memory_index_scan). Full procedure and caveats: system-spec-kit/references/cli/memory_handback.md.
Claude-Code-specific Memory Epilogue template: see assets/prompt_templates.md §11.
Example invocation:
printf '%s' "$JSON_PAYLOAD" | node .opencode/skills/system-spec-kit/scripts/dist/memory/generate-context.js --stdin [spec-folder]
cli_reference.md is ALWAYS loaded as baseline.This skill operates within the behavioral framework defined in AGENTS.md.
Key integrations:
skill_advisor.pyTool roles: Bash dispatches the CLI; Read/Glob/Grep validate output.
The router discovers reference, asset, and script docs dynamically. Start with references/cli_reference.md, references/integration_patterns.md, assets/prompt_quality_card.md, assets/prompt_templates.md, references/agent_delegation.md, references/claude_tools.md, then 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.