ClaudeMod
ModsSecurityWrites / Shell

Agent Usage Guard

A Claude Code mod that holds subagent fan-out, heavy-context prompts and retry loops before they spend your usage window. It reads your plan's usage, counts agents across every session, and asks in Claude Code's own dialog.

Install· Claude Code 2.1.330+
$claude plugin marketplace add rbartoli/agent-usage-guard
$claude plugin install agent-usage-guard@agent-usage-guard
Run claude plugin validate to auditGuide →
Access & PermissionsWrites / Shell

Writes files, executes local shell processes, or programmatically drives Claude.

Drives ClaudeModifies promptReads filesReads env varsReads transcriptReads promptReads mod statePersists local stateDraws UI

Statically scanned from hooks & source. Learn how to audit

Riccardo Bartoli103 starsAdded 4 months ago

agent-usage-guard

Stops Claude Code from spending your five-hour usage window in ten minutes.

agent-usage-guard is a Claude Code mod: it runs inside Claude Code and holds runaway spend before it happens. It reads your plan's live usage, and it holds subagent fan-out, heavy-context churn and retry loops.

agent-usage-guard on Product Hunt

Four scenes in Claude Code's interactive UI. The guard asks before a prompt re-writes the expired cache of a 486k-token session resumed after two hours, before a fifth parallel agent starts against a limit of four, before a twenty-first tool call at 433k context, and before a new agent once subagents have processed 10.9M tokens.

Recorded from Claude Code's interactive UI with the guard loaded. A scripted local API stands in for Claude, so the sessions and token counts are staged and no usage is spent. Every question on screen is the guard's own. Rebuild it from the Northstar fixture.

It acts before the spend, not after it: before an agent starts, a prompt is sent, or a tool call runs. Agent limits hold across every Claude Code session on your machine, and fan-out and heavy context are capped at any usage level, not only near the limit. When you are at the keyboard it asks you, in Claude Code's own question dialog. When nobody can answer, it refuses and tells Claude why, so the model can wait, batch the work, or stop. /agent-guard report shows what it did.

  • Plan-aware. It reads the 5-hour and weekly percentages Claude Code reports, and keeps the end of the window for you.
  • One answer covers a while. An approval lifts its condition until it clears or times out, so the same question does not come back call after call.
  • Local and privacy-minimal. No network, no processes. It stores counts and coarse buckets, never prompt text, tool inputs or model output.
  • Fails open. If one of its hooks fails, the event goes ahead: a broken guard never breaks your session. The one exception is an agent it could not judge, which is refused so that Claude starts it again.

Install

Run these commands inside Claude Code v2.1.287 or later:

/plugin marketplace add rbartoli/agent-usage-guard
/plugin install agent-usage-guard@agent-usage-guard
/reload-plugins

Then run /agent-guard to see what it sees, and /agent-guard simulate concurrency to see the question it asks when too many agents run, with nothing held or spent. Mods are on by default; the overview lists the settings that turn them off.

Why this exists

One afternoon I gave Claude Code a research prompt at max effort. It spawned 394 subagent calls, 341 of them running at once, and pushed 84M context tokens through the API in ten minutes. Session over: "Claude usage limit reached." Locked out until the window reset.

That wasn't a one-off. Sixty days of my own logs held 12 lockouts and 166 ten-minute windows with agent bursts. The failure mode multiplies: a large context × rapid tool loops × parallel agents × blind retries. Each protection below removes one factor.

And it's not just me: 339 subagents from a single prompt, half a weekly Max plan consumed by recursive spawning, and multi-agent runs using ~15× the tokens of a chat session.

What it does

AreaRuleDefaultWhat happens
Plan windowsNew agents need approval once a window is this full80%asks; approval lasts until that window resets
New agents are refused once a window is this full95%refuses
ScheduleWakeup and CronCreate are refused once a window is this full, so no turn starts itself into the limit95%refuses
Each session is told once to finish its step and say what is left95%adds a note to the next prompt
New agents need approval when the 5-hour window rises this fast20 points / 10 minasks
New agents need approval when the 5-hour window's pace over the last 10 minutes would fill it within the hour, before it resetsat least 2 points over 2 minasks
AgentsAgents running at once, across every session on this machine4asks
Agents started or resumed per 10 minutes, across this machine12asks
Tokens processed by subagents per 10 minutes, across this machine; an approval lasts an hour10Masks
Subagents may not start their own agentsdepth 1refuses
ContextClaude is told once to keep the turn bounded300k tokensadds a note to the prompt
A prompt that would re-read this much context500k tokensasks: compact then send, send anyway, or cancel
Tool calls per 10 minutes while a conversation or agent carries this much20 calls at 400kasks: keep going, compact after this turn, or stop
A heavy session idle long enough for its prompt cache to expire150k tokens, 1 h idleasks before re-writing the cache
LoopsThe same tool call failing again and again, with no other call in between3 identical failuresrefuses the identical retry
Refused agent calls within 10 minutes5pauses agent spawns for 10 min

Agents covers subagents, agent-team teammates, workflow agents, and finished subagents resumed with SendMessage. Haiku agents stay out of the running and starts limits, whether Claude asks for Haiku or the agent's own definition picks it; they still count toward the subagent token budget and every plan-window rule. Each tool call is judged on the context of the loop that makes it, so a small subagent never inherits the main conversation's size.

When it asks. The question appears in Claude Code's own dialog, the one Claude uses to ask you something, and the call waits for your answer. Agents started in parallel while it is open are held back, and Claude starts them again once you answer. If you allow it, that condition stays allowed for a while: a plan window until it resets, a heavy context until it shrinks (for tool calls, an hour at most), the agent counts for 10 minutes. If you decline or dismiss the question, or it closes without an answer for any other reason, Claude is told not to start agents for the next 10 minutes (AGENT_GUARD_WINDOW_SECONDS), and is not asked again in that time. Typed words reach Claude, so you can answer "use haiku agents instead".

When nobody can answer. In claude -p, the Agent SDK and dontAsk mode, an agent or tool gate refuses instead of asking. A heavy prompt is held with the reason, and so is a dormant heavy resume once the machine-wide cap of one per 10 minutes is reached. Prompts that start a turn on their own, such as a schedule or /loop firing, a message relayed from a channel like Slack, or a Slack ping, are held the same way, even in a session someone could be asked in; they never lift limits. Claude reads each refusal as the tool's result. Repeat refusals of the same condition are worded differently each time and escalate: the second says nothing has changed and to try something else, the third says to end the turn. If a Stop hook such as /goal keeps reopening the turn, the refusal says the user has to decide.

What it shows. While agents run on this machine, or the guard is holding or has just refused something, a line above the prompt shows it: Usage guard · 3 of 4 agents running · 5 of 12 started in the last 10 min · last refusal 14:22: concurrency. It is bold once a limit is reached or something is held, and gone when there is nothing to say. Claude Code's [-] beside it collapses it. Plan windows and context stay in the status line.

What it leaves alone. It never holds a background task's notification or another session's message, because that would lose the result. It no longer blocks prompts after a usage limit: since v2.1.234, Claude Code waits at a limit and continues at reset on its own (autoContinueAtUsageLimit). The guard's job is to keep you from reaching the limit, and its journal counts the lockouts it did not prevent. Near the limit it only adds a note: from 95%, each session's next prompt tells Claude to finish the step in progress, start nothing large, and end the turn with what is done and what is left, so a lockout finds every session at a clean stop.

Idle compaction. Since v2.1.299, Claude Code compacts a conversation of 200k tokens or more that sits idle for about 54 minutes, before its one-hour prompt cache expires (idleCompaction, on by default). The guard reads the compacted size, so it does not ask about that session. Since v2.1.314 it also runs in VS Code and Claude Desktop's Code tab, for subscribers with telemetry turned off, and on Bedrock, Vertex, Foundry and LLM gateways once the one-hour prompt cache is on. Its dormant question covers what idle compaction leaves out: conversations from 150k to 200k tokens, claude -p and SDK sessions, a machine that was asleep at the 54-minute mark, and setups with idle compaction or auto-compaction turned off.

Claude Code's own resume warning. Since v2.1.304, on Pro and Max plans, Claude Code warns before resuming an inactive conversation, or sending to one whose cache went cold while idle, when that would use a noticeable share of your 5-hour limit: you resume anyway or start a new conversation. It shows only from a minimum share, which Anthropic sets per plan and model, so for most models it shows only on very large conversations. The guard's dormant question asks from 150k tokens, so it still covers most cold resumes, and on the largest you may see both.

Commands

/agent-guard [status]                          what the guard sees right now
/agent-guard allow [agents|context] [minutes]  lift its limits for this session (default: all, 10 min)
/agent-guard pause [minutes]                   the same as allow, for every limit
/agent-guard resume                            end an allow early, lift the agent pause, and let declined questions ask again
/agent-guard report [days]                     what it did on this machine (default: 7 days)
/agent-guard simulate <rule>                   show what a rule does, with nothing held or spent
/agent-guard help                              these commands

/agent-guard runs at once, even mid-turn, and never starts a model turn, so Claude never sees an override and cannot take one as permission. Only you can lift limits: when another plugin runs /agent-guard allow or pause, the guard refuses and says so in the transcript. Sending [allow-usage-guard] or [allow-agent-burst] alone as a prompt, the markers of earlier versions, does the same as /agent-guard allow or allow agents.

What it can and cannot see

Checked against Claude Code v2.1.316:

PathCoverage
Subagents, teammates and workflow agentsHeld before they start (agent.spawn)
A finished subagent sent new work with SendMessageHeld before it resumes, and counted as a start, once
A teammate brought back from disk (Claude Code 2.1.299 or later)Held before it resumes, and counted as a start
/subtask forks, and anything else that starts without agent.spawnCounted when they start, never held: Claude Code offers no event before they do. Forks Claude starts through the Agent tool are held like any agent
Claude Code's internal agents (prompt suggestions, compaction)Not counted
Plan-window percentagesFrom the last API response on a subscription, in claude -p too. API-key sessions report none, so only the token and count budgets apply
Teammates running in their own terminal panesNot visible: their loops run in other processes
Sessions on other machinesNot counted: the cross-session records live in this machine's mod store
Tools the API runs itself, such as the advisorNot holdable: no tool event fires for them

Mods run in claude in a terminal, in the Desktop app's Code tab, in claude -p and the Agent SDK. They don't run in a Desktop-app WSL session (where mods run).

On Team and Enterprise plans, and on machines with managed settings, Claude Code runs its built-in cc-plugin-sec-default plugin ahead of every other, unless managed prependPlugins leaves it out. That plugin sends Claude Code's classic hook events on past user plugins, and Claude Code shows a line for each of the guard's it skipped, such as "agent-usage-guard: its classic.PostToolUse hook was skipped". The guard follows compactions, lockouts, /clear and resumes, and Stop hooks that reopen a turn through events that still reach it. Two things need the classic events: the permission mode reaches the guard only when an agent starts, so it may ask you in dontAsk mode, and /subtask forks go uncounted.

Native limits still matter. Claude Code caps a session at 20 concurrent subagents (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS) and three layers of nesting (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH). It has no limit on the total number of agents a session starts. Since v2.1.316, CLAUDE_CODE_SUBAGENT_EFFORT sets the effort subagents run at when nothing else names one, instead of the session's: a lower one makes each agent cheaper, and the guard still limits how many run. The guard's defaults are stricter and span sessions; the native caps remain the outer wall for the paths the guard only counts.

See what it did

/agent-guard report 30

The report counts usage-limit lockouts (each locked window once), plan-window threshold crossings, wind-down notes, and every question and refusal by rule, with what you answered. It reads every session's journal on this machine and never leaves it. Set AGENT_GUARD_JOURNAL=0 to stop recording.

Security and privacy

A mod runs inside Claude Code with your permissions; read what a mod can reach before you install one. This one is about 3,000 lines of TypeScript with no dependencies, and claude plugin validate . lists every API it calls and every environment variable it reads:

  • It makes no network requests and starts no processes. The only file it reads is its own plugin.json, for the version /agent-guard status shows.
  • It decides only what the rules above describe: whether an agent starts, a prompt is sent, or a tool call runs. It asks you whenever you can answer, and gives the reason when it refuses. It reads permission modes but never changes them, and it writes no settings.
  • The only prompt it submits is your own. After "Compact, then send", it takes the prompt you typed out of the input box and sends it unchanged once compaction finishes, or puts it back if compaction fails. A prompt with an image or an @ mention stays in the input box for you to send, since a resend would drop them.
  • Its prompt hook passes your prompt on unchanged, adds a one-time note for Claude when the context passes 300k or a plan window reaches 95%, or holds the prompt to ask you first (when nobody can answer, it says why instead). Its SessionStart hook changes nothing.
  • It keeps its state in the mod store, a JSON file under ~/.claude/plugins/store/. Each session writes its own counts (running agents, recent starts and dormant resumes, subagent tokens per minute, its latest 5-hour reading), when it was last active (kept 30 days, so a resumed session knows how long it sat idle), and its journal rows (time, a session-id prefix, rule, tool name, context bucket such as 400-500k, plan window and percentage, refusal number, and your answer). Each record is stored under the session's full id, which is also the name of that session's transcript file. If the store stops saving, such as when it is full, the status line says so: other sessions then stop counting this one.
  • It never stores prompt text, tool inputs, error text or model output. When a turn ends on an API error, it reads the conversation's last message, the error Claude Code showed, to tell a usage-limit lockout from other failures. A tool call is reduced to a 13-character fingerprint. Agent names stay in memory and are never written.
  • Journal days older than 90 days are deleted (AGENT_GUARD_JOURNAL_DAYS).
  • demo/, which builds the GIF above, is not part of what runs. It starts Claude Code in a temporary home directory with a made-up API key for a scripted local API, and reads none of your credentials.

Set AGENT_GUARD=0 to turn it off without uninstalling it.

Configuration

Set these as environment variables, or under env in ~/.claude/settings.json. Times are in seconds; a value that isn't a number in range keeps its default, and /agent-guard says so.

VariableMeaning (default)
AGENT_GUARD0, false, off or no turns the guard off (1)
AGENT_GUARD_JOURNAL0 stops the journal (1)
AGENT_GUARD_HAIKU_EXEMPT0 counts Haiku agents in the running and starts limits like any other (1: they stay out)
AGENT_GUARD_JOURNAL_DAYSDays of journal kept (90)
AGENT_GUARD_WINDOW_SECONDSRolling window for budgets, burn and refusals (600)
AGENT_GUARD_AGENT_MAXAgents running at once on this machine (4)
AGENT_GUARD_ROLLING_MAXAgent starts and resumes per window on this machine (12)
AGENT_GUARD_AGENT_TOKENS_MAXSubagent tokens per window on this machine (10000000)
AGENT_GUARD_DEPTH_MAXAgent layers below the main conversation (1)
AGENT_GUARD_LIMIT_ASK_PERCENTPlan-window percentage from which new agents ask (80)
AGENT_GUARD_LIMIT_DENY_PERCENTPlan-window percentage from which new agents, wakeups and scheduled jobs are refused and each session is told to wind down (95)
AGENT_GUARD_BURN_PERCENT5-hour-window points per window that make new agents ask (20)
AGENT_GUARD_CONTEXT_WARNContext at which Claude is told once to keep the turn bounded (300000)
AGENT_GUARD_CONTEXT_HARDContext at which a prompt asks before it is sent (500000)
AGENT_GUARD_TOOL_CONTEXTContext above which tool calls count against the tool budget (400000)
AGENT_GUARD_TOOL_MAXTool calls per window above that context (20)
AGENT_GUARD_DORMANT_SECONDSIdle time after which a heavy session's cache counts as expired (3600)
AGENT_GUARD_DORMANT_CONTEXTContext at which an idle session counts as heavy (150000)
AGENT_GUARD_DORMANT_MAXHeavy dormant resumes per window on this machine when nobody can be asked (1)
AGENT_GUARD_TOOL_FAILURE_MAXIdentical failures before the identical retry is refused (3)
AGENT_GUARD_FUSE_MAXRefused agent calls per fuse period that pause spawns (5)
AGENT_GUARD_FUSE_SECONDSThe fuse period, and how long the pause lasts (600)
AGENT_GUARD_PEER_TTL_SECONDSHow long another session's counts, or an agent with no sign of activity, still count (900)

The dormant default assumes the one-hour prompt cache that subscriptions get within plan usage. With an API key or extra usage, the cache lasts five minutes, so set AGENT_GUARD_DORMANT_SECONDS=300.

Beyond Claude Code

The rules live in a harness-agnostic core (core/) that performs no I/O. The Claude Code mod is its first adapter. docs/architecture.md describes the contract an adapter keeps and what another agent harness must offer to carry each rule.

Tests

claude plugin validate . --strict
claude plugin test

claude plugin test runs the suite inside Claude Code's own test kit: unit tests of the core, and tests that fire real Claude Code events through the hooks module with no session, model or network. TESTING.md covers the layers and what each test proves.

License

MIT

Details

Author
@rbartoli
GitHub Stars
103
Sub-category
Security
License
MIT
Surfaces
terminal
Added
4 months ago
Last synced
today
Events hooked
session.startclassic.SessionStartclassic.UserPromptSubmitclassic.PostToolUseclassic.PostCompactclassic.SubagentStartclassic.StopFailuresession.endsession.measureturn.stepturn.completeprompt.submit

Weekly Mods Digest

Top new Claude Code mods and install commands, once a week. No fluff, unsubscribe anytime.

More Mods

Claude Flightdeck
ModsSecurity

Claude Flightdeck

Live agent dashboard pane with context consumption, advisor timeline, permission verdicts, and subagent swimlanes.

Reads Files
by Sam Casella
GitHub
ModsInterface

Terminal Browser

Browse documentation, GitHub pull requests, and web pages in a split terminal pane directly beside your Claude Code conversation.

Network
by Zenbu Labs
GitHub
Agent Flow
ModsAutomation

Agent Flow

Interactive visual tree of the active session's subagents, background tasks, and teammates beside the transcript via /flow.

UI Only
by Charlie
GitHub

Command Palette

Search for a command to run...