К основному содержанию
команда CX Codex

create-subagent — команда для Claude Code: создание субагента

Команда create-subagent для Claude Code создаёт специализированного субагента, задавая область задач, инструменты и правила работы. Настраивает эксперта проекта или пользователя.

MIT ★ 763 обновлён 2026-03-31

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/commands/create-subagent.md
Открыть на GitHub

Что делает create-subagent

Команда помогает создать субагента с широкой экспертизой в выбранной области, а не агента под одну узкую операцию. Сначала она уточняет домен, поддомен и место установки: .claude/agents/ для проекта или ~/.claude/agents/ для личного использования.

Далее команда просит описать 5-15 связанных задач, выбрать инструменты и продумать адаптацию к окружению проекта. В шаблоне есть YAML-поля для имени, описания, модели, категории, цвета и связанных агентов, а также шаги обнаружения окружения, анализа проблемы и передачи задачи специалисту.

Если не выбрать project или user, команда сначала запросит расположение. Для установки в Claude Code файл нужно поместить в .claude/commands/create-subagent.md; команда использует Write, Read и Bash(mkdir:*).

Какие задачи решает

  • создать субагента для конкретной области знаний
  • разделить экспертизу между доменным и узким специалистом
  • описать 5-15 задач нового агента
  • настроить инструменты и границы полномочий
  • проверить имя и YAML-структуру файла агента

Примеры запросов агенту

  • Запусти /create-subagent и создай эксперта по TypeScript для проекта.
  • Запусти /create-subagent для субагента по производительности базы данных с доступом только к инструментам анализа.
  • Запусти /create-subagent и размести личного агента в ~/.claude/agents/.

Как установить create-subagent

Вручную: положить файлы

.claude/commands/create-subagent.md

Вызов — /create-subagent. Для всех проектов — ~/.claude/commands/

Вопросы о create-subagent

Как установить create-subagent в Claude Code?

Скопируйте файл команды в .claude/commands/create-subagent.md, затем вызовите /create-subagent в Claude Code.

Что делает create-subagent?

Команда создаёт структуру специализированного субагента: помогает выбрать домен, задачи, инструменты, расположение и правила адаптации к проекту.

Когда лучше создать субагента, а не слэш-команду?

Субагент рассчитан на домен с 5-15 связанными задачами и концентрированной экспертизой. Для одной-двух узких задач команда советует рассмотреть слэш-команду.

Исходный текст

create-subagent.md · MIT
---
description: Create a specialized AI subagent following domain expert principles
category: claude-setup
allowed-tools: Write, Bash(mkdir:*), Read
---

# Create Domain Expert Subagent

Create a specialized AI subagent following the domain expert principles. This command helps you build concentrated domain expertise rather than single-task agents.

## Setup

First, specify the subagent location:
- **project** - Add to `.claude/agents/` (shared with team, higher priority)
- **user** - Add to `~/.claude/agents/` (personal use across projects)

If not specified, ask which type to create.

## Required Information

Gather the following from the user:

### 1. Domain Identification
- **Domain name**: The expertise area (e.g., typescript, testing, database)
- **Sub-domain (optional)**: Specific area within domain (e.g., typescript-type, test-jest)
- **Hierarchical placement**: Is this a broad expert or sub-domain specialist?

### 2. Domain Coverage Assessment
Ask the user to identify 5-15 related problems this expert will handle. Examples:
- TypeScript type expert: generics, conditionals, mapped types, declarations, performance
- Database performance expert: query optimization, indexing, execution plans, partitioning
- Testing expert: structure, patterns, fixtures, debugging, coverage

If they list fewer than 5 problems, suggest expanding scope or reconsidering as a slash command instead.

### 3. Tool Requirements
- Leave blank to inherit all tools (recommended for broad experts)
- Specify specific tools for focused permissions (e.g., Read, Grep, Glob for analysis-only)
- Common patterns:
  - Analysis experts: `Read, Grep, Glob, Bash`
  - Fix experts: `Read, Edit, MultiEdit, Bash, Grep`
  - Architecture experts: `Read, Write, Edit, Bash, Grep`

**Tip**: Use `/agents` to adjust tool permissions interactively later.

### 4. Environmental Adaptation
Help define how the agent detects and adapts to project context:
- Framework/library detection (prefer config reads over heavy commands)
- Configuration file checks using internal tools first
- Project structure analysis
- Available tool discovery

**Note**: Prefer internal tools (Read, Grep, Glob) over shell commands for better performance.

## Subagent Template Structure

### YAML Frontmatter
```yaml
---
# REQUIRED FIELDS
name: domain-expert  # Unique identifier (lowercase, hyphens only)
description: Expert in {domain} handling {problem-list}. Use PROACTIVELY for {trigger-conditions}.

# OPTIONAL FIELDS
tools: Read, Grep, Bash  # If omitted, inherits ALL tools
model: opus  # opus, sonnet, or haiku
category: general  # For UI grouping
color: indigo  # Visual color in UI
displayName: Domain Expert  # Human-readable name
bundle: ["related-expert"]  # Related agents to install together
---
```

**Important**: Omitting the `tools` field grants ALL tools. An empty `tools:` field grants NO tools.

### Content Template
```markdown
# {Domain} Expert

You are a {domain} expert with deep knowledge of {specific-areas}.

## Delegation First
0. **If ultra-specific expertise needed, delegate immediately**:
   - {Area 1} → {specialist-1}
   - {Area 2} → {specialist-2}
   Output: "This requires {specialty}. Use {expert-name}. Stopping here."

## Core Process
1. **Environment Detection** (Use Read/Grep before shell):
   - Check configuration files
   - Detect framework/tools
   - Analyze project structure

2. **Problem Analysis** (4-6 categories):
   - {Category 1}: {Description}
   - {Category 2}: {Description}
   - {Category 3-6}: {Description}

3. **Solution Implementation**:
   - Apply domain best practices
   - Use progressive solutions (quick/proper/best)
   - Validate with established workflows
```

## Delegation Patterns

### Broad Domain Experts
- Include step 0 delegation to specialists
- Reference related domain experts
- Clear "stopping here" language
- Example: `typescript-expert` delegates to `typescript-type-expert`

### Sub-Domain Experts  
- Reference parent domain expert
- Define specialization boundaries
- Provide escalation paths
- Example: `typescript-type-expert` references `typescript-expert`

## Quality Checks

Before creating, verify:

### Domain Expert Criteria
- [ ] Covers 5-15 related problems (not just 1-2)
- [ ] Has concentrated, non-obvious knowledge
- [ ] Detects and adapts to environment
- [ ] Integrates with specific tools
- [ ] Would pass the "Would I pay $5/month for this?" test

### Boundary Check
Ask: "Would someone put '{{Domain}} Expert' on their resume?"
- Yes → Good domain boundary
- No → Too narrow, consider broader scope

### Naming Check
- ✅ Good: `typescript-expert`, `database-performance-expert`
- ❌ Avoid: `fix-circular-deps`, `enhanced-typescript-helper`

## Proactive Triggers

For agents that should be used automatically, include trigger phrases:
- "Use PROACTIVELY when {{condition}}"
- "MUST BE USED for {{scenario}}"
- "Automatically handles {{problem-type}}"

## Implementation Steps

1. **Create Directory Structure**
   ```bash
   # For project subagent
   mkdir -p .claude/agents
   
   # For user subagent
   mkdir -p ~/.claude/agents
   ```

2. **Generate Agent File**
   First, convert agent name to kebab-case filename:
   - "TypeScript Expert" → `typescript-expert.md`
   - "Database Performance" → `database-performance.md`
   
   Check if file exists before writing:
   ```bash
   # Check for existing file
   if [[ -f "{{path}}/{{kebab-name}}.md" ]]; then
     # Ask user: overwrite or create {{kebab-name}}-new.md?
   fi
   ```
   
   Create `{{kebab-name}}.md` with the populated template

3. **Validate Structure**
   - Ensure YAML frontmatter is valid
   - Check name follows kebab-case convention
   - Verify description is clear and actionable

4. **Show Usage Examples**
   ```
   # Automatic invocation based on description
   > Fix the TypeScript type errors in my code
   
   # Explicit invocation
   > Use the {{agent-name}} to analyze this issue
   ```

## Common Domain Expert Examples

### Complete Example: TypeScript Type Expert
```markdown
---
name: typescript-type-expert
description: Advanced TypeScript type system specialist for complex generics, conditional types, and type-level programming. Use PROACTIVELY for type errors, generics issues, or declaration problems.
tools: Read, Edit, MultiEdit, Grep, Glob
category: general
---

# TypeScript Type System Expert

You are a TypeScript type system specialist with deep knowledge of advanced type features.

## Delegation First
0. **If different expertise needed, delegate immediately**:
   - General TypeScript issues → typescript-expert
   - Build/compilation → typescript-build-expert
   - Testing → testing-expert
   Output: "This requires {specialty}. Use {expert-name}. Stopping here."

## Core Process
1. **Environment Detection**:
   - Check tsconfig.json for strict mode settings
   - Detect TypeScript version
   - Analyze type complexity in codebase

2. **Problem Analysis**:
   - Generic constraints and inference
   - Conditional types and mapped types
   - Template literal types
   - Type-level programming

3. **Solution Implementation**:
   - Apply progressive fixes (quick/proper/best)
   - Ensure type safety without runtime overhead
   - Validate with tsc --noEmit
```

### Other Language Experts
- `typescript-type-expert`: Type system, generics, conditionals, declarations
- `python-async-expert`: asyncio, concurrency, event loops
- `rust-ownership-expert`: Lifetimes, borrowing, memory safety

### Infrastructure Experts
- `database-performance-expert`: Query optimization, indexing, execution plans
- `container-optimization-expert`: Docker, image size, security
- `kubernetes-expert`: Deployments, networking, scaling

### Quality Experts
- `test-architecture-expert`: Test structure, fixtures, patterns
- `webapp-security-expert`: XSS, CSRF, authentication
- `frontend-performance-expert`: Bundle size, lazy loading, caching

## Notes

- Start with Claude-generated agents, then customize to your needs
- Design focused agents with single, clear responsibilities
- Check project agents into version control for team sharing
- Limit tool access to what's necessary for the agent's purpose

Remember: The goal is concentrated domain expertise that handles multiple related problems, not single-task agents. When in doubt, expand the scope to cover more related problems within the domain.

© carlrannaberg · MIT · carlrannaberg/claudekit

Похожие слэш-команды

Все слэш-команды по теме «Настройка агента: память, контекст, субагенты» →
create-worktree-subagent disler Субагент create-worktree-subagent создаёт изолированный git worktree для параллельной работы. Он нужен, когда создание окружения явно делегируют субагенту. CX Codex ★ 1 573звёзд репо om-create-skill open-mercato Скилл om-create-skill создаёт новый OM-скилл по брифу или разбивает разросшийся SKILL.md на слои references/. Работает в режиме авторинга или консервативного сплита, за линт-гейтом и проверкой полноты. CX Codex +1 4 000установок create-cowork-plugin официальный anthropics Скилл create-cowork-plugin для Claude Code и пяти других платформ, который ведёт разработчика через весь цикл создания плагина в сессии Cowork — от идеи до готового .plugin-файла. CX Codex +1 3 000установок aiconfig-create launchdarkly Скилл aiconfig-create для Claude Code перенаправляет к актуальному скиллу configs-create. Старые ссылки на прежнее имя нужно заменить. CX Codex +1 2 900установок create-skill siviter-xyz Скилл create-skill для Claude Code помогает создавать и обновлять скиллы для ИИ-агентов. Он подключается к таким просьбам и ведёт по структуре файлов и правилам проектирования. CX Codex +1 2 800установок create-rule NeoLabHQ Скилл create-rule помогает написать файл правила в .claude/rules/, чтобы агент перестал повторять одну и ту же ошибку. CX Codex +1 1 300установок

Из того же набора54

Весь набор →
code-search Субагент code-search для Claude Code ищет в кодовой базе файлы, функции и шаблоны и возвращает краткий список путей. Локализует код перед правками без лишних рассуждений модели. CX Codex ★ 763звёзд репо validate-and-fix Команда validate-and-fix для Claude Code запускает проверки проекта и распределяет исправления между параллельными агентами. Она ищет команды сборки, тестов и линтинга в инструкциях проекта и package.json. CX Codex +1 ★ 763звёзд репо migration Команда migration переносит CLAUDE.md, .cursorrules и другие файлы настроек ИИ в один AGENTS.md и ставит на него симлинки под каждый ассистент. CX Codex +1 ★ 763звёзд репо research-expert Субагент research-expert ищет данные в сети в параллельном режиме, подбирает глубину анализа под задачу и сохраняет подробный отчёт в файл, отдавая в чат только краткую сводку. CX Codex ★ 763звёзд репо research Команда research разбивает вопрос на параллельные задачи субагентов, читает их отчёты из /tmp и сводит в один файл со ссылками на источники. CX Codex +1 ★ 763звёзд репо cleanup Команда cleanup находит временные тестовые скрипты, POC-файлы и отчёты после сессий разработки, предлагая список на удаление только после подтверждения. CX Codex +1 ★ 763звёзд репо oracle Субагент oracle для Claude Code разбирает сложные ошибки, архитектурные решения, коммиты и вопросы безопасности. Проводит аудит кода и даёт второе мнение по техническим решениям. CX Codex ★ 763звёзд репо code-review Команда code-review запускает шесть ревью-агентов параллельно: архитектура, качество, безопасность, производительность, тесты, документация. Пригодится перед мержем крупной ветки. CX Codex +1 ★ 763звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой