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…

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.
<a href="https://www.producthunt.com/products/agent-usage-guard?embed=true&utm_source=badge-featured&utm_medium=badge&utm_campaign=badge-agent-usage-guard" target="_blank" rel="noopener noreferrer"> <img alt="agent-usage-guard on Product Hunt" width="250" height="54" src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=1289693&theme=light"> </a>
<img src="https://github.com/rbartoli/agent-usage-guard/releases/download/agent-usage-guard--v1.0.0/agent-usage-guard.gif" alt="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." width="900">
<sub>Recorded from Claude Code's interactive UI with the guard loaded. A <a href="demo/scripted-api.ts">scripted local API</a> 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. <a href="demo/render.sh">Rebuild it</a> from the <a href="demo/fixture/northstar-api">Northstar fixture</a>.</sub>
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.
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. Mods are on by default; the overview lists the settings that turn them off.
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.
| Area | Rule | Default | What happens |
|---|---|---|---|
| Plan windows | New agents need approval once a window is this full | 80% | asks; approval lasts until that window resets |
| New agents are refused once a window is this full | 95% | refuses | |
| Each session is told once to finish its step and say what is left | 95% | adds a note to the next prompt | |
| New agents need approval when the 5-hour window rises this fast | 20 points / 10 min | asks | |
| Agents | Agents running at once, across every session on this machine | 4 | asks |
| Agents started or resumed per 10 minutes, across this machine | 12 | asks | |
| Tokens processed by subagents per 10 minutes, across this machine | 10M | asks | |
| Subagents may not start their own agents | depth 1 | refuses | |
| Context | Claude is told once to keep the turn bounded | 300k tokens | adds a note to the prompt |
| A prompt that would re-read this much context | 500k tokens | asks: compact then send, send anyway, or cancel | |
| Tool calls per 10 minutes while a conversation or agent carries this much | 20 calls at 400k | asks: keep going, compact after this turn, or stop | |
| A heavy session idle long enough for its prompt cache to expire | 150k tokens, 1 h idle | asks before re-writing the cache | |
| Loops | The same tool call failing again and again, with no other call in between | 3 identical failures | refuses the identical retry |
| Refused agent calls within 10 minutes | 5 | pauses agent spawns for 10 min |
Agents covers subagents, agent-team teammates, workflow agents, and finished subagents resumed with SendMessage. 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. 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 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. Its dormant question covers what idle compaction leaves out: conversations from 150k to 200k tokens, claude -p and other non-terminal sessions, a machine that was asleep at the 54-minute mark, and setups with idle compaction or auto-compaction turned off.
/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 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.
Checked against Claude Code v2.1.295:
| Path | Coverage |
|---|---|
| Subagents, teammates and workflow agents | Held before they start (agent.spawn) |
A finished subagent sent new work with SendMessage | Held 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.spawn | Counted 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 percentages | From 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 panes | Not visible: their loops run in other processes |
| Sessions on other machines | Not counted: the cross-session records live in this machine's mod store |
| Tools the API runs itself, such as the advisor | Not 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).
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. The guard's defaults are stricter and span sessions; the native caps remain the outer wall for the paths the guard only counts.
/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.
A mod runs inside Claude Code with your permissions; read what a mod can reach before you install one. This one is about 2,400 lines of TypeScript with no dependencies, and claude plugin validate . lists every API it calls and every environment variable it reads:
plugin.json, for the version /agent-guard status shows.SessionStart hook changes nothing.~/.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).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.
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.
| Variable | Meaning (default) |
|---|---|
AGENT_GUARD | 0, false, off or no turns the guard off (1) |
AGENT_GUARD_JOURNAL | 0 stops the journal (1) |
AGENT_GUARD_JOURNAL_DAYS | Days of journal kept (90) |
AGENT_GUARD_WINDOW_SECONDS | Rolling window for budgets, burn and refusals (600) |
AGENT_GUARD_AGENT_MAX | Agents running at once on this machine (4) |
AGENT_GUARD_ROLLING_MAX | Agent starts and resumes per window on this machine (12) |
AGENT_GUARD_AGENT_TOKENS_MAX | Subagent tokens per window on this machine (10000000) |
AGENT_GUARD_DEPTH_MAX | Agent layers below the main conversation (1) |
AGENT_GUARD_LIMIT_ASK_PERCENT | Plan-window percentage from which new agents ask (80) |
AGENT_GUARD_LIMIT_DENY_PERCENT | Plan-window percentage from which new agents are refused and each session is told to wind down (95) |
AGENT_GUARD_BURN_PERCENT | 5-hour-window points per window that make new agents ask (20) |
AGENT_GUARD_CONTEXT_WARN | Context at which Claude is told once to keep the turn bounded (300000) |
AGENT_GUARD_CONTEXT_HARD | Context at which a prompt asks before it is sent (500000) |
AGENT_GUARD_TOOL_CONTEXT | Context above which tool calls count against the tool budget (400000) |
AGENT_GUARD_TOOL_MAX | Tool calls per window above that context (20) |
AGENT_GUARD_DORMANT_SECONDS | Idle time after which a heavy session's cache counts as expired (3600) |
AGENT_GUARD_DORMANT_CONTEXT | Context at which an idle session counts as heavy (150000) |
AGENT_GUARD_DORMANT_MAX | Heavy dormant resumes per window on this machine when nobody can be asked (1) |
AGENT_GUARD_TOOL_FAILURE_MAX | Identical failures before the identical retry is refused (3) |
AGENT_GUARD_FUSE_MAX | Refused agent calls per fuse period that pause spawns (5) |
AGENT_GUARD_FUSE_SECONDS | The fuse period, and how long the pause lasts (600) |
AGENT_GUARD_PEER_TTL_SECONDS | How 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.
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.
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.
MIT
hooks/register.ts 802 lines1// The Claude Code adapter. It turns Claude Code's events into the core's facts
2// and requests, asks the user when a verdict needs an answer, and keeps the
3// cross-session records in $.store. Every decision lives in ../core.
4
5import type { EngineInterface, On, Timer } from 'claude-code'
6
7import {
8 type AgentRequest,
9 type Ask,
10 type Config,
11 DEFAULT_ALLOW_MINUTES,
12 type Deny,
13 HEADER,
14 type JournalRow,
15 MAIN,
16 type PeerRecord,
17 type PromptSource,
18 SIGNATURE,
19 type SessionState,
20 type ToolRequest,
21 type Verdict,
22 agentGate,
23 applyOverride,
24 canonical,
25 contextBucket,
26 defaultConfig,
27 expireAgents,
28 fingerprint,
29 formatReport,
30 heldForQuestion,
31 helpText,
32 highestLimit,
33 isJournalRow,
34 journalKey,
35 livePeers,
36 lockoutKind,
37 markerScope,
38 newSession,
39 observeAgentActive,
40 observeAgentRunEnd,
41 observeAgentStart,
42 observeCompaction,
43 observeLimits,
44 observeMainContext,
45 observeResponse,
46 observeSpawn,
47 observeToolResult,
48 observeToolStart,
49 observeTurnEnd,
50 parseCommand,
51 parseConfig,
52 peerRecord,
53 promptGate,
54 promptNotes,
55 prune,
56 releaseStart,
57 reserveStart,
58 resolveAgentAsk,
59 resolveHeavyAsk,
60 resolvePromptAsk,
61 resumeGuard,
62 splitJournalKeys,
63 statusLine,
64 statusLineExpiry,
65 statusReport,
66 toolGate,
67} from '../core/index.ts'
68
69type Api = EngineInterface
70
71const COMMAND = 'agent-guard'
72const PEER_PREFIX = 'peer:'
73const LAST_ACTIVE_PREFIX = 'last-active:'
74const HEARTBEAT_MS = 60_000
75/** Keeps one session's day of journal rows well inside the store's 4 MiB. */
76const MAX_ROWS_PER_DAY = 2000
77/** All journal days together stay below half the store, oldest dropped first. */
78const JOURNAL_BUDGET_BYTES = 2_000_000
79/** A peer record nobody refreshed for a day is from a session that is gone. */
80const STALE_PEER_MS = 86_400_000
81/** When a session was last active outlives the session by a month, for a later resume. */
82const LAST_ACTIVE_KEEP_MS = 30 * 86_400_000
83/** A redraw waits at most a day, then times the rest: a JavaScript timer cannot wait past 24.8 days, and a window may reset later. */
84const REDRAW_MAX_MS = 86_400_000
85/** Keys of the tool call's envelope, not of the tool's own arguments. */
86const ENVELOPE_KEYS = new Set(['tool', 'tool_use_id', 'agentId', 'consent'])
87
88let config: Config = defaultConfig()
89let problems: string[] = []
90let session: SessionState = newSession('', false)
91let interactive = false
92/** The session has no AskUserQuestion tool (`--tools` left it out), so nobody can be asked. */
93let askUnavailable = false
94let permissionMode: string | undefined
95let peers: PeerRecord[] = []
96/** Agents a SendMessage call already judged as resumes, while that call runs. */
97const gatedResumes = new Set<string>()
98let lastPublished = 0
99/** The last-active time this process last stored, so a heartbeat does not rewrite it. */
100let lastActiveKept: number | undefined
101let lastStatus: string | undefined
102/** The pending redraw of the status line, and the time it is for. */
103let redraw: { at: number; timer: Timer } | undefined
104let compactAfterTurn = false
105/** A Stop event happened and no prompt has started a new turn since. */
106let stopSeen = false
107let journalCache: { key: string; rows: JournalRow[] } | undefined
108/** One question per family at a time: calls that trip while it is open are held back. */
109const pending = new Map<string, Promise<unknown>>()
110
111export function register(on: On): void {
112 on('session.start', async ($, e, next) => {
113 await loadConfig($)
114 interactive = e.isInteractive
115 await startSession($)
116 $.clock.after(0, () => housekeeping($))
117 try {
118 await $.command.register({
119 name: COMMAND,
120 description: 'agent-usage-guard: status, allow, resume, report',
121 argumentHint: '[status | allow [agents|context] [minutes] | pause [minutes] | resume | report [days] | help]',
122 immediate: true,
123 })
124 } catch (error) {
125 $.ui.log(`agent-usage-guard could not add /${COMMAND}: ${String(error)}`, { to: 'debug' })
126 }
127 return next(e)
128 }).catch(($, e, next) => failOpen($, 'session.start', next.error, () => next(e)))
129
130 on('classic.SessionStart', async ($, e, next) => {
131 if (e.source === 'compact') observeCompaction(session)
132 if (e.source === 'clear' || e.source === 'resume' || e.source === 'fork') await startSession($)
133 return next(e)
134 }).catch(($, e, next) => failOpen($, 'classic.SessionStart', next.error, () => next(e)))
135
136 on('classic.UserPromptSubmit', async ($, e, next) => {
137 trackMode(e.permission_mode, e.agent_id)
138 return next(e)
139 }).catch(($, e, next) => failOpen($, 'classic.UserPromptSubmit', next.error, () => next(e)))
140
141 on('classic.PostToolUse', async ($, e, next) => {
142 trackMode(e.permission_mode, e.agent_id)
143 return next(e)
144 }).catch(($, e, next) => failOpen($, 'classic.PostToolUse', next.error, () => next(e)))
145
146 on('classic.PostCompact', async ($, e, next) => {
147 observeCompaction(session)
148 await refreshStatus($)
149 return next(e)
150 }).catch(($, e, next) => failOpen($, 'classic.PostCompact', next.error, () => next(e)))
151
152 on('classic.Stop', async ($, e, next) => {
153 trackMode(e.permission_mode, e.agent_id)
154 stopSeen = true
155 if (e.stop_hook_active) session.reopened = true
156 return next(e)
157 }).catch(($, e, next) => failOpen($, 'classic.Stop', next.error, () => next(e)))
158
159 on('classic.SubagentStart', async ($, e, next) => {
160 const now = await $.clock.now()
161 if (observeAgentStart(session, now, e.agent_id, e.agent_type)) await publish($, now)
162 return next(e)
163 }).catch(($, e, next) => failOpen($, 'classic.SubagentStart', next.error, () => next(e)))
164
165 on('classic.StopFailure', async ($, e, next) => {
166 if (config.enabled) {
167 // On StopFailure, last_assistant_message is the failed request's own
168 // error message, the text Claude Code shows, not Claude's earlier prose.
169 const text = `${e.error_details ?? ''} ${e.last_assistant_message ?? ''}`
170 const kind = lockoutKind(e.error, text, Object.values(session.limits))
171 if (kind) {
172 const now = await $.clock.now()
173 const reading = session.limits[kind]
174 // A current reading's reset time names the window, so the report counts each lockout once.
175 const resets = reading?.resetsAt !== undefined && reading.resetsAt > now ? reading.resetsAt : undefined
176 await journal($, now, { ev: 'lockout', kind, ...(reading ? { pct: reading.percent } : {}), ...(resets === undefined ? {} : { resets }) })
177 }
178 }
179 return next(e)
180 }).catch(($, e, next) => failOpen($, 'classic.StopFailure', next.error, () => next(e)))
181
182 on('session.end', async ($, e, next) => {
183 await keepLastActive($)
184 try {
185 if (session.id) await $.store.delete(PEER_PREFIX + session.id)
186 } catch {
187 // The record expires on its own once its heartbeat is old.
188 }
189 return next(e)
190 }).catch(($, e, next) => failOpen($, 'session.end', next.error, () => next(e)))
191
192 on('session.measure', async ($, e, next) => {
193 if (config.enabled) {
194 const now = await $.clock.now()
195 if (e.changed.includes('rateLimits')) {
196 const readings = e.rateLimits.map((r) => ({
197 at: now,
198 kind: r.kind,
199 percent: r.percentUsed,
200 ...(r.resetsAt ? { resetsAt: Date.parse(r.resetsAt) } : {}),
201 }))
202 for (const { reading, threshold } of observeLimits(session, config, readings)) {
203 await journal($, now, { ev: 'limit', kind: reading.kind, pct: reading.percent, rule: `${threshold}%` })
204 }
205 await publish($, now)
206 }
207 if (e.context.tokens !== undefined) observeMainContext(session, config, e.context.tokens)
208 await refreshStatus($)
209 }
210 return next(e)
211 }).catch(($, e, next) => failOpen($, 'session.measure', next.error, () => next(e)))
212
213 on('turn.step', async function* ($, e, next) {
214 const result = yield* next(e)
215 // A streaming hook fails open by hand: recording a response must never fail the request.
216 try {
217 if (config.enabled && result.usage) {
218 const now = await $.clock.now()
219 const loop = e.agentId ?? MAIN
220 if (loop === MAIN && stopSeen) session.reopened = true
221 observeResponse(session, config, now, loop, {
222 input: result.usage.input_tokens,
223 output: result.usage.output_tokens,
224 cacheRead: result.usage.cache_read_input_tokens,
225 cacheWrite: result.usage.cache_creation_input_tokens,
226 })
227 if (now - lastPublished >= HEARTBEAT_MS) await publish($, now)
228 }
229 } catch (error) {
230 $.ui.log(`agent-usage-guard: could not record a response (${String(error)})`, { to: 'debug' })
231 }
232 return result
233 })
234
235 on('turn.complete', async ($, e, next) => {
236 const result = await next(e)
237 if (!config.enabled) return result
238 const now = await $.clock.now()
239 if (e.agentId) {
240 observeAgentRunEnd(session, e.agentId)
241 await publish($, now)
242 return result
243 }
244 observeTurnEnd(session)
245 if (compactAfterTurn) {
246 compactAfterTurn = false
247 $.clock.after(0, async () => {
248 const failed = await compact($)
249 if (failed !== undefined) $.ui.log(`agent-usage-guard could not compact (${failed}).`)
250 })
251 }
252 await refreshStatus($)
253 return result
254 }).catch(($, e, next) => failOpen($, 'turn.complete', next.error, () => next(e)))
255
256 on('prompt.submit', async ($, e, next) => {
257 if (!config.enabled) return next(e)
258 const now = await $.clock.now()
259 const source = sourceOf(e.origin.kind)
260
261 const scope = source === 'other' ? undefined : markerScope(e.text)
262 if (scope) {
263 const text = applyOverride(session, now, scope, DEFAULT_ALLOW_MINUTES)
264 await journal($, now, { ev: 'override', rule: scope })
265 await refreshStatus($)
266 return { drop: `${SIGNATURE}: ${text}` }
267 }
268
269 await readMainContext($)
270 const context = session.loops[MAIN]?.context
271 // Other sessions' plan readings are fresher than an idle session's own.
272 if (source !== 'other') await loadPeers($, now)
273 const gate = async (at: number): Promise<Verdict> =>
274 promptGate(session, peers, config, at, { source, text: e.text, idleMs: await idleTime($, at) })
275 const woundDown = session.windDown
276 const send = async (note: string | undefined) => {
277 if (session.windDown && !woundDown) {
278 const limit = highestLimit(session, peers, now)
279 await journal($, now, { ev: 'note', rule: 'wind-down', ...(limit ? { kind: limit.kind, pct: limit.percent } : {}) })
280 }
281 return note ? next({ ...e, context: [...(e.context ?? []), note] }) : next(e)
282 }
283 const verdict = await gate(now)
284 if (session.dormantResumes.at(-1) === now) await publish($, now)
285 stopSeen = false
286 session.reopened = false
287
288 if (verdict.kind === 'allow') return send(verdict.note)
289 if (verdict.kind === 'drop') {
290 await journal($, now, { ev: 'drop', rule: verdict.rule, ctx: contextBucket(context) })
291 return { drop: verdict.message }
292 }
293 if (verdict.kind !== 'ask') return next(e)
294
295 const asked = await askUser($, verdict, contextBucket(context))
296 if (asked.unavailable) {
297 await journalAnswer($, verdict, asked)
298 const alone = await gate(asked.at)
299 if (alone.kind === 'drop') return { drop: alone.message }
300 return send(alone.kind === 'allow' ? alone.note : undefined)
301 }
302 const outcome = resolvePromptAsk(session, verdict, asked.answer)
303 await journalAnswer($, verdict, asked, outcome.kind === 'compact-then-send' ? 'compact' : outcome.kind === 'allow' ? 'allow' : 'cancel')
304 if (outcome.kind === 'allow') return send(promptNotes(session, peers, config, asked.at))
305 if (outcome.kind === 'compact-then-send') {
306 const resend = { text: e.text, ...(e.attachments ? { attachments: e.attachments } : {}) }
307 // Claude Code puts a dropped prompt back in the input box; this one is sent for the user.
308 // The put-back can land before or after the first look, so look again before sending.
309 const takeBack = async () => {
310 if ((await $.prompt.read()).text === resend.text) await fillInput($, '')
311 }
312 $.clock.after(0, async () => {
313 await takeBack()
314 // Sending at full size after a failed compaction is the one thing the user chose against.
315 const failed = await compact($)
316 if (failed !== undefined) {
317 $.ui.log(`agent-usage-guard could not compact (${failed}), so your prompt is back in the input box.`)
318 await fillInput($, resend.text)
319 return
320 }
321 await takeBack()
322 try {
323 await $.prompt.submit({ ...resend, asUser: true })
324 } catch (error) {
325 $.ui.log(`agent-usage-guard could not resend your prompt: ${String(error)}`)
326 await fillInput($, resend.text)
327 }
328 })
329 return { drop: outcome.message }
330 }
331 await fillInput($, e.text)
332 return { drop: outcome.message }
333 }).catch(($, e, next) => failOpen($, 'prompt.submit', next.error, () => next(e)))
334
335 on('agent.spawn', async ($, e, next) => {
336 if (!config.enabled) return next(e)
337 trackMode(e.permissionMode, e.parentAgentId)
338 const now = await $.clock.now()
339 const loop = e.parentAgentId ?? MAIN
340 // Since 2.1.299 a resume raises agent.spawn too, inside the SendMessage call that judged and counted it.
341 const resumed = e.resume?.agentId
342 if (resumed !== undefined && gatedResumes.has(resumed)) return next(e)
343 const known = resumed === undefined ? undefined : session.agents[resumed]
344 const parentDepth = e.parentAgentId ? (session.agents[e.parentAgentId]?.depth ?? 1) : 0
345 const request = { loop, depth: known?.depth ?? parentDepth + 1, resume: resumed !== undefined }
346 const { verdict, reservedAt } = await agentVerdict($, now, request)
347 if (verdict.kind === 'deny') {
348 await journalDenial($, verdict, 'Agent')
349 return { deny: verdict.message }
350 }
351 let started: string | undefined
352 try {
353 const result = await next(e)
354 if (!result.deny && result.agentId) {
355 started = result.agentId
356 const kind = e.isTeammate ? 'teammate' : e.workflow ? 'workflow' : e.fork ? 'fork' : 'subagent'
357 if (known) observeAgentActive(session, started)
358 else observeSpawn(session, await $.clock.now(), { agentId: started, kind, depth: request.depth, ...(e.name ? { name: e.name } : {}) })
359 }
360 return result
361 } finally {
362 if (reservedAt !== undefined) releaseStart(session, reservedAt, started)
363 await publish($, await $.clock.now())
364 }
365 }).catch(($, e, next) =>
366 // A failure before the agent started leaves it unjudged; starting it anyway
367 // would let a broken guard wave through every agent of a parallel batch.
368 next.called
369 ? failOpen($, 'agent.spawn', next.error, () => next(e))
370 : { deny: `agent-usage-guard could not judge this agent${next.error?.kind === 'timeout' ? ' in time' : ''}. Start it again. [${SIGNATURE}]` },
371 )
372
373 on('tool.call', async ($, e, next) => {
374 if (!config.enabled) return next(e)
375 const now = await $.clock.now()
376 const loop = e.agentId ?? MAIN
377
378 let resumed: { id: string; reservedAt: number | undefined } | undefined
379 if (e.tool === 'SendMessage') {
380 const target = resumeTarget(e.to, e.message)
381 if (target) {
382 const { verdict, reservedAt } = await agentVerdict($, now, { loop, depth: session.agents[target]!.depth, resume: true })
383 if (verdict.kind === 'deny') {
384 await journalDenial($, verdict, 'SendMessage')
385 return { deny: verdict.message }
386 }
387 resumed = { id: target, reservedAt }
388 gatedResumes.add(target)
389 }
390 }
391
392 const print = fingerprint(canonical(argumentsOf(e)))
393 if (!resumed) {
394 const label = loop === MAIN ? 'this conversation' : `agent ${session.agents[loop]?.name ?? loop.slice(0, 8)}`
395 const request = { loop, tool: e.tool, fingerprint: print, label }
396 let verdict = toolGate(session, config, now, request)
397 if (verdict.kind === 'ask') verdict = await settleHeavy($, verdict, request)
398 if (verdict.kind === 'deny') {
399 await journalDenial($, verdict, e.tool, contextBucket(session.loops[loop]?.context))
400 return { deny: verdict.message }
401 }
402 }
403
404 observeToolStart(session, loop)
405 let result: Awaited<ReturnType<typeof next>> | undefined
406 try {
407 result = await next(e)
408 return result
409 } finally {
410 observeToolResult(session, await $.clock.now(), loop, print, Boolean(result?.isError) && !result?.deny)
411 if (resumed) {
412 gatedResumes.delete(resumed.id)
413 const delivered = result !== undefined && !result.deny && !result.isError
414 if (resumed.reservedAt !== undefined) releaseStart(session, resumed.reservedAt, delivered ? resumed.id : undefined)
415 if (delivered) observeAgentActive(session, resumed.id)
416 await publish($, await $.clock.now())
417 }
418 }
419 }).catch(($, e, next) => failOpen($, 'tool.call', next.error, () => next(e)))
420
421 on('command.run', { command: COMMAND }, async ($, e) => {
422 const now = await $.clock.now()
423 const command = parseCommand(e.args)
424 if (command.action === 'help') return { text: helpText(command.error) }
425 if (command.action === 'report') return { text: await report($, now, command.days) }
426 if (command.action === 'allow') {
427 // Only the person lifts limits: another plugin's $.command.run reaches this hook too.
428 if (sourceOf(e.origin.kind) === 'other') {
429 const from = e.origin.kind === 'plugin' ? `the ${e.origin.name} plugin` : `a ${e.origin.kind} prompt`
430 $.ui.log(`agent-usage-guard refused /${COMMAND} ${e.args.trim()} from ${from}.`)
431 return { text: `Only you can lift the guard's limits, and this came from ${from}, so nothing changed. Type /${COMMAND} ${e.args.trim()} to lift them.` }
432 }
433 const text = applyOverride(session, now, command.scope, command.minutes)
434 await journal($, now, { ev: 'override', rule: command.scope })
435 await refreshStatus($)
436 return { text }
437 }
438 if (command.action === 'resume') {
439 const text = resumeGuard(session)
440 await refreshStatus($)
441 return { text }
442 }
443 await loadPeers($, now)
444 return { text: statusReport(session, peers, config, now, problems, await pluginVersion($)) }
445 }).catch(($, e, next) => ({ text: `The command failed: ${next.error?.message ?? 'unknown error'}` }))
446}
447
448/** Each variable is named in full, so `claude plugin validate` can list every one the mod reads. */
449async function loadConfig($: Api): Promise<void> {
450 const parsed = parseConfig({
451 AGENT_GUARD: await $.env.get('AGENT_GUARD'),
452 AGENT_GUARD_JOURNAL: await $.env.get('AGENT_GUARD_JOURNAL'),
453 AGENT_GUARD_WINDOW_SECONDS: await $.env.get('AGENT_GUARD_WINDOW_SECONDS'),
454 AGENT_GUARD_AGENT_MAX: await $.env.get('AGENT_GUARD_AGENT_MAX'),
455 AGENT_GUARD_ROLLING_MAX: await $.env.get('AGENT_GUARD_ROLLING_MAX'),
456 AGENT_GUARD_DEPTH_MAX: await $.env.get('AGENT_GUARD_DEPTH_MAX'),
457 AGENT_GUARD_AGENT_TOKENS_MAX: await $.env.get('AGENT_GUARD_AGENT_TOKENS_MAX'),
458 AGENT_GUARD_LIMIT_ASK_PERCENT: await $.env.get('AGENT_GUARD_LIMIT_ASK_PERCENT'),
459 AGENT_GUARD_LIMIT_DENY_PERCENT: await $.env.get('AGENT_GUARD_LIMIT_DENY_PERCENT'),
460 AGENT_GUARD_BURN_PERCENT: await $.env.get('AGENT_GUARD_BURN_PERCENT'),
461 AGENT_GUARD_CONTEXT_WARN: await $.env.get('AGENT_GUARD_CONTEXT_WARN'),
462 AGENT_GUARD_CONTEXT_HARD: await $.env.get('AGENT_GUARD_CONTEXT_HARD'),
463 AGENT_GUARD_TOOL_CONTEXT: await $.env.get('AGENT_GUARD_TOOL_CONTEXT'),
464 AGENT_GUARD_TOOL_MAX: await $.env.get('AGENT_GUARD_TOOL_MAX'),
465 AGENT_GUARD_DORMANT_SECONDS: await $.env.get('AGENT_GUARD_DORMANT_SECONDS'),
466 AGENT_GUARD_DORMANT_CONTEXT: await $.env.get('AGENT_GUARD_DORMANT_CONTEXT'),
467 AGENT_GUARD_DORMANT_MAX: await $.env.get('AGENT_GUARD_DORMANT_MAX'),
468 AGENT_GUARD_TOOL_FAILURE_MAX: await $.env.get('AGENT_GUARD_TOOL_FAILURE_MAX'),
469 AGENT_GUARD_FUSE_MAX: await $.env.get('AGENT_GUARD_FUSE_MAX'),
470 AGENT_GUARD_FUSE_SECONDS: await $.env.get('AGENT_GUARD_FUSE_SECONDS'),
471 AGENT_GUARD_PEER_TTL_SECONDS: await $.env.get('AGENT_GUARD_PEER_TTL_SECONDS'),
472 AGENT_GUARD_JOURNAL_DAYS: await $.env.get('AGENT_GUARD_JOURNAL_DAYS'),
473 })
474 config = parsed.config
475 problems = parsed.problems
476 for (const problem of problems) $.ui.log(`agent-usage-guard: ${problem}`, { to: 'debug' })
477}
478
479/** Starts fresh state for the session id Claude Code reports now. */
480async function startSession($: Api): Promise<void> {
481 const previous = session.id
482 const id = await $.session.id()
483 if (previous && previous !== id) {
484 await keepLastActive($)
485 await $.store.delete(PEER_PREFIX + previous).catch(() => undefined)
486 }
487 session = newSession(id, canAsk())
488 lastActiveKept = undefined
489 journalCache = undefined
490 stopSeen = false
491 compactAfterTurn = false
492}
493
494/** Drops journal days past their retention and records of sessions long gone. */
495async function housekeeping($: Api): Promise<void> {
496 try {
497 const now = await $.clock.now()
498 const keys = await $.store.keys()
499 const { recent, expired } = splitJournalKeys(keys, now, config.journalDays)
500 for (const key of expired) await $.store.delete(key)
501 const days = recent.sort()
502 const sizes = await Promise.all(days.map(async (k) => JSON.stringify((await $.store.get(k)) ?? null).length))
503 let total = sizes.reduce((sum, n) => sum + n, 0)
504 for (let i = 0; total > JOURNAL_BUDGET_BYTES && i < days.length; i++) {
505 await $.store.delete(days[i]!)
506 total -= sizes[i]!
507 }
508 for (const key of keys.filter((k) => k.startsWith(PEER_PREFIX))) {
509 const record = (await $.store.get(key)) as { at?: unknown } | undefined
510 if (typeof record?.at !== 'number' || now - record.at > STALE_PEER_MS) await $.store.delete(key)
511 }
512 for (const key of keys.filter((k) => k.startsWith(LAST_ACTIVE_PREFIX))) {
513 const at = await $.store.get(key)
514 if (typeof at !== 'number' || now - at > LAST_ACTIVE_KEEP_MS) await $.store.delete(key)
515 }
516 } catch (error) {
517 $.ui.log(`agent-usage-guard housekeeping failed: ${String(error)}`, { to: 'debug' })
518 }
519}
520
521/** A person can answer a question: an interactive session not set to never ask. */
522function canAsk(): boolean {
523 return interactive && !askUnavailable && permissionMode !== 'dontAsk'
524}
525
526/** Follows the main loop's permission mode; a subagent's own mode says nothing about who can answer. */
527function trackMode(mode: string | undefined, agentId: string | undefined): void {
528 if (!mode || agentId) return
529 permissionMode = mode
530 session.canAsk = canAsk()
531}
532
533function sourceOf(kind: string): PromptSource {
534 if (kind === 'composer' || kind === 'bridge') return 'user'
535 if (kind === 'sdk') return 'headless'
536 return 'other'
537}
538
539/** Publishes this session's counts for the other sessions on this machine. */
540async function publish($: Api, now: number): Promise<void> {
541 if (!session.id) return
542 lastPublished = now
543 expireAgents(session, now, config.peerTtlMs)
544 prune(session, now, config.windowMs)
545 try {
546 await $.store.set(PEER_PREFIX + session.id, peerRecord(session, now, config.windowMs))
547 } catch (error) {
548 $.ui.log(`agent-usage-guard could not publish its counts: ${String(error)}`, { to: 'debug' })
549 }
550 await keepLastActive($)
551}
552
553/**
554 * Stores when the main conversation was last active, so a later process
555 * that resumes the session knows how long it sat idle. The transcript cannot
556 * say: Claude Code rewrites its modification time on resume, and hourly while
557 * the session is open.
558 */
559async function keepLastActive($: Api): Promise<void> {
560 const last = session.loops[MAIN]?.activeAt
561 if (!session.id || last === undefined || last === lastActiveKept) return
562 try {
563 await $.store.set(LAST_ACTIVE_PREFIX + session.id, last)
564 lastActiveKept = last
565 } catch (error) {
566 $.ui.log(`agent-usage-guard could not store when the session was last active: ${String(error)}`, { to: 'debug' })
567 }
568}
569
570/** Reads the other sessions' records; a failure leaves the last ones read. */
571async function loadPeers($: Api, now: number): Promise<void> {
572 try {
573 const own = PEER_PREFIX + session.id
574 const keys = (await $.store.keys()).filter((k) => k.startsWith(PEER_PREFIX) && k !== own)
575 const records = await Promise.all(keys.map((k) => $.store.get(k)))
576 peers = livePeers(records, now, config.peerTtlMs)
577 } catch (error) {
578 $.ui.log(`agent-usage-guard could not read other sessions: ${String(error)}`, { to: 'debug' })
579 }
580}
581
582/** The main context before a prompt, from Claude Code's own figure. */
583async function readMainContext($: Api): Promise<void> {
584 try {
585 const usage = await $.session.usage()
586 if (usage.context.tokens !== undefined) observeMainContext(session, config, usage.context.tokens)
587 } catch {
588 // Keep the last figure a response reported.
589 }
590}
591
592/** Time since the main conversation was last active: in this process, or, after a resume, in the one before. */
593async function idleTime($: Api, now: number): Promise<number | undefined> {
594 const last = session.loops[MAIN]?.activeAt
595 if (last !== undefined) return now - last
596 try {
597 const kept = await $.store.get(LAST_ACTIVE_PREFIX + session.id)
598 return typeof kept === 'number' ? now - kept : undefined
599 } catch {
600 return undefined
601 }
602}
603
604async function refreshStatus($: Api): Promise<void> {
605 if (!interactive) return
606 try {
607 const now = await $.clock.now()
608 redrawAt($, statusLineExpiry(session, peers, config, now), now)
609 const text = statusLine(session, peers, config, now)
610 if (text === lastStatus) return
611 lastStatus = text
612 $.ui.status(text)
613 } catch (error) {
614 $.ui.log(`agent-usage-guard could not update its status line: ${String(error)}`, { to: 'debug' })
615 }
616}
617
618/** Redraws the status line at `at`, when something it shows runs out: a quiet session has no event that would. */
619function redrawAt($: Api, at: number | undefined, now: number): void {
620 if (redraw?.at === at) return
621 redraw?.timer.cancel()
622 redraw = undefined
623 if (at === undefined) return
624 const timer = $.clock.after(Math.min(at - now, REDRAW_MAX_MS), () => {
625 redraw = undefined
626 return refreshStatus($)
627 })
628 redraw = { at, timer }
629}
630
631type Asked = { answer: string | undefined; unavailable: boolean; at: number }
632
633/**
634 * Journals a question and asks it in Claude Code's own question dialog.
635 * `answer` is undefined when the dialog came back without one. That counts as
636 * a dismissal, whatever ended it: the user dismissed it, or interrupted the
637 * turn, or the dialog failed. A question with no answer is never a yes.
638 * `unavailable` means the question could not be asked at all, because the
639 * session has no AskUserQuestion tool: from then on the session counts as one
640 * nobody can answer, and the gate decides alone. `at` is when the question
641 * ended.
642 */
643async function askUser($: Api, ask: Ask, ctx?: string): Promise<Asked> {
644 await journal($, await $.clock.now(), { ev: 'ask', rule: ask.trips[0]?.rule, ctx })
645 let answer: string | undefined
646 let unavailable = false
647 try {
648 answer = await $.ui.ask(ask.question, { options: ask.options, header: HEADER })
649 } catch (error) {
650 const text = String(error)
651 if (/no tool named "AskUserQuestion"/.test(text)) {
652 askUnavailable = true
653 session.canAsk = false
654 unavailable = true
655 } else if (!/\$\.ui\.ask: no answer\b/.test(text)) {
656 $.ui.log(`agent-usage-guard: the question ended without an answer (${text}), so it counts as dismissed.`, { to: 'debug' })
657 }
658 }
659 return { answer, unavailable, at: await $.clock.now() }
660}
661
662/** Journals how a question ended: the user's `choice`, a dismissal, or no dialog at all. */
663async function journalAnswer($: Api, ask: Ask, asked: Asked, choice?: string): Promise<void> {
664 const answer = asked.unavailable ? 'unavailable' : asked.answer === undefined ? 'dismiss' : choice
665 await journal($, asked.at, { ev: 'answer', rule: ask.trips[0]?.rule, answer })
666}
667
668/**
669 * One question per key at a time: a call that trips while its question is
670 * open is held back at once, and the model makes it again once it is
671 * answered. Waiting instead could outlast the hook's time limit.
672 */
673async function oneAtATime<T>(key: string, held: () => T, run: () => Promise<T>): Promise<T> {
674 // The check for an open question and the claim on it must not straddle an
675 // await, or two parallel calls would each ask.
676 if (pending.has(key)) return held()
677 const asking = run()
678 pending.set(key, asking)
679 try {
680 return await asking
681 } finally {
682 pending.delete(key)
683 }
684}
685
686/** Compacts the conversation. Returns why it did not, or undefined once it has. */
687async function compact($: Api): Promise<string | undefined> {
688 try {
689 return (await $.session.compact()).skip
690 } catch (error) {
691 return error instanceof Error ? error.message : String(error)
692 }
693}
694
695/** A verdict on an agent, and the slot it holds when allowed, for `releaseStart`. */
696type AgentVerdict = { verdict: Verdict; reservedAt?: number }
697
698/** The agent gate, asking at most one question about agents at a time. */
699async function agentVerdict($: Api, now: number, request: AgentRequest): Promise<AgentVerdict> {
700 await loadPeers($, now)
701 expireAgents(session, now, config.peerTtlMs)
702 prune(session, now, config.windowMs)
703 const verdict = agentGate(session, peers, config, now, request)
704 if (verdict.kind === 'allow') return { verdict, reservedAt: reserveStart(session, now) }
705 if (verdict.kind !== 'ask') return { verdict }
706 return oneAtATime<AgentVerdict>('agents', () => ({ verdict: heldForQuestion('agents') }), async () => {
707 const asked = await askUser($, verdict)
708 const resolved = asked.unavailable
709 ? agentGate(session, peers, config, asked.at, request)
710 : resolveAgentAsk(session, config, asked.at, verdict, asked.answer, request.resume)
711 const reservedAt = resolved.kind === 'allow' ? reserveStart(session, asked.at) : undefined
712 await journalAnswer($, verdict, asked, resolved.kind === 'allow' ? 'allow' : 'refuse')
713 await refreshStatus($)
714 return { verdict: resolved, ...(reservedAt === undefined ? {} : { reservedAt }) }
715 })
716}
717
718/** The heavy-context question, one per loop at a time. */
719async function settleHeavy($: Api, ask: Ask, request: ToolRequest): Promise<Verdict> {
720 return oneAtATime(`heavy:${ask.loop}`, () => heldForQuestion('heavy'), async () => {
721 const asked = await askUser($, ask, contextBucket(session.loops[ask.loop]?.context))
722 if (asked.unavailable) {
723 await journalAnswer($, ask, asked)
724 return toolGate(session, config, asked.at, request)
725 }
726 const outcome = resolveHeavyAsk(session, config, asked.at, ask, asked.answer)
727 if (outcome.compactAfterTurn) compactAfterTurn = true
728 await journalAnswer($, ask, asked, outcome.compactAfterTurn ? 'compact' : outcome.verdict.kind === 'allow' ? 'allow' : 'refuse')
729 return outcome.verdict
730 })
731}
732
733/** The agent a plain-text SendMessage would resume: a finished subagent of this session. */
734function resumeTarget(to: unknown, message: unknown): string | undefined {
735 if (typeof to !== 'string' || typeof message !== 'string') return undefined
736 const agent = session.agents[to] ?? Object.values(session.agents).find((a) => a.name === to)
737 if (!agent || agent.running || agent.kind === 'teammate') return undefined
738 return agent.id
739}
740
741/** The tool's own arguments, for its fingerprint. */
742function argumentsOf(e: Readonly<Record<string, unknown>>): Record<string, unknown> {
743 const args: Record<string, unknown> = {}
744 for (const [key, value] of Object.entries(e)) if (!ENVELOPE_KEYS.has(key)) args[key] = value
745 return { tool: e.tool, args }
746}
747
748/** Puts `text` in the input box; a failure leaves the box as it was. */
749async function fillInput($: Api, text: string): Promise<void> {
750 await $.prompt.fill({ text }).catch(() => undefined)
751}
752
753/** Journals a refusal the model reads. */
754async function journalDenial($: Api, verdict: Deny, tool: string, ctx?: string): Promise<void> {
755 await journal($, await $.clock.now(), { ev: 'deny', rule: verdict.rule, tool, ctx, n: verdict.n })
756}
757
758/** Appends a row to this session's journal key for the day. Never throws. */
759async function journal($: Api, now: number, row: Omit<JournalRow, 't' | 's'>): Promise<void> {
760 if (!config.journal || !session.id) return
761 try {
762 const key = journalKey(session.id, now)
763 if (journalCache?.key !== key) {
764 const stored = await $.store.get(key)
765 journalCache = { key, rows: Array.isArray(stored) ? stored.filter(isJournalRow) : [] }
766 }
767 const clean = Object.fromEntries(Object.entries(row).filter(([, v]) => v !== undefined)) as Omit<JournalRow, 't' | 's'>
768 journalCache.rows.push({ t: now, s: session.id.slice(0, 8), ...clean })
769 if (journalCache.rows.length > MAX_ROWS_PER_DAY) journalCache.rows.splice(0, journalCache.rows.length - MAX_ROWS_PER_DAY)
770 await $.store.set(key, journalCache.rows)
771 } catch (error) {
772 $.ui.log(`agent-usage-guard could not write its journal: ${String(error)}`, { to: 'debug' })
773 }
774}
775
776/** The version in the loaded copy's own manifest, so the status shows which copy runs. */
777async function pluginVersion($: Api): Promise<string | undefined> {
778 try {
779 const manifest: unknown = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`))
780 const version = (manifest as { version?: unknown } | null)?.version
781 return typeof version === 'string' ? version : undefined
782 } catch {
783 return undefined
784 }
785}
786
787async function report($: Api, now: number, days: number): Promise<string> {
788 try {
789 const { recent } = splitJournalKeys(await $.store.keys(), now, days)
790 const rows = (await Promise.all(recent.map((k) => $.store.get(k)))).flatMap((v) => (Array.isArray(v) ? v.filter(isJournalRow) : []))
791 return formatReport(rows, now, days)
792 } catch (error) {
793 return `agent-usage-guard could not read its journal: ${String(error)}`
794 }
795}
796
797/** A hook that throws or overruns lets the event go ahead: a broken guard must not break the session. */
798function failOpen<T>($: Api, event: string, error: { kind?: string; message?: string } | undefined, proceed: () => T): T {
799 $.ui.log(`agent-usage-guard: the ${event} hook failed, so the event went ahead (${error?.kind ?? 'error'}: ${error?.message ?? 'unknown'})`, { to: 'debug' })
800 return proceed()
801}
802core/index.ts 55 lines1// The harness-agnostic core of agent-usage-guard. It performs no I/O and reads
2// no clock: an adapter reports facts, asks for verdicts, and carries them out.
3// See docs/architecture.md for the contract an adapter keeps.
4
5export { type AgentRequest, agentGate, heldForQuestion, highestLimit, resolveAgentAsk } from './agents.ts'
6export { type Command, DEFAULT_ALLOW_MINUTES, applyOverride, helpText, parseCommand, resumeGuard } from './commands.ts'
7export { type Config, SPECS, SWITCHES, defaultConfig, parseConfig } from './config.ts'
8export { type JournalEvent, type JournalRow, formatReport, isJournalRow, journalKey, splitJournalKeys } from './journal.ts'
9export { lockoutKind } from './lockout.ts'
10export {
11 type SpawnFacts,
12 type TokenUsage,
13 expireAgents,
14 observeAgentActive,
15 observeAgentRunEnd,
16 observeAgentStart,
17 observeCompaction,
18 observeLimits,
19 observeMainContext,
20 observeResponse,
21 observeSpawn,
22 observeToolResult,
23 observeToolStart,
24 observeTurnEnd,
25 releaseStart,
26 reserveStart,
27} from './observe.ts'
28export {
29 type PromptOutcome,
30 type PromptRequest,
31 type PromptSource,
32 markerScope,
33 promptGate,
34 promptNotes,
35 resolvePromptAsk,
36} from './prompts.ts'
37export {
38 type AgentKind,
39 type AgentRecord,
40 type LimitReading,
41 type LoopId,
42 MAIN,
43 type PeerRecord,
44 type Scope,
45 type SessionState,
46 livePeers,
47 newSession,
48 peerRecord,
49 prune,
50} from './state.ts'
51export { USAGE, statusLine, statusLineExpiry, statusReport } from './status.ts'
52export { canonical, contextBucket, fingerprint } from './text.ts'
53export { type HeavyOutcome, type ToolRequest, resolveHeavyAsk, toolGate } from './tools.ts'
54export { type Ask, type Deny, type Family, HEADER, type Rule, SIGNATURE, type Verdict } from './verdict.ts'
55core/agents.ts 234 lines1// The agent gate: every subagent, teammate, workflow agent and resumed agent
2// passes here before it starts.
3
4import type { Config } from './config.ts'
5import { type LimitReading, type LoopId, type PeerRecord, type SessionState, countOnMachine, overrideCovers, runningAgents, tokensWithin } from './state.ts'
6import { count, duration, join, sentence, shortClock, tokens, windowName } from './text.ts'
7import { ALLOW, type Ask, type Deny, SIGNATURE, type Trip, type Verdict, refuse } from './verdict.ts'
8
9export type AgentRequest = {
10 /** The loop asking for the agent. */
11 loop: LoopId
12 /** Layers below the main conversation the new agent would run at. */
13 depth: number
14 /** True when a finished agent is being sent a new task. */
15 resume: boolean
16}
17
18const AGENT_ALLOW = 'Allow'
19const AGENT_REFUSE = "Don't start it"
20
21export function agentGate(
22 state: SessionState,
23 peers: readonly PeerRecord[],
24 config: Config,
25 now: number,
26 request: AgentRequest,
27): Verdict {
28 if (!config.enabled || overrideCovers(state, now, 'agents')) return ALLOW
29 const what = request.resume ? 'resuming this agent' : 'this agent'
30
31 if (request.depth > config.depthMax) {
32 const base = `${request.resume ? 'This agent cannot be resumed' : 'This agent was not started'}: subagents may not start agents of their own here (depth limit ${config.depthMax}). Do the work yourself and report back.`
33 return refuse(state, config, now, 'depth', 'depth', base, true)
34 }
35 if (state.fuseUntil !== undefined && now < state.fuseUntil) {
36 const base = `Agent spawns in this session are paused until ${shortClock(state.fuseUntil)} after repeated refused agent calls. Continue without agents; the user can lift this with /agent-guard allow.`
37 return refuse(state, config, now, 'fuse', 'fuse', base, false)
38 }
39
40 const limit = highestLimit(state, peers, now)
41 if (limit && limit.percent >= config.limitDenyPercent) {
42 const base = `${sentence(what)} was refused: ${limitDetail(limit)}, and the guard keeps the rest of the window for the user. Continue without agents; the user can lift this with /agent-guard allow.`
43 return refuse(state, config, now, 'limit-deny', 'limit-deny', base, true)
44 }
45
46 const trips = agentTrips(state, peers, config, now, limit).filter((t) => !leased(state, t, now))
47 if (trips.length === 0) return ALLOW
48
49 const details = join(trips.map((t) => t.detail))
50 const declinedAt = state.refusals.agents
51 if (declinedAt !== undefined && now < declinedAt) {
52 const base = `The user declined new agents for now (${details}). Continue without starting agents; the user can lift this with /agent-guard allow.`
53 return refuse(state, config, now, trips[0]!.rule, `agents:${trips[0]!.rule}`, base, true)
54 }
55 if (!state.canAsk) return unattended(state, config, now, trips, details, request.resume)
56 return {
57 kind: 'ask',
58 family: 'agents',
59 loop: request.loop,
60 trips,
61 question: `${sentence(details)}. Allowing lifts ${trips.length > 1 ? 'these limits' : 'this limit'} until ${shortClock(Math.max(...trips.map((t) => t.leaseUntil)))}. ${request.resume ? 'Resume this agent' : 'Start this agent'}?`,
62 options: [AGENT_ALLOW, AGENT_REFUSE],
63 }
64}
65
66/**
67 * Applies the user's answer to an agents question. Any answer other than the
68 * allow label refuses, and typed words reach the model so it can act on them.
69 * `answer` is undefined when the question was dismissed.
70 */
71export function resolveAgentAsk(
72 state: SessionState,
73 config: Config,
74 now: number,
75 ask: Ask,
76 answer: string | undefined,
77 resume = false,
78): Verdict {
79 if (answer === AGENT_ALLOW) {
80 for (const trip of ask.trips) state.leases[trip.leaseKey] = Math.max(state.leases[trip.leaseKey] ?? 0, trip.leaseUntil)
81 return ALLOW
82 }
83 state.refusals.agents = now + config.windowMs
84 const details = join(ask.trips.map((t) => t.detail))
85 const said =
86 answer === undefined
87 ? `The user dismissed the question about ${resume ? 'resuming' : 'starting'} it`
88 : answer === AGENT_REFUSE
89 ? `The user chose not to ${resume ? 'resume' : 'start'} it`
90 : `The user answered "${answer}" instead of allowing it`
91 const base = `${notRun(resume)}: ${details}. ${said}. Continue without starting agents unless the user says otherwise.`
92 return refuse(state, config, now, ask.trips[0]!.rule, `agents:${ask.trips[0]!.rule}`, base, true)
93}
94
95/**
96 * Holds back a call that tripped while the user is already being asked the
97 * same question. It does not wait for the answer, which could outlast the
98 * hook's time limit, and it is not a refusal of the condition: no ladder rung,
99 * no fuse.
100 */
101export function heldForQuestion(subject: 'agents' | 'heavy'): Deny {
102 const message =
103 subject === 'agents'
104 ? 'The user is being asked about starting agents. Wait for that answer, then start this agent again.'
105 : 'The user is being asked whether to keep working at this context size. Wait for that answer, then make this call again.'
106 return { kind: 'deny', rule: 'asking', message: `${message} [${SIGNATURE}]` }
107}
108
109function agentTrips(
110 state: SessionState,
111 peers: readonly PeerRecord[],
112 config: Config,
113 now: number,
114 limit: LimitReading | undefined,
115): Trip[] {
116 const window = config.windowMs
117 const span = duration(window)
118 const until = now + window
119 const trips: Trip[] = []
120
121 const running = runningAgents(state) + peers.reduce((sum, p) => sum + p.running, 0)
122 if (running >= config.agentMax) {
123 trips.push({
124 rule: 'concurrency',
125 detail: `${count(running, 'agent')} ${running === 1 ? 'is' : 'are'} running on this machine (limit ${config.agentMax})`,
126 leaseKey: 'concurrency',
127 leaseUntil: until,
128 })
129 }
130
131 const starts = countOnMachine(state, peers, 'starts', now, window)
132 if (starts >= config.rollingMax) {
133 trips.push({
134 rule: 'starts',
135 detail: `${count(starts, 'agent')} started on this machine in the last ${span} (limit ${config.rollingMax})`,
136 leaseKey: 'starts',
137 leaseUntil: until,
138 })
139 }
140
141 const processed = tokensWithin(state.agentTokens, now, window) + peers.reduce((sum, p) => sum + tokensWithin(p.agentTokens, now, window), 0)
142 if (processed >= config.agentTokensMax) {
143 trips.push({
144 rule: 'agent-tokens',
145 detail: `subagents processed ${tokens(processed)} tokens in the last ${span} (limit ${tokens(config.agentTokensMax)})`,
146 leaseKey: 'agent-tokens',
147 leaseUntil: until,
148 })
149 }
150
151 const burned = burn(state, peers, now, window)
152 if (burned && burned.points >= config.burnPercent) {
153 trips.push({
154 rule: 'burn',
155 detail: `the 5-hour window rose ${burned.points} points in the last ${span} (now ${burned.percent}%)`,
156 leaseKey: 'burn',
157 leaseUntil: until,
158 })
159 }
160
161 if (limit && limit.percent >= config.limitAskPercent) {
162 trips.push({
163 rule: 'limit',
164 detail: limitDetail(limit),
165 leaseKey: `limit:${limit.kind}`,
166 leaseUntil: limit.resetsAt ?? until,
167 })
168 }
169 return trips
170}
171
172function unattended(state: SessionState, config: Config, now: number, trips: Trip[], details: string, resume: boolean): Deny {
173 const first = trips[0]!
174 const advice: Record<string, string> = {
175 concurrency: 'Wait for a running agent to finish before starting another',
176 starts: 'Starts free up as they age out of the window; batch the work or do it yourself',
177 'agent-tokens': 'Do the remaining work yourself instead of in agents',
178 burn: 'Continue without agents until the burn slows',
179 limit: 'Continue without agents',
180 }
181 const base = `${notRun(resume)}: ${details}. Nobody can approve it in this session. ${advice[first.rule] ?? 'Continue without agents'}.`
182 return refuse(state, config, now, first.rule, `agents:${first.rule}`, base, true)
183}
184
185function leased(state: SessionState, trip: Trip, now: number): boolean {
186 const until = state.leases[trip.leaseKey]
187 return until !== undefined && now < until
188}
189
190/** The most-used plan window with a current reading, from this session or its peers. */
191export function highestLimit(state: SessionState, peers: readonly PeerRecord[], now: number): LimitReading | undefined {
192 const readings = [...Object.values(state.limits), ...peers.flatMap((p) => (p.limit ? [p.limit] : []))]
193 const freshest = new Map<string, LimitReading>()
194 for (const r of readings) {
195 if (r.resetsAt !== undefined && r.resetsAt <= now) continue
196 const seen = freshest.get(r.kind)
197 if (!seen || r.at > seen.at) freshest.set(r.kind, r)
198 }
199 let highest: LimitReading | undefined
200 for (const r of freshest.values()) if (!highest || r.percent > highest.percent) highest = r
201 return highest
202}
203
204export function limitDetail(limit: LimitReading): string {
205 const reset = limit.resetsAt === undefined ? '' : ` (resets ${shortClock(limit.resetsAt)})`
206 return `the ${windowName(limit.kind)} window is ${limit.percent}% used${reset}`
207}
208
209/** Points the 5-hour window rose within the rolling window, across this machine. */
210function burn(
211 state: SessionState,
212 peers: readonly PeerRecord[],
213 now: number,
214 windowMs: number,
215): { points: number; percent: number } | undefined {
216 const own = state.limits.five_hour
217 const peerReadings = peers.flatMap((p) => (p.limit?.kind === 'five_hour' ? [p.limit] : []))
218 const current = [own, ...peerReadings].reduce<LimitReading | undefined>(
219 (best, r) => (r && (!best || r.at > best.at) ? r : best),
220 undefined,
221 )
222 if (!current) return undefined
223 const sameWindow = [...state.limitHistory, ...peerReadings].filter(
224 (r) => r.kind === 'five_hour' && r.resetsAt === current.resetsAt && now - r.at < windowMs,
225 )
226 if (sameWindow.length === 0) return undefined
227 const lowest = Math.min(...sameWindow.map((r) => r.percent))
228 return { points: Math.round((current.percent - lowest) * 10) / 10, percent: current.percent }
229}
230
231function notRun(resume: boolean): string {
232 return resume ? 'This agent was not resumed' : 'This agent was not started'
233}
234core/commands.ts 84 lines1// `/agent-guard` and its arguments. The command runs without a model turn and
2// the model cannot run it, and the adapter refuses an override another plugin
3// runs, so an override is always the user's. The model does read the
4// command's reply with its next request.
5
6import { MAIN, type Scope, type SessionState, loopOf } from './state.ts'
7import { duration, sentence, shortClock } from './text.ts'
8import { USAGE, scopeName } from './status.ts'
9
10export type Command =
11 | { action: 'status' }
12 | { action: 'allow'; scope: Scope; minutes: number }
13 | { action: 'resume' }
14 | { action: 'report'; days: number }
15 | { action: 'help'; error?: string }
16
17export const DEFAULT_ALLOW_MINUTES = 10
18const MAX_ALLOW_MINUTES = 8 * 60
19const DEFAULT_REPORT_DAYS = 7
20const MAX_REPORT_DAYS = 3650
21
22export function parseCommand(args: string): Command {
23 const words = args.trim().toLowerCase().split(/\s+/).filter(Boolean)
24 const [verb, ...rest] = words
25 if (verb === undefined || verb === 'status') return { action: 'status' }
26 if (verb === 'help') return { action: 'help' }
27 if (verb === 'resume') return { action: 'resume' }
28 if (verb === 'report') {
29 const days = rest[0] === undefined ? DEFAULT_REPORT_DAYS : Number(rest[0])
30 if (!Number.isInteger(days) || days < 1 || days > MAX_REPORT_DAYS) return { action: 'help', error: `"${rest[0]}" is not a number of days` }
31 return { action: 'report', days }
32 }
33 if (verb === 'allow' || verb === 'pause') {
34 let scope: Scope = 'all'
35 let minutes = DEFAULT_ALLOW_MINUTES
36 for (const word of rest) {
37 if (verb === 'allow' && (word === 'agents' || word === 'context' || word === 'all')) {
38 scope = word
39 continue
40 }
41 const n = Number(word.replace(/m(in(utes?)?)?$/, ''))
42 if (!Number.isInteger(n) || n < 1 || n > MAX_ALLOW_MINUTES) {
43 return { action: 'help', error: `"${word}" is not ${verb === 'allow' ? 'agents, context or ' : ''}a number of minutes from 1 to ${MAX_ALLOW_MINUTES}` }
44 }
45 minutes = n
46 }
47 return { action: 'allow', scope, minutes }
48 }
49 return { action: 'help', error: `unknown subcommand "${verb}"` }
50}
51
52/** Lifts limits for this session, and forgets the declines and the fuse they cover. */
53export function applyOverride(state: SessionState, now: number, scope: Scope, minutes: number): string {
54 const until = now + minutes * 60_000
55 state.override = { until, scope }
56 if (scope !== 'context') {
57 delete state.fuseUntil
58 delete state.refusals.agents
59 state.denials = state.denials.filter((d) => !d.agent)
60 }
61 if (scope !== 'agents') {
62 for (const loop of Object.values(state.loops)) loop.stopped = false
63 state.failures = {}
64 }
65 return `${sentence(scopeName(scope))} lifted for ${duration(minutes * 60_000)}, until ${shortClock(until)}. /agent-guard resume ends it early.`
66}
67
68/** Ends an override and clears declined questions, so the guard asks again. */
69export function resumeGuard(state: SessionState): string {
70 const had = state.override !== undefined
71 delete state.override
72 state.refusals = {}
73 delete state.fuseUntil
74 state.denials = state.denials.filter((d) => !d.agent)
75 loopOf(state, MAIN).stopped = false
76 return had
77 ? 'Limits apply again.'
78 : 'No override was active. Declined questions are cleared, so the guard asks again.'
79}
80
81export function helpText(error?: string): string {
82 return error ? `${sentence(error)}.\n\n${USAGE}` : USAGE
83}
84core/config.ts 127 lines1// Thresholds and switches. The core reads them from a plain record of strings
2// so that any harness can supply them: environment variables, a settings file,
3// or a test's literal object.
4
5export type Config = {
6 enabled: boolean
7 /** Rolling window for agent starts, token burn, tool budgets and denials. */
8 windowMs: number
9 /** Agents running at once across every session on this machine. */
10 agentMax: number
11 /** Agent starts and resumes per window across every session on this machine. */
12 rollingMax: number
13 /** Subagent layers below the main conversation; 1 means subagents cannot spawn. */
14 depthMax: number
15 /** Tokens processed by subagent requests per window across this machine. */
16 agentTokensMax: number
17 /** Plan-window percentage at which new agents need the user's approval. */
18 limitAskPercent: number
19 /** Plan-window percentage at which new agents are refused. */
20 limitDenyPercent: number
21 /** Plan-window points burned within one window that make new agents ask. */
22 burnPercent: number
23 /** Context at which Claude is told, once, to keep the turn bounded. */
24 contextWarn: number
25 /** Context at which a prompt needs the user's approval before it is sent. */
26 contextHard: number
27 /** Context above which a loop's tool calls count against the tool budget. */
28 toolContext: number
29 /** Tool calls per window a loop may make above `toolContext`. */
30 toolMax: number
31 /** Idle time after which a heavy session's prompt cache has likely expired. */
32 dormantMs: number
33 /** Context at which a dormant session counts as heavy. */
34 dormantContext: number
35 /** Dormant heavy resumes per window on this machine when nobody can be asked. */
36 dormantMax: number
37 /** Identical consecutive tool failures before the identical retry is refused. */
38 failureMax: number
39 /** Refused agent calls per `fuseMs` that pause agent spawns for `fuseMs`. */
40 fuseMax: number
41 fuseMs: number
42 /** How long another session's record, or an agent with no sign of activity, still counts. */
43 peerTtlMs: number
44 journal: boolean
45 journalDays: number
46}
47
48type Field = Exclude<keyof Config, 'enabled' | 'journal'>
49
50type Spec = {
51 field: Field
52 env: string
53 default: number
54 min: number
55 max: number
56 /** Multiplier from the variable's unit to the field's (seconds to milliseconds). */
57 scale: number
58}
59
60const SECONDS = 1000
61
62export const SPECS: readonly Spec[] = [
63 { field: 'windowMs', env: 'AGENT_GUARD_WINDOW_SECONDS', default: 600, min: 60, max: 86_400, scale: SECONDS },
64 { field: 'agentMax', env: 'AGENT_GUARD_AGENT_MAX', default: 4, min: 1, max: 1000, scale: 1 },
65 { field: 'rollingMax', env: 'AGENT_GUARD_ROLLING_MAX', default: 12, min: 1, max: 10_000, scale: 1 },
66 { field: 'depthMax', env: 'AGENT_GUARD_DEPTH_MAX', default: 1, min: 1, max: 10, scale: 1 },
67 { field: 'agentTokensMax', env: 'AGENT_GUARD_AGENT_TOKENS_MAX', default: 10_000_000, min: 1, max: 1e12, scale: 1 },
68 { field: 'limitAskPercent', env: 'AGENT_GUARD_LIMIT_ASK_PERCENT', default: 80, min: 1, max: 100, scale: 1 },
69 { field: 'limitDenyPercent', env: 'AGENT_GUARD_LIMIT_DENY_PERCENT', default: 95, min: 1, max: 101, scale: 1 },
70 { field: 'burnPercent', env: 'AGENT_GUARD_BURN_PERCENT', default: 20, min: 1, max: 101, scale: 1 },
71 { field: 'contextWarn', env: 'AGENT_GUARD_CONTEXT_WARN', default: 300_000, min: 1, max: 1e9, scale: 1 },
72 { field: 'contextHard', env: 'AGENT_GUARD_CONTEXT_HARD', default: 500_000, min: 1, max: 1e9, scale: 1 },
73 { field: 'toolContext', env: 'AGENT_GUARD_TOOL_CONTEXT', default: 400_000, min: 1, max: 1e9, scale: 1 },
74 { field: 'toolMax', env: 'AGENT_GUARD_TOOL_MAX', default: 20, min: 1, max: 100_000, scale: 1 },
75 { field: 'dormantMs', env: 'AGENT_GUARD_DORMANT_SECONDS', default: 3600, min: 60, max: 30 * 86_400, scale: SECONDS },
76 { field: 'dormantContext', env: 'AGENT_GUARD_DORMANT_CONTEXT', default: 150_000, min: 1, max: 1e9, scale: 1 },
77 { field: 'dormantMax', env: 'AGENT_GUARD_DORMANT_MAX', default: 1, min: 0, max: 1000, scale: 1 },
78 { field: 'failureMax', env: 'AGENT_GUARD_TOOL_FAILURE_MAX', default: 3, min: 1, max: 1000, scale: 1 },
79 { field: 'fuseMax', env: 'AGENT_GUARD_FUSE_MAX', default: 5, min: 1, max: 1000, scale: 1 },
80 { field: 'fuseMs', env: 'AGENT_GUARD_FUSE_SECONDS', default: 600, min: 10, max: 86_400, scale: SECONDS },
81 { field: 'peerTtlMs', env: 'AGENT_GUARD_PEER_TTL_SECONDS', default: 900, min: 60, max: 86_400, scale: SECONDS },
82 { field: 'journalDays', env: 'AGENT_GUARD_JOURNAL_DAYS', default: 90, min: 1, max: 3650, scale: 1 },
83]
84
85export const SWITCHES = { enabled: 'AGENT_GUARD', journal: 'AGENT_GUARD_JOURNAL' } as const
86
87const OFF = new Set(['0', 'false', 'off', 'no'])
88
89export function defaultConfig(): Config {
90 const config = { enabled: true, journal: true } as Config
91 for (const spec of SPECS) config[spec.field] = spec.default * spec.scale
92 return config
93}
94
95/**
96 * Builds the config from variables by name. Unset variables take their
97 * defaults; a value that is not a number in range is reported in `problems`
98 * and falls back to the default, so a typo never disables a protection.
99 */
100export function parseConfig(vars: Readonly<Record<string, string | undefined>>): {
101 config: Config
102 problems: string[]
103} {
104 const config = defaultConfig()
105 const problems: string[] = []
106 for (const [field, name] of Object.entries(SWITCHES) as [keyof typeof SWITCHES, string][]) {
107 const raw = vars[name]?.trim().toLowerCase()
108 if (raw) config[field] = !OFF.has(raw)
109 }
110 for (const spec of SPECS) {
111 const raw = vars[spec.env]?.trim()
112 if (!raw) continue
113 const value = Number(raw.replaceAll('_', ''))
114 if (!Number.isFinite(value) || value < spec.min || value > spec.max) {
115 problems.push(`${spec.env}=${raw} is not a number from ${spec.min} to ${spec.max}; using ${spec.default}`)
116 continue
117 }
118 config[spec.field] = Math.round(value * spec.scale)
119 }
120 if (config.limitDenyPercent < config.limitAskPercent) {
121 problems.push(
122 `AGENT_GUARD_LIMIT_DENY_PERCENT is below AGENT_GUARD_LIMIT_ASK_PERCENT; new agents are refused from ${config.limitDenyPercent}%`,
123 )
124 }
125 return { config, problems }
126}
127core/journal.ts 178 lines1// The local journal: one row per intervention, answer, override, limit
2// crossing and lockout. Rows hold rule names, tool names, coarse buckets and
3// times, never prompt text, tool inputs or model output.
4
5import { count, duration, windowName } from './text.ts'
6
7export type JournalEvent =
8 | 'ask' // the guard asked the user
9 | 'answer' // the user answered (or dismissed) a question
10 | 'deny' // a model-facing refusal
11 | 'drop' // a prompt was held
12 | 'override' // /agent-guard allow or pause
13 | 'limit' // a plan window crossed an ask or deny threshold
14 | 'note' // Claude was told to wind down
15 | 'lockout' // a request failed on a usage limit
16
17export type JournalRow = {
18 t: number
19 /** First 8 characters of the session id. */
20 s: string
21 ev: JournalEvent
22 rule?: string
23 /** For `answer`: allow, compact, refuse, cancel or dismiss, or unavailable when the question could not be shown. */
24 answer?: string
25 tool?: string
26 ctx?: string
27 /** Plan-window percentage, for `limit`, `note` and `lockout`. */
28 pct?: number
29 kind?: string
30 /** For `lockout`: when the window that locked resets, from a current reading of it. */
31 resets?: number
32 /** For `deny`: which refusal of the condition this was. */
33 n?: number
34}
35
36const KEY_PREFIX = 'journal:'
37const DAY_MS = 86_400_000
38/** Lockout rows with no reset time belong to one lockout while less than an hour apart. */
39const LOCKOUT_GAP_MS = 3_600_000
40
41/** Each session appends only to its own key for the day, so sessions never overwrite each other. */
42export function journalKey(sessionId: string, now: number): string {
43 return `${KEY_PREFIX}${new Date(now).toISOString().slice(0, 10)}:${sessionId}`
44}
45
46/**
47 * Picks the journal's keys out of the store's and splits them by age: `recent`
48 * days can hold rows from the last `days` days, `expired` days ended before
49 * those began.
50 */
51export function splitJournalKeys(keys: readonly string[], now: number, days: number): { recent: string[]; expired: string[] } {
52 const start = now - days * DAY_MS
53 const split = { recent: [] as string[], expired: [] as string[] }
54 for (const key of keys) {
55 if (!key.startsWith(KEY_PREFIX)) continue
56 const day = Date.parse(key.slice(KEY_PREFIX.length, KEY_PREFIX.length + 10))
57 if (Number.isNaN(day)) continue
58 split[day + DAY_MS < start ? 'expired' : 'recent'].push(key)
59 }
60 return split
61}
62
63export function isJournalRow(value: unknown): value is JournalRow {
64 if (typeof value !== 'object' || value === null) return false
65 const r = value as Record<string, unknown>
66 return typeof r.t === 'number' && typeof r.ev === 'string' && typeof r.s === 'string'
67}
68
69type RuleCount = { asks: number; allowed: number; declined: number; denials: number; drops: number }
70
71/** The text `/agent-guard report` prints. */
72export function formatReport(rows: readonly JournalRow[], now: number, days: number): string {
73 const recent = rows.filter((r) => now - r.t < days * DAY_MS).sort((a, b) => a.t - b.t)
74 const lines = [`agent-usage-guard report: last ${count(days, 'day')}`]
75 if (recent.length === 0) {
76 lines.push('', 'Nothing recorded yet. The journal fills as the guard asks, refuses, or sees a limit.')
77 return lines.join('\n')
78 }
79 const sessions = new Set(recent.map((r) => r.s)).size
80 lines.push(`${count(recent.length, 'event')} from ${count(sessions, 'session')}`)
81
82 const lockouts = lockedWindows(recent.filter((r) => r.ev === 'lockout' && r.kind !== 'model'))
83 const modelScoped = recent.filter((r) => r.ev === 'lockout' && r.kind === 'model').length
84 // Only a span of a week or more gives a weekly rate; a shorter one would extrapolate.
85 const rate = days >= 7 ? ` (${(lockouts.length / (days / 7)).toFixed(1)} per week)` : ''
86 lines.push('', `Usage-limit lockouts: ${lockouts.length}${rate}`)
87 for (const row of lockouts.slice(-5)) {
88 lines.push(` ${stamp(row.t)}${row.kind && row.kind !== 'unknown' ? ` · ${windowName(row.kind)} window` : ''}`)
89 }
90 if (modelScoped > 0) lines.push(`Limits on one model, where /model switched away: ${modelScoped}`)
91
92 const crossings = recent.filter((r) => r.ev === 'limit')
93 if (crossings.length > 0) {
94 const byThreshold = countBy(crossings, (r) => `${windowName(r.kind ?? '?')} ${r.rule ?? ''}`.trim())
95 lines.push(`Limit crossings: ${[...byThreshold].map(([k, n]) => `${k} ×${n}`).join(', ')}`)
96 }
97 const windDowns = recent.filter((r) => r.ev === 'note' && r.rule === 'wind-down')
98 if (windDowns.length > 0) lines.push(`Wind-down notes: ${windDowns.length} in ${count(new Set(windDowns.map((r) => r.s)).size, 'session')}`)
99
100 const perRule = new Map<string, RuleCount>()
101 const bump = (rule: string | undefined, field: keyof RuleCount): void => {
102 const key = rule ?? 'unknown'
103 const entry = perRule.get(key) ?? { asks: 0, allowed: 0, declined: 0, denials: 0, drops: 0 }
104 entry[field] += 1
105 perRule.set(key, entry)
106 }
107 for (const row of recent) {
108 if (row.ev === 'ask') bump(row.rule, 'asks')
109 else if (row.ev === 'deny') bump(row.rule, 'denials')
110 else if (row.ev === 'drop') bump(row.rule, 'drops')
111 // A question that could not be shown was neither allowed nor declined.
112 else if (row.ev === 'answer' && row.answer !== 'unavailable') {
113 bump(row.rule, row.answer === 'allow' || row.answer === 'compact' ? 'allowed' : 'declined')
114 }
115 }
116 if (perRule.size > 0) {
117 lines.push('', 'By rule (asks: allowed / declined · refusals to the model · prompts held)')
118 const width = Math.max(...[...perRule.keys()].map((k) => k.length))
119 for (const [rule, c] of [...perRule].sort((a, b) => total(b[1]) - total(a[1]))) {
120 lines.push(` ${rule.padEnd(width)} asks ${c.asks}: ${c.allowed} / ${c.declined} · refusals ${c.denials} · held ${c.drops}`)
121 }
122 }
123
124 const denials = recent.filter((r) => r.ev === 'deny')
125 const late = denials.filter((r) => (r.n ?? 1) >= 3).length
126 const fuses = denials.filter((r) => r.rule === 'fuse').length
127 if (denials.length > 0) lines.push(`Refusals at rung 3 or later: ${late} · refused while the agent fuse was burning: ${fuses}`)
128
129 const tools = countBy(denials.filter((r) => r.tool), (r) => r.tool ?? '')
130 if (tools.size > 0) lines.push(`Refusals by tool: ${[...tools].map(([k, n]) => `${k} ${n}`).join(', ')}`)
131
132 const contexts = countBy(recent.filter((r) => r.ctx), (r) => r.ctx ?? '')
133 if (contexts.size > 0) lines.push(`Context when it acted: ${[...contexts].map(([k, n]) => `${k} ${n}`).join(', ')}`)
134
135 const overrides = recent.filter((r) => r.ev === 'override')
136 if (overrides.length > 0) lines.push(`Overrides: ${overrides.length} (${[...countBy(overrides, (r) => r.rule ?? 'all')].map(([k, n]) => `${k} ${n}`).join(', ')})`)
137
138 lines.push('', `Span: ${stamp(recent[0]!.t)} to ${stamp(recent.at(-1)!.t)} (${duration(recent.at(-1)!.t - recent[0]!.t)})`)
139 return lines.join('\n')
140}
141
142/**
143 * The first row of each locked window. Rows with the same reset time are one
144 * window, whichever session hit it and however often; a row without one, from
145 * an older version or a session with no current reading, joins the row before
146 * it unless an hour or more separates them.
147 */
148function lockedWindows(lockouts: readonly JournalRow[]): JournalRow[] {
149 const firsts: JournalRow[] = []
150 const previous = new Map<string, JournalRow>()
151 for (const row of lockouts) {
152 const kind = row.kind ?? 'unknown'
153 const before = previous.get(kind)
154 previous.set(kind, row)
155 const same =
156 before !== undefined &&
157 (row.resets !== undefined && before.resets !== undefined ? row.resets === before.resets : row.t - before.t < LOCKOUT_GAP_MS)
158 if (!same) firsts.push(row)
159 }
160 return firsts
161}
162
163function total(c: RuleCount): number {
164 return c.asks + c.denials + c.drops
165}
166
167function countBy<T>(items: readonly T[], key: (item: T) => string): Map<string, number> {
168 const counts = new Map<string, number>()
169 for (const item of items) counts.set(key(item), (counts.get(key(item)) ?? 0) + 1)
170 return new Map([...counts].sort((a, b) => b[1] - a[1]))
171}
172
173function stamp(ms: number): string {
174 const d = new Date(ms)
175 const pad = (n: number): string => String(n).padStart(2, '0')
176 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
177}
178core/lockout.ts 29 lines1// Which failed requests were usage-limit lockouts: the outcome the guard
2// exists to prevent, and the figure its report is judged by.
3
4import type { LimitReading } from './state.ts'
5
6/** Claude Code offers `/model` when only one model's limit was reached. */
7const MODEL_SWITCH = /\/model\b[^.\n]{0,40}\bswitch\b|\bswitch(?:ing)?\s+(?:to\s+)?(?:another\s+|a\s+different\s+)?models?\b|\bopus\b[^.\n]{0,24}\blimit\b/i
8
9const PHRASES: ReadonlyArray<[RegExp, string]> = [
10 [/\b(?:5-hour|five-hour|session) limit\b/i, 'five_hour'],
11 [/\bweekly limit\b/i, 'seven_day'],
12 [/\bmonthly spend limit\b|\bspend limit\b|\busage credits\b/i, 'spend_limit'],
13 [/\busage limit\b|\blimit reached\b|\bhit your limit\b/i, 'unknown'],
14]
15
16/**
17 * The window a failed request ran into, or undefined for a failure that is
18 * not a usage limit, such as an overloaded or transient 429. A limit scoped to
19 * one model is reported as `model`: switching models continues the work.
20 */
21export function lockoutKind(error: string, text: string, readings: readonly LimitReading[]): string | undefined {
22 if (error !== 'rate_limit' && error !== 'billing_error') return undefined
23 if (MODEL_SWITCH.test(text)) return 'model'
24 const named = PHRASES.find(([pattern]) => pattern.test(text))?.[1]
25 if (named !== undefined && named !== 'unknown') return named
26 // A generic phrase, or none, is pinned to the window a reading shows full.
27 return readings.find((r) => r.percent >= 100)?.kind ?? named
28}
29core/observe.ts 224 lines1// Facts the harness reports after they happen. None of these decide anything;
2// they keep the state the gates read accurate.
3
4import type { Config } from './config.ts'
5import { type AgentKind, type LimitReading, type LoopId, MAIN, type SessionState, loopOf } from './state.ts'
6
7export type TokenUsage = {
8 input: number
9 output: number
10 cacheRead: number
11 cacheWrite: number
12}
13
14/** Tokens a request carried in: what the loop's next request re-reads, roughly. */
15function contextOf(usage: TokenUsage): number {
16 return usage.input + usage.cacheRead + usage.cacheWrite
17}
18
19/**
20 * One model request finished in `loop`, with the usage the API reported. An
21 * agent that makes one is running, even if it had gone quiet for long enough
22 * to stop counting.
23 */
24export function observeResponse(state: SessionState, config: Config, now: number, loop: LoopId, usage: TokenUsage): void {
25 const context = contextOf(usage)
26 setContext(state, config, loop, context)
27 loopOf(state, loop).activeAt = now
28 const agent = state.agents[loop]
29 if (!agent) return
30 agent.running = true
31 state.agentTokens.push([now, context + usage.output])
32}
33
34/** The main conversation's context as the harness reports it, without a request. */
35export function observeMainContext(state: SessionState, config: Config, tokens: number): void {
36 setContext(state, config, MAIN, tokens)
37}
38
39/** Records a loop's context. Below a threshold, what was tied to it ends: the heavy approval and tool budget, the warning, the prompt approval. */
40function setContext(state: SessionState, config: Config, loop: LoopId, context: number): void {
41 const l = loopOf(state, loop)
42 l.context = context
43 if (context < config.toolContext) {
44 delete l.heavyLeaseUntil
45 l.heavyCalls = []
46 }
47 if (loop !== MAIN) return
48 if (context < config.contextWarn) state.warned = false
49 if (context < config.contextHard) delete state.leases['prompt-context']
50}
51
52/** The conversation was compacted: the old context and approvals tied to it are gone. */
53export function observeCompaction(state: SessionState, loop: LoopId = MAIN): void {
54 const l = loopOf(state, loop)
55 delete l.context
56 delete l.heavyLeaseUntil
57 l.heavyCalls = []
58 if (loop === MAIN) {
59 state.warned = false
60 delete state.leases['prompt-context']
61 }
62}
63
64/**
65 * The plan windows the latest response reported. Returns the windows whose
66 * percentage crossed one of the guard's thresholds since the previous reading,
67 * so the adapter can journal the crossing once.
68 */
69export function observeLimits(
70 state: SessionState,
71 config: Config,
72 readings: readonly LimitReading[],
73): Array<{ reading: LimitReading; threshold: number }> {
74 const crossings: Array<{ reading: LimitReading; threshold: number }> = []
75 for (const reading of readings) {
76 const previous = state.limits[reading.kind]
77 const sameWindow = previous?.resetsAt === reading.resetsAt
78 for (const threshold of [config.limitAskPercent, config.limitDenyPercent]) {
79 const before = sameWindow && previous ? previous.percent : 0
80 if (before < threshold && reading.percent >= threshold) crossings.push({ reading, threshold })
81 }
82 state.limits[reading.kind] = reading
83 state.limitHistory.push(reading)
84 }
85 return crossings
86}
87
88export type SpawnFacts = {
89 agentId: string
90 kind: AgentKind
91 depth: number
92 name?: string
93}
94
95/**
96 * Holds a slot for an agent the gate just allowed. Call it in the same
97 * synchronous step as the verdict: parallel spawns are judged concurrently, and
98 * each must see the slots the others already took. Returns the start's time,
99 * which `releaseStart` takes back if the agent never starts.
100 */
101export function reserveStart(state: SessionState, now: number): number {
102 state.pendingStarts += 1
103 state.starts.push(now)
104 return now
105}
106
107/**
108 * Ends a reservation: `agentId` started, or, when it is undefined, the start
109 * failed and is not counted. Once no gated agent is starting, the starts none
110 * of them claimed are counted.
111 */
112export function releaseStart(state: SessionState, reservedAt: number, agentId: string | undefined): void {
113 state.pendingStarts = Math.max(0, state.pendingStarts - 1)
114 if (agentId === undefined) {
115 const index = state.starts.indexOf(reservedAt)
116 if (index >= 0) state.starts.splice(index, 1)
117 } else {
118 delete state.unclaimed[agentId]
119 }
120 countUnclaimed(state)
121}
122
123/** An agent the gate allowed has started; its start was counted by `reserveStart`. */
124export function observeSpawn(state: SessionState, now: number, facts: SpawnFacts): void {
125 state.agents[facts.agentId] = {
126 id: facts.agentId,
127 kind: facts.kind,
128 depth: facts.depth,
129 running: true,
130 startedAt: now,
131 ...(facts.name ? { name: facts.name } : {}),
132 }
133}
134
135/** A known agent's loop ran again: a resumed subagent or a teammate that woke. */
136export function observeAgentActive(state: SessionState, agentId: string): void {
137 const agent = state.agents[agentId]
138 if (agent) agent.running = true
139}
140
141/**
142 * The harness reported an agent's loop starting. A known agent is running
143 * again. An unknown one started without passing the gate, such as a /subtask
144 * fork the user ran: it is counted, never blocked. While a gated agent is
145 * still starting, its own report looks the same, so an unknown start waits
146 * until every gated agent has claimed its own. An agent with no type is the
147 * harness's own and is left out, which is the one case that returns false.
148 */
149export function observeAgentStart(state: SessionState, now: number, agentId: string, type: string): boolean {
150 if (state.agents[agentId]) {
151 observeAgentActive(state, agentId)
152 return true
153 }
154 if (!type) return false
155 state.unclaimed[agentId] = { at: now, kind: type === 'fork' ? 'fork' : 'subagent' }
156 countUnclaimed(state)
157 return true
158}
159
160/** Once no gated agent is starting, counts the starts none of them claimed. */
161function countUnclaimed(state: SessionState): void {
162 if (state.pendingStarts > 0) return
163 for (const [agentId, { at, kind }] of Object.entries(state.unclaimed)) {
164 observeSpawn(state, at, { agentId, kind, depth: 1 })
165 state.starts.push(at)
166 }
167 state.unclaimed = {}
168}
169
170/** A known agent finished a run. Its context leaves with it. */
171export function observeAgentRunEnd(state: SessionState, agentId: string): void {
172 const agent = state.agents[agentId]
173 if (agent) agent.running = false
174 const loop = state.loops[agentId]
175 if (loop) loop.stopped = false
176}
177
178/**
179 * Agents with no sign of life for `ttlMs` stop counting as running: no model
180 * request, and no tool call running or finished. That catches an agent whose
181 * end the harness never reported; one that is only slow comes back with its
182 * next request.
183 */
184export function expireAgents(state: SessionState, now: number, ttlMs: number): void {
185 for (const agent of Object.values(state.agents)) {
186 const loop = state.loops[agent.id]
187 if (!agent.running || (loop?.toolsRunning ?? 0) > 0) continue
188 if (now - Math.max(agent.startedAt, loop?.activeAt ?? 0) > ttlMs) agent.running = false
189 }
190}
191
192/** A tool call is starting to run in `loop`. */
193export function observeToolStart(state: SessionState, loop: LoopId): void {
194 const l = loopOf(state, loop)
195 l.toolsRunning = (l.toolsRunning ?? 0) + 1
196}
197
198/**
199 * A tool call finished; identical failures in a row feed the retry fuse. Any
200 * other call by the same loop breaks the row, so test, edit, re-run is never
201 * a retry loop.
202 */
203export function observeToolResult(state: SessionState, now: number, loop: LoopId, fingerprint: string, failed: boolean): void {
204 const l = loopOf(state, loop)
205 l.toolsRunning = Math.max(0, (l.toolsRunning ?? 0) - 1)
206 l.activeAt = now
207 for (const [key, failure] of Object.entries(state.failures)) {
208 if (failure.loop === loop && key !== fingerprint) delete state.failures[key]
209 }
210 if (!failed) {
211 delete state.failures[fingerprint]
212 return
213 }
214 const previous = state.failures[fingerprint]
215 state.failures[fingerprint] = { count: (previous?.count ?? 0) + 1, last: now, loop }
216}
217
218/** The main turn ended: per-turn conditions reset. */
219export function observeTurnEnd(state: SessionState): void {
220 state.reopened = false
221 const main = state.loops[MAIN]
222 if (main) main.stopped = false
223}
224core/prompts.ts 146 lines1// The prompt gate. It never touches a prompt the user did not type, such as a
2// background task's notification or another session's message: holding those
3// loses results, and the context warning waits for the user's own next prompt.
4// It never holds a prompt over plan limits either; Claude Code waits at a limit
5// and resumes on its own.
6
7import { highestLimit, limitDetail } from './agents.ts'
8import type { Config } from './config.ts'
9import { MAIN, type PeerRecord, type Scope, type SessionState, countOnMachine, overrideCovers } from './state.ts'
10import { count, duration, sentence, tokens } from './text.ts'
11import { ALLOW, type Allow, type Ask, type Drop, type Rule, SIGNATURE, type Verdict } from './verdict.ts'
12
13/** Who a prompt came from, as far as the guard cares. */
14export type PromptSource = 'user' | 'headless' | 'other'
15
16export type PromptRequest = {
17 source: PromptSource
18 text: string
19 /** Time since the session's last model response, when known. */
20 idleMs?: number
21}
22
23const PROMPT_COMPACT = 'Compact, then send'
24const PROMPT_SEND = 'Send anyway'
25const PROMPT_CANCEL = 'Cancel'
26
27const MARKERS: Readonly<Record<string, Scope>> = {
28 '[allow-usage-guard]': 'all',
29 '[allow-agent-burst]': 'agents',
30}
31
32/**
33 * The bracket markers of earlier versions, when one is the whole prompt. They
34 * act like `/agent-guard allow`: the prompt is not sent, so no model turn runs
35 * and the model never reads the marker.
36 */
37export function markerScope(text: string): Scope | undefined {
38 return MARKERS[text.trim().toLowerCase()]
39}
40
41export function promptGate(
42 state: SessionState,
43 peers: readonly PeerRecord[],
44 config: Config,
45 now: number,
46 request: PromptRequest,
47): Verdict {
48 if (!config.enabled || request.source === 'other') return ALLOW
49 const context = state.loops[MAIN]?.context
50 if (context === undefined || overrideCovers(state, now, 'context')) return withNotes(state, peers, config, now, context)
51
52 const hardLeased = state.leases['prompt-context'] !== undefined
53 if (context >= config.contextHard && !hardLeased) {
54 const detail = `this session holds ${tokens(context)} context tokens (limit ${tokens(config.contextHard)}), and sending re-reads all of them`
55 if (state.canAsk && request.source === 'user') {
56 return promptAsk('prompt-context', `This session holds ${tokens(context)} context tokens, and sending re-reads all of them; compacting first shrinks this request and every later one. Send this prompt?`, detail)
57 }
58 return drop('prompt-context', `${detail}. Compact the session first, or raise AGENT_GUARD_CONTEXT_HARD.`)
59 }
60
61 const idle = request.idleMs
62 if (idle !== undefined && idle >= config.dormantMs && context >= config.dormantContext) {
63 const detail = `this session was idle for ${duration(idle)}, so its prompt cache has likely expired and this request re-writes about ${tokens(context)} tokens`
64 if (state.canAsk && request.source === 'user') {
65 return promptAsk('dormant', `${sentence(detail)}. Send this prompt?`, detail)
66 }
67 const recent = countOnMachine(state, peers, 'dormantResumes', now, config.windowMs)
68 if (recent >= config.dormantMax) {
69 return drop(
70 'dormant',
71 `${detail}, and ${count(recent, 'heavy idle session')} already resumed on this machine in the last ${duration(config.windowMs)} (limit ${config.dormantMax}). Try again later, or compact the session first.`,
72 )
73 }
74 state.dormantResumes.push(now)
75 }
76 return withNotes(state, peers, config, now, context)
77}
78
79/** The user chose to compact first: drop the prompt, compact, then send it. */
80export type CompactThenSend = { kind: 'compact-then-send'; rule: Rule; message: string }
81
82export type PromptOutcome = Allow | Drop | CompactThenSend
83
84/** Applies the user's answer to a prompt question. Dismissing it cancels. */
85export function resolvePromptAsk(state: SessionState, ask: Ask, answer: string | undefined): PromptOutcome {
86 const trip = ask.trips[0]!
87 if (answer === PROMPT_COMPACT) {
88 return { kind: 'compact-then-send', rule: trip.rule, message: `${SIGNATURE}: compacting first, because ${trip.detail}; your prompt is sent once that finishes.` }
89 }
90 if (answer === PROMPT_SEND) {
91 if (trip.rule === 'prompt-context') state.leases['prompt-context'] = Number.MAX_SAFE_INTEGER
92 return ALLOW
93 }
94 return drop(trip.rule, 'cancelled; your prompt is back in the input box.')
95}
96
97function promptAsk(rule: 'prompt-context' | 'dormant', question: string, detail: string): Ask {
98 return {
99 kind: 'ask',
100 family: 'prompt',
101 loop: MAIN,
102 trips: [{ rule, detail, leaseKey: rule, leaseUntil: Number.MAX_SAFE_INTEGER }],
103 question,
104 options: [PROMPT_COMPACT, PROMPT_SEND, PROMPT_CANCEL],
105 }
106}
107
108function drop(rule: Rule, reason: string): Drop {
109 return { kind: 'drop', rule, message: `${SIGNATURE}: ${reason}` }
110}
111
112/** The notes for a prompt the user chose to send, if Claude has not had them yet. */
113export function promptNotes(state: SessionState, peers: readonly PeerRecord[], config: Config, now: number): string | undefined {
114 const verdict = withNotes(state, peers, config, now, state.loops[MAIN]?.context)
115 return verdict.kind === 'allow' ? verdict.note : undefined
116}
117
118function withNotes(state: SessionState, peers: readonly PeerRecord[], config: Config, now: number, context: number | undefined): Verdict {
119 const notes = [contextWarning(state, config, context), windDown(state, peers, config, now)].filter((n) => n !== undefined)
120 return notes.length === 0 ? ALLOW : { kind: 'allow', note: notes.join('\n') }
121}
122
123/** Tells Claude once, when the context first crosses the warning threshold. */
124function contextWarning(state: SessionState, config: Config, context: number | undefined): string | undefined {
125 if (context === undefined || context < config.contextWarn || state.warned) return undefined
126 state.warned = true
127 return `${SIGNATURE}: this session's context is ${tokens(context)} tokens. Keep this turn bounded, and recommend /compact to the user at the next natural break.`
128}
129
130/**
131 * Tells Claude once, when a plan window on this machine reaches the percentage
132 * at which new agents are refused, to finish the step and hand over: parallel
133 * main sessions run on after agents stop, and a lockout cuts each one off
134 * wherever it is. Told again only after the window falls back below it.
135 */
136function windDown(state: SessionState, peers: readonly PeerRecord[], config: Config, now: number): string | undefined {
137 const limit = highestLimit(state, peers, now)
138 if (!limit || limit.percent < config.limitDenyPercent) {
139 state.windDown = false
140 return undefined
141 }
142 if (state.windDown) return undefined
143 state.windDown = true
144 return `${SIGNATURE}: ${limitDetail(limit)}. Finish the step in progress, start nothing large, and end this turn with a short summary of what is done and what is left, so the work can resume after the reset.`
145}
146core/state.ts 240 lines1// The guard's state for one session, plus the small record each session
2// publishes for the others on the same machine. Everything here is plain JSON,
3// so an adapter can keep it in memory, in a key-value store, or in a file
4// between hook processes.
5//
6// The core updates a SessionState in place, inside synchronous functions only:
7// one adapter owns one state, and no update spans an await, so concurrent hooks
8// in the same process cannot interleave halfway through a change.
9
10/** `main` for the main conversation, otherwise the agent's id. */
11export type LoopId = string
12
13export const MAIN: LoopId = 'main'
14
15export type AgentKind = 'subagent' | 'teammate' | 'workflow' | 'fork'
16
17export type AgentRecord = {
18 id: string
19 kind: AgentKind
20 /** Layers below the main conversation: 1 for an agent the main loop started. */
21 depth: number
22 running: boolean
23 startedAt: number
24 name?: string
25}
26
27export type LoopState = {
28 /** Input tokens of the loop's latest model request: what the next one re-reads. */
29 context?: number
30 /** When the loop last finished a model request or a tool call. */
31 activeAt?: number
32 /** Tool calls the loop has running: an agent in one is running, however long the tool takes. */
33 toolsRunning?: number
34 /** Tool calls made while the loop was above the tool-budget threshold. */
35 heavyCalls: number[]
36 /** The user approved heavy work in this loop until then, or until it compacts. */
37 heavyLeaseUntil?: number
38 /** The user chose to stop this turn: refuse its tool calls until it ends. */
39 stopped?: boolean
40}
41
42export type LimitReading = {
43 at: number
44 /** `five_hour`, `seven_day`, a gateway's `spend_limit`, ... */
45 kind: string
46 percent: number
47 resetsAt?: number
48}
49
50export type Scope = 'all' | 'agents' | 'context'
51
52export type Denial = { at: number; key: string; agent: boolean }
53
54export type SessionState = {
55 id: string
56 /** A person can answer questions in this session. */
57 canAsk: boolean
58 loops: Record<LoopId, LoopState>
59 agents: Record<string, AgentRecord>
60 /** Agents the gate allowed that Claude Code has not reported started yet. */
61 pendingStarts: number
62 /** Agents that started outside the gate while a gated agent was starting, by id: counted once it has. */
63 unclaimed: Record<string, { at: number; kind: AgentKind }>
64 /** This session's agent starts and resumes, newest last. */
65 starts: number[]
66 /** Tokens each subagent request processed, as [time, tokens]. */
67 agentTokens: Array<[number, number]>
68 /** Latest reading per plan window, and the readings inside the current window. */
69 limits: Record<string, LimitReading>
70 limitHistory: LimitReading[]
71 /** An approved condition stays approved until the time stored under its key. */
72 leases: Record<string, number>
73 /** A family the user declined is refused without asking until then. */
74 refusals: Record<string, number>
75 denials: Denial[]
76 fuseUntil?: number
77 /** Consecutive identical failures per tool-call fingerprint, and the loop that made them. */
78 failures: Record<string, { count: number; last: number; loop: LoopId }>
79 override?: { until: number; scope: Scope }
80 /** The context warning was given and still applies. */
81 warned: boolean
82 /** Claude was told to wind down, and a plan window is still past the refusal threshold. */
83 windDown: boolean
84 /** A Stop hook reopened the current turn, so "end the turn" cannot clear a block. */
85 reopened: boolean
86 dormantResumes: number[]
87}
88
89/** What one session publishes for the others: counts, never content. */
90export type PeerRecord = {
91 v: 2
92 /** When the session last made a model request or changed this record. */
93 at: number
94 running: number
95 starts: number[]
96 /** Subagent tokens per minute, as [the minute's latest time, tokens], so they age out like starts. */
97 agentTokens: Array<[number, number]>
98 dormantResumes: number[]
99 limit?: LimitReading
100}
101
102export function newSession(id: string, canAsk: boolean): SessionState {
103 return {
104 id,
105 canAsk,
106 loops: {},
107 agents: {},
108 pendingStarts: 0,
109 unclaimed: {},
110 starts: [],
111 agentTokens: [],
112 limits: {},
113 limitHistory: [],
114 leases: {},
115 refusals: {},
116 denials: [],
117 failures: {},
118 warned: false,
119 windDown: false,
120 reopened: false,
121 dormantResumes: [],
122 }
123}
124
125export function loopOf(state: SessionState, id: LoopId): LoopState {
126 const existing = state.loops[id]
127 if (existing) return existing
128 const created: LoopState = { heavyCalls: [] }
129 state.loops[id] = created
130 return created
131}
132
133export function within(times: readonly number[], now: number, windowMs: number): number[] {
134 return times.filter((t) => now - t < windowMs)
135}
136
137/** Tokens of the [time, tokens] pairs inside the window. */
138export function tokensWithin(pairs: ReadonlyArray<readonly [number, number]>, now: number, windowMs: number): number {
139 return pairs.reduce((sum, [t, n]) => (now - t < windowMs ? sum + n : sum), 0)
140}
141
142/** Entries of one rolling list inside the window, in this session and its peers together. */
143export function countOnMachine(
144 state: SessionState,
145 peers: readonly PeerRecord[],
146 list: 'starts' | 'dormantResumes',
147 now: number,
148 windowMs: number,
149): number {
150 return [state[list], ...peers.map((p) => p[list])].reduce((sum, times) => sum + within(times, now, windowMs).length, 0)
151}
152
153/** Running agents, counting those allowed a moment ago that are still starting. */
154export function runningAgents(state: SessionState): number {
155 return Object.values(state.agents).filter((a) => a.running).length + state.pendingStarts
156}
157
158export function overrideCovers(state: SessionState, now: number, scope: Exclude<Scope, 'all'>): boolean {
159 const override = state.override
160 if (!override || now >= override.until) return false
161 return override.scope === 'all' || override.scope === scope
162}
163
164/** Drops what has aged out of every rolling list, so the state stays small. */
165export function prune(state: SessionState, now: number, windowMs: number): void {
166 state.starts = within(state.starts, now, windowMs)
167 state.agentTokens = state.agentTokens.filter(([t]) => now - t < windowMs)
168 state.limitHistory = state.limitHistory.filter((r) => now - r.at < windowMs)
169 state.denials = state.denials.filter((d) => now - d.at < windowMs)
170 state.dormantResumes = within(state.dormantResumes, now, windowMs)
171 for (const [key, until] of Object.entries(state.leases)) if (now >= until) delete state.leases[key]
172 for (const [key, until] of Object.entries(state.refusals)) if (now >= until) delete state.refusals[key]
173 for (const [key, failure] of Object.entries(state.failures)) {
174 if (now - failure.last >= windowMs) delete state.failures[key]
175 }
176 for (const loop of Object.values(state.loops)) loop.heavyCalls = within(loop.heavyCalls, now, windowMs)
177 if (state.fuseUntil !== undefined && now >= state.fuseUntil) delete state.fuseUntil
178 if (state.override && now >= state.override.until) delete state.override
179}
180
181/** The record this session publishes for its peers. */
182export function peerRecord(state: SessionState, now: number, windowMs: number): PeerRecord {
183 const fiveHour = state.limits.five_hour
184 return {
185 v: 2,
186 at: now,
187 running: runningAgents(state),
188 starts: within(state.starts, now, windowMs),
189 agentTokens: perMinute(state.agentTokens, now, windowMs),
190 dormantResumes: within(state.dormantResumes, now, windowMs),
191 ...(fiveHour ? { limit: fiveHour } : {}),
192 }
193}
194
195/** Sums [time, tokens] pairs inside the window per minute, so a record stays small however busy its session. */
196function perMinute(pairs: ReadonlyArray<readonly [number, number]>, now: number, windowMs: number): Array<[number, number]> {
197 const minutes = new Map<number, [number, number]>()
198 for (const [t, n] of pairs) {
199 if (now - t >= windowMs) continue
200 const key = Math.floor(t / 60_000)
201 const minute = minutes.get(key)
202 if (minute) {
203 minute[0] = Math.max(minute[0], t)
204 minute[1] += n
205 } else {
206 minutes.set(key, [t, n])
207 }
208 }
209 return [...minutes.values()]
210}
211
212/**
213 * Accepts only records that look like ours and are fresh: a session that has
214 * made no model request for `ttlMs` is not spending, so its agents stop
215 * counting even if it crashed without clearing its record.
216 */
217export function livePeers(records: readonly unknown[], now: number, ttlMs: number): PeerRecord[] {
218 const peers: PeerRecord[] = []
219 for (const record of records) {
220 if (!isPeerRecord(record)) continue
221 if (now - record.at > ttlMs) continue
222 peers.push(record)
223 }
224 return peers
225}
226
227function isPeerRecord(value: unknown): value is PeerRecord {
228 if (typeof value !== 'object' || value === null) return false
229 const r = value as Record<string, unknown>
230 return (
231 r.v === 2 &&
232 typeof r.at === 'number' &&
233 typeof r.running === 'number' &&
234 Array.isArray(r.starts) &&
235 Array.isArray(r.agentTokens) &&
236 r.agentTokens.every((p) => Array.isArray(p) && typeof p[0] === 'number' && typeof p[1] === 'number') &&
237 Array.isArray(r.dormantResumes)
238 )
239}
240core/status.ts 108 lines1// What the user sees without asking: one status line while something needs
2// attention, and the `/agent-guard` command's text.
3
4import { highestLimit } from './agents.ts'
5import type { Config } from './config.ts'
6import { MAIN, type PeerRecord, type Scope, type SessionState, countOnMachine, runningAgents } from './state.ts'
7import { count, duration, shortClock, tokens, windowName } from './text.ts'
8
9/** The line under the prompt, or undefined when there is nothing to say. */
10export function statusLine(state: SessionState, peers: readonly PeerRecord[], config: Config, now: number): string | undefined {
11 if (!config.enabled) return undefined
12 const parts = liftedOrPaused(state, now)
13 const limit = highestLimit(state, peers, now)
14 if (limit && limit.percent >= config.limitDenyPercent) {
15 parts.push(`${windowName(limit.kind)} window ${limit.percent}%: new agents refused`)
16 } else if (limit && limit.percent >= config.limitAskPercent) {
17 parts.push(`${windowName(limit.kind)} window ${limit.percent}%: new agents need approval`)
18 }
19 const context = state.loops[MAIN]?.context
20 if (context !== undefined && context >= config.contextHard) {
21 parts.push(`context ${tokens(context)}: /compact recommended`)
22 } else if (context !== undefined && context >= config.contextWarn) {
23 parts.push(`context ${tokens(context)}`)
24 }
25 return parts.length > 0 ? parts.join(' · ') : undefined
26}
27
28/** When the line changes with no event to redraw it: an allow or the fuse ends, or the most-used plan window resets. */
29export function statusLineExpiry(state: SessionState, peers: readonly PeerRecord[], config: Config, now: number): number | undefined {
30 if (!config.enabled) return undefined
31 const times = [state.override?.until, state.fuseUntil, highestLimit(state, peers, now)?.resetsAt]
32 const later = times.filter((t): t is number => t !== undefined && t > now)
33 return later.length > 0 ? Math.min(...later) : undefined
34}
35
36/** What is lifted or paused now, worded alike in the status line and the report. */
37function liftedOrPaused(state: SessionState, now: number): string[] {
38 const parts: string[] = []
39 if (state.override && now < state.override.until) {
40 parts.push(`${scopeName(state.override.scope)} lifted until ${shortClock(state.override.until)}`)
41 }
42 if (state.fuseUntil !== undefined && now < state.fuseUntil) {
43 parts.push(`agent spawns paused until ${shortClock(state.fuseUntil)}`)
44 }
45 return parts
46}
47
48export function scopeName(scope: Scope): string {
49 if (scope === 'agents') return 'agent limits'
50 if (scope === 'context') return 'context limits'
51 return 'all limits'
52}
53
54/** The text `/agent-guard` and `/agent-guard status` print. */
55export function statusReport(
56 state: SessionState,
57 peers: readonly PeerRecord[],
58 config: Config,
59 now: number,
60 problems: readonly string[],
61 version?: string,
62): string {
63 const running = version ? ` (${version})` : ''
64 if (!config.enabled) return `Off${running}: AGENT_GUARD is set to turn it off.`
65 const window = config.windowMs
66 const lines = [`On${running}.`]
67
68 const peerRunning = peers.reduce((sum, p) => sum + p.running, 0)
69 const starts = countOnMachine(state, peers, 'starts', now, window)
70 lines.push(
71 `Agents: ${runningAgents(state)} running here, ${peerRunning} in ${count(peers.length, 'other session')} (limit ${config.agentMax}); ${starts} started in the last ${duration(window)} (limit ${config.rollingMax}).`,
72 )
73
74 const limits = Object.values(state.limits).filter((r) => r.resetsAt === undefined || r.resetsAt > now)
75 if (limits.length > 0) {
76 const text = limits
77 .map((r) => `${windowName(r.kind)} ${r.percent}%${r.resetsAt === undefined ? '' : ` (resets ${shortClock(r.resetsAt)})`}`)
78 .join(', ')
79 lines.push(`Plan windows: ${text}. New agents ask from ${config.limitAskPercent}% and are refused from ${config.limitDenyPercent}%.`)
80 } else {
81 lines.push('Plan windows: no reading yet (one arrives with the next response on a subscription).')
82 }
83
84 const context = state.loops[MAIN]?.context
85 lines.push(
86 `Context: ${context === undefined ? 'unknown until the next response' : `${tokens(context)} tokens`} (warn ${tokens(config.contextWarn)}, ask before a prompt from ${tokens(config.contextHard)}).`,
87 )
88
89 const held = liftedOrPaused(state, now)
90 for (const [key, until] of Object.entries(state.leases)) {
91 if (now < until) held.push(`${key} approved${until < Number.MAX_SAFE_INTEGER ? ` until ${shortClock(until)}` : ' until the context shrinks'}`)
92 }
93 for (const [key, until] of Object.entries(state.refusals)) if (now < until) held.push(`${key} declined until ${shortClock(until)}`)
94 if (held.length > 0) lines.push(`Now: ${held.join('; ')}.`)
95 for (const problem of problems) lines.push(`Config: ${problem}.`)
96 lines.push('', USAGE)
97 return lines.join('\n')
98}
99
100export const USAGE = [
101 'Commands:',
102 ' /agent-guard allow [agents|context] [minutes] lift the guard\'s limits for this session (default: all, 10 min)',
103 ' /agent-guard pause [minutes] same as allow, for every limit',
104 ' /agent-guard resume end an allow or pause early, and clear declined questions',
105 ' /agent-guard report [days] what the guard did on this machine (default 7 days)',
106 ' /agent-guard status this summary',
107].join('\n')
108core/text.ts 94 lines1// Formatting shared by every message the guard writes.
2
3/** `1 agent`, `4 agents`. */
4export function count(n: number, noun: string): string {
5 return `${n} ${noun}${n === 1 ? '' : 's'}`
6}
7
8/** Lists details as prose: "a", "a and b", "a, b and c". */
9export function join(details: readonly string[]): string {
10 if (details.length <= 1) return details.join('')
11 return `${details.slice(0, -1).join(', ')} and ${details.at(-1)}`
12}
13
14/** Capitalises the first letter of a sentence assembled from parts. */
15export function sentence(text: string): string {
16 return text.charAt(0).toUpperCase() + text.slice(1)
17}
18
19export function tokens(n: number): string {
20 if (n >= 1_000_000) return `${trim(n / 1_000_000)}M`
21 if (n >= 1000) return `${Math.round(n / 1000)}k`
22 return String(n)
23}
24
25function trim(value: number): string {
26 return value >= 100 ? String(Math.round(value)) : value.toFixed(1).replace(/\.0$/, '')
27}
28
29/** Local wall-clock time, `14:32:07`. */
30export function clock(ms: number): string {
31 const d = new Date(ms)
32 return [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, '0')).join(':')
33}
34
35/** Local time without seconds, `14:32`. */
36export function shortClock(ms: number): string {
37 return clock(ms).slice(0, 5)
38}
39
40/** `45 s`, `12 min`, `2 h 5 min`. */
41export function duration(ms: number): string {
42 const seconds = Math.round(ms / 1000)
43 if (seconds < 60) return `${seconds} s`
44 const minutes = Math.round(seconds / 60)
45 if (minutes < 60) return `${minutes} min`
46 const hours = Math.floor(minutes / 60)
47 const rest = minutes % 60
48 return rest ? `${hours} h ${rest} min` : `${hours} h`
49}
50
51const WINDOW_NAMES: Record<string, string> = {
52 five_hour: '5-hour',
53 seven_day: 'weekly',
54 spend_limit: 'spend',
55}
56
57export function windowName(kind: string): string {
58 return WINDOW_NAMES[kind] ?? kind.replaceAll('_', ' ')
59}
60
61/** Coarse context bucket for the journal, never an exact figure. */
62export function contextBucket(n: number | undefined): string | undefined {
63 if (n === undefined) return undefined
64 if (n < 150_000) return '<150k'
65 if (n < 300_000) return '150-300k'
66 if (n < 400_000) return '300-400k'
67 if (n < 500_000) return '400-500k'
68 return '>=500k'
69}
70
71/** FNV-1a over the text, as 13 base-36 digits. Identifies a call without storing it. */
72export function fingerprint(text: string): string {
73 let hash = 0xcbf29ce484222325n
74 const prime = 0x100000001b3n
75 const mask = 0xffffffffffffffffn
76 for (let i = 0; i < text.length; i++) {
77 hash ^= BigInt(text.charCodeAt(i))
78 hash = (hash * prime) & mask
79 }
80 return hash.toString(36).padStart(13, '0')
81}
82
83/** JSON with sorted keys, so equal inputs give equal fingerprints. */
84export function canonical(value: unknown): string {
85 if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
86 if (value && typeof value === 'object') {
87 const entries = Object.entries(value as Record<string, unknown>)
88 .filter(([, v]) => v !== undefined)
89 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
90 return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`
91 }
92 return JSON.stringify(value) ?? 'null'
93}
94