Caps parallel subagents and monitors; more need a stated reason and the user's approval

Caps how many subagents and monitors Claude runs at the same time. Parallel subagents multiply token use, and a runaway loop can start dozens of monitors; this mod makes going beyond a limit a deliberate decision.
| Situation | What happens |
|---|---|
| Below the limit | The subagent or monitor starts as usual |
| At the limit, no reason given | The start is refused; Claude is told how to retry with a reason, and to do so only if another one in parallel is really necessary |
| At the limit, reason given | A dialog shows the task and Claude's reason: Allow once, No limit this session or Deny |
| Your prompt names a count | "Use 8 subagents", "starte fünf Subagents", "5 monitors" raises the limit to that count for the session; a toast confirms it |
While anything runs, the footer under the prompt shows the count against the limit, for example 🤖 2/4 👁 1/3 for subagents and monitors. A kind with nothing running is left out.
Several subagents started in one message are decided one after another, and a subagent that was let through counts until it is visibly running — otherwise all of them would see an empty slot at the same moment.
| Option | Default |
|---|---|
maxSubagents | 4 |
maxMonitors | 3 |
Change them in /config, or in ~/.claude/settings.json:
"pluginConfigs": {
"concurrency-guard": { "options": { "maxSubagents": 6, "maxMonitors": 2 } }
}
Claude learns the format from the refusal, so nothing has to be configured. For reference: a subagent carries the reason as the first line of its prompt, a monitor in front of its description, each introduced with Over-limit reason:. The mod removes the reason again before the subagent or monitor starts.
/clear resets the limits.TaskStop, their timeout or their end notification; a monitor started before the mod was loaded is not counted.mod-hub loaded, the desktop footer leaves the running count to its 🧰, whose Concurrency row shows it.Remove the mod from CLAUDE_CODE_PLUGIN_DIRS. Its options in pluginConfigs can be deleted.
hooks/register.tsx 321 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { TrackedMonitor } from '../types'
5import { REASON_PREFIX, parseTaskEnds, requestedLimits, takeReasonLine, takeReasonPrefix } from './limits'
6import type { Kind } from './limits'
7import type { HubCall, HubEntry } from './hub'
8
9const ALLOW_ONCE = 'Allow once'
10const ALLOW_SESSION = 'No limit this session'
11const DENY = 'Deny'
12// Stored state is JSON, where Infinity would come back as null.
13const UNLIMITED = 1_000_000
14
15const monitors = atom({ plugin: 'concurrency-guard', key: 'monitors' } as const, [])
16const overrides = atom({ plugin: 'concurrency-guard', key: 'overrides' } as const, { subagents: null, monitors: null })
17const footer = atom({ plugin: 'concurrency-guard', key: 'footer' } as const, null)
18const isHubbed = atom({ plugin: 'concurrency-guard', key: 'isHubbed' } as const, false)
19
20let published: string | null = null
21
22// Without mod-hub the call throws, and the mod keeps its own footer label.
23async function publish($: EngineInterface, entry: HubEntry): Promise<void> {
24 const text = JSON.stringify(entry)
25 if (text === published) {
26 return
27 }
28 let isReached = true
29 try {
30 await ($ as unknown as HubCall).hub.set({ id: 'concurrency-guard', ...entry })
31 } catch {
32 isReached = false
33 }
34 published = isReached ? text : null
35 if ((await read($, isHubbed)) !== isReached) {
36 await update($, isHubbed, () => isReached)
37 }
38}
39
40const LABELS: Record<Kind, string> = { subagents: 'subagent', monitors: 'monitor' }
41const ICONS: Record<Kind, string> = { subagents: '🤖', monitors: '👁' }
42
43// Several Agent calls in one message are checked at the same moment, before any
44// of them shows up as running. Decisions therefore run one after another, and a
45// call that was let through counts as reserved until it is visibly running.
46const reservations: Record<Kind, Set<string>> = { subagents: new Set(), monitors: new Set() }
47let decisionQueue: Promise<unknown> = Promise.resolve()
48
49function serialized<T>(work: () => Promise<T>): Promise<T> {
50 const run = decisionQueue.then(work, work)
51 decisionQueue = run.catch(() => undefined)
52
53 return run
54}
55
56async function runningMonitors($: EngineInterface): Promise<TrackedMonitor[]> {
57 const now = await $.clock.now()
58 const list = await read($, monitors)
59 const alive = list.filter(i => i.deadline === null || i.deadline > now)
60 if (alive.length !== list.length) {
61 await update($, monitors, () => alive)
62 }
63
64 return alive
65}
66
67async function runningSubagents($: EngineInterface): Promise<number> {
68 const monitorIds = new Set((await read($, monitors)).map(i => i.taskId))
69 const agents = await $.agent.list()
70
71 return agents.filter(i => i.status === 'running' && !monitorIds.has(i.id)).length
72}
73
74async function running($: EngineInterface, kind: Kind): Promise<number> {
75 const visible = kind === 'subagents' ? await runningSubagents($) : (await runningMonitors($)).length
76
77 return visible + reservations[kind].size
78}
79
80// Set from the plugin's options when the module registers.
81let defaults: Record<Kind, number> = { subagents: 4, monitors: 3 }
82
83async function limit($: EngineInterface, kind: Kind): Promise<number> {
84 return (await read($, overrides))[kind] ?? defaults[kind]
85}
86
87async function refreshFooter($: EngineInterface): Promise<void> {
88 const parts: string[] = []
89 for (const kind of ['subagents', 'monitors'] as const) {
90 const count = await running($, kind)
91 if (count > 0) {
92 const max = await limit($, kind)
93 parts.push(`${ICONS[kind]} ${count}/${max >= UNLIMITED ? '∞' : max}`)
94 }
95 }
96 const label = parts.length === 0 ? null : parts.join(' ')
97 if (label !== (await read($, footer))) {
98 await update($, footer, () => label)
99 }
100 await publish($, {
101 icon: '🤖',
102 title: 'Concurrency',
103 status: label ?? 'No subagents or monitors running',
104 attention: 'none',
105 actions: [],
106 })
107}
108
109// Under the limit the call runs untouched. At the limit it is refused once
110// with instructions; only a retry that states a reason reaches the person.
111async function gate(
112 $: EngineInterface,
113 kind: Kind,
114 task: string,
115 reason: string | null,
116 retryHint: string,
117): Promise<{ deny: string } | null> {
118 const count = await running($, kind)
119 const max = await limit($, kind)
120 if (count < max) {
121 return null
122 }
123 if (reason === null || reason.length === 0) {
124 return {
125 deny: `Concurrency limit reached: ${count} ${kind} are running and the limit is ${max}. Wait for one to finish. Only if another one in parallel is really necessary, ${retryHint} The user will be asked to approve.`,
126 }
127 }
128
129 let answer: string
130 try {
131 answer = await $.ui.ask(
132 `Claude wants to start ${LABELS[kind]} ${count + 1} while the limit is ${max}.\n\nTask: ${task}\nReason: ${reason}\n\nAllow it?`,
133 { options: [ALLOW_ONCE, ALLOW_SESSION, DENY], header: 'Parallel' },
134 )
135 } catch {
136 answer = DENY
137 }
138
139 if (answer === ALLOW_ONCE) {
140 return null
141 }
142 if (answer === ALLOW_SESSION) {
143 await update($, overrides, current => ({ ...current, [kind]: UNLIMITED }))
144 $.ui.toast(`No ${LABELS[kind]} limit for the rest of this session.`)
145
146 return null
147 }
148 const note = answer === DENY ? '' : ` The user answered: "${answer}".`
149
150 return { deny: `The user did not approve another ${LABELS[kind]} beyond the limit of ${max}.${note} Wait for running ones to finish.` }
151}
152
153export const register: Register = (on, options) => {
154 defaults = {
155 subagents: Number(options.maxSubagents ?? 4),
156 monitors: Number(options.maxMonitors ?? 3),
157 }
158
159 on('session.start', async ($, e, next) => {
160 const result = await next(e)
161 await refreshFooter($)
162
163 return result
164 })
165
166 on('prompt.submit', async ($, e, next) => {
167 if (e.origin.kind === 'composer') {
168 const requested = requestedLimits(e.text)
169 for (const kind of ['subagents', 'monitors'] as const) {
170 const value = requested[kind]
171 if (value !== undefined && value > defaults[kind]) {
172 await update($, overrides, current => ({ ...current, [kind]: value }))
173 $.ui.toast(`${LABELS[kind]} limit raised to ${value} for this session.`)
174 }
175 }
176 }
177
178 if (e.origin.kind === 'task-notification') {
179 const ended = new Set(parseTaskEnds(e.text).map(i => i.taskId))
180 if (ended.size > 0) {
181 await update($, monitors, list => list.filter(i => !ended.has(i.taskId)))
182 }
183 }
184 await refreshFooter($)
185
186 return next(e)
187 })
188
189 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
190 // A call missing its parameters is rejected by Claude Code's own validation.
191 if (typeof e.prompt !== 'string' || typeof e.description !== 'string') {
192 return next(e)
193 }
194 const { reason, rest } = takeReasonLine(e.prompt)
195 const refusal = await serialized(async () => {
196 const decision = await gate(
197 $,
198 'subagents',
199 e.description,
200 reason,
201 `retry this exact call with "${REASON_PREFIX} <one sentence why>" as the first line of \`prompt\`.`,
202 )
203 if (decision === null) {
204 reservations.subagents.add(e.tool_use_id)
205 }
206
207 return decision
208 })
209 if (refusal !== null) {
210 return refusal
211 }
212 try {
213 return await next(reason === null ? e : { ...e, prompt: rest })
214 } finally {
215 reservations.subagents.delete(e.tool_use_id)
216 await refreshFooter($)
217 }
218 })
219
220 // A foreground subagent's tool call only returns when it is done; once it has
221 // spawned it is listed as running, so the reservation is no longer needed.
222 on('agent.spawn', async ($, e, next) => {
223 const result = await next(e)
224 reservations.subagents.delete(e.tool_use_id)
225
226 return result
227 })
228
229 on('tool.call', { tool: 'Monitor' }, async ($, e, next) => {
230 if (typeof e.description !== 'string') {
231 return next(e)
232 }
233 const { reason, rest } = takeReasonPrefix(e.description)
234 const refusal = await serialized(async () => {
235 const decision = await gate(
236 $,
237 'monitors',
238 rest,
239 reason,
240 `retry this exact call with \`description\` set to "${REASON_PREFIX} <one sentence why> | <description>".`,
241 )
242 if (decision === null) {
243 reservations.monitors.add(e.tool_use_id)
244 }
245
246 return decision
247 })
248 if (refusal !== null) {
249 return refusal
250 }
251 try {
252 const result = await next(reason === null ? e : { ...e, description: rest })
253 if (result.deny === undefined && result.isError !== true) {
254 const now = await $.clock.now()
255 const deadline = result.result.persistent === true || result.result.timeoutMs === 0 ? null : now + result.result.timeoutMs
256 await update($, monitors, list => [...list, { taskId: result.result.taskId, description: rest, deadline }])
257 }
258
259 return result
260 } finally {
261 reservations.monitors.delete(e.tool_use_id)
262 await refreshFooter($)
263 }
264 })
265
266 on('tool.call', { tool: 'TaskStop' }, async ($, e, next) => {
267 const result = await next(e)
268 const taskId = e.task_id ?? e.shell_id
269 if (taskId !== undefined) {
270 await update($, monitors, list => list.filter(i => i.taskId !== taskId))
271 }
272 await refreshFooter($)
273
274 return result
275 })
276
277 on('turn.complete', async ($, e, next) => {
278 const result = await next(e)
279 await refreshFooter($)
280
281 return result
282 })
283
284 on('session.end', async ($, e, next) => {
285 if (e.reason === 'clear') {
286 await update($, overrides, () => ({ subagents: null, monitors: null }))
287 await update($, monitors, () => [])
288 await update($, footer, () => null)
289 }
290
291 return next(e)
292 })
293
294 // The terminal draws the mode labels itself, so the label joins them there.
295 // On the desktop, status-band draws the footer from the labels it was handed,
296 // whichever order the mods load in; only a drawn tree survives that.
297 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
298 const label = await read($, footer)
299 if (label === null) {
300 return next(e)
301 }
302 if (e.surface === 'terminal') {
303 return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } })
304 }
305 if (await read($, isHubbed)) {
306 return next(e)
307 }
308 const below = await next(e)
309 const { Box, Text } = $.ui.resolve(e)
310 const rest = below.type !== 'engine' ? below : e.props.modes.length === 0 ? null : <Text dimColor>{e.props.modes.join(' & ')}</Text>
311
312 return (
313 <Box flexDirection="row">
314 <Text dimColor>{label}</Text>
315 {rest !== null && <Text dimColor> · </Text>}
316 {rest}
317 </Box>
318 )
319 })
320}
321hooks/limits.ts 77 lines1export const REASON_PREFIX = 'Over-limit reason:'
2
3export type Kind = 'subagents' | 'monitors'
4
5const NUMBER_WORDS: Record<string, number> = {
6 zwei: 2, drei: 3, vier: 4, fünf: 5, sechs: 6, sieben: 7, acht: 8, neun: 9, zehn: 10, elf: 11, zwölf: 12,
7 two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12,
8}
9
10const COUNT = `(\\d+|${Object.keys(NUMBER_WORDS).join('|')})`
11
12// "Nutze 8 Subagents", "starte fünf Subagenten", "use up to six agents" — a
13// count directly before the noun, optionally with "parallel" in between.
14const REQUEST_PATTERNS: Record<Kind, RegExp> = {
15 subagents: new RegExp(`(?<![\\p{L}\\d])${COUNT}\\s+(?:parallele?n?\\s+|parallel\\s+)?(?:sub-?agent(?:s|en)?|agent(?:s|en)?)(?![\\p{L}])`, 'iu'),
16 monitors: new RegExp(`(?<![\\p{L}\\d])${COUNT}\\s+(?:parallele?n?\\s+|parallel\\s+)?monitor(?:s|e|en)?(?![\\p{L}])`, 'iu'),
17}
18
19export function requestedLimits(text: string): Partial<Record<Kind, number>> {
20 const limits: Partial<Record<Kind, number>> = {}
21 for (const kind of ['subagents', 'monitors'] as const) {
22 const match = REQUEST_PATTERNS[kind].exec(text)
23 const token = match?.[1]?.toLowerCase()
24 const value = token === undefined ? Number.NaN : (NUMBER_WORDS[token] ?? Number(token))
25 if (Number.isInteger(value) && value > 0) {
26 limits[kind] = value
27 }
28 }
29
30 return limits
31}
32
33export type Reasoned = { reason: string | null; rest: string }
34
35// Subagents carry the reason as the first line of their prompt.
36export function takeReasonLine(prompt: string): Reasoned {
37 const [first = '', ...others] = prompt.split('\n')
38 if (!first.trim().startsWith(REASON_PREFIX)) {
39 return { reason: null, rest: prompt }
40 }
41
42 return { reason: first.trim().slice(REASON_PREFIX.length).trim(), rest: others.join('\n').replace(/^\n+/, '') }
43}
44
45// Monitors carry it in their one-line description: "Over-limit reason: <why> | <description>".
46export function takeReasonPrefix(description: string): Reasoned {
47 const trimmed = description.trim()
48 if (!trimmed.startsWith(REASON_PREFIX)) {
49 return { reason: null, rest: description }
50 }
51 const body = trimmed.slice(REASON_PREFIX.length)
52 const separator = body.lastIndexOf('|')
53 if (separator === -1) {
54 return { reason: body.trim(), rest: body.trim() }
55 }
56
57 return { reason: body.slice(0, separator).trim(), rest: body.slice(separator + 1).trim() }
58}
59
60export type TaskEnd = { taskId: string; status: string }
61
62// Background tasks report their end as a <task-notification> delivered like a prompt.
63export function parseTaskEnds(text: string): TaskEnd[] {
64 const ends: TaskEnd[] = []
65 const pattern = /<task-notification>([\s\S]*?)<\/task-notification>/g
66 for (const match of text.matchAll(pattern)) {
67 const body = match[1] ?? ''
68 const taskId = /<task-id>\s*([^<\s]+)\s*<\/task-id>/.exec(body)?.[1]
69 const status = /<status>\s*([^<\s]+)\s*<\/status>/.exec(body)?.[1]
70 if (taskId !== undefined && status !== undefined && ['completed', 'failed', 'killed', 'stopped', 'timeout'].includes(status)) {
71 ends.push({ taskId, status })
72 }
73 }
74
75 return ends
76}
77hooks/hub.ts 12 lines1// mod-hub's contract, restated: listed under dependencies, it would keep this
2// mod from loading where mod-hub is not installed.
3export type HubEntry = {
4 icon: string
5 title: string
6 status: string
7 attention: 'none' | 'info' | 'warning'
8 actions: { key: string; label: string }[]
9}
10
11export type HubCall = { hub: { set: (entry: HubEntry & { id: string }) => Promise<void> } }
12types/index.d.ts 15 lines1export type TrackedMonitor = { taskId: string; description: string; deadline: number | null }
2
3export type LimitOverrides = { subagents: number | null; monitors: number | null }
4
5declare module 'claude-code' {
6 interface PluginState {
7 'concurrency-guard': {
8 monitors: TrackedMonitor[]
9 overrides: LimitOverrides
10 footer: string | null
11 isHubbed: boolean
12 }
13 }
14}
15