/ai-and-reasoning:dispatching-subagentsfrom ai-and-reasoning
Guides choosing between Agent tool, Workflow script, or headless claude -p for launching subagents. Covers parent-turn cost, concurrency, child context, tools, effort control, output contracts, and cost ledger for batch dispatching.
Ships in ai-and-reasoning. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Claude Code has three ways to start a subagent. They differ most in what the launching costs the parent.
| Agent tool | Workflow tool | claude -p children (scripts/headless_fanout.py) | |
|---|---|---|---|
| parent cost | one parent turn per launch and one per completion | one tool call per run | one Bash call per run |
| concurrency | 20, and a 21st launch errors (it does not queue) | min(16, vCPUs − 2): 2 on a 4-vCPU CCotw container | RAM-bound, about 210 MB per child: 40 ran clean on 4 vCPU / 15 GB |
| child context | session prefix (~32–55K tokens), plus parent transcript chunks if a context hook is installed | session prefix | what you pass: about 1.2K tokens with --system-prompt and no tools, 39K with the default prompt |
| tools | agent type's tools, the session's MCP connectors, hooks | as Agent | built-in tools named in --tools, write paths allowlisted; no MCP, hooks or skills |
| effort | session's level, or the effort: in a named agent type's frontmatter | agent(prompt, {effort}) | --effort (measured: low gave 0 thinking tokens, high gave 112–197) |
| needs user opt-in | no | yes: an explicit request, ultracode, or a skill that calls it | no |
| cost visibility | none per child | none per child | total_cost_usd and tokens per child, in a ledger |
| output check | yours | in-script | file plus JSON Schema, or CLI-validated --json-schema |
The headless runner is the default for volume. On 2026-10-11 a codex build
dispatched 314 Haiku children through the Agent tool. The children cost
$11.61. The 1,458 Opus parent turns the dispatching took (each re-reading a
context of about 400K tokens) cost roughly $160–170, about 14× the work. Five of
the same tasks through headless_fanout.py cost $0.10, $0.02 each against
$0.033 per Agent-tool child, and one parent call.
Answer in order. The first yes picks the mechanism.
auditor. If so, use the
Agent tool. Keep the count small, or batch many items into each child,
because every launch costs a parent turn.workflow-authoring first. Accept 2-way concurrency
on a 4-vCPU container, or move the bulk phase to headless children.A fan-out pays when each child does a different job. Several children
attempting the same coding task and keeping the first that passes the visible
tests bought nothing past four on the 60-task code-lanes set (oaustegard/experiments
code-lanes/RESULTS.md, Haiku round, 2026-11-29):
arm (Haiku 5.5, --effort low, headless) | solved / 60 | cost, all 60 |
|---|---|---|
| one attempt, retried on the first visible-test failure (≤3 rounds) | 53 | $0.043 |
| first visible passer of 4 samples | 53 | $0.18 |
| first visible passer of 16 samples | 53 | $0.64 |
| Sonnet 5.5, one attempt with the same retry | 55 | ≤ $0.89 |
agent-routing.transcript-lanes, 2026-11-30). Keep the selector; use the map only when the
worker's input must be a few hundred tokens, and then with sections near
(under) 100K tokens.| rule | banned when | earned when |
|---|---|---|
| Use headless for volume | the child needs an MCP connector or the parent's transcript | the inputs can be written into the prompt or a file first |
| Agent tool for small counts | the parent context is already past ~300K tokens, so each launch turn is expensive | the parent context is small, or the results feed the next launch |
| Judges in headless children | — | always: a child with no hooks cannot see the parent discussing the items it scores |
tasks.jsonl:
{"id", "prompt"} plus any of out (absolute path of a JSON file the child
writes), json_schema (structured output, no file), model, tools,
allow, deny, system_prompt, timeout. {out} in a prompt expands to the out
path. This is the same {id, prompt, out} shape claude-workspace's
scripts/fanout.py dispatches over the Agent tool, so one file runs on
either engine."tools": "". Put a large prefix shared by every task in
system_prompt, since that is the cacheable part.S=/mnt/skills/user/dispatching-subagents/scripts/headless_fanout.py
python3 $S run tasks.jsonl --work RUN --schema schema.json --dry-run
Check --model, --tools and the Edit(//...) rule against the out path.python3 $S run tasks.jsonl --work RUN --schema schema.json \
--model haiku --concurrency 16 --max-usd 5 > RUN.log 2>&1; python3 $S status RUN
(Bash run_in_background: true.) Defaults are --tools Read,Grep,Glob,Write,
1 retry, 900 s per child, concurrency 16, and 5-minute prompt-cache writes
(--cache-ttl 5m).status. It reports attempts, ok, failing ids with reasons, total
cost, tokens and permission denials. Rerunning the same command skips done
tasks and retries the rest.What the runner enforces per child:
--session-id and --no-session-persistence;--setting-sources "" and --strict-mcp-config, so no hooks and no MCP;--permission-mode dontAsk with an allowlist: Read/Grep/Glob when listed,
Edit(//<out>) for the out file, and any --allow rules; deny rules (task
field or --deny) go to --disallowedTools and win over the allowlist, so a
child can hold Bash with Bash(curl:*) refused;structured_output is present. The child's claim of success does not count.dontAskMeasured 2026-10-11, Claude Code 2.1.296:
Edit(//abs/path/**) or Edit(rel/**) (relative to
the child's cwd). Write(path) and a bare Edit are both refused.Bash(grep:*) style prefixes work. A prefix rule matches the start of the
command only, so Bash(curl -s https://api.github.com/*) still admits
-X DELETE appended after it. Never allow Bash for a child that holds a
token or that could reach a write API. Fetch live data yourself and put it in
the prompt instead.permission_denials, and the ledger counts
them. A child that hits a denial usually reports the step as failed and stops
(it does not route around).run_in_background: true,
at most 20 in flight. A launch over 20 errors and is lost.scripts/fanout.py keeps the ledger and validates outputs.
Its next can report a slot free before the agent stops. Dispatch one
replacement per completion notification instead (diagnosed 2026-10-11, the
codex build).SendMessage / ListAgents; the
measured traps (reply by agentId, never by the envelope's from; subagents have
no ListAgents) are in references/native-messaging.md.[no-context] in judge and eval prompts where the delegating-with-context
hook is installed, or the judge sees the parent discussing what it scores.Load workflow-authoring before writing the script, and run only with the
user's explicit opt-in. Give agent() its effort where it matters. For a
bulk phase on a small container, a Workflow step can shell out to
headless_fanout.py instead of awaiting 100 agent() calls two at a time.
| situation | use instead |
|---|---|
| which model or effort a child should get, cascades, escalation | agent-routing |
fan-out from claude.ai chat, where no Agent tool or claude binary exists | orchestrating-chat-agents |
| per-item classification at large volume, where a cheap non-Claude model is enough | invoking-gemini |
| a deterministic multi-step pipeline with no model judgment between steps | flowing |
| work that must outlive this session or container | create_session (claude-workspace docs/delegation.md) |
| hundreds of workers fixing failing tests for hours, each fix merged behind a no-regression gate | swarming-to-green (it runs this skill's headless runner per worker) |
| improving one program against an automatic scorer with rounds of cheap proposers and a writer | evolving-with-swarms |
| one subagent for one question | the Agent tool directly, with no ledger |
Abandon a headless run mid-way when the first wave's ledger shows the same
failure reason on most tasks (a prompt or permission bug, not bad luck), or
when denials is non-zero on tasks meant to need no tools. Stop it, fix the
task file, and rerun; done tasks are kept.
session_id equals yours. The session variables leaked
(CLAUDE_CODE_SESSION_ID and the rest). Run children only through the runner,
or strip SESSION_ENV yourself.denials > 0. The write rule
did not match: the Edit(//...) path differs from the path in the prompt, or
someone used Write(...). Dry-run and compare.modelUsage lists claude-haiku-5-5 on a Sonnet or Opus run. This is Claude Code's
own side call, about 3% of the cost. It is expected. Read the per-model split
before attributing cost.oaustegard/experiments METHODS.md).--no-session-persistence children. Move the common prefix
into system_prompt, and cap the run with --max-usd. The runner stops
launching once the cap is reached.--concurrency. The runner backs off and retries.claude -p call carries
about 1,370 tokens of the CLI's own, even with --system-prompt, --tools "" and
--setting-sources "": about 550 read from cache and about 810 written fresh on
every call (they hold per-session details, so no later call can read them). On a
60-token Haiku answer that overhead is most of the bill. Batch small items into one
child, or account for it per call (measured 2026-11-09, oaustegard/experiments
haiku-swarm-poc).cacheCreationEphemeral1hInputTokens is non-zero in modelUsage. The CLI
writes prompt cache at the 1-hour TTL by default, at 2x input against 1.25x for
the 5-minute one. FORCE_PROMPT_CACHING_5M=1 (or CLAUDE_CODE_PROMPT_CACHE_TTL=5m)
switches it; the runner sets it unless --cache-ttl 1h. Use 1h only when
children sharing a prefix start more than five minutes apart.MAX_THINKING_TOKENS=0 and
--settings '{"alwaysThinkingEnabled": false}' are ignored, and
CLAUDE_CODE_MAX_OUTPUT_TOKENS below what the model wants fails the call with
"exceeded the N output token maximum" while billing the tokens. Effort low is the
floor; there it thought 0 tokens on 65% of short-idea calls (mean 95, top tenth
302 or more).--output-format stream-json --verbose each child emits a rate_limit_event whose
unifiedWindows carry five-hour and seven-day utilization. Read it to pause
before the window runs out instead of failing mid-run; ten parallel lanes used
most of a five-hour window in about 70 minutes on 2026-11-09.python3 $S status RUN # exit 0 only when every task's last attempt is ok
python3 /mnt/skills/user/dispatching-subagents/scripts/test_headless_fanout.py # offline, fake claude binary
A bad success is a run where every task passes the schema check but the outputs are copies of the example in the prompt, or are empty lists. Read three outputs before using any aggregate.
claude -p children with no flags inherited the parent's
session id and wrote transcripts under the parent's id. Fixed by the runner's
environment strip and --session-id.--allowedTools "Write(/abs/out/**)" was refused under
dontAsk and the child wrote no file. Edit(//abs/out/**) works.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub oaustegard/claude-skills --plugin ai-and-reasoning20 skills in this plugin
/agent-routingDecide which model, effort level, and cascade shape each subagent gets, and how to keep improvement loops safe (evaluator-as-selector, stop on regression). Routes on measured cost-per-completed-task rather than per-token price, because a tier's token count varies more by task shape than price varies across tiers. Covers per-model effort semantics, the concision lever, cascade preconditions, context handoff, and watching a subagent fan-out live. Use when choosing a subagent's model or effort, when choosing how to escalate a failed attempt, or when asked which model or effort a task should get. Grounded in a 2026-07 calibration, a 2026-08 coding-cost study, a 2026-09 seeded-bug repair battery, a 2026-10 Haiku 5.5 ladder priced per spawn, a 2026-10 retry-versus-escalation ladder on 295 SWE-bench Verified tasks, and a 2026-11 Haiku-swarm-versus-Sonnet-loop search at equal spend; Managed Agents API specifics are operational, not calibrated./challengingCross-context adversarial review for deliverables before shipping. Use when producing blog posts, technical recommendations, analysis briefs, code, or any artifact where accuracy matters more than speed. Triggers on "challenge this", "review before shipping", "adversarial pass", "stress test this"./convening-expertsConvenes expert panels for problem-solving. Use when user mentions panel, experts, multiple perspectives, MECE, DMAIC, RAPID, Six Sigma, root cause analysis, strategic decisions, process improvement, or asks for philosophers/ancients (Socratic, Aristotelian, Stoic method experts)./deciding-with-confidenceRoutes, triages, flags and rates a piece of text with a probability for every option: which department or queue a ticket goes to, which intent a message expresses, whether a yes/no condition holds (is this tool call grounded, should the agent ask first, is the customer angry), and how severe or urgent it is on a rubric, each with a calibrated confidence. Runs Claude Haiku in the request and response shapes of OpenAI's Decisions API, or of TypeSafe's System One API (Jev's), for when no purpose-built decision model is at hand. Use for "route this ticket", "triage these", "classify with a confidence", "give me a probability that", "rate the severity", "score against this rubric", guardrail checks before a tool call, "a Decisions API without OpenAI", or a stand-in for Jev./delegating-with-contextDelegates work to a subagent or spawned session by writing only the task, while a PreToolUse hook pages the parent transcript through Jev and appends the chunks that task needs. Use before writing any Agent tool prompt or create_session prompt, and when asked to delegate this, hand this off, use a subagent, spawn an agent, run agents in parallel, or brief a subagent on what we have done so far./down-skillingDistill Opus-level reasoning into optimized instructions for Haiku 5.5 (and Sonnet). Generates explicit, procedural prompts with n-shot examples that maximize smaller model performance on a given task. Use when user says "down-skill", "distill for Haiku", "optimize for Haiku", "make this work on Haiku", "generate Haiku instructions", or needs to delegate a task to a smaller model with high reliability.Other plugins' skills for the same job