Soft-denies subagent spawns with no model set and heavy-model spawns late in the five-hour window, and forecasts five-hour and weekly caps at the current pace

A Claude Code mod that keeps subagent spending deliberate.
general-purpose, claude by default) that sets no model is denied once with a reminder to choose one from the task. Re-issue the identical call to run it on the inherited model anyway.opus, fable by default) while the five-hour window is at or past warnAt (75%) is denied once with the reading and the projected cap time. Re-issue unchanged to spend it anyway, or name a model: choosing a heavy one after seeing the reading passes.QM 5h cap ~3:40pm · week cap ~Oct 25, 9:00am · agents 4 (2 opus, 2 sonnet). Each part shows only when it has something to say, and the line is hidden when none does. It doesn't repeat the usage percentages: pair it with a status line that shows them. A timer redraws it every minute, so a passed cap time or a reset doesn't stay up while the session is idle./quartermaster leads with both windows (percent, reset and time to it, burn rate, forecast), then this session's agents, each guard's fires, re-issues and changes, and the config.Spawns made by other plugins or by workflow scripts can't re-issue, so for them the guards never deny: they toast, once per plugin and agent type (model guard) or per plugin and window (heavy guard).
Quartermaster is a function-hooks plugin, built against Claude Code 2.1.292. That hooks API is early access and moves between releases, so a newer build may need changes here. The pace line and toasts need a subscription that reports rate limits.
/plugin marketplace add bloknayrb/claudestuff
/plugin install quartermaster@claudestuff-marketplace
| Field | Type | Default | Meaning |
|---|---|---|---|
warnAt | number | 75 | Five-hour usage (%) at which the heavy-model guard starts |
heavyModels | list | opus, fable | Model names or id fragments, matched case-insensitively |
guardTypes | list | general-purpose, claude | Agent types with no model of their own |
requireModel | boolean | true | Turns the model guard on or off |
The heavy-model guard knows a spawn's model only when the call names one, when it is a fork, or when its type is in guardTypes (it then inherits the parent's). It assumes no default subagent model is configured; with one, those spawns run on the default instead. Other agent types that set no model go unjudged.
A denied call's identity is a hash of prompt, description, subagentType and model, never the tool call id. The identical call issued again within ten minutes, from the same agent, runs. The same task (prompt and description) with another model or agent type counts as acting on the deny. Counters (fires, reissued, changed) and the last 200 outcomes are kept so a guard that is mostly re-issued can be narrowed or removed.
~/.claude/state/mods/quartermaster/<sessionId>.json: { "loadedAt", "lastError" }. One file is written per session id and never pruned; they are small and safe to delete.It makes no model calls. A guard that fails lets the spawn through and logs to the debug log.
/quartermaster says pace unknown when there is no forecast.claude plugin test plugins/quartermaster runs the tests. tsconfig.json extends .claude-plugin/types/tsconfig.json, which Claude Code writes when it first loads the mod from a folder you own (--plugin-dir, or a mods folder). Load it once before running tsc -p. Every function that takes $ lives in hooks/register.ts, because the validator refuses $ passed across an import.
hooks/register.ts 638 lines1import type { AgentSpawnResult, EngineInterface, Hook, Register, SessionRateLimit, Timer } from 'claude-code'
2import { atom, read, update } from 'claude-code'
3import type { QmDenial, QmGuard, QmHealth } from '../types'
4import { current, parseConfig, shapeOf } from './config'
5import { spawnHash, taskHash } from './hash'
6import type { Reading, Window } from './pace'
7import {
8 agentsClause,
9 alertClause,
10 clockText,
11 dateClockText,
12 durationText,
13 fitCap,
14 fitRate,
15 fiveHour,
16 forecast,
17 matchWindow,
18 sevenDay,
19 statusText,
20 usageLine,
21 weekFitReadings,
22 withIdle,
23 windowText,
24} from './pace'
25import type { Fired, SpawnView } from './rules'
26import {
27 DENIAL_TTL_MS,
28 MODEL_TEXT,
29 effectiveModel,
30 isHeavy,
31 isLive,
32 modelGuardFires,
33 settle,
34 sourceLabel,
35 sourceOf,
36 takeOne,
37 toastKey,
38 viewOf,
39} from './rules'
40
41// Every function that takes `$` lives in this file: the validator refuses `$` passed across an import.
42// So do the atoms: read/update accept only an atom the scan can see made
43// in this file. config.ts, hash.ts, pace.ts and rules.ts take no `$`.
44
45// ==== state ====
46
47// Session-scoped values ($.state): kept across hot reloads, reset on /clear and resume.
48const denied = atom({ plugin: 'quartermaster', key: 'denied' } as const, [] as QmDenial[])
49const agents = atom({ plugin: 'quartermaster', key: 'agents' } as const, {} as Record<string, string>)
50const spawnModels = atom({ plugin: 'quartermaster', key: 'spawnModels' } as const, {} as Record<string, string>)
51const sourceToasts = atom({ plugin: 'quartermaster', key: 'sourceToasts' } as const, [] as string[])
52const sourceSpawns = atom({ plugin: 'quartermaster', key: 'sourceSpawns' } as const, {} as Record<string, number>)
53const health = atom({ plugin: 'quartermaster', key: 'health' } as const, null as QmHealth | null)
54
55// ==== health ====
56
57const MOD = 'quartermaster'
58
59/** USERPROFILE, then HOME (Windows usually has no HOME); forward slashes. */
60async function homeDir($: EngineInterface): Promise<string | null> {
61 const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
62 return home === undefined || home === '' ? null : home.split('\\').join('/')
63}
64
65async function writeHealth($: EngineInterface): Promise<void> {
66 try {
67 const held = await read($, health)
68 const home = await homeDir($)
69 if (held === null || home === null) return
70 const body = JSON.stringify({ loadedAt: held.loadedAt, lastError: held.lastError })
71 await $.fs.write(`${home}/.claude/state/mods/${MOD}/${held.sessionId}.json`, `${body}\n`)
72 } catch {
73 // Best-effort: a missing heartbeat reads as unknown, never as ok.
74 }
75}
76
77/** Writes the heartbeat when it is missing or belongs to another session id; `fresh` forces a new loadedAt. */
78async function ensureHeartbeat($: EngineInterface, fresh = false): Promise<void> {
79 const sessionId = await $.session.id()
80 const held = await read($, health)
81 if (!fresh && held !== null && held.sessionId === sessionId) return
82 const loadedAt = await $.clock.now()
83 await update($, health, () => ({ sessionId, loadedAt, lastError: null }))
84 await writeHealth($)
85 // A command is declared "for this session" and no session.start follows a /clear, so a re-arm declares it
86 // again (registering a name twice replaces it).
87 if (!fresh) await registerCommand($)
88}
89
90async function registerCommand($: EngineInterface): Promise<void> {
91 try {
92 await $.command.register({ name: COMMAND, description: 'Quartermaster: five-hour and weekly forecasts, this session\'s agents, guard fires' })
93 } catch (error) {
94 // A failed registration must not cost the caller its other work.
95 await noteFailure($, 'command.register', error)
96 }
97}
98
99function describeError(error: unknown): string {
100 if (typeof error === 'object' && error !== null) {
101 const { message, kind } = error as { message?: unknown; kind?: unknown }
102 if (typeof message === 'string' && message !== '') return message
103 if (typeof kind === 'string') return kind
104 }
105 return String(error)
106}
107
108/** Fail-open bookkeeping: the debug log and the heartbeat's lastError. Never throws. */
109async function noteFailure($: EngineInterface, where: string, error: unknown): Promise<void> {
110 const message = `${where}: ${describeError(error)}`
111 try {
112 $.ui.log(`quartermaster: ${message}`, { to: 'debug' })
113 } catch {
114 // The debug log is best-effort too.
115 }
116 try {
117 await ensureHeartbeat($)
118 const ts = await $.clock.now()
119 await update($, health, held => (held === null ? held : { ...held, lastError: { ts, message } }))
120 await writeHealth($)
121 } catch {
122 // Nothing left to tell: the hook still fails open.
123 }
124}
125
126// ==== ledger ====
127
128type Counter = { fires: number; reissued: number; changed: number }
129type Counters = Record<QmGuard, Counter>
130type Outcome = 'denied' | 'reissued' | 'changed' | 'toast'
131type Fire = { ts: number; guard: QmGuard; input_hash: string; outcome: Outcome }
132
133const RING_MAX = 200
134
135let chain: Promise<unknown> = Promise.resolve()
136
137/**
138 * Runs $.store read-modify-writes one at a time. $.store has no append or compare-and-set, and
139 * parallel Agent calls run their spawn hooks concurrently, so unserialized writes lose increments.
140 * Never call serial() from inside work passed to serial(): it would wait on itself.
141 */
142function serial<T>(work: () => Promise<T>): Promise<T> {
143 const run = chain.then(work, work)
144 chain = run.catch(() => undefined)
145 return run
146}
147
148function counter(raw: Partial<Counter> | undefined): Counter {
149 return { fires: raw?.fires ?? 0, reissued: raw?.reissued ?? 0, changed: raw?.changed ?? 0 }
150}
151
152async function readCounters($: EngineInterface): Promise<Counters> {
153 const raw = (await $.store.get('counters')) as Partial<Record<QmGuard, Partial<Counter>>> | undefined
154 return { model: counter(raw?.model), heavy: counter(raw?.heavy) }
155}
156
157async function readRing($: EngineInterface): Promise<Fire[]> {
158 const raw = await $.store.get('ring')
159 return Array.isArray(raw) ? (raw as Fire[]) : []
160}
161
162/** Bumps each guard's counter for the outcome (a toast bumps none) and appends to the 200-entry ring. */
163function recordFires($: EngineInterface, guards: readonly QmGuard[], hash: string, outcome: Outcome): Promise<void> {
164 return serial(async () => {
165 const ts = await $.clock.now()
166 const counters = await readCounters($)
167 const ring = await readRing($)
168 for (const guard of guards) {
169 if (outcome === 'denied') counters[guard].fires += 1
170 if (outcome === 'reissued') counters[guard].reissued += 1
171 if (outcome === 'changed') counters[guard].changed += 1
172 ring.push({ ts, guard, input_hash: hash, outcome })
173 }
174 if (outcome !== 'toast') await $.store.set('counters', counters)
175 await $.store.set('ring', ring.slice(-RING_MAX))
176 })
177}
178
179/**
180 * Where each window's readings live, how many are kept, the gap under which a new one is skipped, and the
181 * shortest step an idle stretch is filled at (withIdle). The five-hour list skips only a repeat of the same percent
182 * within a minute; the weekly list keeps one reading per quarter hour whatever it says (672 in a week), so a
183 * busy day can't push the week's start out of the fit.
184 */
185type Series = { storeKey: string; max: number; gapMs: number; sameOnly: boolean; fillMs: number }
186const FIVE_HOUR: Series = { storeKey: 'readings', max: 300, gapMs: 60_000, sameOnly: true, fillMs: 60_000 }
187const WEEK: Series = { storeKey: 'weekReadings', max: 700, gapMs: 15 * 60_000, sameOnly: false, fillMs: 15 * 60_000 }
188
189/** Keeps the current window and the one before it (the two latest resets). */
190function keepTwoWindows<T>(byWindow: Record<string, T>): Record<string, T> {
191 const keys = Object.keys(byWindow)
192 .sort((a, b) => Number(a) - Number(b))
193 .slice(-2)
194 return Object.fromEntries(keys.map(key => [key, byWindow[key] as T]))
195}
196
197type WindowReadings = { key: string; readings: Reading[] }
198
199async function allReadings($: EngineInterface, series: Series): Promise<Record<string, Reading[]>> {
200 return ((await $.store.get(series.storeKey)) ?? {}) as Record<string, Reading[]>
201}
202
203/** The readings of the window that resets at resetsAt, under the key matchWindow picks. */
204async function windowReadings($: EngineInterface, resetsAt: number, series: Series = FIVE_HOUR): Promise<WindowReadings> {
205 const all = await allReadings($, series)
206 const key = matchWindow(Object.keys(all), resetsAt)
207 return { key, readings: all[key] ?? [] }
208}
209
210/** Adds a reading to its window and returns the window; one inside the series' gap is skipped. */
211function addReading($: EngineInterface, resetsAt: number, reading: Reading, series: Series = FIVE_HOUR): Promise<WindowReadings> {
212 return serial(async () => {
213 const all = await allReadings($, series)
214 const key = matchWindow(Object.keys(all), resetsAt)
215 const list = all[key] ?? []
216 const prior = list[list.length - 1]
217 if (prior !== undefined && (!series.sameOnly || prior[1] === reading[1]) && reading[0] - prior[0] < series.gapMs) {
218 return { key, readings: list }
219 }
220 const kept = [...list, reading].slice(-series.max)
221 await $.store.set(series.storeKey, keepTwoWindows({ ...all, [key]: kept }))
222 return { key, readings: kept }
223 })
224}
225
226const THRESHOLDS = [50, 75, 90] as const
227
228/**
229 * The highest threshold this reading crossed that no session has toasted in this window, or null.
230 * Marks every threshold crossed as sent, so a jump toasts once. Global: $.store is shared.
231 */
232function claimThreshold($: EngineInterface, key: string, pct: number): Promise<number | null> {
233 return serial(async () => {
234 const all = ((await $.store.get('toasts')) ?? {}) as Record<string, number[]>
235 const sent = all[key] ?? []
236 const crossed: number[] = THRESHOLDS.filter(t => pct >= t)
237 const top = crossed[crossed.length - 1]
238 if (top === undefined || sent.includes(top)) return null
239 const marked = [...new Set([...sent, ...crossed])].sort((a, b) => a - b)
240 await $.store.set('toasts', keepTwoWindows({ ...all, [key]: marked }))
241 return top
242 })
243}
244
245// ==== pacing ====
246
247/**
248 * Stores each window's reading, and toasts a five-hour threshold the first time any session crosses it.
249 * A failed weekly write is logged and passed over, so it never costs the five-hour reading or its toast.
250 */
251async function recordReading($: EngineInterface, limits: readonly SessionRateLimit[]): Promise<void> {
252 const week = sevenDay(limits)
253 if (week !== null && week.resetsAt !== null) {
254 try {
255 await addReading($, week.resetsAt, [await $.clock.now(), week.pct], WEEK)
256 } catch (error) {
257 await noteFailure($, 'weekly reading', error)
258 }
259 }
260 const window = fiveHour(limits)
261 if (window === null || window.resetsAt === null) return
262 const { key, readings } = await addReading($, window.resetsAt, [await $.clock.now(), window.pct])
263 const crossed = await claimThreshold($, key, window.pct)
264 if (crossed !== null) $.ui.toast(`Quartermaster: ${windowText(window.pct, window.resetsAt, fitCap(readings), await $.clock.now())}.`)
265}
266
267type Outlook = { window: Window; readings: readonly Reading[]; series: Series }
268
269/** A window and the readings its fit may use: the weekly ones only once they span WEEK_MIN_SPAN_MS. */
270async function outlook($: EngineInterface, window: Window | null, series: Series): Promise<Outlook | null> {
271 if (window === null) return null
272 if (window.resetsAt === null) return { window, readings: [], series }
273 const { readings } = await windowReadings($, window.resetsAt, series)
274 return { window, readings: series === WEEK ? weekFitReadings(readings) : readings, series }
275}
276
277/** The readings a fit takes now, the idle stretch since the last one included (withIdle). */
278function fitReadings(o: Outlook, now: number): readonly Reading[] {
279 // Past its reset a window forecasts nothing, and a fill would grow with every idle minute.
280 if (o.window.resetsAt !== null && now >= o.window.resetsAt) return o.readings
281 return withIdle(o.readings, o.window.pct, now, o.series.fillMs)
282}
283
284function forecastOf(o: Outlook, now: number) {
285 return forecast(fitCap(fitReadings(o, now)), o.window.resetsAt, o.window.pct, now)
286}
287
288/** The last text this module drew, so a tick that changes nothing redraws nothing; null before the first. */
289let drawn: string | undefined | null = null
290
291/**
292 * The one status line. It carries only what a usage bar doesn't: a cap coming in either window, and the
293 * subagents this session has run. With neither, it is hidden.
294 */
295async function refreshStatus($: EngineInterface, limits?: readonly SessionRateLimit[]): Promise<void> {
296 const rateLimits = limits ?? (await $.session.usage()).rateLimits
297 const now = await $.clock.now()
298 const short = await outlook($, fiveHour(rateLimits), FIVE_HOUR)
299 const week = await outlook($, sevenDay(rateLimits), WEEK)
300 const tally = await read($, agents)
301 const text = statusText([
302 short === null ? null : alertClause('5h', forecastOf(short, now), clockText),
303 week === null ? null : alertClause('week', forecastOf(week, now), dateClockText),
304 Object.keys(tally).length === 0 ? null : agentsClause(tally),
305 ])
306 if (text === drawn) return
307 drawn = text
308 $.ui.status(text)
309}
310
311/**
312 * Status events stop while the session sits idle, so a timer redraws the line: a cap time that has passed,
313 * or a window that has reset, must not stay up. Timers are dropped on a reload, and session.start starts one.
314 */
315const TICK_MS = 60_000
316let ticker: Timer | null = null
317
318function startTicker($: EngineInterface): void {
319 ticker?.cancel()
320 ticker = $.clock.every(TICK_MS, () => {
321 void refreshStatus($).catch(error => noteFailure($, 'status tick', error))
322 })
323}
324
325// ==== guards ====
326
327type SpawnEvent = Parameters<Hook<'agent.spawn'>>[1]
328type SpawnNext = Parameters<Hook<'agent.spawn'>>[2]
329
330const DENIALS_MAX = 50
331const SPAWN_MODELS_MAX = 200
332const SOURCE_TOASTS_MAX = 200
333
334async function judge($: EngineInterface, view: SpawnView, label: string): Promise<Fired> {
335 const cfg = current.cfg
336 const fired: Fired = { guards: [], denyTexts: [], toastTexts: [], windowKey: null }
337 if (modelGuardFires(view, cfg)) {
338 fired.guards.push('model')
339 fired.denyTexts.push(MODEL_TEXT)
340 fired.toastTexts.push(`Quartermaster: ${label} spawned ${view.subagentType} with no model set.`)
341 }
342 const model = effectiveModel(view, cfg)
343 if (isHeavy(model, cfg.heavyModels)) {
344 const window = fiveHour((await $.session.usage()).rateLimits)
345 if (window !== null && window.pct >= cfg.warnAt) {
346 const held = window.resetsAt === null ? null : await windowReadings($, window.resetsAt)
347 const now = await $.clock.now()
348 // The same fit the status line draws, so the deny never names a cap the line has let fade.
349 const cap = held === null ? null : fitCap(withIdle(held.readings, window.pct, now, FIVE_HOUR.fillMs))
350 const reading = windowText(window.pct, window.resetsAt, cap, now)
351 fired.windowKey = held === null ? null : held.key
352 fired.guards.push('heavy')
353 fired.denyTexts.push(`Quartermaster: ${reading}. Re-issue unchanged to spend it anyway.`)
354 fired.toastTexts.push(`Quartermaster: ${label} spawned an agent on ${model}; ${reading}.`)
355 }
356 }
357 return fired
358}
359
360async function safeRecord($: EngineInterface, guards: readonly QmGuard[], hash: string, outcome: Outcome): Promise<void> {
361 if (guards.length === 0) return
362 try {
363 await recordFires($, guards, hash, outcome)
364 } catch (error) {
365 // The verdict stands whatever the ledger does.
366 await noteFailure($, 'fire ledger', error)
367 }
368}
369
370function trimRecord(map: Record<string, string>, max: number): Record<string, string> {
371 const entries = Object.entries(map)
372 return entries.length <= max ? map : Object.fromEntries(entries.slice(-max))
373}
374
375/** Lets the spawn start and remembers which model it got, for the tally. */
376async function admit($: EngineInterface, e: SpawnEvent, next: SpawnNext): Promise<AgentSpawnResult> {
377 const started = await next(e)
378 const { agentId, model } = started
379 if (agentId !== undefined && model !== undefined) {
380 await update($, spawnModels, map => trimRecord({ ...map, [agentId]: model }, SPAWN_MODELS_MAX))
381 }
382 return started
383}
384
385/**
386 * Toast keys this module instance has claimed. A key is checked and added with no await between, so
387 * parallel spawns can't both claim it. Module memory is lost on a hot reload, so the
388 * claim is then persisted to $.state, which a reloaded module checks.
389 */
390const claimed = new Set<string>()
391
392async function claimToast($: EngineInterface, key: string): Promise<boolean> {
393 if (claimed.has(key)) return false
394 claimed.add(key)
395 let fresh = false
396 try {
397 await update($, sourceToasts, list => {
398 fresh = !list.includes(key)
399 return fresh ? [...list, key].slice(-SOURCE_TOASTS_MAX) : list
400 })
401 } catch (err) {
402 // Release the claim, or a failed write would suppress this toast for the rest of the session.
403 claimed.delete(key)
404 throw err
405 }
406 return fresh
407}
408
409/** A workflow's or another plugin's spawn can't re-issue: it always starts, and its guards toast instead. */
410async function toastOnly(
411 $: EngineInterface,
412 e: SpawnEvent,
413 next: SpawnNext,
414 view: SpawnView,
415 source: string,
416 fired: Fired,
417 hash: string,
418): Promise<AgentSpawnResult> {
419 await update($, sourceSpawns, map => ({ ...map, [source]: (map[source] ?? 0) + 1 }))
420 const shown: QmGuard[] = []
421 const texts: string[] = []
422 for (const [i, guard] of fired.guards.entries()) {
423 if (await claimToast($, toastKey(guard, source, view.subagentType, fired.windowKey))) {
424 shown.push(guard)
425 texts.push(fired.toastTexts[i] ?? '')
426 }
427 }
428 if (texts.length > 0) {
429 $.ui.toast(texts.join(' '))
430 // Only a toast actually shown takes a ring row, so suppressed repeats can't push real denials out.
431 await safeRecord($, shown, hash, 'toast')
432 }
433 return admit($, e, next)
434}
435
436/** Removes and returns one live pending denial that `match` picks; decided inside update, so parallel calls can't share one. */
437async function takeDenial($: EngineInterface, match: (d: QmDenial) => boolean, newest = false): Promise<QmDenial | undefined> {
438 let taken: QmDenial | undefined
439 await update($, denied, list => {
440 const result = takeOne(list, match, newest)
441 taken = result.taken
442 return result.rest
443 })
444 return taken
445}
446
447const onSpawn: Hook<'agent.spawn'> = async ($, e, next) => {
448 const view = viewOf(e)
449 const hash = spawnHash(view)
450 const source = sourceOf(e.workflow !== undefined, next.origin.plugin)
451 if (source !== null) return toastOnly($, e, next, view, source, await judge($, view, sourceLabel(source)), hash)
452
453 const now = await $.clock.now()
454 // The soft-deny contract: an unchanged re-issue runs, whatever the guards say now. One denial, one re-issue.
455 // Checked before judge, so nothing judge reads (usage, the store) can affect a re-issue.
456 const same = await takeDenial($, d => d.hash === hash && isLive(d, view.loop, now))
457 if (same !== undefined) {
458 await safeRecord($, same.guards, hash, 'reissued')
459 return admit($, e, next)
460 }
461
462 const fired = await judge($, view, 'the model')
463
464 const task = taskHash(view)
465 const earlier = await takeDenial($, d => d.task === task && isLive(d, view.loop, now), true)
466 const { changed, deny } =
467 earlier === undefined ? { changed: [] as QmGuard[], deny: fired.guards } : settle(earlier.guards, fired.guards, view)
468 if (earlier !== undefined) await safeRecord($, changed, earlier.hash, 'changed')
469 if (deny.length === 0) return admit($, e, next)
470
471 const entry: QmDenial = { hash, task, loop: view.loop, guards: deny, ts: now }
472 // The earlier denial stays live, minus the guards already credited as changed, so an unchanged re-issue
473 // of either call still matches its own hash and `changed` is never credited twice.
474 const kept = earlier === undefined ? [] : [{ ...earlier, guards: earlier.guards.filter(g => !changed.includes(g)) }]
475 await update($, denied, list =>
476 [...list.filter(d => now - d.ts <= DENIAL_TTL_MS), ...kept, entry].slice(-DENIALS_MAX),
477 )
478 await safeRecord($, deny, hash, 'denied')
479 return { deny: deny.map(g => fired.denyTexts[fired.guards.indexOf(g)] ?? '').join('\n') }
480}
481
482// ==== tally ====
483
484/** Counts distinct subagents by agentId: a resumed subagent's later turns carry the same id. */
485const onTurnComplete: Hook<'turn.complete'> = async ($, e, next) => {
486 const ended = await next(e)
487 const agentId = e.agentId
488 if (agentId === undefined) {
489 // A main-loop turn: re-arms the heartbeat under a new session id after /clear.
490 await ensureHeartbeat($)
491 return ended
492 }
493 if ((await read($, agents))[agentId] !== undefined) return ended
494 const model = (await read($, spawnModels))[agentId] ?? e.usage?.model ?? 'unknown'
495 await update($, agents, map => (map[agentId] === undefined ? { ...map, [agentId]: model } : map))
496 await refreshStatus($)
497 return ended
498}
499
500// ==== lifecycle ====
501
502/** Empties every session-scoped value, and this module's toast claims. Values never go undefined. */
503async function clearSession($: EngineInterface): Promise<void> {
504 claimed.clear()
505 await update($, denied, () => [])
506 await update($, agents, () => ({}))
507 await update($, spawnModels, () => ({}))
508 await update($, sourceToasts, () => [])
509 await update($, sourceSpawns, () => ({}))
510 // Draw the next line whatever this one drew, in case the engine cleared it with the session.
511 drawn = null
512 // No session.start follows: the next measure or main turn re-arms the heartbeat under the new id.
513 await update($, health, () => null)
514}
515
516const onSessionStart: Hook<'session.start'> = async ($, e, next) => {
517 $.ui.log(`quartermaster: list options arrived as ${current.shapes}`, { to: 'debug' })
518 // session.start fires on every hot reload too: each load gets a fresh heartbeat.
519 // First, so a failure below (usage, a full store) still leaves the idle redraw running.
520 startTicker($)
521 drawn = null
522 await ensureHeartbeat($, true)
523 await registerCommand($)
524 const { rateLimits } = await $.session.usage()
525 await recordReading($, rateLimits)
526 await refreshStatus($, rateLimits)
527 return next(e)
528}
529
530const onMeasure: Hook<'session.measure'> = async ($, e, next) => {
531 // Re-arms the heartbeat under a new session id after /clear.
532 await ensureHeartbeat($)
533 await recordReading($, e.rateLimits)
534 await refreshStatus($, e.rateLimits)
535 return next(e)
536}
537
538const onSessionEnd: Hook<'session.end'> = async ($, e, next) => {
539 // Before next(e): one 1.5 s bound covers the whole session.end chain, core's end step included.
540 if (e.reason === 'clear' || e.reason === 'resume') {
541 await clearSession($)
542 await refreshStatus($)
543 }
544 return next(e)
545}
546
547// ==== report ====
548
549const COMMAND = 'quartermaster'
550export const REPORT_FAILED = 'Quartermaster: the report failed; the debug log has the reason.'
551
552/** `model guard: 12 fires · 3 re-issued (25%) · 8 changed (67%)`: a high re-issue rate means narrow or remove it. */
553function guardLine(name: string, c: Counter): string {
554 const rate = (n: number) => (c.fires === 0 ? '—' : `${Math.round((100 * n) / c.fires)}%`)
555 return `${name}: ${c.fires} fires · ${c.reissued} re-issued (${rate(c.reissued)}) · ${c.changed} changed (${rate(c.changed)})`
556}
557
558/** One window's line in the report, or that there is no reading for it. */
559function windowLine(name: string, o: Outlook | null, now: number, time: (ms: number) => string): string {
560 if (o === null) return `${name}: no reading`
561 return `${name}: ${usageLine(o.window, forecastOf(o, now), fitRate(fitReadings(o, now)), now, time)}`
562}
563
564/**
565 * `weekly store 1 window, 34 readings over 8h 15m`: the raw weekly history. A window count that keeps
566 * climbing, or readings that never span the 12 h gate, would mean the weekly resetsAt moves between readings.
567 */
568async function weekStoreText($: EngineInterface, week: Window | null): Promise<string> {
569 const all = await allReadings($, WEEK)
570 const windows = Object.keys(all).length
571 const list = week === null || week.resetsAt === null ? [] : (await windowReadings($, week.resetsAt, WEEK)).readings
572 const first = list[0]
573 const last = list[list.length - 1]
574 const span = first === undefined || last === undefined ? '' : ` over ${durationText(last[0] - first[0])}`
575 return `weekly store ${windows} window${windows === 1 ? '' : 's'}, ${list.length} readings${span}`
576}
577
578/** Usage first, then this session's agents, then the guards' record, then config. */
579const onCommand: Hook<'command.run'> = async $ => {
580 const cfg = current.cfg
581 const counters = await readCounters($)
582 const ring = await readRing($)
583 const { rateLimits } = await $.session.usage()
584 const now = await $.clock.now()
585 const short = await outlook($, fiveHour(rateLimits), FIVE_HOUR)
586 const week = await outlook($, sevenDay(rateLimits), WEEK)
587 const sources = Object.entries(await read($, sourceSpawns)).map(([source, n]) => `${source} ${n}`)
588 const usage =
589 short === null && week === null
590 ? ['usage: no rate-limit reading (rate limits come with a subscription)']
591 : [windowLine('five-hour', short, now, clockText), windowLine('weekly', week, now, dateClockText)]
592 const lines = [
593 'Quartermaster',
594 ...usage,
595 `this session: ${agentsClause(await read($, agents))}${sources.length > 0 ? ` · toast-only spawns: ${sources.join(', ')}` : ''}`,
596 guardLine('model guard', counters.model),
597 guardLine('heavy guard', counters.heavy),
598 `config: warnAt ${cfg.warnAt}% · heavy ${cfg.heavyModels.join(', ') || 'none'} · guard types ${cfg.guardTypes.join(', ') || 'none'} · requireModel ${cfg.requireModel ? 'on' : 'off'}`,
599 `debug: ring ${ring.length} of the last ${RING_MAX} outcomes · ${await weekStoreText($, sevenDay(rateLimits))} · list options arrived as ${current.shapes}`,
600 ]
601 return { text: lines.join('\n') }
602}
603
604// ==== register ====
605
606export const register: Register = (on, options) => {
607 current.cfg = parseConfig(options)
608 current.shapes = `heavyModels ${shapeOf(options['heavyModels'])}, guardTypes ${shapeOf(options['guardTypes'])}`
609 // A fresh load draws its first line whatever the last load drew.
610 drawn = null
611
612 on('session.start', onSessionStart).catch(async ($, e, next) => {
613 await noteFailure($, 'session.start', next.error)
614 return next(e)
615 })
616 // Fail open: a broken guard lets the spawn through (next.called replays, never re-runs).
617 on('agent.spawn', onSpawn).catch(async ($, e, next) => {
618 await noteFailure($, 'agent.spawn', next.error)
619 return next(e)
620 })
621 on('session.measure', onMeasure).catch(async ($, e, next) => {
622 await noteFailure($, 'session.measure', next.error)
623 return next(e)
624 })
625 on('turn.complete', onTurnComplete).catch(async ($, e, next) => {
626 await noteFailure($, 'turn.complete', next.error)
627 return next(e)
628 })
629 on('session.end', onSessionEnd).catch(async ($, e, next) => {
630 await noteFailure($, 'session.end', next.error)
631 return next(e)
632 })
633 on('command.run', { command: COMMAND }, onCommand).catch(async ($, _e, next) => {
634 await noteFailure($, 'command.run', next.error)
635 return { text: REPORT_FAILED }
636 })
637}
638hooks/config.ts 51 lines1import type { PluginOptions } from 'claude-code'
2
3export type QmConfig = {
4 warnAt: number
5 heavyModels: string[]
6 guardTypes: string[]
7 requireModel: boolean
8}
9
10export const DEFAULTS: QmConfig = {
11 warnAt: 75,
12 heavyModels: ['opus', 'fable'],
13 guardTypes: ['general-purpose', 'claude'],
14 requireModel: true,
15}
16
17/** The live config, set by register() on every load; read by the hook handlers. */
18export const current: { cfg: QmConfig; shapes: string } = {
19 cfg: { ...DEFAULTS, heavyModels: [...DEFAULTS.heavyModels], guardTypes: [...DEFAULTS.guardTypes] },
20 shapes: 'unknown',
21}
22
23/** A list option arrives as an array or as a comma-separated string; either reads the same. */
24export function toList(value: unknown, fallback: string[]): string[] {
25 if (Array.isArray(value)) return value.map(v => String(v).trim()).filter(v => v !== '')
26 if (typeof value === 'string') return value.split(',').map(v => v.trim()).filter(v => v !== '')
27 return [...fallback]
28}
29
30/** How an option value arrived, for the debug log and /quartermaster (pins how list options arrive). */
31export function shapeOf(value: unknown): string {
32 return Array.isArray(value) ? 'array' : typeof value
33}
34
35function toPercent(value: unknown): number {
36 const n =
37 typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN
38 return Number.isFinite(n) ? Math.min(100, Math.max(0, n)) : DEFAULTS.warnAt
39}
40
41export function parseConfig(options: PluginOptions): QmConfig {
42 const requireModel = options['requireModel']
43 return {
44 warnAt: toPercent(options['warnAt']),
45 // Lower-cased once here: heavy matching is a case-insensitive substring.
46 heavyModels: toList(options['heavyModels'], DEFAULTS.heavyModels).map(m => m.toLowerCase()),
47 guardTypes: toList(options['guardTypes'], DEFAULTS.guardTypes),
48 requireModel: typeof requireModel === 'boolean' ? requireModel : DEFAULTS.requireModel,
49 }
50}
51hooks/hash.ts 29 lines1/** cyrb53: a fast 53-bit string hash. A collision only costs one wrong re-issue match. */
2export function cyrb53(text: string, seed = 0): string {
3 let h1 = 0xdeadbeef ^ seed
4 let h2 = 0x41c6ce57 ^ seed
5 for (let i = 0; i < text.length; i++) {
6 const ch = text.charCodeAt(i)
7 h1 = Math.imul(h1 ^ ch, 2654435761)
8 h2 = Math.imul(h2 ^ ch, 1597334677)
9 }
10 h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
11 h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
12 return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0')
13}
14
15export type SpawnFields = { prompt: string; description: string; subagentType: string; model: string | undefined }
16
17/** Re-issue identity: prompt, description, agent type and model, never tool_use_id (a re-issue gets a new one). */
18export function spawnHash(f: SpawnFields): string {
19 return cyrb53(JSON.stringify([f.prompt, f.description, f.subagentType, f.model ?? null]))
20}
21
22/**
23 * Task identity: the same prompt and description under any model or agent type. Links a changed call
24 * back to its deny; switching to a typed agent such as Explore is acting on the deny too.
25 */
26export function taskHash(f: Pick<SpawnFields, 'prompt' | 'description'>): string {
27 return cyrb53(JSON.stringify([f.prompt, f.description]))
28}
29hooks/pace.ts 240 lines1import type { SessionRateLimit } from 'claude-code'
2
3export type Reading = [ts: number, pct: number]
4export type Window = { pct: number; resetsAt: number | null }
5
6/** A window from rateLimits, an array by kind (`five_hour`, `seven_day`); resetsAt may be missing. */
7function windowOf(limits: readonly SessionRateLimit[], kind: string): Window | null {
8 const window = limits.find(limit => limit.kind === kind)
9 if (window === undefined) return null
10 const resetsAt = window.resetsAt === undefined ? NaN : Date.parse(window.resetsAt)
11 return { pct: window.percentUsed, resetsAt: Number.isFinite(resetsAt) ? resetsAt : null }
12}
13
14export function fiveHour(limits: readonly SessionRateLimit[]): Window | null {
15 return windowOf(limits, 'five_hour')
16}
17
18export function sevenDay(limits: readonly SessionRateLimit[]): Window | null {
19 return windowOf(limits, 'seven_day')
20}
21
22/** A new window's store key: resetsAt to the nearest minute. Rounding alone splits jitter across hh:mm:30. */
23export function windowKey(resetsAt: number): string {
24 return String(Math.round(resetsAt / 60_000) * 60_000)
25}
26
27export const WINDOW_SLACK_MS = 60_000
28
29/**
30 * The store key for resetsAt: the nearest existing key within a minute of it, else a new windowKey.
31 * Sub-minute jitter stays one window on either side of hh:mm:30.
32 */
33export function matchWindow(keys: readonly string[], resetsAt: number): string {
34 let best: string | null = null
35 for (const key of keys) {
36 const gap = Math.abs(Number(key) - resetsAt)
37 if (gap <= WINDOW_SLACK_MS && (best === null || gap < Math.abs(Number(best) - resetsAt))) best = key
38 }
39 return best ?? windowKey(resetsAt)
40}
41
42/** Least-squares line of percent over time, slope in percent per minute; null under 3 readings or one instant. */
43export function fitLine(readings: readonly Reading[]): { t0: number; slope: number; intercept: number } | null {
44 if (readings.length < 3) return null
45 const t0 = readings[0]![0]
46 const xs = readings.map(r => (r[0] - t0) / 60_000)
47 const ys = readings.map(r => r[1])
48 const n = readings.length
49 const mx = xs.reduce((a, b) => a + b, 0) / n
50 const my = ys.reduce((a, b) => a + b, 0) / n
51 let sxy = 0
52 let sxx = 0
53 for (let i = 0; i < n; i++) {
54 sxy += (xs[i]! - mx) * (ys[i]! - my)
55 sxx += (xs[i]! - mx) ** 2
56 }
57 if (sxx === 0) return null
58 const slope = sxy / sxx
59 return { t0, slope, intercept: my - slope * mx }
60}
61
62/** When the fitted line reaches 100, or null under 3 readings or no growth. */
63export function fitCap(readings: readonly Reading[]): number | null {
64 const line = fitLine(readings)
65 if (line === null || line.slope <= 0) return null
66 return line.t0 + Math.round(((100 - line.intercept) / line.slope) * 60_000)
67}
68
69/** The fitted rate in percent per hour, or null with no fit. */
70export function fitRate(readings: readonly Reading[]): number | null {
71 const line = fitLine(readings)
72 return line === null ? null : line.slope * 60
73}
74
75/** The median gap between consecutive readings, or 0 under two. */
76function medianGap(readings: readonly Reading[]): number {
77 const gaps = readings.slice(1).map((r, i) => r[0] - readings[i]![0]).sort((a, b) => a - b)
78 return gaps.length === 0 ? 0 : gaps[Math.floor(gaps.length / 2)]!
79}
80
81/**
82 * The readings plus the idle stretch since the last one, as flat readings at the live percent and one at
83 * `now`. Readings stop while the session is idle; without these, a frozen fit's cap time would pass and read
84 * "capped soon" through hours of flat usage. The fill steps at the readings' own median spacing (never under
85 * `minStepMs`), so the idle stretch weighs what the same stretch of watched readings would, and the forecast
86 * fades instead of lingering. Under three real readings there is no fit to correct, and nothing is added.
87 */
88export function withIdle(readings: readonly Reading[], pct: number, now: number, minStepMs: number): readonly Reading[] {
89 const last = readings[readings.length - 1]
90 if (readings.length < 3 || last === undefined || now <= last[0]) return readings
91 const stepMs = Math.max(minStepMs, medianGap(readings))
92 const filled: Reading[] = [...readings]
93 for (let t = last[0] + stepMs; t < now; t += stepMs) filled.push([t, pct])
94 filled.push([now, pct])
95 return filled
96}
97
98/**
99 * The weekly fit needs this much history: a burst's first half hour, projected across a week, would call a
100 * cap days early.
101 */
102export const WEEK_MIN_SPAN_MS = 12 * 60 * 60_000
103
104/** The weekly readings a fit may use: all of them once they span WEEK_MIN_SPAN_MS, else none. */
105export function weekFitReadings(readings: readonly Reading[]): readonly Reading[] {
106 const first = readings[0]
107 const last = readings[readings.length - 1]
108 return first !== undefined && last !== undefined && last[0] - first[0] >= WEEK_MIN_SPAN_MS ? readings : []
109}
110
111/** `3:40pm` in the hooks environment's local time (not UTC), as the user's own statusline prints it. */
112export function clockText(ms: number): string {
113 const d = new Date(ms)
114 const h = d.getHours()
115 return `${h % 12 === 0 ? 12 : h % 12}:${String(d.getMinutes()).padStart(2, '0')}${h < 12 ? 'am' : 'pm'}`
116}
117
118const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
119
120/** `Oct 25, 9:00am`: for the weekly window, where a bare clock or weekday could mean the next week. */
121export function dateClockText(ms: number): string {
122 const d = new Date(ms)
123 return `${MONTHS[d.getMonth()]} ${d.getDate()}, ${clockText(ms)}`
124}
125
126/** `2d 4h`, `2h 10m`, `25m`, rounded down; `0m` for anything not ahead. */
127export function durationText(ms: number): string {
128 const mins = Math.max(0, Math.floor(ms / 60_000))
129 const d = Math.floor(mins / 1440)
130 const h = Math.floor((mins % 1440) / 60)
131 const m = mins % 60
132 if (d > 0) return `${d}d ${h}h`
133 if (h > 0) return `${h}h ${m}m`
134 return `${m}m`
135}
136
137export type Forecast =
138 | { kind: 'capped' }
139 | { kind: 'soon' }
140 | { kind: 'cap'; at: number }
141 | { kind: 'safe' }
142 | { kind: 'unknown' }
143
144/**
145 * Where the window is headed. A reset already past (the session sat idle across it) knows nothing, so a
146 * stale `capped` never outlives its window. A fit that puts the cap before now (a steep rise that then
147 * flattened) reads `soon`, never a past time.
148 */
149export function forecast(cap: number | null, resetsAt: number | null, pct: number, now: number): Forecast {
150 if (resetsAt !== null && now >= resetsAt) return { kind: 'unknown' }
151 if (pct >= 100) return { kind: 'capped' }
152 if (cap !== null && cap <= now) return { kind: 'soon' }
153 if (cap === null) return { kind: 'unknown' }
154 if (resetsAt !== null && cap >= resetsAt) return { kind: 'safe' }
155 return { kind: 'cap', at: cap }
156}
157
158/** The status line's clause for a window: only a forecast worth acting on, else null. */
159export function alertClause(label: string, f: Forecast, time: (ms: number) => string): string | null {
160 if (f.kind === 'capped') return `${label} capped`
161 if (f.kind === 'soon') return `${label} capped soon`
162 if (f.kind === 'cap') return `${label} cap ~${time(f.at)}`
163 return null
164}
165
166function forecastText(f: Forecast, time: (ms: number) => string): string {
167 if (f.kind === 'capped') return 'capped'
168 if (f.kind === 'soon') return 'capped soon'
169 if (f.kind === 'cap') return `cap ~${time(f.at)}`
170 if (f.kind === 'safe') return 'no cap before reset'
171 return 'pace unknown'
172}
173
174function rateText(rate: number): string {
175 return `~${Math.abs(rate) < 10 ? rate.toFixed(1) : Math.round(rate)}%/h`
176}
177
178/** `42%, resets 5:00pm (in 2h 10m) · ~12%/h · cap ~3:40pm`: one window's line in /quartermaster. */
179export function usageLine(
180 window: Window,
181 f: Forecast,
182 rate: number | null,
183 now: number,
184 time: (ms: number) => string,
185): string {
186 const { pct, resetsAt } = window
187 const due = resetsAt !== null && now >= resetsAt
188 const resets =
189 resetsAt === null ? '' : due ? ', reset due' : `, resets ${time(resetsAt)} (in ${durationText(resetsAt - now)})`
190 const parts = [`${pct}%${resets}`]
191 // A rate fitted to a window that has reset describes nothing now.
192 if (rate !== null && f.kind !== 'capped' && !due) parts.push(rateText(rate))
193 parts.push(forecastText(f, time))
194 return parts.join(' · ')
195}
196
197/** `five-hour window at 82%, resets 5:00pm; on pace to cap at 3:40pm`: the reading the heavy guard and toasts give. */
198export function windowText(pct: number, resetsAt: number | null, cap: number | null, now = 0): string {
199 const resets = resetsAt === null ? '' : `, resets ${clockText(resetsAt)}`
200 const pace =
201 pct >= 100
202 ? 'already capped'
203 : cap !== null && now > 0 && cap <= now
204 ? 'about to cap'
205 : cap === null
206 ? 'pace unknown'
207 : resetsAt !== null && cap >= resetsAt
208 ? 'not on pace to cap before the reset'
209 : `on pace to cap at ${clockText(cap)}`
210 return `five-hour window at ${pct}%${resets}; ${pace}`
211}
212
213const FAMILIES = ['fable', 'opus', 'sonnet', 'haiku']
214
215/** A model id's family (`claude-opus-5-5` → `opus`), else the id itself. */
216export function familyOf(model: string): string {
217 const id = model.toLowerCase()
218 return FAMILIES.find(f => id.includes(f)) ?? id
219}
220
221/** `agents 4 (2 opus, 2 sonnet)`: distinct subagents and the split by model family, largest first. */
222export function agentsClause(tally: Readonly<Record<string, string>>): string {
223 const counts = new Map<string, number>()
224 for (const model of Object.values(tally)) {
225 const family = familyOf(model)
226 counts.set(family, (counts.get(family) ?? 0) + 1)
227 }
228 const split = [...counts.entries()]
229 .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
230 .map(([family, n]) => `${n} ${family}`)
231 const total = Object.keys(tally).length
232 return `agents ${total}${split.length > 0 ? ` (${split.join(', ')})` : ''}`
233}
234
235/** `QM 5h cap ~3:40pm · agents 4 (2 opus, 2 sonnet)`, or undefined when no clause has anything to say. */
236export function statusText(clauses: readonly (string | null)[]): string | undefined {
237 const shown = clauses.filter((c): c is string => c !== null)
238 return shown.length === 0 ? undefined : `QM ${shown.join(' · ')}`
239}
240hooks/rules.ts 123 lines1import type { AgentSpawnInput } from 'claude-code'
2import type { QmDenial, QmGuard } from '../types'
3import type { QmConfig } from './config'
4
5// The guards' decisions, with no `$`: register.ts reads the world and acts; this file only decides.
6
7export const MODEL_TEXT =
8 'Quartermaster: set `model` for this agent from its task (haiku: mechanical; sonnet: well-specified; opus: judgement). Re-issue unchanged to keep the inherited model.'
9
10/** A denial answers a re-issue or a changed call only this long. */
11export const DENIAL_TTL_MS = 10 * 60_000
12
13/** What the guards read of a spawn. A blank model is unset; `loop` is `parentAgentId`, or `main`. */
14export type SpawnView = {
15 prompt: string
16 description: string
17 subagentType: string
18 fork: boolean
19 parentModel: string
20 model: string | undefined
21 loop: string
22}
23
24/** The guards that fired, with aligned texts (the deny for a model's call, the toast otherwise) and the window. */
25export type Fired = { guards: QmGuard[]; denyTexts: string[]; toastTexts: string[]; windowKey: string | null }
26
27type LooseSpawn = Partial<Record<keyof AgentSpawnInput, unknown>> & { subagent_type?: unknown }
28
29/**
30 * Reads a spawn event in either shape: AgentSpawnInput, or the Agent tool's input that the 2.1.292 test kit
31 * gives a plugin's own spawn (`subagent_type`; no `subagentType`, `fork` or `parentModel`).
32 */
33export function viewOf(input: AgentSpawnInput): SpawnView {
34 const e = input as unknown as LooseSpawn
35 const text = (value: unknown) => (typeof value === 'string' ? value : '')
36 const type = text(e.subagentType) || text(e.subagent_type)
37 const model = text(e.model).trim()
38 return {
39 prompt: text(e.prompt),
40 description: text(e.description),
41 // An Agent call with no subagent_type is general-purpose.
42 subagentType: type === '' ? 'general-purpose' : type,
43 fork: e.fork === true,
44 parentModel: text(e.parentModel),
45 model: model === '' ? undefined : model,
46 loop: text(e.parentAgentId) || 'main',
47 }
48}
49
50/**
51 * Who can't re-issue a denied spawn: a workflow script's `agent()` (`e.workflow` set), or another
52 * plugin's `$.agent.spawn` (`next.origin`). null is the model's own Agent call, the only one ever denied.
53 */
54export function sourceOf(isWorkflow: boolean, originPlugin: string): string | null {
55 if (isWorkflow) return 'workflow'
56 return originPlugin === 'engine' ? null : originPlugin
57}
58
59export function sourceLabel(source: string): string {
60 return source === 'workflow' ? 'a workflow' : source
61}
62
63/** One toast per key per session: the model toast per (source, type), the heavy toast per (source, window). */
64export function toastKey(guard: QmGuard, source: string, subagentType: string, window: string | null): string {
65 return guard === 'model' ? `model/${source}/${subagentType}` : `heavy/${source}/${window ?? 'none'}`
66}
67
68export function modelGuardFires(view: SpawnView, cfg: QmConfig): boolean {
69 return cfg.requireModel && !view.fork && view.model === undefined && cfg.guardTypes.includes(view.subagentType)
70}
71
72/**
73 * The model a spawn will run on, where that is knowable before it starts. A fork always inherits; an
74 * unset model on a guarded type inherits the parent's (assuming no default subagent model is configured);
75 * an unset model on any other type is its definition's, which no event shows, so it is unknown.
76 */
77export function effectiveModel(view: SpawnView, cfg: QmConfig): string | null {
78 if (view.fork) return view.parentModel
79 if (view.model !== undefined) return view.model
80 return cfg.guardTypes.includes(view.subagentType) ? view.parentModel : null
81}
82
83/** Substring, any case: `opus` matches the alias and `claude-opus-5-5`. heavyModels is lower-cased. */
84export function isHeavy(model: string | null, heavyModels: readonly string[]): boolean {
85 if (model === null || model === '') return false
86 const id = model.toLowerCase()
87 return heavyModels.some(token => id.includes(token))
88}
89
90/** A pending denial counts only in the loop it was denied in, and only for DENIAL_TTL_MS. */
91export function isLive(d: QmDenial, loop: string, now: number): boolean {
92 return d.loop === loop && now - d.ts <= DENIAL_TTL_MS
93}
94
95/**
96 * Removes one entry `match` picks, and only that one: three identical denials answer three re-issues. By default
97 * the first match; `newest` takes the last, so a task match settles against the denial the model was just shown.
98 */
99export function takeOne(
100 list: readonly QmDenial[],
101 match: (d: QmDenial) => boolean,
102 newest = false,
103): { rest: QmDenial[]; taken: QmDenial | undefined } {
104 const i = newest ? list.findLastIndex(match) : list.findIndex(match)
105 if (i < 0) return { rest: [...list], taken: undefined }
106 return { rest: [...list.slice(0, i), ...list.slice(i + 1)], taken: list[i] }
107}
108
109/**
110 * How a call repeating an earlier denial's task settles each guard:
111 * - a guard of the denial that the new call no longer trips is `changed`;
112 * - after a heavy deny, a call that names a model itself and still trips the heavy guard is an informed
113 * override: `changed`, and it does not deny again;
114 * - any guard that still trips otherwise denies again, as a fresh fire.
115 */
116export function settle(earlier: readonly QmGuard[], fired: readonly QmGuard[], view: SpawnView): { changed: QmGuard[]; deny: QmGuard[] } {
117 // A fork ignores `model` and always runs on the parent's, so naming one is no override.
118 const overridden = earlier.includes('heavy') && fired.includes('heavy') && view.model !== undefined && !view.fork
119 const changed = earlier.filter(g => !fired.includes(g) || (g === 'heavy' && overridden))
120 const deny = fired.filter(g => !(g === 'heavy' && overridden))
121 return { changed, deny }
122}
123types/index.d.ts 28 lines1export type QmGuard = 'model' | 'heavy'
2
3/**
4 * A spawn denied once and waiting for its re-issue: the full hash, the task hash, the loop it was
5 * denied in (`parentAgentId`, or `main`), the guards that denied it, and when.
6 */
7export type QmDenial = { hash: string; task: string; loop: string; guards: QmGuard[]; ts: number }
8
9/** What the heartbeat file says, and for which session. */
10export type QmHealth = {
11 sessionId: string
12 loadedAt: number
13 lastError: { ts: number; message: string } | null
14}
15
16declare module 'claude-code' {
17 interface PluginState {
18 quartermaster: {
19 denied: QmDenial[]
20 agents: Record<string, string>
21 spawnModels: Record<string, string>
22 sourceToasts: string[]
23 sourceSpawns: Record<string, number>
24 health: QmHealth | null
25 }
26 }
27}
28