agent-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Agent Development for Claude Code

面向Claude Code的Agent开发

Build effective custom agents for Claude Code with proper delegation, tool access, and prompt design.
构建具备合理委托机制、工具访问权限和提示词设计的高效自定义Claude Code Agent。

Agent Description Pattern

Agent描述模式

The description field determines whether Claude will automatically delegate tasks.
描述字段决定Claude是否会自动委托任务。

Strong Trigger Pattern

强触发模式

yaml
---
name: agent-name
description: |
  [Role] specialist. MUST BE USED when [specific triggers].
  Use PROACTIVELY for [task category].
  Keywords: [trigger words]
tools: Read, Write, Edit, Glob, Grep, Bash
model: sonnet
---
yaml
---
name: agent-name
description: |
  [Role] specialist. MUST BE USED when [specific triggers].
  Use PROACTIVELY for [task category].
  Keywords: [trigger words]
tools: Read, Write, Edit, Glob, Grep, Bash
model: sonnet
---

Weak vs Strong Descriptions

弱描述 vs 强描述

Weak (won't auto-delegate)Strong (auto-delegates)
"Analyzes screenshots for issues""Visual QA specialist. MUST BE USED when analyzing screenshots. Use PROACTIVELY for visual QA."
"Runs Playwright scripts""Playwright specialist. MUST BE USED when running Playwright scripts. Use PROACTIVELY for browser automation."
Key phrases:
  • "MUST BE USED when..."
  • "Use PROACTIVELY for..."
  • Include trigger keywords
弱描述(不会自动委托)强描述(会自动委托)
"Analyzes screenshots for issues""Visual QA specialist. MUST BE USED when analyzing screenshots. Use PROACTIVELY for visual QA."
"Runs Playwright scripts""Playwright specialist. MUST BE USED when running Playwright scripts. Use PROACTIVELY for browser automation."
关键短语:
  • "MUST BE USED when..."
  • "Use PROACTIVELY for..."
  • 包含触发关键词

Delegation Mechanisms

委托机制

  1. Explicit:
    Task tool subagent_type: "agent-name"
    - always works
  2. Automatic: Claude matches task to agent description - requires strong phrasing
Session restart required after creating/modifying agents.
  1. 显式委托
    Task tool subagent_type: "agent-name"
    - 始终有效
  2. 自动委托:Claude将任务与Agent描述匹配 - 需要使用强表述
创建/修改Agent后需要重启会话

Tool Access Principle

工具访问原则

If an agent doesn't need Bash, don't give it Bash.
Agent needs to...Give toolsDon't give
Create files onlyRead, Write, Edit, Glob, GrepBash
Run scripts/CLIsRead, Write, Edit, Glob, Grep, Bash
Read/audit onlyRead, Glob, GrepWrite, Edit, Bash
Why? Models default to
cat > file << 'EOF'
heredocs instead of Write tool. Each bash command requires approval, causing dozens of prompts per agent run.
如果Agent不需要Bash权限,就不要授予它Bash权限。
Agent需要执行...授予工具不授予工具
仅创建文件Read, Write, Edit, Glob, GrepBash
运行脚本/CLIRead, Write, Edit, Glob, Grep, Bash
仅读取/审计Read, Glob, GrepWrite, Edit, Bash
原因:模型默认使用
cat > file << 'EOF'
heredoc而非Write工具。每个Bash命令都需要确认,会导致每次Agent运行时出现大量确认提示。

Allowlist Pattern

白名单模式

Instead of restricting Bash, allowlist safe commands in
.claude/settings.json
:
json
{
  "permissions": {
    "allow": [
      "Write", "Edit", "WebFetch(domain:*)",
      "Bash(cd *)", "Bash(cp *)", "Bash(mkdir *)", "Bash(ls *)",
      "Bash(cat *)", "Bash(head *)", "Bash(tail *)", "Bash(grep *)",
      "Bash(diff *)", "Bash(mv *)", "Bash(touch *)", "Bash(file *)"
    ]
  }
}
与其限制Bash,不如在
.claude/settings.json
中设置安全命令白名单:
json
{
  "permissions": {
    "allow": [
      "Write", "Edit", "WebFetch(domain:*)",
      "Bash(cd *)", "Bash(cp *)", "Bash(mkdir *)", "Bash(ls *)",
      "Bash(cat *)", "Bash(head *)", "Bash(tail *)", "Bash(grep *)",
      "Bash(diff *)", "Bash(mv *)", "Bash(touch *)", "Bash(file *)"
    ]
  }
}

Model Selection (Quality First)

模型选择(质量优先)

Don't downgrade quality to work around issues - fix root causes instead.
ModelUse For
OpusCreative work (page building, design, content) - quality matters
SonnetMost agents - content, code, research (default)
HaikuOnly script runners where quality doesn't matter
不要为了规避问题而降低模型质量 - 应修复根本原因。
模型适用场景
Opus创意工作(页面构建、设计、内容创作)- 质量优先
Sonnet大多数Agent - 内容生成、代码开发、研究(默认选择)
Haiku仅适用于对质量要求不高的脚本运行场景

Memory Limits

内存限制

Root Cause Fix (REQUIRED)

根本原因修复(必须执行)

Add to
~/.bashrc
or
~/.zshrc
:
bash
export NODE_OPTIONS="--max-old-space-size=16384"
Increases Node.js heap from 4GB to 16GB.
将以下内容添加到
~/.bashrc
~/.zshrc
bash
export NODE_OPTIONS="--max-old-space-size=16384"
将Node.js堆内存从4GB增加到16GB。

Parallel Limits (Even With Fix)

并行限制(即使修复后)

Agent TypeMax ParallelNotes
Any agents2-3Context accumulates; batch then pause
Heavy creative (Opus)1-2Uses more memory
Agent类型最大并行数说明
任意Agent2-3上下文会累积;批量运行后需暂停
重型创意类(Opus)1-2占用更多内存

Recovery

恢复步骤

  1. source ~/.bashrc
    or restart terminal
  2. NODE_OPTIONS="--max-old-space-size=16384" claude
  3. Check what files exist, continue from there
  1. source ~/.bashrc
    或重启终端
  2. NODE_OPTIONS="--max-old-space-size=16384" claude
  3. 检查现有文件,从断点处继续

Sub-Agent vs Remote API

子Agent vs 远程API调用

Always prefer Task sub-agents over remote API calls.
AspectRemote API CallTask Sub-Agent
Tool accessNoneFull (Read, Grep, Write, Bash)
File readingMust pass all content in promptCan read files iteratively
Cross-referencingSingle context windowCan reason across documents
Decision qualityGeneric suggestionsSpecific decisions with rationale
Output quality~100 lines typical600+ lines with specifics
typescript
// ❌ WRONG - Remote API call
const response = await fetch('https://api.anthropic.com/v1/messages', {...})

// ✅ CORRECT - Use Task tool
// Invoke Task with subagent_type: "general-purpose"
始终优先使用Task子Agent而非远程API调用。
维度远程API调用Task子Agent
工具访问权限完整权限(Read, Grep, Write, Bash)
文件读取必须在提示中传递所有内容可迭代读取文件
交叉引用单一上下文窗口可跨文档推理
决策质量通用建议带推理依据的特定决策
输出质量典型约100行600+行且包含细节
typescript
// ❌ 错误示例 - 远程API调用
const response = await fetch('https://api.anthropic.com/v1/messages', {...})

// ✅ 正确示例 - 使用Task工具
// 调用Task并指定subagent_type: "general-purpose"

Declarative Over Imperative

声明式优于命令式

Describe what to accomplish, not how to use tools.
描述要完成的目标,而非如何使用工具

Wrong (Imperative)

错误示例(命令式)

markdown
undefined
markdown
undefined

Check for placeholders

检查占位符

bash
grep -r "PLACEHOLDER:" build/*.html
undefined
bash
grep -r "PLACEHOLDER:" build/*.html
undefined

Right (Declarative)

正确示例(声明式)

markdown
undefined
markdown
undefined

Check for placeholders

检查占位符

Search all HTML files in build/ for:
  • PLACEHOLDER: comments
  • TODO or TBD markers
  • Template brackets like [Client Name]
Any match = incomplete content.
undefined
搜索build/目录下所有HTML文件中的以下内容:
  • PLACEHOLDER: 注释
  • TODO或TBD标记
  • 类似[Client Name]的模板括号
任何匹配项均表示内容未完成。
undefined

What to Include

应包含/应排除的内容

IncludeSkip
Task goal and contextExplicit bash/tool commands
Input file paths"Use X tool to..."
Output file paths and formatStep-by-step tool invocations
Success/failure criteriaShell pipeline syntax
Blocking checks (prerequisites)Micromanaged workflows
Quality checklists
应包含应排除
任务目标和上下文显式的bash/工具命令
输入文件路径"使用X工具来..."
输出文件路径和格式分步的工具调用说明
成功/失败标准Shell管道语法
阻塞检查(前置条件)微观管理的工作流
质量检查清单

Self-Documentation Principle

自文档化原则

"Agents that won't have your context must be able to reproduce the behaviour independently."
Every improvement must be encoded into the agent's prompt, not left as implicit knowledge.
"不具备你当前上下文的Agent必须能够独立重现行为。"
所有改进都必须编码到Agent的提示中,而非留作隐性知识。

What to Encode

应编码的内容

DiscoveryWhere to Capture
Bug fix patternAgent's "Corrections" or "Common Issues" section
Quality requirementAgent's "Quality Checklist" section
File path conventionAgent's "Output" section
Tool usage patternAgent's "Process" section
Blocking prerequisiteAgent's "Blocking Check" section
发现项记录位置
错误修复模式Agent的"修正"或"常见问题"部分
质量要求Agent的"质量检查清单"部分
文件路径约定Agent的"输出"部分
工具使用模式Agent的"流程"部分
阻塞前置条件Agent的"阻塞检查"部分

Test: Would a Fresh Agent Succeed?

测试:全新Agent能否成功执行?

Before completing any agent improvement:
  1. Read the agent prompt as if you have no context
  2. Ask: Could a new session follow this and produce the same quality?
  3. If no: Add missing instructions, patterns, or references
完成任何Agent改进前:
  1. 以无上下文的视角阅读Agent提示
  2. 自问:新会话能否遵循此提示并产出同等质量的结果?
  3. 如果不能:添加缺失的说明、模式或参考内容

Anti-Patterns

反模式

Anti-PatternWhy It Fails
"As we discussed earlier..."No prior context exists
Relying on files read during devAgent may not read same files
Assuming knowledge from errorsAgent won't see your debugging
"Just like the home page"Agent hasn't built home page
反模式失败原因
"正如我们之前讨论的..."不存在前置上下文
依赖开发期间读取的文件Agent可能不会读取相同文件
假设Agent能从错误中学习Agent看不到你的调试过程
"就像主页一样"Agent尚未构建过主页

Flexibility vs Rigidity

灵活性与刚性

Match specification level to task type. Over-specifying flexible agents makes them brittle.
Task TypeSpecification LevelExample
Mechanical/repetitiveHigh (rigid steps)Version checker, file copier
Judgment-basedLow (guidelines)Docs auditor, code reviewer
CreativeMinimal (goals only)Content writer, brainstormer
根据任务类型匹配规范程度。过度规范灵活型Agent会使其变得脆弱。
任务类型规范程度示例
机械/重复性任务高(刚性步骤)版本检查器、文件复制器
基于判断的任务低(仅提供指南)文档审计器、代码审查器
创意类任务极低(仅提供目标)内容创作者、头脑风暴工具

Signs You've Over-Specified

过度规范的迹象

  • Agent fills in template sections with "N/A"
  • Agent tries to complete all phases even when irrelevant
  • Scoring systems produce meaningless numbers
  • Agent fails when scope doesn't match assumptions
  • Long agents (>150 lines) for simple tasks
  • Agent用"N/A"填充模板部分
  • Agent尝试完成所有阶段,即使某些阶段不相关
  • 评分系统产生无意义的数值
  • 当范围与假设不符时Agent执行失败
  • 简单任务使用超过150行的Agent提示

Flexible Agent Guidelines

灵活型Agent指南

DO:
  • Describe what to look for, not exact steps
  • Provide output examples, not rigid templates
  • Include scope control ("if >30 items, ask user")
  • Give escape hatches ("if unsure, flag for review")
  • Keep under 100 lines for judgment tasks
DON'T:
  • Require filling every section of a template
  • Create elaborate weighted scoring systems
  • List every possible check exhaustively
  • Assume scope without asking
应做:
  • 描述需要查找的内容,而非精确步骤
  • 提供输出示例,而非刚性模板
  • 包含范围控制("如果超过30项,询问用户")
  • 提供逃生舱口("如果不确定,标记为需要审查")
  • 判断类任务的提示保持在100行以内
不应做:
  • 要求填充模板的每个部分
  • 创建复杂的加权评分系统
  • 详尽列出所有可能的检查项
  • 未询问就假设任务范围

Example: Docs Auditor

示例:文档审计器

Over-specified (bad):
markdown
undefined
过度规范(错误):
markdown
undefined

Phase 1: Discovery

阶段1:发现

Execute Glob for all .md files...
执行Glob命令查找所有.md文件...

Phase 6: Generate Report

阶段6:生成报告

CategoryWeightScoreWeighted
Links20%X/100X

**Right-sized (good):**
```markdown
类别权重分数加权分数
链接20%X/100X

**合理规范(正确)**:
```markdown

What to Check

检查内容

  • TODOs, broken links, stale versions
  • TODO项、失效链接、过时版本

Output Format

输出格式

List issues by severity. Include file:line and fix.
按严重程度列出问题。包含文件:行号和修复建议。

Scope Control

范围控制

If >30 files, ask user which to focus on.

---
如果超过30个文件,询问用户重点关注哪些。

---

Agent Prompt Structure

Agent提示结构

Effective agent prompts include:
markdown
undefined
有效的Agent提示包含以下部分:
markdown
undefined

Your Role

你的角色

[What the agent does]
[Agent的功能]

Blocking Check

阻塞检查

[Prerequisites that must exist]
[必须满足的前置条件]

Input

输入

[What files to read]
[需要读取的文件]

Process

流程

[Step-by-step with encoded learnings]
[包含已编码经验的分步说明]

Output

输出

[Exact file paths and formats]
[精确的文件路径和格式]

Quality Checklist

质量检查清单

[Verification steps including learned gotchas]
[包含已发现问题的验证步骤]

Common Issues

常见问题

[Patterns discovered during development]
undefined
[开发过程中发现的模式]
undefined

Pipeline Agents

流水线Agent

When inserting a new agent into a numbered pipeline (e.g.,
HTML-01
HTML-05
HTML-11
):
Must UpdateWhat
New agent"Workflow Position" diagram + "Next" field
Predecessor agentIts "Next" field to point to new agent
Common bug: New agent is "orphaned" because predecessor still points to old next agent.
Verification:
bash
grep -n "Next:.*→\|Then.*runs next" .claude/agents/*.md
在编号流水线中插入新Agent时(例如:
HTML-01
HTML-05
HTML-11
):
必须更新内容
新Agent"工作流位置"图 + "下一步"字段
前置Agent其"下一步"字段指向新Agent
常见错误:新Agent被"孤立",因为前置Agent仍指向旧的下一个Agent。
验证命令:
bash
grep -n "Next:.*→\|Then.*runs next" .claude/agents/*.md

The Sweet Spot

最佳适用场景

Best use case: Tasks that are repetitive but require judgment.
Example: Auditing 70 skills manually = tedious. But each audit needs intelligence (check docs, compare versions, decide what to fix). Perfect for parallel agents with clear instructions.
Not good for:
  • Simple tasks (just do them)
  • Highly creative tasks (need human direction)
  • Tasks requiring cross-file coordination (agents work independently)
最佳用例重复但需要判断的任务。
示例:手动审计70个技能非常繁琐,但每个审计都需要智能判断(检查文档、对比版本、决定修复内容)。这非常适合配备清晰指令的并行Agent。
不适用场景:
  • 简单任务(直接手动完成即可)
  • 高度创意的任务(需要人类指导)
  • 需要跨文件协调的任务(Agent独立工作)

Effective Prompt Template

有效提示模板

For each [item]:
1. Read [source file]
2. Verify with [external check - npm view, API call, etc.]
3. Check [authoritative source]
4. Score/evaluate
5. FIX issues found ← Critical instruction
Key elements:
  • "FIX issues found" - Without this, agents only report. With it, they take action.
  • Exact file paths - Prevents ambiguity
  • Output format template - Ensures consistent, parseable reports
  • Batch size ~5 items - Enough work to be efficient, not so much that failures cascade
对于每个[项]:
1. 读取[源文件]
2. 通过[外部检查 - npm view、API调用等]验证
3. 检查[权威来源]
4. 评分/评估
5. 修复发现的问题 ← 关键指令
关键要素:
  • "修复发现的问题" - 没有此指令,Agent仅会报告问题;有此指令,Agent会采取行动。
  • 精确的文件路径 - 避免歧义
  • 输出格式模板 - 确保一致、可解析的报告
  • 批量大小约5项 - 工作量足够高效,又不会导致故障扩散

Workflow Pattern

工作流模式

1. ME: Launch 2-3 parallel agents with identical prompt, different item lists
2. AGENTS: Work in parallel (read → verify → check → edit → report)
3. AGENTS: Return structured reports (score, status, fixes applied, files modified)
4. ME: Review changes (git status, spot-check diffs)
5. ME: Commit in batches with meaningful changelog
6. ME: Push and update progress tracking
Why agents don't commit: Allows human review, batching, and clean commit history.
1. 我:启动2-3个并行Agent,使用相同提示但不同的项列表
2. Agent:并行工作(读取 → 验证 → 检查 → 编辑 → 报告)
3. Agent:返回结构化报告(评分、状态、已应用的修复、修改的文件)
4. 我:审查变更(git status、抽查差异)
5. 我:分批提交并添加有意义的变更日志
6. 我:推送并更新进度跟踪
Agent不提交的原因:允许人类审查、分批处理,并保持清晰的提交历史。

Signs a Task Fits This Pattern

任务符合该模式的迹象

Good fit:
  • Same steps repeated for many items
  • Each item requires judgment (not just transformation)
  • Items are independent (no cross-item dependencies)
  • Clear success criteria (score, pass/fail, etc.)
  • Authoritative source exists to verify against
Bad fit:
  • Items depend on each other's results
  • Requires creative/subjective decisions
  • Single complex task (use regular agent instead)
  • Needs human input mid-process
适合:
  • 相同步骤重复应用于多个项
  • 每个项需要判断(而非仅转换)
  • 项之间相互独立(无跨项依赖)
  • 有明确的成功标准(评分、通过/失败等)
  • 存在可用于验证的权威来源
不适合:
  • 项之间依赖彼此的结果
  • 需要创意/主观决策
  • 单一复杂任务(使用常规Agent即可)
  • 过程中需要人类输入

Quick Reference

快速参考

Agent Frontmatter Template

Agent前置模板

yaml
---
name: my-agent
description: |
  [Role] specialist. MUST BE USED when [triggers].
  Use PROACTIVELY for [task category].
  Keywords: [trigger words]
tools: Read, Write, Edit, Glob, Grep, Bash
model: sonnet
---
yaml
---
name: my-agent
description: |
  [Role] specialist. MUST BE USED when [triggers].
  Use PROACTIVELY for [task category].
  Keywords: [trigger words]
tools: Read, Write, Edit, Glob, Grep, Bash
model: sonnet
---

Fix Bash Approval Spam

修复Bash确认提示泛滥问题

  1. Remove Bash from tools if not needed
  2. Put critical instructions FIRST (right after frontmatter)
  3. Use allowlists in
    .claude/settings.json
  1. 如果不需要,从工具列表中移除Bash
  2. 将关键指令放在最前面(紧跟前置内容)
  3. .claude/settings.json
    中使用白名单

Memory Crash Recovery

内存崩溃恢复

bash
export NODE_OPTIONS="--max-old-space-size=16384"
source ~/.bashrc && claude
bash
export NODE_OPTIONS="--max-old-space-size=16384"
source ~/.bashrc && claude