К основному содержанию
плагин

subagent-spawn-cap — плагин для Claude Code: бюджет спавнов субагентов

Плагин subagent-spawn-cap считает спавны субагентов за сессию: спрашивает разрешение на 20-м, потом каждые 10, а на 60-м отказывает. Возвращает лимит, который Claude убрал в 2.1.224.

MIT ★ 586 обновлён 2026-10-26

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add karanb192/claude-code-hooks
/plugin install subagent-spawn-cap@claude-code-hooks
Открыть на GitHub

Что делает subagent-spawn-cap

Плагин вешает хук PreToolUse на инструмент Agent (старое имя Task). Каждый спавн субагента дописывает строку в журнал сессии, и число строк — израсходованный бюджет. На 20-м спавне хук возвращает ask, дальше спрашивает каждые 10, на 60-м отвечает deny.

Журнал — append-only файл ~/.claude/subagent-spawn-cap/<session_id>.jsonl, по строке на разрешённый или спрошенный спавн. Дозапись выбрана из-за гонки: параллельные вызовы в одном ходу запускают параллельные процессы хука, и счётчик с чтением-записью такое не переживёт. Отказ в журнал не попадает, а спрошенный спавн записывается до вашего ответа. Хуки срабатывают и внутри субагентов с тем же session_id, поэтому вложенные веера идут в общий бюджет.

Пороги живут в переменных SPAWN_CAP_ASK, SPAWN_CAP_ASK_STEP и SPAWN_CAP_DENY в блоке env файла settings.json; после правки нужен перезапуск, неверное значение откатывается к дефолту. В headless-запуске claude -p и в режиме dontAsk запрос на подтверждение превращается в отказ, поэтому с дефолтами сессия кончится на 20-м спавне, а не на 60-м: для CI поставьте SPAWN_CAP_ASK равным SPAWN_CAP_DENY. Видны только спавны через Agent — скрипт Workflow пройдёт мимо.

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

  • остановить веер субагентов, ушедший в рекурсию
  • задать потолок спавнов на длинную сессию
  • вернуть счётчик после того, как встроенный лимит убрали в 2.1.224
  • уложить ночной прогон в известное число субагентов
  • посмотреть по журналу, сколько субагентов породила сессия

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

  • Разбей рефакторинг на субагентов, по одному на модуль
  • Запусти по субагенту на каждый пакет и собери отчёты
  • Продолжай в этой сессии, бюджет спавнов ещё не кончился

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

Через маркетплейс плагинов

/plugin marketplace add karanb192/claude-code-hooks
/plugin install subagent-spawn-cap@claude-code-hooks

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

Вопросы о subagent-spawn-cap

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

Сначала добавьте маркетплейс: /plugin marketplace add karanb192/claude-code-hooks. Потом поставьте плагин: /plugin install subagent-spawn-cap@claude-code-hooks. После установки перезапустите Claude.

Что делает subagent-spawn-cap?

Считает спавны субагентов в сессии и просит подтверждение на 20-м, затем каждые 10, а на 60-м отказывает. Спавны изнутри субагентов идут в тот же счёт.

Можно ли ставить его вместе с guard-pack?

guard-pack уже включает этот страж, так что два плагина дадут одно и то же. Достаточно одного.

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

subagent-spawn-cap · MIT
# subagent-spawn-cap

> A total-spawns-per-session budget for subagents: asks from spawn 20, again every 10, denies at 60, counted across nested fan-outs. The cap Claude Code shipped in 2.1.212 and removed in 2.1.224, back as a hook you control.

A `PreToolUse` hook on the `Agent` tool (older name `Task`). Every spawn in a session appends one line to a per-session ledger; the line count is the budget spent. Spawn `SPAWN_CAP_ASK` (default 20) prompts you, then every `SPAWN_CAP_ASK_STEP` spawns (default 10) prompts again, and spawn `SPAWN_CAP_DENY` (default 60) is denied. Hooks also fire inside subagents ([`agent_id` / `agent_type`](https://code.claude.com/docs/en/hooks#common-input-fields)) with the parent's `session_id` (observed in local subagent transcripts; the docs do not state it), so nested fan-outs share the budget.

**Why:** Claude Code had this cap natively from 2.1.212 ("Added a per-session cap on subagent spawns (default 200, override with `CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION`)") to 2.1.224 ("Removed the 200-subagent-per-session spawn cap; long-running sessions no longer refuse new agents (concurrency and depth limits still apply)"), per the [CHANGELOG](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md). The remaining native caps bound the rate (20 concurrent) and depth, not the total, which is the shape of [#92349](https://github.com/anthropics/claude-code/issues/92349) (325 agents for a settings audit), [#91942](https://github.com/anthropics/claude-code/issues/91942) (160 subagents, session limit exhausted), [#69206](https://github.com/anthropics/claude-code/issues/69206) (218 spawned, about 10 intended) and [#69578](https://github.com/anthropics/claude-code/issues/69578) (recursive loop, about 800k tokens).

## Install

```
/plugin marketplace add karanb192/claude-code-hooks   # once per machine
/plugin install subagent-spawn-cap@claude-code-hooks
```

Restart Claude Code, done. Already running [guard-pack](../guard-pack)? It includes this guard; do not install both.

## What it does

| Event | Matcher | What happens |
|-------|---------|--------------|
| PreToolUse | `Agent\|Task` | Counts the session's ledger lines plus this call. At `SPAWN_CAP_ASK` and every `SPAWN_CAP_ASK_STEP` after it: appends, returns `"ask"`. At or above `SPAWN_CAP_DENY`: returns `"deny"`, no append. Otherwise: appends, returns `{}`. Other tools: `{}` with no filesystem work. |

Per the [hooks reference](https://code.claude.com/docs/en/hooks#pretooluse-decision-control) an `ask` reason is shown to you and a `deny` reason to Claude, so the two texts have different readers. What you see in the permission prompt at spawn 20:

```
⚠️ [spawn-cap] Subagent spawn #20 in this session (ask threshold SPAWN_CAP_ASK=20, next check at #30, hard cap SPAWN_CAP_DENY=60). Approve to continue; the next 9 spawns then pass without asking. Deny to stop the fan-out. Reset this session's count by deleting ~/.claude/subagent-spawn-cap/<session_id>.jsonl; change the cadence via SPAWN_CAP_ASK / SPAWN_CAP_ASK_STEP in the settings.json env block (restart needed).
```

What Claude sees at spawn 60:

```
🚨 [spawn-cap] Subagent spawn #60 in this session hit the hard cap (SPAWN_CAP_DENY=60). Do not retry: finish with the results you already have and tell the user the session's spawn budget is spent. The user can reset it by deleting ~/.claude/subagent-spawn-cap/<session_id>.jsonl, or raise SPAWN_CAP_DENY in the settings.json env block and restart.
```

## Configuration

Hook processes inherit the environment Claude Code was launched with: set these in the `env` block of `settings.json` and restart. Invalid values fall back to the default.

| Variable | Default | Purpose |
|----------|---------|---------|
| `SPAWN_CAP_ASK` | `20` | First spawn number that prompts. Positive integer. |
| `SPAWN_CAP_ASK_STEP` | `10` | Prompt again every this many spawns after `SPAWN_CAP_ASK`; `1` prompts on every spawn. Positive integer. |
| `SPAWN_CAP_DENY` | `60` | Spawn number denied outright. Clamped up to `SPAWN_CAP_ASK` if set lower; equal to it skips the ask stage. |
| `SPAWN_CAP_ALLOW` | unset | The literal string `true` lets spawns through past both thresholds while set; each is still recorded and logged `ALLOW_OVERRIDE`. |

`HOOK_SAFETY_LEVEL` is not read: the repo's levels pick pattern sets, a budget is a number, and a hidden level-to-number table would move your budget whenever you tune the level for another guard.

**Unattended runs.** In `claude -p` with no permission host and in `dontAsk` mode, anything that would prompt is denied ([headless reference](https://code.claude.com/docs/en/headless)), so the ask threshold is the effective hard stop: with the defaults an unattended session ends at spawn 20, not 60. Set `SPAWN_CAP_ASK` equal to `SPAWN_CAP_DENY` for CI so Claude gets the deny text it can act on.

## State

One append-only JSONL per session at `~/.claude/subagent-spawn-cap/<session_id>.jsonl`, one line per allowed or asked spawn (`ts`, `n`, `decision`, `subagent_type`, `description` truncated to 80 chars, plus `agent_id` / `agent_type` inside subagents). Append-only because parallel tool calls in one turn fire parallel hook processes; `O_APPEND` writes survive that, a read-modify-write counter does not. Denied calls are not written. An asked call is written before you answer, so a declined ask still consumed one budget unit. Ledgers untouched for 7 days are pruned, at most once a day. Delete a session's file to reset its budget. Verdicts, `ALLOW_OVERRIDE` bypasses and config warnings go to `~/.claude/hooks-logs/`; the ledger never stores the prompt; no network calls.

## Known limits

- Only spawns through the `Agent` tool are seen; a Workflow script or other non-tool path is invisible to `PreToolUse`.
- Counts key on `session_id`, so a resumed session continues its count.
- Parallel calls in one turn each read the count before any appends; a batch can overshoot a threshold by up to the native concurrency limit, and the next call is judged on the full count.
- The ledger is a plain file; an agent with Bash could delete it. [config-guard](../config-guard) does not cover that directory yet.
- Session ids are sanitised to `[A-Za-z0-9._-]` for the file name (real ids are UUIDs); `O_APPEND` atomicity holds on macOS and Linux, Windows makes no cross-process guarantee.

## Uninstall

```
/plugin uninstall subagent-spawn-cap@claude-code-hooks
```

Part of [claude-code-hooks](https://github.com/karanb192/claude-code-hooks).

© Karan Bansal · MIT · karanb192/claude-code-hooks

Похожие плагины

Все плагины по теме «Настройка агента: память, контекст, субагенты» →
Creed Space nell MCP-сервер Creed Space подключает к ИИ-агентам систему конституционных правил и готовые персоны. Помогает проверять ответы и запросы на соответствие заданным принципам. CX Codex +1 10 491установок autobahn LilMGenius Скилл autobahn для Claude Code отделяет рискованные части задачи и передаёт безопасный остаток новому субагенту. CX Codex +1 1 500установок careful garrytan Скилл careful для Claude Code ставит хук, который проверяет команды Bash и PowerShell до запуска. На каждый rm -rf, DROP TABLE или git push --force агент спрашивает подтверждение. CX Codex +1 417установок nah manuelschipper Плагин nah для Claude Code проверяет команды и операции агента перед выполнением и останавливает те, что точно разрушат систему. Срабатывает на команды Bash, правки файлов, вызовы MCP-инструментов. ★ 494звёзд репо env-file-protection davila7 Хук env-file-protection для Claude Code, который запрещает агенту перезаписывать файлы .env*. Срабатывает на каждом вызове инструмента Write, если имя файла начинается с .env. 279установок team-spawn Seth Hobson Команда team-spawn для Claude Code, Codex и Cursor собирает многоагентную команду по пресету или заданному составу для ревью, отладки, разработки, исследования, аудита безопасности и миграции. CX Codex +1 ★ 42 780звёзд репо

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

Весь набор →
session-logger Плагин session-logger для Claude Code записывает ход сессии в Markdown-файл. Хуки фиксируют репозиторий, затронутые файлы и команды Bash. ★ 586звёзд репо format-code Плагин format-code для Claude Code форматирует файл сразу после записи или изменения: ruff для Python, prettier для JS, TS, JSON, MD, YAML и HTML. ★ 586звёзд репо auto-stage Плагин auto-stage для Claude Code автоматически добавляет изменённые ассистентом файлы в индекс Git, устраняя ручной вызов git add перед коммитом. ★ 586звёзд репо config-watch Плагин config-watch показывает в сессии любое изменение настроек или скиллов, случившееся посреди работы, либо блокирует его. Для случаев, когда установщик или npm-скрипт правит конфиг во время сессии. ★ 586звёзд репо config-guard Плагин config-guard для Claude Code блокирует правку агентом файлов с его ограничениями: настроек, скриптов хуков и манифестов плагинов. Чтение разрешено. ★ 586звёзд репо case-insensitive-guard Плагин case-insensitive-guard для Claude Code перехватывает опасные файловые команды и блокирует удаление не того пути из-за регистра букв. Срабатывает на командах Bash вроде rm -rf. ★ 586звёзд репо protect-tests Плагин protect-tests останавливает «липовый зелёный» результат: не даёт агенту удалять, переименовывать или отключать тесты через skip/xfail вместо того, чтобы чинить код. Работает с pytest, jest, Go, JUnit, RSpec и другими фреймворками. ★ 586звёзд репо git-safety Плагин git-safety для Claude Code перехватывает вызовы Bash и блокирует опасные команды git и gh CLI до выполнения. ★ 586звёзд репо

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

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