Warns as the account's 5-hour and 7-day usage windows fill, tells the model as they near the limit, refuses new subagents past a set percent, and warns and…

A Claude Code plugin marketplace from Darling Data.
/plugin marketplace add erikdarlingdata/claude-plugins
sqlserver-query-plansTeaches Claude to read a SQL Server execution plan and say what is actually slow, and why.
/plugin install sqlserver-query-plans@erikdarling
Point Claude at a .sqlplan file and ask. The skill is model-invoked — you do not need to call it explicitly.
The hard part of plan analysis is not spotting operators. It is knowing which numbers mean what they appear to mean. This plugin is built mostly out of the conclusions that sound authoritative and are wrong:
ActualElapsedms ranks them by depth and always crowns the root node. Batch mode reports standalone times. Exchange operators report times that are close to meaningless.EstimateRows is per-execution; ActualRows is a total. Without dividing by ActualExecutions, the inner side of every nested loop looks catastrophically underestimated when it may have estimated perfectly.Impact figure is a percentage of an estimated cost.It also ships scripts/extract.py, which flattens a .sqlplan into a compact digest. This is not a convenience:
.sqlplan files are UTF-16, so grep silently matches nothing and reports no error. A negative result from grep on a plan file is worthless.encoding="utf-16", because they were opened and re-saved. Strict XML parsers reject them.The extractor handles the encoding, computes correct self-time attribution (subtracting children in row mode, within a thread rather than across threads in parallel plans, and not at all in batch mode), normalizes cardinality per execution, and recognizes the optimizer's default-guess selectivity fingerprints. --node N drills into a single operator; --sql recovers full statement text.
Requires Python 3 (standard library only). Without it, the skill degrades to a documented grep-based fallback and says plainly what it cannot determine.
This plugin also works in GitHub Copilot CLI, which reads the same SKILL.md and plugin.json format.
copilot plugin marketplace add erikdarlingdata/claude-plugins
copilot plugin install sqlserver-query-plans@erikdarling
Or add just the skill, without the marketplace:
/skills add ./plugins/sqlserver-query-plans/skills/query-plan-analysis
As in Claude Code, the skill is model-invoked: point Copilot at a .sqlplan and ask.
Small hook modules for people who run several agents at once. Each one is a plugin of its own. Install only the ones you want, and set their options in /config (or under pluginConfigs in settings.json). They need a Claude Code version that loads plugin hook modules.
subagent-fenceStops the mistakes an unattended agent makes that cannot be taken back.
/plugin install subagent-fence@erikdarling
For the main session and every subagent it refuses four things. A force-push. A push to a protected branch. A git command that skips the repository's hooks. Killing processes by name (pkill, killall, taskkill /IM, Stop-Process -Name), because a name match can kill another session's processes.
Three more guards are off until you set them. One bans folders: nothing reads, writes or enters them. One keeps a subagent from editing a plain git checkout, or running a changing git command there, so it works in its own worktree. One stops a subagent reading a big text file whole instead of by offset and limit.
| Option | Default | What it does | | :- | :- | :- | | guard_force_push | on | Refuse --force, --force-with-lease, -f and +refspec pushes | | guard_protected_branches | on | Refuse a push that targets a protected branch | | protected_branches | main, master, dev | The branch names a push cannot target | | guard_no_verify | on | Refuse the git flag that skips hooks | | guard_kill_by_name | on | Refuse killing processes by name | | banned_paths | none | Folders that nothing reads, writes or enters | | guard_shared_checkout | off | Keep subagents out of plain git checkouts | | shared_checkout_root | empty | Limit that guard to checkouts under this folder. Empty detects a plain checkout anywhere: a folder whose .git is a directory, where a linked worktree has a .git file | | read_limit_bytes | 0 (off) | Refuse a subagent's Read of a text file over this size when it gives no limit |
model-allowlistChecks the model a subagent is spawned with.
/plugin install model-allowlist@erikdarling
A pinned model id goes stale: a dated or versioned name keeps pointing at an old model after the tier moves on. This refuses a spawn that names one and asks for a tier alias (opus, sonnet, haiku) instead. A spawn with no model is always allowed, because the agent file or the parent decides then.
You can add rules of your own. One example: the lane agent runs Sonnet, and Opus only when the brief says design, security or hard debugging. With no rules, every alias is allowed.
| Option | Default | What it does | | :- | :- | :- | | refuse_pinned_ids | on | Refuse any model that is not an allowed alias | | allowed_aliases | opus, sonnet, haiku, fable, inherit | The names that count as aliases. A trailing [1m]-style suffix is ignored | | rules | none | One rule per entry, written agent type pattern => model => brief pattern => message |
A rule applies when the spawn's agent type matches the first pattern and it names that model (* for any model). The brief must then match the brief pattern, or the spawn is refused. Leave the brief pattern empty to refuse the pairing outright. The message is optional and can use {type} and {model}. Patterns are case-insensitive regular expressions. A rule that does not parse is skipped. For example:
^(lane|worker-.*)$ => opus => \b(design|security|hard[- ]debug) => {type} runs sonnet; name the reason in the brief to use opus.
seat-resumeBrings interrupted sessions back after a crash, a reboot or a closed terminal.
/plugin install seat-resume@erikdarling
The plugin writes one small file per interactive session: its id, name, folder, permission mode and last activity. It marks the file when the session ends. /resume-sessions lists the sessions that died or were interrupted in the last 72 hours, with the command that reopens each. The script's -Launch switch reopens all of them in terminal tabs. Sessions you left with /exit, Ctrl+C or /clear stay closed. The plugin name still says "seat", but everything you see says "session".
This one is Windows only. The bundled script (scripts/resume-sessions.ps1) is PowerShell. It compares Windows process start times to tell a live session from a reused process id. It reopens tabs in WezTerm or Windows Terminal. Nobody has tried the plugin on macOS or Linux.
| Option | Default | What it does | | :- | :- | :- | | registry_dir | empty: session-registry in your Claude config folder | Where the per-session files go | | sessions_dir | empty: sessions in your Claude config folder | Where Claude Code records its running sessions | | resume_script | empty: the bundled script | The PowerShell script /resume-sessions runs | | powershell | pwsh | The program that runs it (powershell for Windows PowerShell 5.1) | | terminal | wezterm | wezterm or windows-terminal: where -Launch reopens sessions |
The Claude config folder is CLAUDE_CONFIG_DIR when that is set, otherwise .claude in your home folder.
open-asksKeeps the questions Claude asks you from scrolling away. Every time a reply asks you something or leaves a decision to you, Claude records it. The question stays in a band above your prompt, with Claude's recommended answer, until you answer, decline or drop it. Claude gets ask_add, ask_resolve and ask_list tools. You get /asks (done <ids>, clear, hide, show). Open asks are saved per session, so a resumed session still has them.
/plugin install open-asks@erikdarling
| Option | Default | What it does |
|---|---|---|
maxBandAsks | 6 | Most asks the band draws. The rest stay in /asks. |
maxQuestionChars | 400 | Longest question or recommendation shown before it is cut. |
keepDays | 30 | Saved asks from other sessions are removed after this many days. 0 keeps them. |
subagent-bandA live view of your subagents. The band above the prompt has one row per running subagent: type, model, effort, steps, context size, advisor calls and estimated cost. /fleet opens a pane with every subagent of the session, finished ones included. /subagent-cost totals the estimated cost by agent type and by issue number in the description, with the main session's own cost. /steer <id> <text> sends a running subagent a message. Claude gets a cheap subagent_vitals tool, so it does not have to read output files to check progress. Costs are list-price estimates, not your bill.
/plugin install subagent-band@erikdarling
| Option | Default | What it does |
|---|---|---|
priceTable | opus:4:20, sonnet:2:10, haiku-5-5:0.1:0.5, haiku:1:5, fable:10:50 | Input and output USD per million tokens for each model family. A model id is matched by containing the family name, first entry first. Haiku 5.5 requests with a prompt over 100,000 tokens (cache reads and writes included) are priced at 5x for the whole request, as Anthropic bills them. |
cacheWriteMultiplier | 1.25 | Cache write price as a multiple of the input price. |
cacheReadMultiplier | 0.1 | Cache read price as a multiple of the input price. |
usage-budgetWatches the account's 5-hour and 7-day usage windows. A toast tells you each time a window crosses a percent. Past a higher percent, Claude also gets a one-time note so it can stop starting optional work and write its handoff. Past the last one, new subagents are refused until the window resets.
It also checks pace. When the 7-day usage runs 10 or more points ahead of the share of the week that has passed (70% used with 60% of the week gone), you get a toast and Claude gets a note, once per window and again each time the gap grows by another margin. New subagents are refused too. The message gives the usage, the elapsed share, and the UTC time the refusal lifts if usage stays flat: the moment the week catches up to within the margin. Waiting until then lifts it, and so does setting paceMargin to 0, which turns the check off. Without a reset time for the window, the check is skipped.
The status line shows the percents, but a session cannot read its own status line. So the plugin also writes the figures to <config>/usage-budget/latest.json each time they come in. <config> is CLAUDE_CONFIG_DIR, or else the .claude folder in your home folder. A session reads that file when it needs the numbers, for example to log a usage check:
{
"at": "2026-10-14T04:48:00.000Z",
"rateLimits": [
{ "kind": "five_hour", "percentUsed": 41, "resetsAt": "2026-10-14T08:00:00Z" },
{ "kind": "seven_day", "percentUsed": 75, "resetsAt": "2026-10-17T00:00:00Z" }
],
"pace": { "used": 75, "elapsed": 60, "ahead": 15, "until": "2026-10-14 13:12Z" }
}
at is the UTC time of the write. resetsAt is null when the window has no reset time. pace is null unless 7-day usage runs at least paceMargin points ahead of the week. Then it holds the figures the pace warning gives (elapsed and ahead to a tenth of a point), and until is the UTC minute the refusal lifts if usage stays flat. Each write replaces the file, so it holds only the latest figures. The write is not atomic, so a reader that gets JSON it cannot parse should read again. A failed write never stops the plugin. The first one in a session raises a toast with the path and the reason, so the file does not go stale without a word. If the reason is a missing folder, create the folder once.
/plugin install usage-budget@erikdarling
| Option | Default | What it does |
|---|---|---|
warnPercents | 70, 85, 95 | Percents that raise a toast, once each per window. |
tellModelAtPercent | 85 | From here the model is told as well. 0 never tells it. |
spawnGatePercent | 95 | A new subagent is refused when either window is at or past this. 0 turns the refusal off. |
paceMargin | 10 | Points the 7-day usage may run ahead of the share of the week passed before the warning and the refusal. 0 turns the pace check off. |
usage_file | <config>/usage-budget/latest.json | Where the latest figures are written. A leading <config> stands for the Claude config folder. An empty value turns the file off. |
subagent-wallA wall-clock limit for subagents. After a warning time, a subagent is told to finish up. After the limit, it can only run git and gh commands and write .md or .txt files. It commits, reports and ends instead of running on. It also nudges a code-changing subagent that has a lot of context but no edited file to stop exploring and make the change. The main session is never limited.
/plugin install subagent-wall@erikdarling
| Option | Default | What it does |
|---|---|---|
warnMinutes | 45 | Minutes before a subagent is told to finish up. 0 turns the warning off. |
limitMinutes | 60 | Minutes before it is held to git, gh and note writes. 0 turns the limit off. |
noEditNudgeK | 100 | Thousands of context tokens before the no-edit nudge. 0 turns it off. |
codeAgentTypes | general-purpose | Comma-separated subagent types that get the no-edit nudge. |
This repository is also a pi package: the root package.json declares every plugins/*/skills and plugins/*/extensions directory, and pi reads the same SKILL.md format the other two harnesses do. Install straight from git — no marketplace step:
pi install git:github.com/erikdarlingdata/claude-plugins
As everywhere else, the skill is model-invoked: point pi at a .sqlplan and ask.
pi-session-resume (pi only)Your machine restarts for updates with a dozen pi sessions open; this brings them all back with one command, as terminal tabs, in their original directories, with full history:
pi-resume-sessions
An extension (auto-loaded by the install above) records every open interactive session; the pi-resume-sessions script reopens the interrupted ones — Ghostty tabs on macOS, tmux anywhere. Sessions you quit deliberately (Ctrl+D, /quit) stay closed; sessions killed by a reboot, a closed window, or a crash come back. Idle-time filters keep abandoned sessions from resurrecting.
The script needs a one-time symlink onto your PATH, and macOS needs a one-time Automation permission — see plugins/pi-session-resume/README.md for both, plus the design notes. This one is pi-only: Claude Code and Copilot CLI don't load pi extensions.
pi-subagent-watchdog (pi only)Background subagents only report back when they finish — nothing wakes the orchestrator while one wedges on a giant grep or balloons from 200k to 2M tokens. This extension (auto-loaded by the install above) polls every running subagent's live vitals — tokens, cost, context %, tool uses, turns, wall clock, compactions — and batches nearby threshold crossings into one compact orchestrator check-in. Full structured records persist outside LLM context; per-agent and fleet-wide rate limits keep the watchdog from becoming its own token amplifier. Two orchestrator postures: guide (assess with judgment) and strict (thresholds are budgets — wrap up by default, one evidence-cited extension max). Optional automatic hard stop handles the truly wedged, with the outcome reported from the RPC reply rather than assumed. An optional exact model invariant hard-stops any top-level child that bypasses the manager's pre-spawn model policy. Optional per-agent cost signal and hard stop, plus session and daily USD budget warnings. The CLI surfaces also identify each child's effective model and thinking level.
Humans get a /watchdog panel (vitals, manual check-ins, steering, hard stop) plus /watchdog help | status | config | reload — config edits apply live, no session restart. See plugins/pi-subagent-watchdog/README.md for signals, modes, and design notes. Requires the pi-subagents extension; pi-only for the same reason as above.
pi-subagent-guardrails (pi only)Token-budget guardrails for multi-agent setups, built after an overnight orchestration burned through its usage limit (95% of the spend came at more than 150k context). It has three pieces:
guardrails.md: the written rules for fan-out caps, model tiers, context discipline, session length and ranking.lane agent type for code-editing lanes: Sonnet, its own worktree, draft PRs, no fan-out tools.The wall is deliberately not auto-loaded, because it would wall off your interactive session too. See plugins/pi-subagent-guardrails/README.md for install and the recommended watchdog and pi-subagents settings.
pi-setup-guide.md — a distilled ~15-minute setup for pi written for Claude Code ex-pats: install, model/thinking defaults, the trust model, a Claude-to-pi habit translation table, a tested-together extension stack, full source for a few small quality-of-life extensions (refusal fallback, tab-title status, ! command wake-ups + autocomplete), how to point pi at years of accumulated Claude Code memory instead of migrating it, and a troubleshooting section of the gotchas that actually happened. The plugins in this repo (§11–§13 of the guide) slot into that stack.
Built by Erik Darling at Darling Data. SQL Server consulting, training, and free tools: <https://erikdarling.com>
MIT
hooks/register.ts 255 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register, SessionRateLimit } from 'claude-code'
3
4import type { Warned } from '../types'
5
6const DEFAULT_THRESHOLDS = [70, 85, 95]
7
8// "70, 85, 95" -> [70, 85, 95]; anything that does not parse to at least one percent falls back to the defaults.
9function parsePercents(value: unknown): number[] {
10 const parsed = String(value ?? '')
11 .split(/[\s,]+/)
12 .map(v => Number(v))
13 .filter(n => Number.isFinite(n) && n > 0 && n <= 100)
14
15 return parsed.length > 0 ? parsed : DEFAULT_THRESHOLDS
16}
17
18const DEFAULT_PACE_MARGIN = 10
19const DEFAULT_GATE = 95
20const DEFAULT_TELL_MODEL_AT = 85
21const WEEK_MS = 7 * 24 * 60 * 60 * 1000
22const MINUTE_MS = 60 * 1000
23
24// "10" -> 10; 0 turns the check off; anything that does not parse to a non-negative number falls back to the default,
25// so a typo in an option cannot turn a check off without a word.
26function parseNonNegative(value: unknown, fallback: number): number {
27 const text = String(value ?? '').trim()
28 const parsed = text === '' ? NaN : Number(text)
29
30 return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback
31}
32
33const utc = (ms: number) => `${new Date(ms).toISOString().slice(0, 16).replace('T', ' ')}Z`
34const pts = (n: number) => String(Math.round(n * 10) / 10)
35
36// How far the 7-day window's usage runs ahead of the share of the week that has passed, in points, and the UTC time
37// at which that gap falls back under the margin if usage stays flat. Null when the check does not apply: another
38// window, no reset time to measure the week from, or a gap under the margin.
39type Pace = { used: number; elapsed: number; ahead: number; until: string }
40
41function paceOf(w: SessionRateLimit, now: number, margin: number): Pace | null {
42 const resetsAt = w.resetsAt ? Date.parse(w.resetsAt) : NaN
43 if (w.kind !== 'seven_day' || margin <= 0 || !Number.isFinite(resetsAt)) {
44 return null
45 }
46
47 const elapsed = Math.min(100, Math.max(0, 100 * (1 - (resetsAt - now) / WEEK_MS)))
48 const ahead = w.percentUsed - elapsed
49 // The tiny slack keeps a gap of exactly the margin from slipping under it by floating-point error.
50 if (ahead < margin - 1e-9) {
51 return null
52 }
53
54 // Elapsed reaches (percentUsed - margin) at this moment; rounded up to the minute so the refusal is surely over by then.
55 const liftsAt = resetsAt - WEEK_MS + ((w.percentUsed - margin) / 100) * WEEK_MS
56
57 return { used: w.percentUsed, elapsed, ahead, until: utc(Math.ceil(liftsAt / MINUTE_MS - 1e-6) * MINUTE_MS) }
58}
59
60const paceFacts = (p: Pace) =>
61 `the account's 7-day usage is at ${p.used}% with ${pts(p.elapsed)}% of the week passed, ${pts(p.ahead)} points ahead of pace`
62
63const warned = atom({ plugin: 'usage-budget', key: 'warned' } as const, {} as Record<string, Warned>)
64const note = atom({ plugin: 'usage-budget', key: 'note' } as const, null as string | null)
65// Set after the first failed write of the usage file, so that failure is toasted once, not on every measure.
66const writeFailed = atom({ plugin: 'usage-budget', key: 'writeFailed' } as const, false as boolean)
67
68// A pending note for the model gains the new text; nothing already pending is dropped.
69const addNote = (pending: string | null, text: string) => `${pending ? `${pending} ` : ''}${text}`
70
71const NAMES: Record<string, string> = { five_hour: '5-hour', seven_day: '7-day' }
72const name = (kind: string) => NAMES[kind] ?? kind
73const short = (kind: string) => (kind === 'five_hour' ? '5h' : kind === 'seven_day' ? '7d' : kind)
74const resets = (w: SessionRateLimit) => (w.resetsAt ? ` (resets ${w.resetsAt.slice(0, 16).replace('T', ' ')}Z)` : '')
75
76const slashes = (p: string) => p.trim().replace(/\\/g, '/').replace(/\/+$/, '')
77
78// Where the latest figures go: the usage_file option, where a leading <config> stands for CLAUDE_CONFIG_DIR or else
79// the .claude folder in the home folder (as seat-resume finds it). The option's default is
80// <config>/usage-budget/latest.json; an empty usage_file turns the file off: null.
81const DEFAULT_USAGE_FILE = '<config>/usage-budget/latest.json'
82
83async function usageFileOf($: EngineInterface, options: PluginOptions): Promise<string | null> {
84 const option = typeof options.usage_file === 'string' ? options.usage_file.trim() : DEFAULT_USAGE_FILE
85 if (!option) {
86 return null
87 }
88 if (!option.startsWith('<config>')) {
89 return slashes(option)
90 }
91
92 const configDir = await $.env.get('CLAUDE_CONFIG_DIR')
93 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
94
95 return slashes(`${slashes(configDir || `${home}/.claude`)}${option.slice('<config>'.length)}`)
96}
97
98// The latest rate-limit figures as a small JSON file, so a session that cannot see its own status line (a coordinator
99// writing its usage checks) can read them. $.fs has no mkdir: the write is left to create the folder. A failed write
100// never fails the measure. It is toasted once per session, so a missing folder does not leave the file silently stale.
101// The write is not atomic, so a reader that catches it half-written should read again.
102async function writeLatest($: EngineInterface, options: PluginOptions, rateLimits: SessionRateLimit[], paceMargin: number) {
103 const path = await usageFileOf($, options)
104 if (!path) {
105 return
106 }
107 try {
108 await writeBody($, path, rateLimits, paceMargin)
109 } catch (err) {
110 if (!(await read($, writeFailed))) {
111 await update($, writeFailed, () => true)
112 const reason = String(err instanceof Error ? err.message : err).slice(0, 200)
113 $.ui.toast(`usage-budget: could not write ${path} (${reason}). The file stays out of date until a write works; ` +
114 'if its folder does not exist, create it once.')
115 }
116 }
117}
118
119// The file gives elapsed and ahead to a tenth of a point, as the toast does, not as raw floating point.
120const roundPace = (p: Pace | null) => (p ? { ...p, elapsed: Math.round(p.elapsed * 10) / 10, ahead: Math.round(p.ahead * 10) / 10 } : null)
121
122async function writeBody($: EngineInterface, path: string, rateLimits: SessionRateLimit[], paceMargin: number) {
123
124 const now = await $.clock.now()
125 const week = rateLimits.find(w => w.kind === 'seven_day')
126 const body = {
127 at: new Date(now).toISOString(),
128 rateLimits: rateLimits.map(w => ({ kind: w.kind, percentUsed: w.percentUsed, resetsAt: w.resetsAt ?? null })),
129 pace: roundPace(week ? paceOf(week, now, paceMargin) : null),
130 }
131 await $.fs.write(path, `${JSON.stringify(body, null, 2)}\n`)
132}
133
134export const register: Register = (on, options) => {
135 const gate = parseNonNegative(options.spawnGatePercent, DEFAULT_GATE)
136 const thresholds = parsePercents(options.warnPercents ?? DEFAULT_THRESHOLDS.join(', '))
137 // From this level on, the main session's model is told too, not just the person. 0 never tells the model.
138 const tellModelAt = parseNonNegative(options.tellModelAtPercent, DEFAULT_TELL_MODEL_AT)
139 // New spawns are refused, and the seat warned, when 7-day usage runs this many points ahead of the share of the week
140 // that has passed. 0 turns the check off.
141 const paceMargin = parseNonNegative(options.paceMargin, DEFAULT_PACE_MARGIN)
142
143 on('session.measure', async ($, e, next) => {
144 if (e.rateLimits.length > 0) {
145 $.ui.status(e.rateLimits.map(w => `${short(w.kind)} ${Math.round(w.percentUsed)}%`).join(' · '))
146 await writeLatest($, options, e.rateLimits, paceMargin).catch(() => undefined)
147 }
148
149 for (const w of e.rateLimits) {
150 const level = Math.max(0, ...thresholds.filter(t => w.percentUsed >= t))
151 const resetsAt = w.resetsAt ?? ''
152 const prior = (await read($, warned))[w.kind]
153 const priorLevel = prior && prior.resetsAt === resetsAt ? prior.level : 0
154 if (level <= priorLevel) {
155 continue
156 }
157
158 await update($, warned, all => ({ ...all, [w.kind]: { level, resetsAt } }))
159 $.ui.toast(`Usage: the ${name(w.kind)} window is at ${w.percentUsed}%${resets(w)}`)
160 if (tellModelAt > 0 && level >= tellModelAt) {
161 const gateLine = gate > 0
162 ? level >= gate
163 ? ` New subagent spawns are now refused (limit ${gate}%).`
164 : ` New subagent spawns will be refused at ${gate}%.`
165 : ''
166 await update($, note, pending => addNote(pending,
167 `usage-budget: the account's ${name(w.kind)} usage window is at ${w.percentUsed}%${resets(w)}.` +
168 `${gateLine} Start no new optional work, finish what is in flight, keep the handoff current, and tell the user.`))
169 }
170 }
171
172 // Pace: warn once per window, and again each time the gap grows by another margin.
173 const now = paceMargin > 0 && e.rateLimits.some(w => w.kind === 'seven_day' && w.resetsAt) ? await $.clock.now() : 0
174 for (const w of e.rateLimits) {
175 const pace = paceOf(w, now, paceMargin)
176 if (!pace) {
177 continue
178 }
179
180 const key = `${w.kind}:pace`
181 const level = Math.floor((pace.ahead + 1e-9) / paceMargin)
182 const prior = (await read($, warned))[key]
183 const priorLevel = prior && prior.resetsAt === (w.resetsAt ?? '') ? prior.level : 0
184 if (level <= priorLevel) {
185 continue
186 }
187
188 await update($, warned, all => ({ ...all, [key]: { level, resetsAt: w.resetsAt ?? '' } }))
189 $.ui.toast(`Usage: ${paceFacts(pace)} (limit ${paceMargin}). New subagents are refused until ${pace.until} if usage stays flat.`)
190 if (tellModelAt > 0) {
191 await update($, note, pending => addNote(pending,
192 `usage-budget: ${paceFacts(pace)} (limit ${paceMargin}). New subagent spawns are refused ` +
193 `until ${pace.until} (UTC) if usage stays flat. Start no new optional work, finish what is in flight, ` +
194 'keep the handoff current, and tell the user.'))
195 }
196 }
197
198 return next(e)
199 })
200
201 // Hand a pending note to the model on its next tool result (main session only).
202 on('tool.call', async ($, e, next) => {
203 const ran = await next(e)
204 if (e.agentId || ran.deny !== undefined) {
205 return ran
206 }
207
208 const pending = await read($, note)
209 if (!pending) {
210 return ran
211 }
212
213 await update($, note, () => null)
214
215 return { ...ran, context: [...(ran.context ?? []), pending] }
216 }).catch(($, e, next) => next(e)) // never in the way of a tool call: replays what already ran
217
218 on('agent.spawn', async ($, e, next) => {
219 if (gate <= 0 && paceMargin <= 0) {
220 return next(e)
221 }
222
223 const { rateLimits } = await $.session.usage()
224 if (gate > 0) {
225 const over = rateLimits.find(w => w.percentUsed >= gate)
226 if (over) {
227 return {
228 deny:
229 `usage-budget: the account's ${name(over.kind)} usage window is at ${over.percentUsed}%${resets(over)}, ` +
230 `at or past the ${gate}% limit for new subagents. Spawn none; finish the work in hand, write the handoff, and tell the user.`,
231 }
232 }
233 }
234
235 if (paceMargin > 0) {
236 if (rateLimits.some(w => w.kind === 'seven_day' && w.resetsAt)) {
237 const now = await $.clock.now()
238 for (const w of rateLimits) {
239 const pace = paceOf(w, now, paceMargin)
240 if (pace) {
241 return {
242 deny:
243 `usage-budget: ${paceFacts(pace)} (limit ${paceMargin} points). New subagents are refused until ${pace.until} ` +
244 '(UTC) if usage stays flat. Spawn none; finish the work in hand, write the handoff, and tell the user. ' +
245 "Waiting until then lifts it, and so does the user setting this plugin's paceMargin option to 0.",
246 }
247 }
248 }
249 }
250 }
251
252 return next(e)
253 }).catch(($, e, next) => next(e)) // if the check itself fails, the spawn goes ahead
254}
255types/index.d.ts 9 lines1/** The highest threshold already announced for one window, until that window resets. */
2export type Warned = { level: number; resetsAt: string }
3
4declare module 'claude-code' {
5 interface PluginState {
6 'usage-budget': { warned: Record<string, Warned>; note: string | null; writeFailed: boolean }
7 }
8}
9