agent-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAgent 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
委托机制
- Explicit: - always works
Task tool subagent_type: "agent-name" - Automatic: Claude matches task to agent description - requires strong phrasing
Session restart required after creating/modifying agents.
- 显式委托:- 始终有效
Task tool subagent_type: "agent-name" - 自动委托:Claude将任务与Agent描述匹配 - 需要使用强表述
创建/修改Agent后需要重启会话。
Tool Access Principle
工具访问原则
If an agent doesn't need Bash, don't give it Bash.
| Agent needs to... | Give tools | Don't give |
|---|---|---|
| Create files only | Read, Write, Edit, Glob, Grep | Bash |
| Run scripts/CLIs | Read, Write, Edit, Glob, Grep, Bash | — |
| Read/audit only | Read, Glob, Grep | Write, Edit, Bash |
Why? Models default to heredocs instead of Write tool. Each bash command requires approval, causing dozens of prompts per agent run.
cat > file << 'EOF'如果Agent不需要Bash权限,就不要授予它Bash权限。
| Agent需要执行... | 授予工具 | 不授予工具 |
|---|---|---|
| 仅创建文件 | Read, Write, Edit, Glob, Grep | Bash |
| 运行脚本/CLI | Read, Write, Edit, Glob, Grep, Bash | — |
| 仅读取/审计 | Read, Glob, Grep | Write, Edit, Bash |
原因:模型默认使用 heredoc而非Write工具。每个Bash命令都需要确认,会导致每次Agent运行时出现大量确认提示。
cat > file << 'EOF'Allowlist Pattern
白名单模式
Instead of restricting Bash, allowlist safe commands in :
.claude/settings.jsonjson
{
"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.jsonjson
{
"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.
| Model | Use For |
|---|---|
| Opus | Creative work (page building, design, content) - quality matters |
| Sonnet | Most agents - content, code, research (default) |
| Haiku | Only script runners where quality doesn't matter |
不要为了规避问题而降低模型质量 - 应修复根本原因。
| 模型 | 适用场景 |
|---|---|
| Opus | 创意工作(页面构建、设计、内容创作)- 质量优先 |
| Sonnet | 大多数Agent - 内容生成、代码开发、研究(默认选择) |
| Haiku | 仅适用于对质量要求不高的脚本运行场景 |
Memory Limits
内存限制
Root Cause Fix (REQUIRED)
根本原因修复(必须执行)
Add to or :
~/.bashrc~/.zshrcbash
export NODE_OPTIONS="--max-old-space-size=16384"Increases Node.js heap from 4GB to 16GB.
将以下内容添加到或:
~/.bashrc~/.zshrcbash
export NODE_OPTIONS="--max-old-space-size=16384"将Node.js堆内存从4GB增加到16GB。
Parallel Limits (Even With Fix)
并行限制(即使修复后)
| Agent Type | Max Parallel | Notes |
|---|---|---|
| Any agents | 2-3 | Context accumulates; batch then pause |
| Heavy creative (Opus) | 1-2 | Uses more memory |
| Agent类型 | 最大并行数 | 说明 |
|---|---|---|
| 任意Agent | 2-3 | 上下文会累积;批量运行后需暂停 |
| 重型创意类(Opus) | 1-2 | 占用更多内存 |
Recovery
恢复步骤
- or restart terminal
source ~/.bashrc NODE_OPTIONS="--max-old-space-size=16384" claude- Check what files exist, continue from there
- 或重启终端
source ~/.bashrc NODE_OPTIONS="--max-old-space-size=16384" claude- 检查现有文件,从断点处继续
Sub-Agent vs Remote API
子Agent vs 远程API调用
Always prefer Task sub-agents over remote API calls.
| Aspect | Remote API Call | Task Sub-Agent |
|---|---|---|
| Tool access | None | Full (Read, Grep, Write, Bash) |
| File reading | Must pass all content in prompt | Can read files iteratively |
| Cross-referencing | Single context window | Can reason across documents |
| Decision quality | Generic suggestions | Specific decisions with rationale |
| Output quality | ~100 lines typical | 600+ 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
undefinedmarkdown
undefinedCheck for placeholders
检查占位符
bash
grep -r "PLACEHOLDER:" build/*.htmlundefinedbash
grep -r "PLACEHOLDER:" build/*.htmlundefinedRight (Declarative)
正确示例(声明式)
markdown
undefinedmarkdown
undefinedCheck 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]的模板括号
任何匹配项均表示内容未完成。
undefinedWhat to Include
应包含/应排除的内容
| Include | Skip |
|---|---|
| Task goal and context | Explicit bash/tool commands |
| Input file paths | "Use X tool to..." |
| Output file paths and format | Step-by-step tool invocations |
| Success/failure criteria | Shell 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
应编码的内容
| Discovery | Where to Capture |
|---|---|
| Bug fix pattern | Agent's "Corrections" or "Common Issues" section |
| Quality requirement | Agent's "Quality Checklist" section |
| File path convention | Agent's "Output" section |
| Tool usage pattern | Agent's "Process" section |
| Blocking prerequisite | Agent's "Blocking Check" section |
| 发现项 | 记录位置 |
|---|---|
| 错误修复模式 | Agent的"修正"或"常见问题"部分 |
| 质量要求 | Agent的"质量检查清单"部分 |
| 文件路径约定 | Agent的"输出"部分 |
| 工具使用模式 | Agent的"流程"部分 |
| 阻塞前置条件 | Agent的"阻塞检查"部分 |
Test: Would a Fresh Agent Succeed?
测试:全新Agent能否成功执行?
Before completing any agent improvement:
- Read the agent prompt as if you have no context
- Ask: Could a new session follow this and produce the same quality?
- If no: Add missing instructions, patterns, or references
完成任何Agent改进前:
- 以无上下文的视角阅读Agent提示
- 自问:新会话能否遵循此提示并产出同等质量的结果?
- 如果不能:添加缺失的说明、模式或参考内容
Anti-Patterns
反模式
| Anti-Pattern | Why It Fails |
|---|---|
| "As we discussed earlier..." | No prior context exists |
| Relying on files read during dev | Agent may not read same files |
| Assuming knowledge from errors | Agent 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 Type | Specification Level | Example |
|---|---|---|
| Mechanical/repetitive | High (rigid steps) | Version checker, file copier |
| Judgment-based | Low (guidelines) | Docs auditor, code reviewer |
| Creative | Minimal (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
undefinedPhase 1: Discovery
阶段1:发现
Execute Glob for all .md files...
执行Glob命令查找所有.md文件...
Phase 6: Generate Report
阶段6:生成报告
| Category | Weight | Score | Weighted |
|---|---|---|---|
| Links | 20% | X/100 | X |
**Right-sized (good):**
```markdown| 类别 | 权重 | 分数 | 加权分数 |
|---|---|---|---|
| 链接 | 20% | X/100 | X |
**合理规范(正确)**:
```markdownWhat 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
undefinedYour 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[开发过程中发现的模式]
undefinedPipeline Agents
流水线Agent
When inserting a new agent into a numbered pipeline (e.g., → → ):
HTML-01HTML-05HTML-11| Must Update | What |
|---|---|
| New agent | "Workflow Position" diagram + "Next" field |
| Predecessor agent | Its "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-01HTML-05HTML-11| 必须更新 | 内容 |
|---|---|
| 新Agent | "工作流位置"图 + "下一步"字段 |
| 前置Agent | 其"下一步"字段指向新Agent |
常见错误:新Agent被"孤立",因为前置Agent仍指向旧的下一个Agent。
验证命令:
bash
grep -n "Next:.*→\|Then.*runs next" .claude/agents/*.mdThe 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 instructionKey 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 trackingWhy 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确认提示泛滥问题
- Remove Bash from tools if not needed
- Put critical instructions FIRST (right after frontmatter)
- Use allowlists in
.claude/settings.json
- 如果不需要,从工具列表中移除Bash
- 将关键指令放在最前面(紧跟前置内容)
- 在中使用白名单
.claude/settings.json
Memory Crash Recovery
内存崩溃恢复
bash
export NODE_OPTIONS="--max-old-space-size=16384"
source ~/.bashrc && claudebash
export NODE_OPTIONS="--max-old-space-size=16384"
source ~/.bashrc && claude