Pick orchestrator settings once; the main agent delegates all reads and writes, and subagent limits (models, how many run at once, context per subagent) are…

An Orchestrator switch above the prompt. The main agent delegates all reads and writes to subagents; models, how many run at once and each subagent's context are enforced.
/plugin install orchestrator --marketplace katipally/modz
Update, then restart your sessions (more in the main README):
claude plugin marketplace update modz
claude plugin update orchestrator@modz
● Orchestrator ON Settings ▴ ⠹ 2/2 running Save as default Reset
Models ☑ Opus ☑ Sonnet ☐ Haiku
Agents at once ○ 1 ● 2 ○ 3 ○ 4 ○ Custom…
Context limit ● 200k ○ 400k ○ Custom…
Main agent ☑ Delegates reads & writes
Delegates reads & writes ticked, the main agent is refused Read, Write, Edit, NotebookEdit, Glob, Grep and Bash. Subagents keep them.Save as default keeps your settings across sessions and shows ✓ Default while they match; Reset restores the saved ones.Orchestrator ON/OFF toggles with one click; Settings shows or hides the rows below it./orch on|off, /orch max=4 ctx=300k models=sonnet,haiku delegate=off, /orch save, /orch reset.hooks/register.tsx 348 lines1import { atom, read, update } from 'claude-code'
2import type { Register, BoxProps, ElementConstructor, EngineInterface, RenderChildren, RenderElement, RenderNode, SelectOption, Timer } from 'claude-code'
3
4import type { Config, Field, Model } from '../types'
5
6const MODELS: Model[] = ['opus', 'sonnet', 'haiku']
7const FALLBACK: Config = { isOn: true, models: ['sonnet', 'haiku'], maxAgents: 2, contextK: 200, delegate: true }
8const AGENT_PRESETS = [1, 2, 3, 4]
9const CONTEXT_PRESETS = [200, 400]
10const CUSTOM = 'custom'
11const USER_ORIGINS = new Set(['composer', 'bridge', 'sdk'])
12const DELEGATED_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep', 'Bash'])
13
14const CONFIG_REF = { plugin: 'orchestrator', key: 'config' } as const
15const config = atom(CONFIG_REF, FALLBACK)
16const running = atom({ plugin: 'orchestrator', key: 'running' } as const, [])
17const spin = atom({ plugin: 'orchestrator', key: 'spin' } as const, 0)
18const spawned = atom({ plugin: 'orchestrator', key: 'spawned' } as const, [])
19const retired = atom({ plugin: 'orchestrator', key: 'retired' } as const, [])
20const saved = atom({ plugin: 'orchestrator', key: 'saved' } as const, null)
21
22// The spinner turns only while a subagent this session spawned is still running.
23const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
24const SPIN_MS = 100
25let spinner: Timer | undefined
26const track = async ($: EngineInterface, agentId: string, isRunning: boolean) => {
27 await update($, running, ids => (isRunning ? [...ids, agentId] : ids.filter(id => id !== agentId)))
28 const count = (await read($, running)).length
29 if (count > 0 && !spinner) spinner = $.clock.every(SPIN_MS, () => void update($, spin, n => n + 1))
30 if (count === 0) {
31 spinner?.cancel()
32 spinner = undefined
33 }
34}
35// Spawns between the cap check and their agent joining `running`, so parallel Agent calls cannot all pass one check.
36let starting = 0
37const editing = atom({ plugin: 'orchestrator', key: 'editing' } as const, null)
38const isOpen = atom({ plugin: 'orchestrator', key: 'isOpen' } as const, false)
39
40const contextLabel = (k: number) => (k >= 1000 ? `${k / 1000}M` : `${k}k`)
41const title = (m: Model) => m[0]!.toUpperCase() + m.slice(1)
42
43const summary = (c: Config) =>
44 `${c.isOn ? 'ON' : 'OFF'} | models: ${c.models.join(', ')} | max at once: ${c.maxAgents} | context: ${contextLabel(c.contextK)} | delegate: ${c.delegate ? 'on' : 'off'}`
45
46const same = (a: Config, b: Config) =>
47 a.isOn === b.isOn && a.delegate === b.delegate && a.maxAgents === b.maxAgents && a.contextK === b.contextK &&
48 MODELS.every(m => a.models.includes(m) === b.models.includes(m))
49
50// Old saved defaults lack newer fields, so they merge over FALLBACK.
51const loadDefaults = async ($: EngineInterface) => {
52 const stored = (await $.store.get('defaults')) as Partial<Config> | undefined
53 return stored ? { ...FALLBACK, ...stored } : null
54}
55const saveDefaults = async ($: EngineInterface, c: Config) => {
56 await $.store.set('defaults', c)
57 await update($, saved, () => c)
58}
59const resetConfig = async ($: EngineInterface) => {
60 const stored = await loadDefaults($)
61 await update($, saved, () => stored)
62 await update($, config, () => stored ?? FALLBACK)
63 return stored ?? FALLBACK
64}
65
66const brief = (c: Config) =>
67 [
68 'Orchestrator mode (chosen by the user for this request):',
69 '- You are the orchestrator. Break the work down, delegate it to subagents with the Agent tool, then verify and merge their results.',
70 c.delegate && '- Do not read, search, edit or run commands yourself. Every read and write, verification included, goes to a subagent; those tools are refused for you.',
71 `- Allowed subagent models: ${c.models.join(', ')}. Always set \`model\` on every Agent call to one of these, matched to the difficulty of the subtask.`,
72 `- At most ${c.maxAgents} subagents run at the same time. A spawn or a message to a finished subagent past that is refused until one finishes.`,
73 `- Each subagent's context is capped at ${contextLabel(c.contextK)} tokens. At the cap its tools are refused and it must report; it cannot be messaged again. Spawn a fresh subagent with a self-contained brief to carry on.`,
74 '- Give each subagent one task or a few closely related ones. For unrelated work spawn a fresh subagent instead of messaging an old one.',
75 '- Subagents must not spawn subagents. Tell them so in each brief.',
76 ].filter(Boolean).join('\n')
77
78// "300", "300k" and "1m" all read as thousands of tokens for ctx.
79const toNumber = (v: string) => Number(v.trim().replace(/k$/i, '').replace(/m$/i, '000'))
80
81// `/orch max=4 ctx=200 models=sonnet,haiku on` style edits; unknown words are reported back.
82const parse = (args: string, c: Config): { next: Config; bad: string[] } => {
83 const bad: string[] = []
84 let next = c
85 for (const word of args.split(/\s+/).filter(Boolean)) {
86 const [k, v = ''] = word.split('=')
87 const n = toNumber(v)
88 const picked = v.split(',').filter((m): m is Model => MODELS.includes(m as Model))
89 if (k === 'on' || k === 'off') next = { ...next, isOn: k === 'on' }
90 else if (k === 'max' && n >= 1) next = { ...next, maxAgents: Math.floor(n) }
91 else if (k === 'ctx' && n > 0) next = { ...next, contextK: n }
92 else if (k === 'delegate' && (v === 'on' || v === 'off')) next = { ...next, delegate: v === 'on' }
93 else if (k === 'models' && picked.length > 0) next = { ...next, models: picked }
94 else bad.push(word)
95 }
96 return { next, bad }
97}
98
99const withValue = (presets: number[], value: number) =>
100 (presets.includes(value) ? presets : [...presets, value].sort((a, b) => a - b))
101
102// Every modz mod places its tile in one shared band: a lead column (the bot), then a column of tiles, then an optional
103// right column. A column with no tiles is not drawn, and columns wrap under each other when the width runs out.
104const BAND = 'modz-band'
105const SLOTS: Record<string, 'lead' | 'left' | 'right'> = {
106 buddy: 'lead',
107 'usage-limits': 'left',
108 'cache-timer': 'left',
109 'model-info': 'left',
110 orchestrator: 'left',
111}
112const ORDER = Object.keys(SLOTS)
113const keyOf = (n: RenderNode) => (typeof n !== 'string' && n.type === 'Box' ? String(n.props?.key ?? '') : '')
114const rank = (n: RenderNode) => {
115 const i = ORDER.indexOf(keyOf(n))
116 return i < 0 ? ORDER.length : i
117}
118const pack = (Box: ElementConstructor<BoxProps>, below: RenderElement, tile: RenderElement) => {
119 const isEmpty = below.type === 'Box' && !below.children?.length
120 const tiles = keyOf(below) === BAND
121 ? (below.type === 'Box' ? below.children ?? [] : []).flatMap(col => (typeof col !== 'string' && col.type === 'Box' ? col.children ?? [] : [col]))
122 : isEmpty ? [] : [below]
123 const all = [...tiles, tile].sort((a, b) => rank(a) - rank(b))
124 const [lead, left, right] = (['lead', 'left', 'right'] as const).map(slot => all.filter(n => (SLOTS[keyOf(n)] ?? 'left') === slot))
125 return (
126 <Box key={BAND} flexDirection="row" flexWrap="wrap" columnGap={3}>
127 {lead!.length > 0 && <Box key="modz-lead" flexDirection="column" justifyContent="center">{lead}</Box>}
128 {left!.length > 0 && <Box key="modz-left" flexDirection="column" flexGrow={right!.length > 0 ? 1 : 0}>{left}</Box>}
129 {right!.length > 0 && <Box key="modz-right" flexDirection="column" alignItems="flex-end">{right}</Box>}
130 </Box>
131 )
132}
133
134
135export const register: Register = on => {
136 on('session.start', async ($, e, next) => {
137 await $.command.register({
138 name: 'orch',
139 description: 'Orchestrator settings: on, off, max=N, ctx=200k, models=sonnet,haiku, delegate=on|off, save, reset',
140 argumentHint: '[on|off] [max=N] [ctx=N] [models=a,b] [delegate=on|off] [save|reset]',
141 })
142 const held = await $.state.get(CONFIG_REF)
143 const stored = await loadDefaults($)
144 await update($, saved, () => stored)
145 if (held.version === 0 && stored) await update($, config, () => stored)
146 return next(e)
147 })
148
149 on('command.run', { command: 'orch' }, async ($, e) => {
150 const words = e.args.trim()
151 if (words === 'save') {
152 const c = await read($, config)
153 await saveDefaults($, c)
154 return { text: `Saved as default: ${summary(c)}` }
155 }
156 if (words === 'reset') return { text: `Reset: ${summary(await resetConfig($))}` }
157 const { next, bad } = parse(words, await read($, config))
158 await update($, config, () => next)
159 return { text: `Orchestrator ${summary(next)}${bad.length ? `\nIgnored: ${bad.join(' ')}` : ''}` }
160 })
161
162 on('prompt.submit', async ($, e, next) => {
163 const c = await read($, config)
164 if (!c.isOn || !USER_ORIGINS.has(e.origin.kind)) return next(e)
165 return next({ ...e, context: [...(e.context ?? []), brief(c)] })
166 }).catch(($, e, next) => next(e))
167
168 on('agent.spawn', async ($, e, next) => {
169 const c = await read($, config)
170 if (!c.isOn || e.workflow) return next(e)
171 if (e.parentAgentId !== undefined) {
172 return { deny: 'Orchestrator mode: only the main agent may spawn subagents. Do this work yourself.' }
173 }
174 if (!e.fork && !c.models.some(m => e.model?.includes(m))) {
175 return { deny: `Orchestrator mode: set model to one of ${c.models.join(', ')}.` }
176 }
177 if ((await read($, running)).length + starting >= c.maxAgents) {
178 return { deny: `Orchestrator mode: ${c.maxAgents} subagents are already running, the most at once. Wait for one to finish, then spawn this.` }
179 }
180 starting++
181 try {
182 const ran = await next(e)
183 if (ran.agentId) {
184 await update($, spawned, ids => [...ids, ran.agentId!])
185 await track($, ran.agentId, true)
186 }
187 return ran
188 } finally {
189 starting--
190 }
191 }).catch(($, e, next) => next(e))
192
193 on('turn.complete', async ($, e, next) => {
194 if (e.agentId && (await read($, running)).includes(e.agentId)) await track($, e.agentId, false)
195 return next(e)
196 })
197
198 on('tool.call', async ($, e, next) => {
199 const c = await read($, config)
200 if (!c.isOn) return next(e)
201 if (e.agentId === undefined) {
202 // Only the model's own calls: another mod's $.tool.call on the main loop is not the orchestrator doing the work.
203 return c.delegate && DELEGATED_TOOLS.has(e.tool) && next.origin.plugin === 'engine' ? { deny: 'Orchestrator mode: delegate reads, searches, edits and commands to a subagent.' } : next(e)
204 }
205 if ((await read($, retired)).includes(e.agentId)) {
206 return { deny: `Orchestrator mode: this subagent reached its context limit of ${contextLabel(c.contextK)} tokens. Stop using tools and reply now with your report.` }
207 }
208 return next(e)
209 }).catch(($, e, next) => next(e))
210
211 on('turn.step', async function* ($, e, next) {
212 const response = yield* next(e)
213 const id = e.agentId
214 const u = response.usage
215 if (id && u) {
216 const c = await read($, config)
217 const [mine, done] = await Promise.all([read($, spawned), read($, retired)])
218 const context = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens + u.output_tokens
219 if (c.isOn && mine.includes(id) && !done.includes(id) && context >= c.contextK * 1000) await update($, retired, ids => [...ids, id])
220 }
221 return response
222 })
223
224 on('session.send', async ($, e, next) => {
225 const c = await read($, config)
226 if (!c.isOn || e.agentId !== undefined) return next(e)
227 const id = (await $.agent.list()).find(a => a.id === e.to || a.name === e.to)?.id ?? e.to
228 if (!(await read($, spawned)).includes(id)) return next(e)
229 if ((await read($, retired)).includes(id)) {
230 return { isDelivered: false as const, reason: `Orchestrator mode: that subagent reached its context limit of ${contextLabel(c.contextK)} tokens and cannot be messaged. Spawn a fresh subagent with a self-contained brief.` }
231 }
232 if ((await read($, running)).includes(id)) return next(e)
233 if ((await read($, running)).length + starting >= c.maxAgents) {
234 return { isDelivered: false as const, reason: `Orchestrator mode: ${c.maxAgents} subagents are already running, the most at once. Wait for one to finish, then send this.` }
235 }
236 starting++
237 try {
238 const sent = await next(e)
239 if (sent.isDelivered) await track($, id, true)
240 return sent
241 } finally {
242 starting--
243 }
244 }).catch(($, e, next) => next(e))
245
246 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
247 const below = await next(e)
248 if (e.props.hasSurvey) return below
249 const elements = $.ui.resolve(e)
250 if (!('Select' in elements)) return below
251 const { Box, Button, Input, Select, Text } = elements
252 const [c, edit, open, busy, turn, defaults] = await Promise.all([read($, config), read($, editing), read($, isOpen), read($, running), read($, spin), read($, saved)])
253 const isDefault = same(c, defaults ?? FALLBACK)
254 const set = (fn: (c: Config) => Config) => update($, config, fn)
255 const toggle = (m: Model) =>
256 set(c => {
257 const models = MODELS.filter(x => (x === m) !== c.models.includes(x))
258 return models.length ? { ...c, models } : c
259 })
260
261 const LABEL_WIDTH = Math.max(...['Models', 'Agents at once', 'Context limit', 'Main agent'].map(l => l.length))
262 const row = (label: string, ...controls: RenderChildren[]) => (
263 <Box flexDirection="row" flexWrap="wrap" columnGap={1} paddingLeft={2}>
264 <Text dimColor>{label.padEnd(LABEL_WIDTH)}</Text>
265 {controls}
266 </Box>
267 )
268 const mark = (isChosen: boolean) => (isChosen ? '●' : '○')
269
270 // In the terminal a Select answers only the keyboard, so there every option is a button one click picks, the
271 // chosen one marked; every other surface keeps its native Select.
272 const choice = (key: string, value: string, options: readonly SelectOption[], onSelect: (v: string) => unknown) =>
273 e.surface !== 'terminal' ? (
274 <Select key={key} value={value} options={options} onSelect={onSelect} />
275 ) : (
276 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
277 {options.map(o => (
278 <Button key={`${key}:${o.value}`} plain dimColor={o.value !== value} label={`${mark(o.value === value)} ${o.label ?? o.value}`} onPress={() => onSelect(o.value)} />
279 ))}
280 </Box>
281 )
282
283 const numberPicker = (key: Field, value: number, presets: number[], label: (n: number) => string, apply: (n: number) => Config) =>
284 edit === key ? (
285 <Box flexDirection="row" columnGap={2}>
286 <Input
287 key={`${key}-custom`}
288 autoFocus
289 placeholder={key === 'max' ? 'agents at once' : 'tokens, e.g. 300k or 1m'}
290 submitLabel="Set"
291 onSubmit={async v => {
292 const n = toNumber(v)
293 if (!(n >= 1)) return $.ui.toast(`Not a number: ${v}`)
294 await set(() => apply(key === 'max' ? Math.floor(n) : n))
295 await update($, editing, () => null)
296 }}
297 />
298 <Button key={`${key}-cancel`} plain dimColor label="Cancel" onPress={() => update($, editing, () => null)} />
299 </Box>
300 ) : (
301 choice(
302 key,
303 String(value),
304 [...withValue(presets, value).map(n => ({ value: String(n), label: label(n) })), { value: CUSTOM, label: 'Custom…' }],
305 v => (v === CUSTOM ? update($, editing, () => key) : set(() => apply(Number(v)))),
306 )
307 )
308
309 return pack(Box, below, (
310 <Box key="orchestrator" flexDirection="column">
311 <Box flexDirection="row" flexWrap="wrap" columnGap={3}>
312 <Button key="orch" plain dimColor={!c.isOn} onPress={async () => {
313 await set(c => ({ ...c, isOn: !c.isOn }))
314 await update($, editing, () => null)
315 }}>
316 <Text color={c.isOn ? 'success' : 'inactive'}>{mark(c.isOn)}</Text>
317 {' Orchestrator '}
318 <Text color={c.isOn ? 'success' : 'inactive'} bold={c.isOn}>{c.isOn ? 'ON' : 'OFF'}</Text>
319 </Button>
320 <Button key="settings" plain dimColor label={`Settings ${open ? '▴' : '▾'}`} onPress={async () => {
321 await update($, isOpen, o => !o)
322 await update($, editing, () => null)
323 }} />
324 {busy.length > 0 && <Text color="planMode">{SPINNER[turn % SPINNER.length]} {busy.length}/{c.maxAgents} running</Text>}
325 {open && isDefault && <Text dimColor>✓ Default</Text>}
326 {open && !isDefault && (
327 <Button key="save" plain label="Save as default" onPress={async () => {
328 await saveDefaults($, c)
329 $.ui.toast(`Saved: ${summary(c)}`)
330 }} />
331 )}
332 {open && !isDefault && (
333 <Button key="reset" plain dimColor label="Reset" onPress={async () => $.ui.toast(`Reset: ${summary(await resetConfig($))}`)} />
334 )}
335 </Box>
336 {open && row('Models', ...MODELS.map(m => (
337 <Button key={`model-${m}`} plain label={`${c.models.includes(m) ? '☑' : '☐'} ${title(m)}`} dimColor={!c.models.includes(m)} onPress={() => toggle(m)} />
338 )))}
339 {open && row('Agents at once', numberPicker('max', c.maxAgents, AGENT_PRESETS, String, n => ({ ...c, maxAgents: n })))}
340 {open && row('Context limit', numberPicker('ctx', c.contextK, CONTEXT_PRESETS, contextLabel, n => ({ ...c, contextK: n })))}
341 {open && row('Main agent', (
342 <Button key="delegate" plain dimColor={!c.delegate} label={`${c.delegate ? '☑' : '☐'} Delegates reads & writes`} onPress={() => set(c => ({ ...c, delegate: !c.delegate }))} />
343 ))}
344 </Box>
345 ))
346 })
347}
348types/index.d.ts 27 lines1export type Model = 'opus' | 'sonnet' | 'haiku'
2
3export type Field = 'max' | 'ctx'
4
5export type Config = {
6 isOn: boolean
7 models: Model[]
8 maxAgents: number
9 contextK: number
10 delegate: boolean
11}
12
13declare module 'claude-code' {
14 interface PluginState {
15 orchestrator: {
16 config: Config
17 editing: Field | null
18 isOpen: boolean
19 running: string[]
20 spawned: string[]
21 retired: string[]
22 saved: Config | null
23 spin: number
24 }
25 }
26}
27