Agent Creator

Caution

Agents with vague descriptions trigger on the wrong requests — or never trigger at all. A bad description means Claude picks the wrong agent, spams irrelevant ones, or silently falls back to the main conversation. Most hand-written agents also leak CLAUDE.md rules into the body (already injected) or forget the Triggers: keyword list that drives auto-selection.

Tip

Describe the role, allowed files and expected result. Agent Creator drafts frontmatter and a system prompt, validates them, and returns paths and a verdict. It asks the main caller to arrange independent research or a final text-optimizer pass when needed.

Current authoring contracts

The agent and its five on-demand references were checked against official Claude Code documentation and changelog through 2.1.285. They distinguish ordinary agents, conversation forks and skill forks; document omitClaudeMd; and separate plugin field restrictions from repository delegation policy.

Quick reference

FieldValue
Triggers”create agent”, “improve agent”, “scaffold agent”
Modelinherit — runs on the session’s model
ToolsRead, Write, Edit, Glob, Grep, Bash, Agent, WebFetch, WebSearch

Scope guard

Agent Creator sizes the task before starting. One bounded unit = one deliverable, roughly 5 files, roughly 10 steps.

SituationWhat the agent does
Brief fits one bounded unitStarts immediately
Brief exceeds ~5 files / ~10 steps, or bundles several independent deliverablesStops before starting, returns a split proposal: 2-N bounded subtasks, each with scope and a suggested owner
Scope grows mid-flightStops at the next clean boundary, reports done / remaining / how to split
Brief is missing GOAL, SCOPE, CONTEXT, CONSUMER or acceptanceStates the safe assumption and returns the open question to the main caller; never invents scope

“Create six agents for my team” gets a split proposal — one agent per subtask. The same rule that agent-creator applies to itself is the one it writes into every agent it generates.

Tip

Got a split proposal instead of an agent file? That is the guard working. Pick one agent from the proposal and re-send it, or spawn the subtasks as parallel agents in a single message.

Guardrails in every generated agent

Two blocks land in the body of every agent Agent Creator writes. They are part of the output contract, not advice. One of them is also called Return Contract — a separate thing from Agent Creator’s own return contract described later on this page: this one is what a generated agent hands back, that one is what Agent Creator itself hands back.

GuardrailApplies toWhat it says
Return ContractEvery generated agent, unconditionallyVerdict first, <=30 lines, path:line. !=bodies/output/log/preamble. Unconditional — spend one step on what the MAIN SESSION needs and return only that. Bulk material — long logs, full diffs, dumps, long reports — goes into a file under .claude/reports/<YYYYMMDD-HHMMSS>_<name>/, and only the PATH comes back. Agents that dump everything burn the main session’s context. If the agent-return guard is installed, a return over ~1000 est-tokens (chars/4) is blocked for compression; over <=2500 it must file the detail and answer with path + verdict + <=3 lines.
Scope FitOnly agents whose domain writes code, scripts, SQL, schemas, infra or configBuild for the actual scale and the problems that exist today, not imagined load or speculative abstraction — a 10-user app does not need hardening against DB lock contention. After finishing, one pass: can this be simpler — fewer files, less config, less indirection?

For generic agents, Scope Fit is omitted for research, docs and review-only work; Return Contract remains required. Team profiles use the explicit teams-setup exception: shared return and scope rules live in team.md, with only six domain sections in each profile. Agent Creator applies its own Return Contract: paths and validation verdicts, without full bodies.

Delegation

Agent Creator completes bounded work itself and requests main-caller delegation for large independent Explore analysis or a final brewtools:text-optimizer pass. It does not nest or delegate its own verification. Claude Code supports nested delegation within its configured depth; Brewcode policy keeps spawns in the main conversation so the caller can integrate each result.

Ordinary subagents cannot use AskUserQuestion, even if it is listed in tools:. Conversation forks retain the parent tool pool; a skill’s context: fork creates an ordinary subagent and does not gain that exception. This delegated creator returns unresolved questions to its caller.

Optimization handoff

Agent Creator returns exact created or updated paths and validation evidence to the main caller. The main caller resolves and reads the installed Brewtools text-optimize skill and its guard and references, then executes its Medium workflow. These resources belong to Brewtools, not the Brewcode plugin root. The creator cannot spawn optimizers or verifiers, or invoke the explicit-only skill through the Skill tool.

For a user-started pass in the main conversation:

/brewtools:text-optimize Optimize .claude/agents/reviewer.md in Medium mode, preserving all meaning.

Replace the example path with the file Agent Creator returned. For its final handoff, the main caller applies these additional acceptance requirements from Agent Creator:

  1. Before optimization edits, run Phase 0 snapshot and require exit 0 plus RUN_DIR. Clean targets are the default; existing explicit authorization to edit named dirty targets permits --allow-dirty, while unrelated changes remain preserved.
  2. Inventory protected facts and assign one optimizer per file. Give it the full GOAL/ROLE/SCOPE/CONTEXT/CONSUMER/DONE brief, exact target and original paths, RUN_DIR, an authorized report path, and cross-file decisions (empty by default). Require an immediate owned-draft checkpoint after every atomic edit. Missing snapshot or RUN_DIR means stop before editing; the optimizer cannot create its own snapshot.
  3. Run verify --no-restore, then ask a fresh independent read-only verifier to compare original and current files from disk without the writer’s report. Require 100% meaning preservation, including names, numbers, paths, examples, negations, and scope.
  4. Repair owned losses, refresh checkpoints, repeat the gates and agent validation, or refuse acceptance while preserving concurrent bytes. Report optimization as requested or pending until the main caller returns gate evidence.

If Brewtools is unavailable, report optimization as skipped. The validated agent remains usable.

When to use

  • New agent — you need a specialized subagent (reviewer, code-generator, security-scanner, etc.)
  • Agent not triggering — the agent exists but Claude doesn’t auto-select it reliably
  • Trigger collisions — two agents compete for the same request; need <commentary> disambiguation
  • System prompt quality — existing agent body is vague prose instead of dense tables + checklists
  • Post-update drift — agent worked before but a plugin update changed naming or available tools

Examples

"Create an agent for code review — reads only, outputs severity table"
"My reviewer agent doesn't trigger when I say 'check this PR'"
"Improve the description of my tester agent, it keeps clashing with developer"
# Natural language triggers — all route to agent-creator
"new agent for security scanning"
"agent isn't picking up my requests"
"fix agent description"

Flow

  1. Clarify intent

    Resolves role, tools and model from the brief. It records a safe assumption and returns consequential open questions to the caller. For improvement requests, it reads the existing agent file first.

  2. Parallel analysis

    Reads the closest well-built existing agent and supplied research. If independent research exceeds the bounded unit, returns Explore assignments for the main caller to dispatch.

  3. Synthesize

    Extracts project-specific patterns, naming conventions, and anti-patterns. Determines description format: single-line, with Triggers: list, or multi-line with <example> blocks (for ambiguous agents only).

  4. Write

    Produces a complete .md file with frontmatter, role, return contract, scope and procedures at a path discoverable from the intended launch directory. Every generated agent gets a role-sized maxTurns; roles that can lose meaningful work also get checkpoint instructions.

  5. Validate

    Checks name format ([a-z0-9-]+), description keyword density, tool minimality (least privilege), no duplicated CLAUDE.md rules in body, unique name in scope, the Return Contract block present, and Scope Fit present exactly when the agent writes code.

  6. Optimize

    Returns paths and validation evidence for the main caller to execute the installed Brewtools text-optimize Medium workflow, with a pre-edit snapshot and independent acceptance as described above. Until gate evidence returns, optimization is requested or pending; if Brewtools is unavailable, it is skipped. The report records measured results without promising a savings percentage.

Frontmatter reference — all fields
---
name: agent-name              # REQ: lowercase-hyphens; no leading `-`, no `:` (reserved for plugin namespacing)
description: "..."            # REQ: action verb + Triggers: keyword list
model: sonnet                 # OPT: fable|opus|sonnet|haiku|inherit  (fable=claude-fable-5, Mythos-class, CC 2.1.170+)
effort: high                  # OPT: low|medium|high|xhigh|max (no auto, no bare integer)
maxTurns: 20                  # OPT: integer, max turns before abort
tools: Read, Glob, Grep       # OPT: omit = inherit all
disallowedTools: Write, Edit  # OPT: explicit deny list
skills: skill1, skill2        # OPT: full content injected into context at startup
color: cyan                   # OPT: 8 valid values -- magenta is NOT one
memory: project               # OPT: user|project|local -- auto-adds Read/Write/Edit
background: true              # OPT: keeps it backgrounded even when Claude wants the result; hard-errors on a teammate-spawned agent since CC 2.1.269 -- drop it from a definition that may run as a teammate
omitClaudeMd: true            # OPT: skips ordinary instructions; managed policy exception below; ignored as main
isolation: worktree           # OPT: FM accepts `worktree` only -- LOW PRIORITY, see below (`remote` is invocation-level, never FM)
permissionMode: default       # OPT: LOCAL-ONLY -- ignored + warn in plugin agents
mcpServers: [server1]         # OPT: LOCAL-ONLY -- ignored + warn in plugin agents
initialPrompt: "..."          # OPT: LOCAL-ONLY -- first prompt sent on start
hooks: {}                     # OPT: local agent hook map; ignored for plugin agents
experimental: {cacheTtl: "5m"} # OPT: file definitions only; ignored in --agents JSON
---

Scope — current references checked through Claude Code 2.1.285:

ScopeFields
Local + pluginmodel, effort, maxTurns, tools, disallowedTools, skills, memory, background, omitClaudeMd, isolation: worktree — execution mode still affects behavior
Local only — ignored for plugin agentspermissionMode, hooks, mcpServers, initialPrompt
File definitions onlycolor, experimental.cacheTtl; ignored in --agents JSON
Unconfirmed internal/older fields — do not emitobserver, observerMessage, observeSubagents

initialPrompt auto-submits the first user turn only for a local definition running as the main session (--agent or the agent setting). Plugin agents and ordinary subagent spawns ignore it. Use project/user agents when permissionMode, hooks, mcpServers or initialPrompt is required. omitClaudeMd: true skips user/project/local CLAUDE.md and project rules; ordinary managed policy still loads, except for managed agent definitions. Main-session agents ignore this field. Pass essential task constraints in the delegation prompt. isolation: remote is invocation-level only, availability-gated, and never a valid frontmatter value.

Caution

isolation is low priority — don’t set it by default. Every spawn with isolation: worktree costs a git worktree setup plus disk, and there’s a known data-loss bug when it’s combined with permissionMode: bypassPermissions (#29110). Use it only when several agents write to the same files concurrently.

Caution

Do not set permissionMode: bypassPermissions by default. This is equivalent to running with --dangerously-skip-permissions — it silently skips all safety prompts. Only use it for fully-sandboxed CI environments where there is no interactive user. For local development, prefer permissionMode: default or permissionMode: acceptEdits. Also note: permissionMode is local-only — plugin agents ignore it entirely.

Description patterns by ambiguity level:

House description budget: at most 150 tokens (roughly 600 characters), lead sentence at most 160 characters, and 3-7 English trigger terms. Example blocks use the explicit budget exception; they are optional and do not guarantee activation.

OverlapFormatExample
None — unique domainSingle-line action + Triggers"Implements features, fixes bugs. Triggers: implement, fix bug, add feature"
Some — 1-2 other agentsSingle-line + detailed Triggers"Creates bash scripts. Triggers: create script, bash script, shell script"
High — overlapping domainsBlock scalar plus one <example> by default; a second requires the description-budget exceptionSee agent-template.md

Claude Code allows depth-limited nested spawning. Brewcode policy requires main-conversation spawns. Plugin agent paths resolve through ${CLAUDE_PLUGIN_ROOT}; keep runtime and credentials separate.

The known-issue reference records dated reports and issue states. An issue closure alone does not prove runtime repair.

Subagent resource limits — turns, timeouts, checkpointing

Caution

There is no wall-clock timeout for a subagent. Not in frontmatter, not in settings.json, not as an environment variable. A subagent is bounded by turns, API-call timeouts, and token caps only. An agent stuck inside a single 25-minute Bash call is one turn — maxTurns will not touch it.

A turn = one model inference plus its tool calls; tool results return, then the next turn begins. Parallel tool calls in one assistant message count as ONE turn, so turns are usually fewer than tool calls. Observed in real transcripts from this repo: 12 turns / 19 tool calls, 21 / 33, 40 / 53, 51 / 55.

maxTurns sized by role — every generated agent gets an explicit value:

RolemaxTurns
explorer / quick search40
reviewer / architect / tester60
docs / generator80
developer / orchestrator120

These are repository role defaults based on observed transcripts, not upstream limits or a wall-clock guarantee. Rule of thumb: maxTurns ≈ 2-3x the role’s typical run.

maxTurns is an emergency anti-loop stop, not a budget. On exhaustion the run aborts; since 2.1.246 the caller sees a result marked partial with a SendMessage continuation hint instead of a silent finish — but that marker only prompts a resume, it does not restore unwritten analysis, so written files stay the one guaranteed survivor. That is why agent-creator also writes a checkpointing instruction into every generated agent body: record incremental progress to a report file after each milestone, and on resume read that file first and continue from the last checkpoint.

Relevant environment variables (set under env in settings.json):

VariableBoundsDefault
CLAUDE_CODE_MAX_TURNSTurn cap for ALL agents globallyunset
API_TIMEOUT_MSA single API call10 min
CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MSBackground-agent stall; resets on streaming10 min
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTSConcurrent subagents20
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTHSubagent nesting depth below main; 1 turns nesting off — verify the live cap, don’t hardcode a number3
CLAUDE_CODE_MAX_OUTPUT_TOKENSOutput tokens per responsemodel max
MAX_MCP_OUTPUT_TOKENSMCP result size25k
BASH_DEFAULT_TIMEOUT_MS / BASH_MAX_TIMEOUT_MSBash tool only120s / 600s

Tip

No total-per-session spawn cap exists. CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION (default 200, added in 2.1.212) was removed in 2.1.224 — concurrency and nesting depth are the only live spawn limits now.

For a soft wall-clock budget, Agent Deadline Setup installs PreToolUse checks: warn at 80%, then deny tools outside its finalization set at 100%. The checks occur at tool boundaries and do not interrupt an already running call.

Recovering a partial result:

Path / toolUse
.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonlFull subagent transcript (retention: cleanupPeriodDays)
run_in_background: true + ReadRead the background task’s output file; TaskOutput is deprecated and unavailable in the background pool
TaskStopKill a running subagent
SendMessageResume a stopped subagent with context intact

Reference files (read on demand)

Agent Creator keeps its full frontmatter catalog, scope/tool rules, execution model, templates, and known-issue log out of this page’s body — same on-demand pattern the source file itself uses. Read the one that matches what you’re doing; skip the rest.

FileWhat it holds
agent-frontmatter-fields.mdRequired/optional fields, including omitClaudeMd, plugin exclusions and file-only cache TTL
agent-scope-and-tools.mdDeciding tools:, where a generated file should live, model precedence, delegation patterns
agent-context-and-execution.mdWhat a subagent inherits from its parent, execution modes, turn/token/concurrency limits
agent-template.mdDescription budget, system prompt structure, the Guardrails block, the Validation Checklist
agent-known-issues.mdDated issue evidence and changelog deltas through 2.1.285

Return Contract

Verdict first, <=30 lines, path:line. No agent bodies, no pasted frontmatter, no analysis transcripts, no preamble. Per generated agent: file path, one-line role, model/maxTurns/tools on one line, validation verdict (pass, or the failing checklist item), text-optimizer run or skipped, and any assumption made about the brief. Longer material — analysis notes, generated bodies, full validation runs — goes to .claude/reports/<YYYYMMDD-HHMMSS>_agent-creator/; only the path comes back.

This is the same discipline Agent Creator bakes into every generated agent — see the Return Contract row in the Guardrails table above, a separate contract from this one. /brewtools:agent-return-setup enforces this at ~1000 / ~2500 est-tokens when installed; the contract itself ships unconditionally.

🧩

Skill Creator

Same design process for skills instead of agents.

⏰

Agent Deadline

Installs soft-deadline hooks for subagent runs — the practical continuation of the resource-limits section above.

🔗

GitHub source

Full frontmatter reference, description patterns, and system prompt templates.

🚀

Brewcode overview

All brewcode agents, skills, and hooks in one place.

Updating plugins

Use /brewtools:plugin-update to check and update the brewcode plugin suite in one command. See the FAQ for details.