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

agent-patterns — скилл для Claude Code: что делает и как установить

Скилл agent-patterns для Claude Code описывает паттерны мультиагентных систем и субагентов для организации задач в изолированных контекстах.

MIT 115 установок ★ 29 обновлён 2026-08-17

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add oakoss/agent-skills --skill agent-patterns -a claude-code
Открыть на GitHub

Что делает agent-patterns

Скилл даёт правила архитектуры субагентов в AI-средах разработки. Он объясняет, когда выносить задачи в отдельные изолированные контексты, а когда оставаться в основном диалоге. Внутри собраны шаблоны: рой взаимозаменяемых агентов, последовательный пайплайн, иерархическое разделение задач и циклы ревью кода.

В материалах расписаны встроенные агенты Claude Code вроде Explore, Plan и Bash, их права и модели. Приводятся схемы ограничения инструментов через списки tools и disallowedTools, а также формат конфигурации в .claude/agents/*.md.

Субагенты не умеют порождать других субагентов — вложенность ограничена одним уровнем. Поэтому многоэтапную цепочку всегда ведёт основной диалог, а фоновые агенты работают без доступа к MCP-инструментам.

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

  • спроектировать архитектуру кастомных субагентов в .claude/agents/
  • разгрузить контекст основного диалога от шумных логов и тестов
  • настроить права доступа и списки разрешённых инструментов для агента
  • организовать параллельную обработку пачек задач силами двух-четырёх воркеров

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

  • Помоги составить конфиг субагента для безопасного ревью кода без прав на запуск Bash
  • Как организовать параллельный сбор данных из пяти источников через субагентов?
  • Выбери архитектурный паттерн для разбиения большой миграции на изолированные шаги

Как установить agent-patterns

1Через Skills CLI (Vercel)

npx skills add oakoss/agent-skills --skill agent-patterns -a claude-code

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

~/.claude/skills/agent-patterns/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/agent-patterns/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об agent-patterns

Как установить agent-patterns в Claude Code?

Выполните команду npx skills add oakoss/agent-skills --skill agent-patterns -a claude-code в терминале.

Что делает скилл agent-patterns?

Он предоставляет готовые шаблоны оркестрации, правила изоляции контекста и форматы настройки субагентов для кодинг-ассистентов.

Может ли субагент запускать других субагентов?

Нет, действует строгое ограничение в один уровень вложенности: запускать субагентов разрешено только из основного контекста.

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

SKILL.md · MIT
---
name: agent-patterns
description: |
  Multi-agent design patterns for Claude Code and AI development systems. Covers custom subagents, built-in subagents (Explore/Plan/General-purpose), fungible vs specialized agents, delegation, orchestration, batch workflows, context hygiene, and failure recovery.

  Use when: designing multi-agent systems, creating custom subagents, delegating bulk operations, orchestrating parallel work, choosing between fungible and specialized agents, configuring agent frontmatter, or debugging agent coordination issues.
license: MIT
metadata:
  author: oakoss
  version: '1.1'
  source: https://code.claude.com/docs/en/sub-agents
user-invocable: false
---

# Agent Patterns

Multi-agent design, delegation, and orchestration in Claude Code and AI-assisted development. Default to fungible agents for large-scale software dev; use specialized agents only for peer review or discourse-based workflows.

Subagents in Claude Code are specialized AI assistants that run in isolated context windows with custom system prompts, specific tool access, and independent permissions. They preserve main conversation context by keeping exploration, test runs, and verbose operations out of the primary thread.

Key constraint: subagents cannot spawn other subagents. Multi-step orchestration requires chaining subagents from the main conversation.

## Quick Reference

| Pattern                   | Description                                       | When to Use                                  |
| ------------------------- | ------------------------------------------------- | -------------------------------------------- |
| Fungible swarm            | Identical agents pick tasks from a shared board   | Large-scale software dev, resilient systems  |
| Sequential pipeline       | Each agent builds on previous output              | Multi-step workflows with clear dependencies |
| Hierarchical              | Manager decomposes, workers execute in parallel   | Complex tasks with independent subtasks      |
| Peer collaboration        | Agents iterate until consensus                    | Code review, quality-critical outputs        |
| Orchestrator delegation   | Main conversation chains subagents                | Multi-phase workflows, parallel specialists  |
| Two-stage review          | Spec compliance check, then code quality check    | High-stakes code, complex requirements       |
| Question-first delegation | Agent asks clarifying questions before proceeding | Ambiguous tasks, expensive-to-redo work      |
| Review loop enforcement   | Fix-review cycle with max iteration escalation    | Any review workflow needing convergence      |

| Built-in Subagent | Model    | Tools     | Purpose                                           |
| ----------------- | -------- | --------- | ------------------------------------------------- |
| Explore           | Haiku    | Read-only | File discovery, code search, codebase exploration |
| Plan              | Inherits | Read-only | Codebase research during plan mode                |
| General-purpose   | Inherits | All tools | Complex research, multi-step operations           |
| Bash              | Inherits | Terminal  | Running terminal commands in separate context     |
| Claude Code Guide | Haiku    | Read-only | Answering questions about Claude Code features    |

| Configuration            | Value                                                                             |
| ------------------------ | --------------------------------------------------------------------------------- |
| Custom agent location    | `.claude/agents/*.md` (project), `~/.claude/agents/*.md` (user)                   |
| CLI agents               | `--agents '{...}'` (session only, JSON format)                                    |
| Plugin agents            | Plugin `agents/` directory (lowest priority)                                      |
| Required fields          | `name`, `description`                                                             |
| Optional fields          | `tools`, `disallowedTools`, `model`, `permissionMode`, `skills`, `hooks`, `color` |
| Model values             | `sonnet`, `opus`, `haiku`, `inherit` (default)                                    |
| Permission modes         | `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, `plan`                  |
| Nesting limit            | Subagents cannot spawn other subagents (one level only)                           |
| Foreground vs background | Foreground blocks main conversation; background runs concurrently                 |
| Batch size               | 5-8 items per agent (standard tasks)                                              |
| Parallel agents          | 2-4 simultaneously                                                                |

## When to Use Subagents vs Main Conversation

| Use Subagents When                                              | Use Main Conversation When                                 |
| --------------------------------------------------------------- | ---------------------------------------------------------- |
| Task produces verbose output (test suites, logs, API responses) | Task needs frequent back-and-forth or iterative refinement |
| Enforcing specific tool restrictions or permissions             | Multiple phases share significant context                  |
| Work is self-contained and can return a summary                 | Making a quick, targeted change                            |
| Parallel independent research paths                             | Latency matters (subagents start fresh and gather context) |

## Tool Access Patterns

| Agent Role         | Recommended Tools                       | Rationale                                     |
| ------------------ | --------------------------------------- | --------------------------------------------- |
| Read-only reviewer | `Read, Grep, Glob`                      | Cannot modify code; safe for audits           |
| File creator       | `Read, Write, Edit, Glob, Grep`         | NO Bash; avoids heredoc approval spam         |
| Script runner      | `Read, Write, Edit, Glob, Grep, Bash`   | Full access for build/deploy tasks            |
| Research agent     | `Read, Grep, Glob, WebFetch, WebSearch` | External data access for documentation lookup |

Subagents inherit all tools by default (including MCP tools). Use `tools` as an allowlist or `disallowedTools` as a denylist to restrict access. MCP tools are not available in background subagents.

## Common Mistakes

| Mistake                                                     | Correct Pattern                                                                                            |
| ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| Expecting subagents to spawn sub-subagents                  | Subagents cannot nest; chain subagents from the main conversation instead                                  |
| Giving Bash tool to agents that only create files           | Use Write and Edit tools only; Bash causes approval spam from heredoc usage                                |
| Omitting `disallowedTools` for sensitive operations         | Use `disallowedTools` to explicitly deny dangerous tools even when inheriting                              |
| Spawning too many agents (5+) for a small task              | Start with 2-3 agents; coordination overhead outweighs benefit at higher counts                            |
| Burying critical instructions past line 300 of agent prompt | Put critical rules immediately after frontmatter; models deprioritize late instructions                    |
| Using specialized agents for large-scale software dev       | Use fungible agents with a shared task board; specialized agents create single points of failure           |
| Not including "FIX issues found" in delegation prompts      | Without explicit action directive, agents only report problems without making changes                      |
| Setting model to Haiku for content generation               | Default to Sonnet; Haiku only for script execution, fast lookups, or pass/fail checks                      |
| Not writing clear descriptions for custom agents            | Claude uses the `description` field to decide when to auto-delegate; vague descriptions prevent delegation |
| Using MCP tools in background subagents                     | MCP tools are not available in background subagents; run in foreground instead                             |
| Not preloading skills into subagents                        | Subagents do not inherit skills from the parent; list them explicitly in the `skills` field                |

## Delegation

- **Explore codebase before designing agent prompts**: Claude auto-delegates to the built-in Explore subagent (Haiku, read-only) for file discovery and code search; supports quick, medium, and very thorough modes
- **Plan multi-agent architecture for complex projects**: Use plan mode; Claude delegates research to the Plan subagent before presenting a plan
- **Execute batch operations across many files**: Chain General-purpose subagents from the main conversation with identical prompts and non-overlapping item lists
- **Isolate high-volume operations**: Delegate test runs, log processing, or doc fetching to subagents to keep verbose output out of your main context
- **Run parallel research**: Spawn multiple subagents simultaneously for independent investigations; Claude synthesizes findings when all complete
- **Resume interrupted work**: Ask Claude to continue a previous subagent; resumed agents retain full conversation history including tool calls and reasoning

> For project-level workflow sequencing, phase-gate validation, goal decomposition, and capability scoring, use the `orchestration` skill.

## References

- [Agent types and design patterns](references/agent-types.md)
- [Delegation patterns and batch workflows](references/delegation-patterns.md)
- [Sub-agent configuration and prompt engineering](references/sub-agent-configuration.md)
- [Communication and orchestration patterns](references/orchestration.md)
- [Troubleshooting and anti-patterns](references/troubleshooting.md)

© oakoss · MIT · oakoss/agent-skills

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
multi-agent-patterns NeoLabHQ Скилл multi-agent-patterns для Claude Code помогает спроектировать систему из нескольких агентов. Включается, когда задачу можно разбить на части или одному агенту не хватает контекста. CX Codex +1 1 400установок orchestration stablyai Скилл orchestration для Claude Code запускает задачи в отдельном воркере Orca и возвращает результаты. CX Codex +1 359 600установок arena backnotprop Скилл arena для Claude Code запускает параллельных кандидатов под одну задачу, выбирает базовый вариант и переносит в него удачные части остальных. Защищает от фиксации на ошибочной архитектуре. CX Codex +1 10 800установок delegate-setup amElnagdy Скилл delegate-setup настраивает карту линий делегирования: какой CLI-исполнитель берёт фичи, тесты или UI, с моделью и уровнем усилий. Пишет конфиг только после вашего явного «да». CX Codex +1 6 500установок context-engineering-collection muratcankoylan Скилл context-engineering-collection для Claude Code даёт руководство по проектированию контекста и архитектуры ИИ-агентов. Его применяют при создании и оптимизации агентов, отладке контекста и разработке многоагентных систем. CX Codex +1 4 500установок Swarm Orchestration ruvnet Скилл Swarm Orchestration для Claude Code управляет роями агентов с параллельным выполнением задач, динамической топологией и балансировкой нагрузки. Координирует специалистов разного профиля. CX Codex +1 2 100установок

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

Весь набор →
package-publishing Скилл package-publishing помогает настроить package.json, сборку ESM и CJS и публикацию TypeScript-библиотеки в npm. Пригодится при настройке точек входа и проверок перед релизом. CX Codex +1 119установок svelte Справочник по Svelte 5 и SvelteKit для ИИ-агента: руны, сниппеты, роутинг, form actions и таблица перевода кода с Svelte 4. CX Codex +1 117установок react-native Помогает проектировать мобильные приложения на React Native и Expo с файловой маршрутизацией, EAS Build и нативными API под iOS и Android. CX Codex +1 117установок tiptap Скилл помогает собирать React-редакторы на Tiptap: настраивать расширения, SSR, загрузку изображений и совместное редактирование. Пригодится при добавлении редактора в приложение. CX Codex +1 117установок tanstack-cli Скилл tanstack-cli настраивает сборку библиотек через TanStack Config и Vite с генерацией типов и релизом через conventional commits. CX Codex +1 115установок better-auth Подгружает агенту справочник по better-auth: конфиг, плагины, стратегии сессий и типовые ошибки. Даёт справку при настройке входа, 2FA и организаций. CX Codex +1 114установок meta-skill-creator Скилл meta-skill-creator помогает создавать и проверять агентские скиллы по открытому стандарту Agent Skills. Он пригодится при подготовке SKILL.md, структуры папок и файлов для распространения. CX Codex +1 114установок figma-developer Скилл figma-developer для Claude Code получает из Figma цвета, шрифты и иконки через REST API и собирает CSS-переменные и React-компоненты. Автоматизирует перенос изменений макета в код. CX Codex +1 114установок

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

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