create-worker

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Create Worker

创建Worker

This skill provides comprehensive guidance for creating and configuring workers in Claude Code.
本Skill为在Claude Code中创建和配置Worker提供全面指导。

Understanding Workers

理解Worker

Workers are specialized AI assistants that Claude Code can delegate tasks to. Each worker:
  • Operates in its own context window (preserving main conversation context)
  • Has a specific purpose and expertise area
  • Can be configured with specific tools and permissions
  • Includes a custom system prompt guiding its behavior
Worker是Claude Code可以委派任务的专业AI助手。每个Worker具备以下特性:
  • 在独立的上下文窗口中运行(保留主对话上下文)
  • 拥有特定的用途和专业领域
  • 可配置特定工具与权限
  • 包含指导其行为的自定义系统提示词

When to Create Workers

何时创建Worker

Create a worker when:
  • Tasks require specialized expertise that benefits from focused instructions
  • Context preservation is important (workers don't pollute main context)
  • The same specialized workflow is needed repeatedly
  • Different tool permissions are needed for different tasks
  • Parallel execution of independent tasks is desired
Choose skills instead when:
  • The capability extends Claude's knowledge without needing separate context
  • No specialized agent persona is needed
  • Tool restrictions are sufficient without full agent isolation
Choose slash commands when:
  • Users need explicit control over when to invoke functionality
  • The workflow should be user-initiated, not model-initiated
在以下场景创建Worker:
  • 任务需要专业技能,且聚焦的指令能带来帮助
  • 上下文保留很重要(Worker不会污染主上下文)
  • 需要重复使用相同的专业工作流
  • 不同任务需要不同的工具权限
  • 需要并行执行独立任务
在以下场景选择Skill:
  • 功能仅需扩展Claude的知识,无需独立上下文
  • 不需要专业的Agent角色设定
  • 仅通过工具限制就能满足需求,无需完全隔离Agent
在以下场景选择斜杠命令:
  • 用户需要明确控制功能的调用时机
  • 工作流需要由用户主动触发,而非模型自动触发

Two Approaches to Workers

Worker的两种实现方式

Approach 1: File-Based Agents

方式一:基于文件的Agent

Persistent worker definitions stored as Markdown files.
Locations (in priority order):
LocationScopePriority
.claude/agents/
Current projectHighest
~/.claude/agents/
All projectsLower
File Format:
markdown
---
name: agent-name
description: Description of when this agent should be used
tools: Read, Write, Bash, Glob, Grep  # Optional - omit to inherit all
model: sonnet  # Optional - sonnet, opus, haiku, or inherit
permissionMode: default  # Optional - see permission modes below
skills: skill1, skill2  # Optional - skills to auto-load
---

Your agent's system prompt goes here. This defines the agent's
role, capabilities, approach, and constraints.

Include:
- Role definition and expertise areas
- Step-by-step workflow for common tasks
- Constraints and rules to follow
- Output format expectations
- Examples of good behavior
持久化的Worker定义以Markdown文件形式存储。
存储位置(优先级从高到低):
位置作用范围优先级
.claude/agents/
当前项目最高
~/.claude/agents/
所有项目较低
文件格式:
markdown
---
name: agent-name
description: Description of when this agent should be used
tools: Read, Write, Bash, Glob, Grep  # 可选 - 留空则继承所有工具
model: sonnet  # 可选 - sonnet, opus, haiku,或继承会话模型
permissionMode: default  # 可选 - 详见下方权限模式
skills: skill1, skill2  # 可选 - 自动加载的Skill
---

此处填写Agent的系统提示词。这将定义Agent的
角色、能力、工作方式和约束条件。

需包含:
- 角色定义与专业领域
- 常见任务的分步工作流
- 需要遵循的约束与规则
- 输出格式要求
- 良好行为示例

Approach 2: Teams Delegation

方式二:团队委派

Dynamic worker delegation using
teams
for on-demand agents.
teams(action: 'delegate', tasks: [{
  text: '<the agent\'s instructions and task>',
  assignee: 'worker-name'
}])
Workers are delegated with a task description and an assignee name. Multiple workers can be delegated in parallel by including multiple tasks in the array.
使用
teams
命令动态委派Worker,实现按需创建Agent。
teams(action: 'delegate', tasks: [{
  text: '<the agent\'s instructions and task>',
  assignee: 'worker-name'
}])
通过任务描述和受派者名称委派Worker。在数组中添加多个任务即可并行委派多个Worker。

Configuration Reference

配置参考

Required Fields

必填字段

FieldDescription
name
Unique identifier (lowercase letters, numbers, hyphens only, max 64 chars)
description
When the agent should be used (include "PROACTIVELY" for auto-invocation)
字段描述
name
唯一标识符(仅允许小写字母、数字、连字符,最长64字符)
description
Agent的适用场景(若需自动调用,需包含"PROACTIVELY")

Optional Fields

可选字段

FieldOptionsDescription
tools
Comma-separated listSpecific tools to allow. Omit to inherit all.
model
sonnet
,
opus
,
haiku
,
inherit
Model to use. Default: inherit from session.
permissionMode
See belowHow permissions are handled
skills
Comma-separated listSkills to auto-load when agent starts
字段选项描述
tools
逗号分隔的列表允许使用的特定工具。留空则继承所有工具。
model
sonnet
,
opus
,
haiku
,
inherit
使用的模型。默认:继承会话模型。
permissionMode
详见下方权限处理方式
skills
逗号分隔的列表Agent启动时自动加载的Skill

Permission Modes

权限模式

ModeBehavior
default
Normal permission prompting
acceptEdits
Auto-accept file edits
bypassPermissions
Skip all permission prompts
plan
Planning mode (research only)
ignore
Ignore this agent
模式行为
default
常规权限提示
acceptEdits
自动接受文件编辑
bypassPermissions
跳过所有权限提示
plan
规划模式(仅调研)
ignore
忽略该Agent

Available Tools

可用工具

File Operations:
Read
,
Write
,
Edit
,
Glob
,
Grep
Execution:
Bash
,
BashOutput
Web:
WebFetch
,
WebSearch
Specialized:
Task
,
NotebookEdit
,
TodoWrite
,
Skill
文件操作:
Read
,
Write
,
Edit
,
Glob
,
Grep
执行:
Bash
,
BashOutput
网络:
WebFetch
,
WebSearch
专业工具:
Task
,
NotebookEdit
,
TodoWrite
,
Skill

Creating a Worker

创建Worker的步骤

Step 1: Define the Purpose

步骤1:明确用途

Answer these questions:
  1. What specialized task does this agent handle?
  2. What expertise or personality should it have?
  3. What tools does it need (or shouldn't have)?
  4. Should it be invoked automatically or explicitly?
回答以下问题:
  1. 该Agent处理哪些专业任务?
  2. 它应具备哪些专业技能或角色设定?
  3. 它需要(或不需要)哪些工具?
  4. 它应自动调用还是手动调用?

Step 2: Choose the Approach

步骤2:选择实现方式

Use file-based agents when:
  • The agent will be reused across sessions
  • Team sharing via version control is desired
  • Configuration should persist
Use teams delegation when:
  • One-off or dynamic worker dispatch is needed
  • Workers are spawned as part of a workflow
  • Parallel execution is required
选择基于文件的Agent:
  • Agent需要跨会话重复使用
  • 需要通过版本控制与团队共享
  • 配置需要持久化保存
选择团队委派:
  • 需要一次性或动态派遣Worker
  • Worker作为工作流的一部分被创建
  • 需要并行执行任务

Step 3: Write the System Prompt

步骤3:编写系统提示词

Structure the agent's prompt with these sections:
markdown
<role>
Define who this agent is and what it excels at.
</role>

<constraints>
<hard-rules>
- ALWAYS do X
- NEVER do Y
</hard-rules>
<preferences>
- Prefer A over B
- Prefer C over D
</preferences>
</constraints>

<workflow>
按以下结构编写Agent的提示词:
markdown
<role>
定义该Agent的身份及其擅长的领域。
</role>

<constraints>
<hard-rules>
- 始终执行X
- 绝不执行Y
</hard-rules>
<preferences>
- 优先选择A而非B
- 优先选择C而非D
</preferences>
</constraints>

<workflow>

How to Approach Tasks

任务处理流程

  1. Phase 1: Description
  2. Phase 2: Description
  3. Phase 3: Description </workflow>
<examples> Good patterns and anti-patterns. </examples> ```
  1. 阶段1:描述
  2. 阶段2:描述
  3. 阶段3:描述 </workflow>
<examples> 良好实践与反面示例。 </examples> ```

Step 4: Configure Tools and Permissions

步骤4:配置工具与权限

Restrictive (read-only analysis):
yaml
tools: Read, Glob, Grep
Standard development:
yaml
tools: Read, Write, Edit, Bash, Glob, Grep
Full access (omit tools field):
yaml
undefined
只读分析(限制性配置):
yaml
tools: Read, Glob, Grep
标准开发配置:
yaml
tools: Read, Write, Edit, Bash, Glob, Grep
完全访问(省略tools字段):
yaml
undefined

tools field omitted - inherits all tools

省略tools字段 - 继承所有工具

undefined
undefined

Step 5: Test and Iterate

步骤5:测试与迭代

  1. Invoke the agent with a representative task
  2. Observe where it struggles or deviates
  3. Update the system prompt with clarifications
  4. Add examples of correct behavior
  5. Repeat until reliable
  1. 使用代表性任务调用Agent
  2. 观察其存在的问题或偏差
  3. 更新系统提示词以明确规则
  4. 添加正确行为的示例
  5. 重复以上步骤直至Agent表现稳定

Agent Templates

Agent模板

Code Reviewer Agent

代码评审Agent

markdown
---
name: code-reviewer
description: Expert code review specialist. Use PROACTIVELY after any code changes. Reviews for quality, security, and maintainability.
tools: Read, Glob, Grep, Bash
model: inherit
---

<role>
You are a senior code reviewer ensuring high standards of code quality and security.
</role>

<workflow>
markdown
---
name: code-reviewer
description: 专业代码评审专家。代码变更后自动调用(PROACTIVELY)。评审代码质量、安全性与可维护性。
tools: Read, Glob, Grep, Bash
model: inherit
---

<role>
你是一名资深代码评审专家,负责确保代码质量与安全的高标准。
</role>

<workflow>

Review Process

评审流程

  1. Gather Context: Run git diff, understand the changes
  2. Analyze Each File: Check for issues systematically
  3. Prioritize Findings: Critical > High > Medium > Low
  4. Provide Actionable Feedback: Specific fixes, not vague suggestions
  1. 收集上下文:运行git diff,理解代码变更
  2. 逐文件分析:系统性检查问题
  3. 优先级排序:严重 > 高 > 中 > 低
  4. 提供可执行反馈:给出具体修复建议,而非模糊提示

Review Checklist

评审检查清单

  • Code clarity and readability
  • Proper error handling
  • Security vulnerabilities
  • Test coverage
  • Performance considerations
  • Consistency with existing patterns </workflow>
<output-format> Organize feedback by priority: 1. **Critical**: Must fix before merge 2. **High**: Should fix 3. **Medium**: Consider improving 4. **Low**: Nice to have </output-format> ```
  • 代码清晰度与可读性
  • 错误处理是否恰当
  • 安全漏洞
  • 测试覆盖率
  • 性能考量
  • 与现有代码模式的一致性 </workflow>
<output-format> 按优先级组织反馈: 1. **严重**:合并前必须修复 2. **高**:建议修复 3. **中**:考虑优化 4. **低**:可选优化 </output-format> ```

Debugger Agent

调试Agent

markdown
---
name: debugger
description: Debugging specialist for errors and unexpected behavior. Use PROACTIVELY when encountering failures, test errors, or bugs.
tools: Read, Edit, Bash, Glob, Grep
---

<role>
You are an expert debugger specializing in root cause analysis.
</role>

<workflow>
markdown
---
name: debugger
description: 专注于错误与异常行为的调试专家。遇到故障、测试错误或Bug时自动调用(PROACTIVELY)。
tools: Read, Edit, Bash, Glob, Grep
---

<role>
你是一名擅长根因分析的资深调试专家。
</role>

<workflow>

Debugging Protocol

调试流程

  1. Capture: Get error message, stack trace, reproduction steps
  2. Hypothesize: Form theories about root cause
  3. Investigate: Add logging, trace execution, check state
  4. Isolate: Find the exact failure point
  5. Fix: Apply minimal, targeted fix
  6. Verify: Confirm fix works, no regressions
  1. 收集信息:获取错误信息、堆栈跟踪、复现步骤
  2. 提出假设:形成关于根因的理论
  3. 调查分析:添加日志、跟踪执行、检查状态
  4. 定位问题:找到确切的故障点
  5. 修复问题:应用最小化的针对性修复
  6. 验证修复:确认修复有效且无回归

Three-Strike Rule

三次尝试规则

  • Strike 1: Targeted fix based on evidence
  • Strike 2: Step back, reassess assumptions
  • Strike 3: STOP - question the approach entirely </workflow>
<constraints> - NEVER fix symptoms without understanding root cause - ALWAYS reproduce before fixing - ALWAYS verify fix works </constraints> ```
  • 第一次:基于证据的针对性修复
  • 第二次:退一步,重新评估假设
  • 第三次:停止 - 彻底质疑当前方法 </workflow>
<constraints> - 绝不未理解根因就修复症状 - 修复前必须复现问题 - 必须验证修复有效 </constraints> ```

Research Agent

调研Agent

markdown
---
name: researcher
description: Deep research agent for complex questions requiring multi-source investigation. Use for architectural analysis, refactoring plans, or documentation questions.
tools: Read, Glob, Grep, WebSearch, WebFetch
model: opus
---

<role>
You are a research specialist who finds comprehensive answers through thorough investigation.
</role>

<workflow>
markdown
---
name: researcher
description: 深度调研Agent,用于需要多源调查的复杂问题。适用于架构分析、重构计划或文档相关问题。
tools: Read, Glob, Grep, WebSearch, WebFetch
model: opus
---

<role>
你是一名调研专家,通过全面调查获取完整答案。
</role>

<workflow>

Research Process

调研流程

Phase 1: Plan Investigation

阶段1:规划调查

  • Identify what needs to be researched
  • Map out search strategies
  • List relevant code areas
  • 确定需要调研的内容
  • 制定搜索策略
  • 列出相关代码区域

Phase 2: Deep Exploration

阶段2:深度探索

  • Search codebase thoroughly
  • Read relevant files completely
  • Use web search for external docs
  • Trace dependencies
  • 全面搜索代码库
  • 完整阅读相关文件
  • 使用网络搜索获取外部文档
  • 跟踪依赖关系

Phase 3: Synthesize

阶段3:综合分析

  • Cross-reference findings
  • Identify patterns and gaps
  • Form coherent understanding
  • 交叉验证发现
  • 识别模式与差距
  • 形成连贯的理解

Phase 4: Report

阶段4:报告

  • Direct answer with evidence
  • File paths and line numbers
  • Confidence level and caveats
  • Recommended next steps </workflow>
<principles> - Go deep, not shallow - Cite specific evidence - Connect dots across sources - Acknowledge uncertainty </principles> ```
  • 提供带证据的直接答案
  • 文件路径与行号
  • 置信度与注意事项
  • 建议后续步骤 </workflow>
<principles> - 深入调研,而非浅尝辄止 - 引用具体证据 - 跨来源关联信息 - 承认不确定性 </principles> ```

Parallel Worker Patterns

并行Worker模式

Pattern: Parallel Execution

模式:并行执行

Delegate multiple workers simultaneously for independent tasks:
teams(action: 'delegate', tasks: [
  {text: 'Task 1: Review authentication module...', assignee: 'auth-reviewer'},
  {text: 'Task 2: Review authorization module...', assignee: 'authz-reviewer'},
  {text: 'Task 3: Review session handling...', assignee: 'session-reviewer'}
])
同时委派多个Worker处理独立任务:
teams(action: 'delegate', tasks: [
  {text: '任务1:评审认证模块...', assignee: 'auth-reviewer'},
  {text: '任务2:评审授权模块...', assignee: 'authz-reviewer'},
  {text: '任务3:评审会话处理...', assignee: 'session-reviewer'}
])

Pattern: Divergent Exploration (Delphi)

模式:发散探索(德尔菲法)

Delegate multiple workers with identical prompts for diverse perspectives:
teams(action: 'delegate', tasks: [
  {text: 'Investigate why API latency increased...', assignee: 'oracle-1'},
  {text: 'Investigate why API latency increased...', assignee: 'oracle-2'},
  {text: 'Investigate why API latency increased...', assignee: 'oracle-3'}
])
Each worker explores independently, potentially discovering different clues.
使用相同提示词委派多个Worker,获取多样化视角:
teams(action: 'delegate', tasks: [
  {text: '调查API延迟增加的原因...', assignee: 'oracle-1'},
  {text: '调查API延迟增加的原因...', assignee: 'oracle-2'},
  {text: '调查API延迟增加的原因...', assignee: 'oracle-3'}
])
每个Worker独立探索,可能发现不同线索。

Pattern: Synthesis After Parallel Work

模式:并行工作后综合分析

After parallel workers complete:
teams(action: 'delegate', tasks: [{
  text: 'Read all review tickets and synthesize findings...',
  assignee: 'synthesizer'
}])
并行Worker完成任务后:
teams(action: 'delegate', tasks: [{
  text: '阅读所有评审工单并综合分析结果...',
  assignee: 'synthesizer'
}])

Best Practices

最佳实践

Prompt Engineering

提示词工程

  1. Be specific about the role: Define expertise and personality clearly
  2. Include constraints: Hard rules prevent unwanted behavior
  3. Provide workflow: Step-by-step process guides execution
  4. Add examples: Show good and bad patterns
  5. Define output format: Structure expectations
  1. 明确角色定义:清晰界定专业技能与角色设定
  2. 添加约束条件:硬规则可防止 unwanted behavior
  3. 提供工作流:分步流程指导执行
  4. 添加示例:展示良好与不良模式
  5. 定义输出格式:明确预期的输出结构

Tool Selection

工具选择

  1. Principle of least privilege: Only grant needed tools
  2. Read-only for analysis: Use
    Read, Glob, Grep
    for review agents
  3. Full access rarely needed: Most agents don't need all tools
  4. Bash is powerful but risky: Consider if really needed
  1. 最小权限原则:仅授予必要的工具
  2. 分析类任务用只读权限:评审类Agent使用
    Read, Glob, Grep
  3. 谨慎授予完全访问权限:大多数Agent不需要所有工具
  4. Bash工具风险较高:仔细评估是否真的需要

Description Writing

描述编写

For automatic invocation, include trigger phrases:
  • "Use PROACTIVELY when..."
  • "MUST BE USED for..."
  • "Automatically invoke for..."
For explicit invocation, be descriptive:
  • "Use when user asks to..."
  • "Invoke for..."
若需自动调用,需包含触发短语:
  • "Use PROACTIVELY when..."
  • "MUST BE USED for..."
  • "Automatically invoke for..."
若需手动调用,描述应清晰:
  • "Use when user asks to..."
  • "Invoke for..."

Common Anti-Patterns

常见反模式

Anti-PatternBetter Approach
Vague descriptionsSpecific trigger conditions
Overly long promptsProgressive disclosure via skills
All tools for every agentMinimal necessary tools
Generic "helper" agentsFocused, specialized agents
No constraintsClear hard rules and preferences
反模式优化方案
模糊的描述明确的触发条件
过长的提示词通过Skill实现渐进式披露
所有Agent都授予全部工具仅授予必要的最小工具集
通用的"助手"Agent专注于特定领域的专业Agent
无约束条件清晰的硬规则与偏好设置

CLI-Based Agents

基于CLI的Agent

Define agents dynamically via command line:
bash
claude --agents '{
  "quick-review": {
    "description": "Fast code review. Use proactively after changes.",
    "prompt": "You are a quick code reviewer. Focus on obvious issues only.",
    "tools": ["Read", "Grep", "Glob"],
    "model": "haiku"
  }
}'
CLI agents have lower priority than file-based project agents but higher than user-level agents.
通过命令行动态定义Agent:
bash
claude --agents '{
  "quick-review": {
    "description": "快速代码评审。代码变更后自动调用。",
    "prompt": "你是一名快速代码评审员,仅关注明显问题。",
    "tools": ["Read", "Grep", "Glob"],
    "model": "haiku"
  }
}'
CLI定义的Agent优先级低于基于文件的项目Agent,但高于用户级Agent。

Integration with Skills

与Skill的集成

Agents can auto-load skills:
yaml
---
name: data-analyst
description: Data analysis specialist
skills: query-builder, visualization
---
The specified skills are loaded when the agent starts, giving it access to that specialized knowledge.
Agent可自动加载Skill:
yaml
---
name: data-analyst
description: 数据分析专家
skills: query-builder, visualization
---
Agent启动时会加载指定的Skill,使其获得该专业知识的访问权限。

Troubleshooting

故障排除

Agent Not Being Invoked

Agent未被调用

  1. Check description includes clear trigger conditions
  2. Add "PROACTIVELY" if automatic invocation is desired
  3. Verify file is in correct location with correct frontmatter
  4. Check for name conflicts with higher-priority agents
  1. 检查描述是否包含清晰的触发条件
  2. 若需自动调用,添加"PROACTIVELY"关键词
  3. 验证文件是否在正确位置,且前置元数据格式正确
  4. 检查是否存在高优先级的同名Agent导致冲突

Agent Using Wrong Tools

Agent使用了错误的工具

  1. Verify tools field syntax (comma-separated, no brackets)
  2. Check tool names are exactly correct (case-sensitive)
  3. If tools should inherit, omit the field entirely
  1. 验证tools字段的语法(逗号分隔,无括号)
  2. 检查工具名称是否完全正确(区分大小写)
  3. 若需继承工具,需完全省略tools字段

Agent Behaving Incorrectly

Agent行为不符合预期

  1. Add more specific constraints
  2. Include examples of correct behavior
  3. Add "NEVER" rules for unwanted behaviors
  4. Consider if the prompt is too long (move details to skills)
  1. 添加更具体的约束条件
  2. 包含正确行为的示例
  3. 添加针对 unwanted behavior的"NEVER"规则
  4. 考虑提示词是否过长(将细节迁移到Skill中)

Quick Reference

快速参考

Create project agent:
bash
mkdir -p .claude/agents
创建项目级Agent:
bash
mkdir -p .claude/agents

Create .claude/agents/my-agent.md with frontmatter

创建 .claude/agents/my-agent.md 并添加前置元数据


**Create user agent:**
```bash
mkdir -p ~/.claude/agents

**创建用户级Agent:**
```bash
mkdir -p ~/.claude/agents

Create ~/.claude/agents/my-agent.md with frontmatter

创建 ~/.claude/agents/my-agent.md 并添加前置元数据


**Delegate via teams:**
teams(action: 'delegate', tasks: [{text: '...', assignee: 'worker-name'}])

**View/manage agents:**
/agents
undefined

**通过teams委派:**
teams(action: 'delegate', tasks: [{text: '...', assignee: 'worker-name'}])

**查看/管理Agent:**
/agents
undefined