Skip to content
Conduit

skill

claude-code-delegate

Delegate orchestrator-authored implementation plans to Claude Code, then review the resulting diff in a plan-execute-review loop.

DongL/claude-code-delegatecommunitylistedunreviewed

Set up

Skills are installed by placing their folder where your agent loads skills.

The download comes from github.com/DongL/claude-code-delegate itself, not from our server, so what you get is exactly what its author published.

Install instructions come from the README

Skills do not use an MCP config. Follow the steps in the README below.

README

synced Oct 26, 2026

Claude Code Delegate

Let your AI orchestrator (Codex, Claude Code, Cursor, etc.) delegate implementation tasks to Claude Code or OpenCode — with DeepSeek V4 as the low-cost model backend.

An orchestrator owns planning and review. This toolkit handles everything in between: classify the task, wrap it in a prompt template, invoke the selected executor (Claude Code or OpenCode), compact the output, and return a structured result. Neither the wrapper nor the pipeline approves changes — that's the orchestrator's job.

Supported pairings include Codex orchestrating Claude Code, Claude Code orchestrating OpenCode, and any MCP/shell-capable orchestrator using either executor backend.

flowchart LR
    subgraph Orchestrator["Orchestrator"]
        Codex["Codex / Claude Code / GPT<br/>(plans + reviews)"]
    end

    subgraph Entry["Entry Points"]
        MCP["🔷 mcp_server.py<br/>stdio JSON-RPC<br/><i>(preferred)</i>"]
        SH["🔹 run-claude-code.sh<br/><i>(fallback)</i>"]
    end

    subgraph Pipeline["Pipeline (5 stages)"]
        P["pipeline.py"]
        CL["① classifier.py<br/>→ model + effort"]
        EV["② classifier.py<br/>→ template/envelope"]
        IV["③ invoker.py<br/>claude -p ..."]
        OI["③ opencode_invoker.py<br/>opencode run ..."]
        CT["④ compact_claude_stream.py<br/>→ structured result"]
        PL["⑤ profile_logger.py<br/>→ JSONL"]
    end

    subgraph Backends["Executor Backends"]
        CC["Claude Code CLI<br/>(claude -p)"]
        OC["OpenCode CLI<br/>(opencode run)"]
    end

    subgraph Models["Model Providers"]
        PRO["DeepSeek V4 Pro<br/>1.6T / 49B active"]
        FLASH["DeepSeek V4 Flash<br/>284B / 13B active"]
        QWEN["Qwen 3.6 Plus Free<br/><i>(OpenCode fallback)</i>"]
    end

    Codex -->|"delegate_task (preferred)"| MCP
    Codex -->|"(fallback)"| SH
    SH --> P
    MCP -->|typed JSON-RPC| P
    P -->|①| CL
    P -->|②| EV
    P -->|③| IV
    P -->|③| OI
    IV --> CC
    OI --> OC
    CC --> PRO
    CC --> FLASH
    OC --> PRO
    OC --> FLASH
    OC -.->|fallback| QWEN
    P -->|④| CT
    P -->|⑤| PL
    CT -->|result + cost| Codex

The diagram spans five areas. Orchestrator — Codex, Claude Code, GPT, or another host plans and reviews; Claude Code/OpenCode executes. Entry Points — MCP transport (JSON-RPC over stdio, preferred) and shell wrapper (fallback). Pipeline — five stages: classify (model + effort), envelope (prompt template), invoke (Claude Code or OpenCode), compact (structured result), profile (JSONL log). Executor Backends — Claude Code CLI and OpenCode CLI. Model Providers — DeepSeek V4 Pro and Flash primary; Qwen as OpenCode fallback.

What This Is / Is Not

This project is...This project is not...
A delegation layer for AI-to-AI coding workflowsA fully autonomous coding agent
A pipeline that standardizes classification, invocation, and output compactionA replacement for the orchestrator's planning and review role
Transport-agnostic: MCP server + shell wrapper, same pipeline"Claude Code connected to DeepSeek" — the model backend is replaceable

Installation

One-command

curl -fsSL https://raw.githubusercontent.com/DongL/claude-code-delegate/main/install.sh | bash

Manual

git clone https://github.com/DongL/claude-code-delegate.git ~/.claude-code-delegate
mkdir -p ~/.agents/skills ~/.claude/skills ~/.codex/skills
ln -sfn ~/.claude-code-delegate ~/.agents/skills/claude-code-delegate
ln -sfn ~/.claude-code-delegate ~/.claude/skills/claude-code-delegate
ln -sfn ~/.claude-code-delegate ~/.codex/skills/claude-code-delegate
bash ~/.claude-code-delegate/tests/run_tests.sh
pip3 install mcp  # optional: Python SDK dependency for scripts/mcp_server.py

Update

Re-run the one-command install (it auto-detects an existing install and does git pull --ff-only):

curl -fsSL https://raw.githubusercontent.com/DongL/claude-code-delegate/main/install.sh | bash

Or update manually:

git -C ~/.claude-code-delegate pull --ff-only

As an orchestrator skill

Symlink into the skill directory so Codex, Claude Code, or another skill-aware orchestrator discovers SKILL.md:

mkdir -p ~/.agents/skills
ln -sfn "$PWD" ~/.agents/skills/claude-code-delegate

The resolver in SKILL.md finds the wrapper across these paths:

  1. $CLAUDE_DELEGATE_DIR — explicit override
  2. $HOME/.agents/skills/claude-code-delegate — current agent skill path
  3. $HOME/.codex/skills/claude-code-delegate — legacy Codex path

Verify

./scripts/run-claude-code.sh --flash 'hello from delegate'

If the setup is correct, you will see a compact report with model, usage, and cost.

Provider Setup (DeepSeek V4)

This project defaults to DeepSeek V4 models for low-cost delegation. If you use vanilla Claude Code with Anthropic models, skip this section and override the model per-invocation: CLAUDE_DELEGATE_MODEL=claude-sonnet-4-6 ./scripts/run-claude-code.sh "your prompt"

export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_AUTH_TOKEN=<your DeepSeek API key>
export ANTHROPIC_MODEL=deepseek-v4-pro[1m]
export ANTHROPIC_DEFAULT_OPUS_MODEL=deepseek-v4-pro[1m]
export ANTHROPIC_DEFAULT_SONNET_MODEL=deepseek-v4-pro[1m]
export ANTHROPIC_DEFAULT_HAIKU_MODEL=deepseek-v4-flash[1m]
export CLAUDE_CODE_SUBAGENT_MODEL=deepseek-v4-flash[1m]
export CLAUDE_CODE_EFFORT_LEVEL=max

Get your API key at platform.deepseek.com/api_keys. Verify:

claude -p "hello" --model deepseek-v4-flash[1m]

Or use cc-switch for GUI-based provider management with 50+ presets.

OpenCode (alternative executor)

Set CLAUDE_DELEGATE_EXECUTOR=opencode to use OpenCode instead of Claude Code. OpenCode reads its own config from ~/.config/opencode/config.json and ./opencode.json[c]. No Anthropic API key required.

export CLAUDE_DELEGATE_EXECUTOR=opencode

How Your Orchestrator Calls It

MCP transport (preferred)

Add to your project's .mcp.json:

{
  "mcpServers": {
    "claude-code-delegate": {
      "command": "python3",
      "args": ["scripts/mcp_server.py"]
    }
  }
}

Your orchestrator discovers seven tools via tools/list and delegates with one typed call:

delegate_task(prompt="fix the type error in src/cli.py")
// → { classification, result, usage, cost_usd, terminal_reason }

To use Claude Code as the orchestrator and OpenCode as the executor, pass executor="opencode" through MCP or use --opencode / --executor opencode with the shell wrapper.

Also available: classify_task, aggregate_profile, format_jira_text, start_delegation, poll_delegation, and poll_delegation_compact. Requires pip install mcp.

Shell wrapper (fallback)

Same pipeline, invoked through a CLI:

./scripts/run-claude-code.sh "fix the type error in src/cli.py"

The wrapper parses flags, calls scripts/run-pipeline.py, and prints a compact report. No mcp package needed. Full CLI reference in docs/shell-wrapper-reference.md.

Both transports share scripts/pipeline.py — the same classify → envelope → invoke → compact → profile logic.

Triggering Delegation in Conversation

When talking to your orchestrator, use natural language. The orchestrator reads SKILL.md and invokes the delegate tools automatically. You can include flags inline — the orchestrator knows the flag table and passes them through.

delegate this: fix the typo in src/cli.py

No flags needed for routine edits. Auto-classification picks flash/pro based on the prompt.

delegate this --pro --effort max: refactor the auth module

Pro model with max reasoning for complex work.

delegate this --interactive: clean up dead code in src/legacy/

Review each tool command before it runs (sets acceptEdits permission mode).

delegate this --stream: investigate why the build fails on Node 22

Raw JSON output for debugging a failed delegation.

start a background delegation --pro: add test coverage for all of src/api.py

Long-running task — starts async, poll with --poll <job_id>.

delegate this --flash --opencode: regenerate the CSS from the design tokens

OpenCode executor. Always pair --flash or --qwen with --opencode. Model routing to OpenCode:

  • --flash → opencode/deepseek-v4-flash-free
  • --qwen → opencode/qwen3.6-plus-free

DeepSeek V4 Pro is not available on OpenCode Zen. opencode/deepseek-v4-flash-free is a free beta model ($0/1M tokens) served through OpenCode Zen.

delegate this --full-context --mcp none: <detailed prompt with context>

Skip template wrapping, no external MCP tools.

delegate this --allow-subagents: add tests for all three API endpoints

Allow parallel subagents for independent work.

Async delegation (lease + single-flight)

For long-running tasks, use --start / --poll to prevent duplicate delegations:

# Start background delegation — returns job_id immediately
./scripts/run-claude-code.sh --start "refactor the auth module"

# Poll status
./scripts/run-claude-code.sh --poll <job_id>

A running job holds an execution lease. --start refuses to launch a second delegation while a job is running, preventing the orchestrator from wasting tokens on duplicate/retry delegations. See the Async Delegation section in docs/shell-wrapper-reference.md for full details.

The Delegation Loop

  1. Plan — The orchestrator reads project context and produces a concrete plan with ownership boundaries and verification commands.
  2. Delegate — The pipeline classifies the task, wraps it in a prompt template, resolves model/effort/permission settings, invokes the selected executor, and compacts the output.
  3. Execute — The executor (Claude Code or OpenCode) implements the plan using the configured model backend.
  4. Compact — The pipeline parses the executor's output into a concise report: result text, token usage, cost, and terminal status.
  5. Review — The orchestrator inspects git diff, test output, and the compact report, then decides to accept, reject, or request a correction pass.
  6. Report — The orchestrator gives a final summary: what changed, which tests ran, residual risk.

Correction iterations repeat steps 2–5 until the diff is correct.

Why This Architecture

Cost efficiency. The orchestrator handles planning and review — tasks that benefit from strong reasoning models. The executor handles code edits, test runs, and file operations — tasks that work well with cheaper models. You pay premium rates only for the steps that need them. A typical delegation costs ~$0.28 on DeepSeek V4. The same workload on premium-tier models (Claude Opus 4, GPT-5) would cost $3–$5 — a 10–20× difference.

Structural enforcement. The delegation loop enforces a clean separation: plan before you code, review before you merge. Every task gets classified automatically (flash for edits, pro for architecture), wrapped in a prompt template with coding guidelines and ownership boundaries, and returned as a structured compact report — not raw JSON. The orchestrator cannot skip the plan; the executor cannot skip review.

Auditability. Every delegation produces a diff, a compact report with token usage and cost, and an append-only profile log. Nothing is accepted silently. Correction passes show exactly what changed between iterations.

Model specialization. Planning calls for broad context and high-level reasoning. Execution calls for precision and speed. No single model is best at both. Delegation lets you pair a strong planning model or agent (Codex, Claude Code, Opus) with a fast execution backend (Claude Code or OpenCode using DeepSeek V4 Flash, Qwen, Haiku, or another configured model) — $0.28/delegation vs. $3–$5 on premium-tier models.

Safety boundary. The execution plan defines which files may be touched and which commands may run. Subagents are disabled by default for Claude Code (via --disallowedTools Task Agent). For OpenCode, the default takes no action (OpenCode's default allows subagents); passing --allow-subagents adds --agent build to explicitly enable subagents. A heartbeat confirms the executor is still alive during long tasks. The executor cannot silently refactor the codebase or revert unrelated changes.

Consistent invocation. Model, effort, permissions, and MCP config are identical across every delegation — no flag drift between tasks. Profile metadata accumulates for trend analysis over time.

Executor flexibility. Claude Code and OpenCode share the same pipeline (classify, envelope, compact, profile). Switch via --executor or CLAUDE_DELEGATE_EXECUTOR without changing orchestrator integration. Use Claude Code for Anthropic-model tasks with effort/reasoning budget control. Use OpenCode for open-source models (DeepSeek, Qwen) without an Anthropic API key.

Progressive trust. Start with --interactive to review every tool command. Graduate to --bypass once you trust the output quality. Same pipeline — only the permission mode changes.

Use claude -p for quick one-off answers. Use the delegation layer when you want consistent, reviewable, AI-to-AI execution with a paper trail.

Cost & Context Efficiency

The delegation pipeline converts executor output into a compact report — the orchestrator sees a structured summary (classification, result text, token usage, cost), not megabytes of execution logs. This saves context window in every delegation.

Prompt caching amplifies the savings. Repeated delegation cycles reuse cached system prompts, instruction templates, and prior context across invocations. In one optimization run of two passes:

MetricValue
Fresh input tokens~150,000
Cache-read tokens~1,890,000
Output tokens~22,000
Reused context served from cache~92%

Dollar savings vary by provider cache pricing, model tier, task size, and cache hit behavior. The 92% reuse figure reflects a specific workload on a specific provider — not a guarantee.

CLI Reference

FlagEnv VarEffect
(default)Pro model, quiet output, bypass permissions
--start—Launch in background, return job_id JSON (async + lease guard)
--poll JOB_ID—Poll job status (running/completed/failed)
--pro / --flashCLAUDE_DELEGATE_MODELModel tier selection
--qwenCLAUDE_DELEGATE_MODELQwen model selection
--effort low|medium|high|maxCLAUDE_DELEGATE_EFFORTReasoning budget override
--quiet / --streamCLAUDE_DELEGATE_OUTPUT_MODEOutput format (quiet: compact report, stream: raw JSON)
--interactiveCLAUDE_DELEGATE_PERMISSION_MODEAuto-accept edits, prompt on tool commands
--bypassCLAUDE_DELEGATE_PERMISSION_MODEFully non-interactive (default)
--mcp all|none|jira|linear|sequential-thinkingCLAUDE_DELEGATE_MCP_MODEMCP server loading
--full-contextCLAUDE_DELEGATE_CONTEXT_MODESkip prompt template wrapping
--allow-subagentsCLAUDE_DELEGATE_SUBAGENTSAllow Claude Code/OpenCode to spawn subagents
--opencodeCLAUDE_DELEGATE_EXECUTORShorthand for --executor opencode
--executor claude-code|opencodeCLAUDE_DELEGATE_EXECUTORExecutor backend selection

Env var equivalents and full details: docs/shell-wrapper-reference.md. Permission modes and security: SECURITY.md.

Components

FilePurpose
SKILL.mdOrchestrator contract — delegation loop, resolver, responsibilities
CONTEXT.mdDomain glossary — Orchestrator, Executor, Pro vs Flash, MCP terminology
scripts/pipeline.pyDelegation pipeline — shared by both transports
scripts/run-pipeline.pyCLI entry point for shell wrapper consumers
scripts/run-claude-code.shShell wrapper — flag parsing only
scripts/mcp_server.pyMCP server — typed JSON-RPC tools over stdio
scripts/compact_claude_stream.pyOutput parser — JSON stream → structured report
scripts/claude_adapter.pyClaude Code stream-json adapter
scripts/opencode_adapter.pyOpenCode event stream adapter
scripts/profile_logger.pyProfile record construction and JSONL append
scripts/aggregate_profile_log.pyProfile log aggregation and summarization
scripts/jira_safe_text.pyMarkdown → Jira-safe plain text converter
scripts/invoker.pyClaude Code executor — subprocess launcher and heartbeat
scripts/opencode_invoker.pyOpenCode executor — subprocess launcher and heartbeat
scripts/heartbeat.pyShared subprocess heartbeat monitor
scripts/classifier.pyTask classifier + prompt template builder
tests/run_tests.shTest runner — pipeline, invocation, and compaction
docs/shell-wrapper-reference.mdFull CLI flag/env-var reference
docs/jira-workflow.mdJira-specific delegation conventions

Quality Gates

CI/CD quality gates enforce merge and release confidence. The policy is defined in ADR 0003 (docs/adr/0003-ci-cd-quality-gates.md).

Gate Tiers

TierTriggerScopeExternal Services
Default CIEvery PR and push to mainbash scripts/quality-gate.sh via .github/workflows/quality-gate.ymlNone — fake claude, mock MCP
SmokeManual, pre-releaseHuman-supervised checks against live Jira, GitHub, Claude providerReal tokens required
ReleaseBefore tagging a releasebash scripts/release-gate-report.sh — aggregates default CI + smoke resultsNone for report; smoke results are inputs

Local Parity

Run the same command CI runs:

bash scripts/quality-gate.sh

This invokes bash tests/run_tests.sh by default. Override the test command for experimentation:

CLAUDE_DELEGATE_QUALITY_GATE_TEST_COMMAND="bash my-tests.sh" bash scripts/quality-gate.sh

CI runs the identical command — no divergence between developer machine and CI environment.

CI Behavior

  • Trigger: every PR against main and every push to main
  • Workflow: .github/workflows/quality-gate.yml
  • Runner: ubuntu-latest with only actions/checkout@v4
  • Heartbeat: disabled (CLAUDE_DELEGATE_HEARTBEAT_SECONDS=0) for clean CI output
  • Result: non-zero exit = gate failure = merge blocked

Release Confidence Reporting

Generate a structured report before cutting a release:

bash scripts/release-gate-report.sh

The report records: gate status (PASS/FAIL), commit hash, tag, tests run, and residual risk. A failed gate prints RELEASE BLOCKED and exits non-zero.

Sandbox and Isolation Assumptions

  • No real tokens. Default CI requires no ANTHROPIC_API_KEY, JIRA_API_TOKEN, or GITHUB_TOKEN.
  • Fake claude on PATH. The test suite prepends a fake claude script that records invocation arguments and returns valid JSON.
  • Mock MCP servers. MCP integration tests use mock servers, not live Jira/Linear/GitHub.
  • Isolated Claude runtime. The pipeline writes a minimal settings.json to .claude-delegate/runtime/claude-config/ and sets CLAUDE_CONFIG_DIR to point there. No ~/.claude coupling, no enabled plugins, no hooks.
  • No subagents in CI. Subagents are disabled by default (--disallowedTools Task Agent).

External-System Caveats

Real external-system integration is out of default CI:

  • Claude provider: real model invocation is not tested in CI. The fake claude script validates the invocation path (args, env vars, flags) but not the provider response.
  • Jira: issue transitions and comments are not performed in CI. Jira MCP operations use the --mcp jira mode with mock servers for CI tests.
  • GitHub release publishing: not tested in CI. Release reports are local artifacts.

Smoke tests against live external systems are reserved for manual pre-release checks. A future secret-backed CI environment for live smoke tests requires a separate decision (see ADR 0003).

Debugging & Diagnostics

Health check — verify the environment in one command:

bash scripts/run-claude-code.sh --health

Require claude (CI environments):

CLAUDE_DELEGATE_HEALTH_REQUIRE_CLAUDE=1 bash scripts/run-claude-code.sh --health

Debug a failing delegation with structured logs:

CLAUDE_DELEGATE_LOG_LEVEL=DEBUG CLAUDE_DELEGATE_LOG_FORMAT=text \
  bash scripts/run-claude-code.sh --flash "test prompt" 2>debug.log
grep ERROR debug.log

Logs go to stderr. stdout (the compact report) is unchanged. Set CLAUDE_DELEGATE_LOG_LEVEL=ERROR to silence all but errors in production.

Profiling

Prerequisite: set CLAUDE_DELEGATE_PROFILE_LOG to enable recording. Each delegation appends one JSONL record:

export CLAUDE_DELEGATE_PROFILE_LOG=logs/profile.jsonl

In conversation — just ask:

"generate profiling analysis"

The MCP tool returns a text summary: record count, success/error rate, model distribution, token usage, cache hit ratio, and cost.

Programmatic access via MCP:

// Text summary
aggregate_profile(profile_log_path="logs/profile.jsonl", format="text")
// → Records: 12  Success: 10  Error: 2
//   Cache hit ratio: 71.43%
//   Total cost: $2.20

// Machine-readable (for orchestrator consumption)
aggregate_profile(profile_log_path="logs/profile.jsonl", format="json")
// → { total_records: 12, success_count: 10, tokens: {...}, cost: {...} }

Shell fallback for the same operations:

export CLAUDE_DELEGATE_PROFILE_LOG=logs/profile.jsonl
./scripts/run-claude-code.sh "your prompt"
python3 scripts/aggregate_profile_log.py logs/profile.jsonl

Each record: model, effort, task type, token usage, cache hit ratio, cost, prompt character counts.

Requirements

  • Claude Code (orchestrator or default executor)
  • OpenCode (alternative executor, via --opencode or --executor opencode)
  • python3 (standard library only; pip install mcp optional for MCP server)
  • Access to a model/provider supported by the selected executor

License

MIT

编排器负责规划和审查。本工具处理中间所有环节:分类任务、包装 prompt 模板、调用所选执行器(Claude Code 或 OpenCode)、压缩输出、返回结构化结果。wrapper 和 pipeline 均不批准变更 —— 这是编排器的职责。

支持的组合包括:Codex 编排 Claude Code、Claude Code 编排 OpenCode,以及任何支持 MCP 或 shell 的编排器调用任一执行器后端。

flowchart LR
    subgraph Orchestrator["Orchestrator"]
        Codex["Codex / Claude Code / GPT<br/>(plans + reviews)"]
    end

    subgraph Entry["Entry Points"]
        MCP["🔷 mcp_server.py<br/>stdio JSON-RPC<br/><i>(preferred)</i>"]
        SH["🔹 run-claude-code.sh<br/><i>(fallback)</i>"]
    end

    subgraph Pipeline["Pipeline (5 stages)"]
        P["pipeline.py"]
        CL["① classifier.py<br/>→ model + effort"]
        EV["② classifier.py<br/>→ template/envelope"]
        IV["③ invoker.py<br/>claude -p ..."]
        OI["③ opencode_invoker.py<br/>opencode run ..."]
        CT["④ compact_claude_stream.py<br/>→ structured result"]
        PL["⑤ profile_logger.py<br/>→ JSONL"]
    end

    subgraph Backends["Executor Backends"]
        CC["Claude Code CLI<br/>(claude -p)"]
        OC["OpenCode CLI<br/>(opencode run)"]
    end

    subgraph Models["Model Providers"]
        PRO["DeepSeek V4 Pro<br/>1.6T / 49B active"]
        FLASH["DeepSeek V4 Flash<br/>284B / 13B active"]
        QWEN["Qwen 3.6 Plus Free<br/><i>(OpenCode fallback)</i>"]
    end

    Codex -->|"delegate_task (preferred)"| MCP
    Codex -->|"(fallback)"| SH
    SH --> P
    MCP -->|typed JSON-RPC| P
    P -->|①| CL
    P -->|②| EV
    P -->|③| IV
    P -->|③| OI
    IV --> CC
    OI --> OC
    CC --> PRO
    CC --> FLASH
    OC --> PRO
    OC --> FLASH
    OC -.->|fallback| QWEN
    P -->|④| CT
    P -->|⑤| PL
    CT -->|result + cost| Codex

该图涵盖五部分。编排器 — Codex、Claude Code、GPT 或其他宿主负责规划和审查;Claude Code/OpenCode 执行。入口 — MCP 传输(stdio JSON-RPC,推荐)和 shell wrapper(后备)。流水线 — 五阶段:分类(model + effort)、包装(prompt 模板)、调用(Claude Code 或 OpenCode)、压缩(结构化结果)、画像(JSONL 日志)。执行器后端 — Claude Code CLI 和 OpenCode CLI。模型提供商 — DeepSeek V4 Pro 和 Flash 为主力;Qwen 作为 OpenCode 后备。

这是什么 / 不是什么

本项目是...本项目不是...
AI-to-AI 编码工作流的委派层全自主编码 agent
标准化分类、调用和输出压缩的流水线编排器规划和审查角色的替代品
传输无关:MCP server + shell wrapper,共享同一 pipeline「连接 DeepSeek 的 Claude Code」——模型后端可替换

安装

一行命令

curl -fsSL https://raw.githubusercontent.com/DongL/claude-code-delegate/main/install.sh | bash

手动安装

git clone https://github.com/DongL/claude-code-delegate.git ~/.claude-code-delegate
mkdir -p ~/.agents/skills ~/.claude/skills ~/.codex/skills
ln -sfn ~/.claude-code-delegate ~/.agents/skills/claude-code-delegate
ln -sfn ~/.claude-code-delegate ~/.claude/skills/claude-code-delegate
ln -sfn ~/.claude-code-delegate ~/.codex/skills/claude-code-delegate
bash ~/.claude-code-delegate/tests/run_tests.sh
pip3 install mcp  # 可选:scripts/mcp_server.py 的 Python SDK 依赖

更新

重新运行一行命令安装(它会自动检测已有安装并执行 git pull --ff-only):

curl -fsSL https://raw.githubusercontent.com/DongL/claude-code-delegate/main/install.sh | bash

或手动更新:

git -C ~/.claude-code-delegate pull --ff-only

作为编排器 skill

创建符号链接到 skill 目录,让 Codex、Claude Code 或其他支持 skill 的编排器发现 SKILL.md:

mkdir -p ~/.agents/skills
ln -sfn "$PWD" ~/.agents/skills/claude-code-delegate

SKILL.md 中的解析器按以下路径查找 wrapper:

  1. $CLAUDE_DELEGATE_DIR —— 显式覆盖
  2. $HOME/.agents/skills/claude-code-delegate —— 当前 agent skill 路径
  3. $HOME/.codex/skills/claude-code-delegate —— 旧版 Codex 路径

验证

./scripts/run-claude-code.sh --flash 'hello from delegate'

配置正确的话,会看到一个包含 model、usage 和 cost 的简洁报告。

Provider 设置(DeepSeek V4)

本项目默认使用 DeepSeek V4 模型以降低委派成本。如果你使用原生 Claude Code + Anthropic 模型,跳过本节,在每次调用时覆盖模型即可:CLAUDE_DELEGATE_MODEL=claude-sonnet-4-6 ./scripts/run-claude-code.sh "你的 prompt"

export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_AUTH_TOKEN=<你的 DeepSeek API key>
export ANTHROPIC_MODEL=deepseek-v4-pro[1m]
export ANTHROPIC_DEFAULT_OPUS_MODEL=deepseek-v4-pro[1m]
export ANTHROPIC_DEFAULT_SONNET_MODEL=deepseek-v4-pro[1m]
export ANTHROPIC_DEFAULT_HAIKU_MODEL=deepseek-v4-flash[1m]
export CLAUDE_CODE_SUBAGENT_MODEL=deepseek-v4-flash[1m]
export CLAUDE_CODE_EFFORT_LEVEL=max

在 platform.deepseek.com/api_keys 获取 API key。验证:

claude -p "hello" --model deepseek-v4-flash[1m]

或者使用 cc-switch 进行 GUI 方式的 provider 管理,内置 50+ 预设。

OpenCode(替代执行器)

设置 CLAUDE_DELEGATE_EXECUTOR=opencode 即可使用 OpenCode 而不是 Claude Code。OpenCode 会读取自己的配置:~/.config/opencode/config.json 和 ./opencode.json[c]。不需要 Anthropic API key。

export CLAUDE_DELEGATE_EXECUTOR=opencode

编排器如何调用

MCP 传输(推荐)

在项目的 .mcp.json 中添加:

{
  "mcpServers": {
    "claude-code-delegate": {
      "command": "python3",
      "args": ["scripts/mcp_server.py"]
    }
  }
}

编排器通过 tools/list 发现七个工具,一次类型化调用即可委派:

delegate_task(prompt="修复 src/cli.py 中的类型错误")
// → { classification, result, usage, cost_usd, terminal_reason }

如果要让 Claude Code 作为编排器、OpenCode 作为执行器,可以通过 MCP 传入 executor="opencode",或在 shell wrapper 中使用 --opencode / --executor opencode。

还提供:classify_task、aggregate_profile、format_jira_text、start_delegation、poll_delegation、poll_delegation_compact。需要 pip install mcp。

Shell wrapper(后备)

同一流水线,通过 CLI 调用:

./scripts/run-claude-code.sh "修复 src/cli.py 中的类型错误"

wrapper 解析标志,调用 scripts/run-pipeline.py,输出简洁报告。不需要 mcp 包。完整 CLI 参考见 docs/shell-wrapper-reference.md。

两个传输共享 scripts/pipeline.py —— 相同的 classify → envelope → invoke → compact → profile 逻辑。

在对话中触发委派

直接自然语言与编排器对话即可。编排器读取 SKILL.md 并自动调用委派工具。可以在消息中直接带上标志——编排器理解标志表并传递它们。

delegate this: fix the typo in src/cli.py

日常编辑无需标志。自动分类会根据 prompt 选择 flash/pro。

delegate this --pro --effort max: refactor the auth module

Pro 模型 + 最大推理预算,用于复杂工作。

delegate this --interactive: clean up dead code in src/legacy/

在每条工具命令执行前进行审查(设置 acceptEdits 权限模式)。

delegate this --stream: investigate why the build fails on Node 22

原始 JSON 输出,用于调试失败的委派。

start a background delegation --pro: add test coverage for all of src/api.py

长时间任务——后台启动,用 --poll <job_id> 查询状态。

delegate this --flash --opencode: regenerate the CSS from the design tokens

OpenCode 执行器。务必同时带上 --flash 或 --qwen。 OpenCode 模型路由:

  • --flash → opencode/deepseek-v4-flash-free
  • --qwen → opencode/qwen3.6-plus-free

DeepSeek V4 Pro 在 OpenCode Zen 上不可用。 opencode/deepseek-v4-flash-free 是 OpenCode Zen 提供的免费 beta 模型($0/1M tokens)。

delegate this --full-context --mcp none: <带上下文的详细 prompt>

跳过模板包装,无外部 MCP 工具。

delegate this --allow-subagents: add tests for all three API endpoints

允许并行 subagent 处理独立工作。

委派循环

  1. Plan —— 编排器读取项目上下文,生成包含所有权边界和验证命令的具体计划。
  2. Delegate —— pipeline 分类任务、包装 prompt 模板、解析 model/effort/permission 设置、调用所选执行器、压缩输出。
  3. Execute —— 执行器(Claude Code 或 OpenCode)使用配置的模型后端执行计划。
  4. Compact —— pipeline 将执行器输出解析为简洁报告:结果文本、token 用量、成本、终止状态。
  5. Review —— 编排器检查 git diff、测试输出和报告,决定接受、拒绝或要求修正。
  6. Report —— 编排器给出最终摘要:变更内容、测试结果、剩余风险。

修正循环重复步骤 2–5,直到 diff 正确。

为什么选择这种架构

成本效率。 编排器处理规划和审查——这些任务受益于强推理模型。执行器处理代码编辑、测试运行和文件操作——这些任务用便宜模型即可胜任。你只需为需要的步骤支付 premium 费率。一次典型委派在 DeepSeek V4 上约 $0.28。同样的工作量在 premium 级模型(Claude Opus 4、GPT-5)上需 $3–$5——10–20 倍的差距。

结构性强制。 委派循环强制清晰的关注点分离:先计划再编码,先审查再合并。每个任务自动分类(flash 用于编辑,pro 用于架构),包装在包含编码规范和所有权边界的 prompt 模板中,返回结构化简洁报告——而非原始 JSON。编排器不能跳过计划;执行器不能跳过审查。

可审计性。 每次委派生成 diff、token 用量和成本的简洁报告,以及追加式画像日志。没有任何东西被静默接受。修正过程显示每次迭代之间的确切变更。

模型专业化。 规划需要广泛上下文和高层次推理。执行需要精确和速度。没有哪个模型两者都擅长。委派让你将强规划模型或 agent(Codex、Claude Code、Opus)与快速执行后端(Claude Code 或 OpenCode,使用 DeepSeek V4 Flash、Qwen、Haiku 或其他已配置模型)配对——每次委派约 $0.28,而 premium 级模型需 $3–$5。

安全边界。 执行计划定义哪些文件可以接触,哪些命令可以运行。subagent 默认禁用(Claude Code 通过 --disallowedTools Task Agent,OpenCode 通过不传递 --agent 标志)。使用 --allow-subagents 启用。心跳确认执行器在长任务期间仍在运行。执行器不能静默重构代码库或还原无关变更。

一致调用。 model、effort、permissions 和 MCP config 在每次委派中完全一致——不会出现任务间标志漂移。画像元数据随时间积累,用于趋势分析。

执行器灵活性。 Claude Code 和 OpenCode 共享同一条 pipeline(分类、包装、压缩、画像)。通过 --executor 或 CLAUDE_DELEGATE_EXECUTOR 切换,无需改变编排器集成。Claude Code 适合需要 Anthropic 兼容模型和 effort/推理预算控制的任务;OpenCode 适合无需 Anthropic API key 的开源模型(DeepSeek、Qwen)工作流。

渐进式信任。 从 --interactive 开始,审查每个工具命令。一旦信任输出质量,过渡到 --bypass。同一流水线——只有权限模式改变。

快速回答用 claude -p。需要一致、可审查、有纸质记录的 AI-to-AI 执行时用委派层。

成本与上下文效率

委派流水线将执行器输出转换为简洁报告——编排器看到的是结构化摘要(分类、结果文本、token 用量、成本),而非兆字节的执行日志。这节省了每次委派的上下文窗口。

提示缓存放大了这一节约效果。重复的委派循环复用缓存的系统提示、指令模板和先前上下文。一次优化运行(两轮)的数据:

指标数值
新鲜输入 token~150,000
缓存读取 token~1,890,000
输出 token~22,000
从缓存提供的复用上下文~92%

节省的金额因 provider 缓存定价、模型层级、任务大小和缓存命中行为而异。92% 的复用率反映了特定工作负载在特定 provider 上的表现——并非保证值。

CLI 参考

标志环境变量效果
(默认)Pro 模型,quiet 输出,bypass 权限
--pro / --flashCLAUDE_DELEGATE_MODEL模型层级选择
--qwenCLAUDE_DELEGATE_MODELQwen 模型选择
--effort low|medium|high|maxCLAUDE_DELEGATE_EFFORT推理预算覆盖
--quiet / --streamCLAUDE_DELEGATE_OUTPUT_MODE输出格式(quiet: 简洁报告,stream: 原始 JSON)
--interactiveCLAUDE_DELEGATE_PERMISSION_MODE自动接受编辑,工具命令需确认
--bypassCLAUDE_DELEGATE_PERMISSION_MODE完全非交互(默认)
--mcp all|none|jira|linear|sequential-thinkingCLAUDE_DELEGATE_MCP_MODEMCP server 加载
--full-contextCLAUDE_DELEGATE_CONTEXT_MODE跳过 prompt 模板包装
--allow-subagentsCLAUDE_DELEGATE_SUBAGENTS允许 Claude Code/OpenCode 生成 subagent
--opencodeCLAUDE_DELEGATE_EXECUTOR--executor opencode 的简写
--executor claude-code|opencodeCLAUDE_DELEGATE_EXECUTOR执行器后端选择

环境变量等价项和完整细节:docs/shell-wrapper-reference.md。权限模式和安全:SECURITY.md。

组件

文件用途
SKILL.md编排器契约 —— 委派循环、解析器、职责
CONTEXT.md领域词汇表 —— 编排器、执行器、Pro vs Flash、MCP 术语
scripts/pipeline.py委派流水线 —— 两个传输共享
scripts/run-pipeline.pyCLI 入口 —— 供 shell wrapper 调用
scripts/run-claude-code.shShell wrapper —— 仅做标志解析
scripts/mcp_server.pyMCP server —— 基于 stdio 的类型化 JSON-RPC 工具
scripts/compact_claude_stream.py输出解析器 —— JSON 流 → 结构化报告
scripts/claude_adapter.pyClaude Code stream-json 适配器
scripts/opencode_adapter.pyOpenCode 事件流适配器
scripts/profile_logger.py画像记录构建和 JSONL 追加
scripts/aggregate_profile_log.py画像日志聚合和摘要
scripts/jira_safe_text.pyMarkdown → Jira 安全纯文本转换器
scripts/invoker.pyClaude Code 执行器 —— 子进程启动和心跳
scripts/opencode_invoker.pyOpenCode 执行器 —— 子进程启动和心跳
scripts/heartbeat.py共享子进程心跳监控
scripts/classifier.py任务分类器 + prompt 模板构建器
tests/run_tests.sh测试运行器 —— pipeline、调用和压缩
docs/shell-wrapper-reference.md完整 CLI 标志/环境变量参考
docs/jira-workflow.mdJira 委派约定

画像分析

前置条件:设置 CLAUDE_DELEGATE_PROFILE_LOG 启用记录。每次委派追加一条 JSONL 记录:

export CLAUDE_DELEGATE_PROFILE_LOG=logs/profile.jsonl

对话中直接问:

"生成 profiling analysis"

MCP 工具自动调用并返回文本摘要:记录数、成功/错误率、模型分布、token 用量、缓存命中率、成本。

程序化访问——通过 MCP:

// 文本摘要
aggregate_profile(profile_log_path="logs/profile.jsonl", format="text")
// → Records: 12  Success: 10  Error: 2
//   Cache hit ratio: 71.43%
//   Total cost: $2.20

// 机器可读(供编排器消费)
aggregate_profile(profile_log_path="logs/profile.jsonl", format="json")
// → { total_records: 12, success_count: 10, tokens: {...}, cost: {...} }

Shell 后备方式:

export CLAUDE_DELEGATE_PROFILE_LOG=logs/profile.jsonl
./scripts/run-claude-code.sh "你的 prompt"
python3 scripts/aggregate_profile_log.py logs/profile.jsonl

每条记录包含:model、effort、任务类型、token 用量、缓存命中率、成本、prompt 字符数。

依赖

  • Claude Code(编排器或默认执行器)
  • OpenCode(替代执行器,通过 --opencode 或 --executor opencode)
  • python3(仅标准库;pip install mcp 可选,用于 MCP server)
  • 所选执行器支持的模型/provider

许可证

MIT

↑↓ navigate openesc close