Compacts before the 5-hour/weekly usage limit is hit, pauses until it resets, then resumes the task automatically.

A Claude Code mod (plugin of function hooks) that handles usage limits for you:
Early-access API: written against Claude Code 2.1.289+ Mods (
claude-codehooks API). It may need updates as that API changes.
Clone the repo, then use one of these. Use only one: two routes load two plugins both named quota-guard.
Add CLAUDE_CODE_PLUGIN_DIRS to the env block of your user settings file, ~/.claude/settings.json (on Windows C:\Users\<you>\.claude\settings.json), keeping your other keys:
{
"env": {
"CLAUDE_CODE_PLUGIN_DIRS": "C:/Users/you/code/claude-quota-guard"
}
}
; on Windows (: on macOS/Linux).env block of the user settings file. It is never read from project settings (.claude/settings.json or .claude/settings.local.json in a repo); putting it there does nothing.git pull to update. A terminal session reloads it when a file is saved. The Desktop Code tab does not watch the folder unless you also set CLAUDE_CODE_PLUGIN_DIR_WATCH to 1 in the same env block; without it, restart the session after updating the mod.CLAUDE_CODE_PLUGIN_DIRS is already set in the environment a session is launched with, that value wins over the settings file.claude --plugin-dir /path/to/claude-quota-guard
~/.claude/skills/quota-guardThis also auto-loads, but it is a copy: it does not follow the repo, so it drifts. Prefer the folder route above.
/quota status (/quota-guard status is an alias). It prints the thresholds and State: IDLE.quota-guard · waiting for first usage reading./quota is an unknown command: the plugin is not loaded. Run claude --debug and look for quota-guard: lines. A healthy start has hooks module quota-guard@inline loaded and $.command.register (quota-guard): /quota listed.env block (not a project file), that the path exists, and that you started a new session.reload failed, the previous version stays loaded (while editing): the message names the offending function or line.~/.claude/skills/quota-guard, a hot-reload copy, plus the settings entry).claude -p, an SDK run with no surface) are never paused: nobody would be there to resume them, so the mod stays out of the way.$.session.compact is refused outright ("not available in a headless (-p / SDK) session yet"; measured on Claude Code 2.1.299, the version Desktop bundles). The mod then queues the built-in /compact command through $.command.run instead. In a terminal session the direct call works and is used./compact runs once the session is idle. The mod tags its instructions with the operation that asked, reads the outcome in its own session.compact hook (the summarizer never sees the tag), and never takes the command's reply as proof: a successful /compact replies with no text.Not compacted — quota-guard: this queued compaction is no longer needed./compact, or auto-compact, while the mod's request is queued counts as the pause's compaction./quota status shows the last quota compaction and the last resume prompt as they actually went: the route ($.session.compact or the /compact command), the number of calls, the engine's own words for a refusal, veto or failure, token counts, the engine version and the build. It shows them after a failure too, and across reloads.| Command | What it does | |||||||
|---|---|---|---|---|---|---|---|---|
/quota status (alias /quota-guard) | usage windows, thresholds, state, task on record | |||||||
/quota on / off | enable / disable automatic management | |||||||
/quota threshold N | 5-hour threshold (50-100; default 98). A running turn is interrupted above it (default 99); setting the threshold at or above that point moves the interruption to N+1 | |||||||
/quota weekly N | weekly threshold | |||||||
/quota ctxmin N | compact before pausing only if context is above N% (default 30) | |||||||
/quota pause [min] | force a pause (compacts per the context rule) for testing | |||||||
/quota cancel | cancel the pending auto-resume (holds until you act) | |||||||
/quota resume | resume now | |||||||
| `/quota idle [on\ | off\ | any\ | waiting\ | min N\ | ttl M\ | margin S\ | fail N]` | idle compaction: status and settings; fail N rehearses N rejected attempts |
/quota ctx [close] | open / close the full context pane |
Settings changed with a /quota command are saved in the plugin's shared store, and they are saved whole: once any of them has been changed (threshold, coord, idle, test and so on), that saved configuration, thresholds included, wins over the defaults. A store saved by an earlier version therefore keeps its 94% threshold until you run /quota threshold 98. Each session picks the change up when it next loads.
Prompt-cache reads are about a tenth of the price of fresh input. If a session sits idle longer than the cache lifetime, the next request re-sends the whole context at full price. Compacting just before the cache expires reads the context at the cheap cached rate and leaves a small context behind.
idleMarginSeconds (default 180) before the cache would expire, when no turn is running and the context is at least idleCompactMinTokens (default 200,000)./quota idle waiting (or the idleRequiresBackground setting) restricts it to sessions waiting on a background command, monitor or agent; then the summary is told what it is waiting on.cacheTtlMinutes, default 60). If your sessions use the 5-minute cache, run /quota idle ttl 5./quota status shows the last attempt and its outcome (ok, skipped with the reason, or failed); a refused attempt is retried up to three more times while the cache is warm./quota status shows the attempt window, the engine's exact skip or error text, tokens before and after, the cache's expiry, and the build id (compare it with version in plugin.json to confirm which source a session loaded). A statistics-store error is shown as a warning and never turns a successful compaction into a failure. /quota idle fail N rehearses N rejected attempts so you can watch the retry policy live.Every open session shares the same account limits, so after a reset they all wake together. Without help, sessions stagger themselves through the plugin's shared store, which is best-effort: the store has no compare-and-set, so two sessions can claim the same slot. The optional helper removes that race.
helper/quota_guard_helper.py is one small local service: Python 3 and its standard library only (tested on 3.7 and 3.12; Python is the one extra thing anybody receiving this repo must have). It keeps reservations in one SQLite database and decides every admission inside a BEGIN IMMEDIATE transaction, so processes cannot both see a slot as free.127.0.0.1:47823 runs the bundled script with Python (py -3, then python, then python3) as a background process of its own, which outlives that session. Its output goes to ~/.quota-guard/helper.log, next to the database ~/.quota-guard/coord.db. A helper that stops answering is started again, within a minute, by the next session that needs it./quota status says to stop it once so the bundled one takes its place./quota coord off stops using it (saved: every session follows when it next loads); /quota coord helper [url] uses it again and starts it at once if needed; /quota coord check tests reachability. A helper at another address is used but never started. Running it yourself still works: python helper/quota_guard_helper.py./quota status (the Helper: line) says what was tried. The Helper: line also says whether this session started the helper, found it running, or found an older one./quota status and a notice identify the fallback; the next automatic resume tries the helper again. A reachable helper's pending probe, spacing and quota refusal are still respected. /quota resume bypasses helper admission.helper/).A session only learns the account's usage from its own responses. A session sitting in one long tool call (a build, a test run, a wait) gets no reading at all, while other sessions of the account may be spending the same 5-hour window. Live, a session sat in one command for 3.5 minutes while other sessions took the account to its limit, and it saw none of it. With the helper configured:
/quota status has a Usage sharing line: when this session last shared, and the last higher figure another session reported. A helper started before this version answers that it does not know the endpoints. Sharing then stays off with one notice, and coordination is unaffected. Stop that helper once: quota-guard starts the current one. GET /state lists the readings it holds.The tests use a mocked engine, so confirm it once in a real session (a spare one). The helper is not needed for this.
/reload-plugins, then /quota status: the line ends with build <version>; compare it with version in .claude-plugin/plugin.json./quota idle ttl 5, /quota idle margin 180, /quota idle min 1k./quota idle fail 2 straight after the answer, before the first attempt: the attempts fall at about 2:00 (rejected), 2:30 (rejected) and 3:00 (compacts); the cache stays warm until 5:00. (A shorter ttl cannot work: a retry that would land at expiry is refused on purpose.)/quota status shows each attempt's outcome (on Desktop, ok via the /compact command), the engine's token counts and, when the engine reports it, the summarizer's cache read/write counts (otherwise "cache usage unavailable"). The transcript gains a compaction boundary./quota idle fail 0, /quota idle ttl 60, /quota idle margin 180, /quota idle min 200k.Simulated quota, real actions: the compaction is real (it costs one summary request), the usage is not. Use a spare Desktop session with some conversation in it.
/reload-plugins, then /quota status: the build at the end of the idle line matches version in .claude-plugin/plugin.json./quota test on, /quota test actions real, /quota sim clear, /quota sim ctx 50./quota pause 1. Expect a compaction boundary in the transcript and a toast Paused until approximately HH:MM. /quota status shows Last quota compaction (op N): OK ... via the /compact command with token counts and engine 2.1.299 (or whatever your Desktop bundles).[quota-guard recovery #N], with the toast Quota reset verified; the task is continuing. /quota status shows Last resume prompt (op N): accepted ... its turn started HH:MM and State: IDLE. Do not type while it runs: your own prompt is a takeover./quota coord helper with no helper running before step 3; the continuation still comes, with a notice that the shared store's spacing was used./quota test off.If a step does not happen, /quota status shows what the engine answered instead; that text is what to report.
No need to burn real quota:
/quota test on simulated usage, dry-run actions
/quota sim 80 heads-up only
/quota sim 98 compact, then pause (any percentage works: /quota sim N [minutes to reset])
/quota sim at 99 fg.log the next tool call whose input contains "fg.log" moves usage to 99%: the limit
arriving mid-turn (a slash command typed during a turn waits for the turn to end in an
SDK host such as Desktop, so this is how to rehearse an interrupted turn there)
/quota sim exhausted
/quota sim reset60 100% used, resets in 60 s
/quota sim reset-ok usage drops after the reset (default)
/quota sim reset-fail reset time slips by 2 minutes once
/quota sim reset-delay first resume attempt fails, second works
/quota sim weekly
/quota sim ctx N simulate context fill (try 20 vs 50 around the 30% rule)
/quota sim unavailable toggle usage data off/on
/quota sim restart drop memory and reload from the store while paused
/quota test actions real do real compaction/prompts under simulated usage
/quota test off
hooks/core.ts is a pure state machine (idle -> armed -> compacting -> paused -> resuming -> idle, plus a manual stopped hold). No engine imports; unit-tested.hooks/register.tsx is the adapter: session.measure for usage, $.session.compact or the queued /compact command, $.turn.abort, $.prompt.submit, $.store for persistence, $.clock for the heartbeat, ui.render for the bar and pane.hooks/transport.ts names what the engine's answers mean (its refusal texts, the operation tag, the /compact command's reply), so that classification is unit-tested against the exact strings.[quota-guard recovery #N] marker); an accepted prompt is not enough. A continuation that was accepted but has not started within 3 minutes, while nothing else is running, stops auto-resume with a notice. It is not sent again, because a late start would then run it twice. /quota resume or a prompt of your own continues from there./quota included. To rehearse the limit arriving mid-turn, use /quota sim at (below)./quota status give the engine's reason./compact command, so it waits until the session is idle.<system-reminder> messages such as "The session ... you started finished a turn") as prompts of the same kind as your typing. They are treated as notices: kept during a pause and delivered with the continuation, never a takeover of the pause, never the task on record. Live, before this, one such note cancelled a pause 20 minutes in, and another ran straight into the exhausted limit.hooks/register.tsx 2161 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { CtxDetail, QuotaBar } from '../types'
5
6import {
7 DEFAULTS,
8 FIVE,
9 WEEK,
10 blocksAutomation,
11 describeWindow,
12 fmtClock,
13 fmtDur,
14 heldNotices,
15 initialState,
16 needsHeartbeat,
17 resumeMarker,
18 resumePrompt,
19 statusLine,
20 step,
21} from './core'
22import type { Config, Ev, Fx, State, Usage, Win } from './core'
23import { IDLE_DEFAULTS, clearOnNotification, freshPending, idleInstructions, pendingFromTool, planIdleCompact } from './idle'
24import type { IdleCfg, Pending } from './idle'
25import { classifyRefusal, readCommandText, readTag, tagInstructions } from './transport'
26
27const HEARTBEAT_MS = 30_000
28const USER_KINDS = ['composer', 'bridge', 'sdk', 'slack-ping']
29// Claude Desktop sends its own status notes ("The session ... you started finished a turn") into a session as prompts of
30// the same kind as the person's typing, wrapped in <system-reminder>. They are notices, not the person: during a pause
31// they are kept for the continuation, and they never cancel a pause or become the task on record.
32const injectedNote = (text: string) => /^\s*<system-reminder>/.test(text)
33const PREFIX = 'quota-guard: '
34const bar = atom({ plugin: 'quota-guard', key: 'bar' } as const, null)
35const detail = atom({ plugin: 'quota-guard', key: 'detail' } as const, null)
36const PANE = 'quota-ctx'
37
38const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
39const when = (w: Win | undefined, now: number) => {
40 if (!w?.resetsAt || w.resetsAt <= now) return undefined
41 return w.resetsAt - now > 20 * 3600_000 ? `${DAYS[new Date(w.resetsAt).getDay()]} ${fmtClock(w.resetsAt)}` : fmtClock(w.resetsAt)
42}
43const tok = (n?: number) => (n === undefined ? '' : n >= 1_000_000 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`)
44const CELLS = 10
45const filled = (pct: number) => Math.max(0, Math.min(CELLS, Math.round((pct / 100) * CELLS)))
46const fmtTok = (n: number) => (n >= 1_000_000 ? `${(n / 1e6).toFixed(2)}M` : n >= 10_000 ? `${Math.round(n / 1000)}k` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(Math.round(n)))
47const tail = (path: string) => path.split(/[\\/]/).slice(-2).join('/')
48
49function buildDetail(b: any, api: any): CtxDetail {
50 const win = b.rawMaxTokens || b.maxTokens || 1
51 const mcp = new Map<string, number>()
52 for (const t of b.mcpTools ?? []) mcp.set(t.serverName, (mcp.get(t.serverName) ?? 0) + (t.isLoaded ? t.tokens : 0))
53 return {
54 model: b.model,
55 total: b.totalTokens,
56 window: win,
57 percent: b.percentage,
58 autoAt: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined,
59 categories: (b.categories ?? []).map((c: any) => ({ name: c.name, tokens: c.tokens, kind: c.kind })),
60 memory: (b.memoryFiles ?? []).map((m: any) => ({ path: tail(m.path), tokens: m.tokens })).sort((x: any, y: any) => y.tokens - x.tokens).slice(0, 8),
61 mcp: [...mcp.entries()].map(([server, tokens]) => ({ server, tokens })).sort((x, y) => y.tokens - x.tokens).slice(0, 8),
62 agents: (b.agents ?? []).map((a: any) => ({ name: a.agentType, tokens: a.tokens })).sort((x: any, y: any) => y.tokens - x.tokens).slice(0, 6),
63 skills: b.skills ? { count: b.skills.includedSkills ?? b.skills.totalSkills, total: b.skills.totalSkills, tokens: b.skills.tokens, top: (b.skills.skillFrontmatter ?? []).map((k: any) => ({ name: k.name, tokens: k.tokens })).sort((x: any, y: any) => y.tokens - x.tokens).slice(0, 6) } : undefined,
64 api: api ? { input: api.input_tokens, cacheRead: api.cache_read_input_tokens, cacheWrite: api.cache_creation_input_tokens, output: api.output_tokens } : undefined,
65 }
66}
67
68// one distinct colour per category, assigned by size rank so the bar and the list always agree
69const PALETTE = ['green', 'cyan', 'yellow', 'magenta', 'red', 'blue', 'white']
70const colorAt = (rank: number) => PALETTE[rank % PALETTE.length] ?? 'white'
71// Continuous bar: each segment is as wide as its share of the whole window, so the
72// filled part is always exactly the context percentage. Segments are sized in cells
73// (fractions allowed; the engine refuses fractional percentages).
74// Remote surfaces (desktop, editor, mobile) can draw vectors: a rounded pill with a soft
75// track, segments clipped to it, and a hairline where compaction starts to apply.
76const HEX = ['#3fb950', '#22b8cf', '#e3b341', '#c678dd', '#f0626b', '#5b8def', '#adb5bd']
77const hexAt = (rank: number) => HEX[rank % HEX.length] ?? '#adb5bd'
78
79function ctxPill(Svg: any, segs: { pct: number; hex: string }[], w: number, bh: number, tickPct?: number) {
80 const pad = 2
81 const H = bh + pad * 2
82 let x = 0
83 const bars = segs
84 .filter(sg => sg.pct > 0)
85 .map(sg => {
86 const sw = Math.max(0, Math.min(w - x, (sg.pct / 100) * w))
87 const out = `<rect x="${x.toFixed(2)}" y="${pad}" width="${sw.toFixed(2)}" height="${bh}" fill="${sg.hex}"/>`
88 x += sw
89 return out
90 })
91 .join('')
92 const tickMark = tickPct && tickPct > 0 && tickPct < 100 ? `<rect x="${((tickPct / 100) * w - 0.6).toFixed(2)}" y="0" width="1.2" height="${H}" rx="0.6" fill="#8b949e" opacity="0.85"/>` : ''
93 const source =
94 `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${H}" viewBox="0 0 ${w} ${H}">` +
95 `<defs><clipPath id="p"><rect x="0" y="${pad}" width="${w}" height="${bh}" rx="${bh / 2}"/></clipPath></defs>` +
96 `<rect x="0" y="${pad}" width="${w}" height="${bh}" rx="${bh / 2}" fill="#8b949e" fill-opacity="0.28"/>` +
97 `<g clip-path="url(#p)">${bars}</g>${tickMark}</svg>`
98 return <Svg source={source} alt="Context window usage" width={w} height={H} />
99}
100
101function swatch(Svg: any, hex: string) {
102 return (
103 <Svg
104 source={`<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"><rect width="10" height="10" rx="3" fill="${hex}"/></svg>`}
105 alt="category colour"
106 width={10}
107 height={10}
108 />
109 )
110}
111
112function ctxBar(Box: any, segs: { pct: number; color: string }[], width: number) {
113 return (
114 <Box width={width} height={1} flexShrink={0} backgroundColor="gray">
115 {segs
116 .filter(x => x.pct > 0)
117 .map(x => (
118 <Box width={Math.max(0, Math.min(width, (x.pct / 100) * width))} height={1} flexShrink={0} backgroundColor={x.color} />
119 ))}
120 </Box>
121 )
122}
123
124const tone = (pct: number) => (pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'green')
125
126type Sim = {
127 five: { percent: number; resetsAt: number }
128 week?: { percent: number; resetsAt: number }
129 mode: 'ok' | 'fail' | 'delay'
130 failedOnce: boolean
131 probeFails: number
132 unavailable: boolean
133 ctx?: number
134 // a rehearsal of the limit arriving mid-turn: the next tool call whose input contains `marker` moves five-hour
135 // usage to `pct` and takes a reading, as a real response would report it. Needed where a slash command typed
136 // during a turn waits for the turn to end (an SDK host, so Claude Desktop), and so cannot move usage mid-turn.
137 at?: { pct: number; marker: string }
138}
139
140type Overrides = Partial<Config> & { testMode?: boolean; dryActions?: boolean; legend?: boolean; idle?: Partial<IdleCfg>; helperUrl?: string; helperOff?: boolean }
141
142let S: State | null = null
143let cfg: Config = { ...DEFAULTS }
144// Account-wide coordination helper, used unless /quota coord off (empty = best-effort coordination through the shared store)
145// Identifies the source a running session loaded: bump it with `version` in plugin.json on every release.
146const BUILD = '0.3.6-helper-autostart'
147const DEFAULT_HELPER = 'http://127.0.0.1:47823'
148let helperUrl = ''
149let testMode = false
150let dryActions = true
151let legend = false
152let sim: Sim | null = null
153let sid = ''
154let turnId: string | undefined
155let timer: { cancel: () => void } | undefined
156let loading: Promise<void> | undefined
157let lastText = ''
158let idleCfg: IdleCfg = { ...IDLE_DEFAULTS }
159let waiting: Pending[] = [] // background work the session is currently waiting on
160let lastResponseAt: number | undefined
161// One idle cycle protects one response's cache. `idleCycle` identifies it; every wait inside an attempt is
162// followed by a check that the cycle (and the session) is still the one that started it, so an old result can
163// never touch the budget, timer or outcome of a newer response.
164type IdleAttempt = {
165 cycle: number
166 at: number // when the attempt started
167 endedAt?: number
168 expiresAt: number // when the cache it was protecting lapses
169 outcome: 'running' | 'ok' | 'vetoed' | 'failed' | 'exhausted' | 'cold'
170 detail: string
171 tokensBefore?: number
172 tokensAfter?: number
173 usage?: { cacheRead?: number; cacheCreation?: number; input?: number; output?: number } // the summarizer's own request, when the engine reported it
174 warn?: string // a problem AFTER the engine's answer (stats not saved): never turns a success into a failure
175 route?: CompactRoute
176}
177let idleAttempt: IdleAttempt | undefined
178let idleCycle = 0
179let idleRun = 0 // id of the attempt in flight, 0 = none
180let idleRunSeq = 0
181let idleHandled: 'ok' | 'vetoed' | 'exhausted' | undefined // terminal outcome of idleCycle
182let idleTries = 0
183let lastIdleCompactAt: number | undefined
184let idleTimer: { cancel: () => void } | undefined
185let idleStats: { at: number; before: number; count: number } | undefined
186let warned = false
187// bumped when a session ends: everything started before that (loads, effects, retries) belongs to the
188// old session and must neither mutate the new one nor reuse its operation numbers
189let epoch = 0
190let turnSeq = 0 // bumped by every turn.start: a queued idle compaction is not wanted once the person is working again
191// What the last quota compaction and resume prompt actually did, in the engine's own words. Kept per session in the
192// store so a reload, a restart or a later look at /quota status still shows why an automatic step did not happen.
193type Diag = {
194 compaction?: { op: number; session: string; gen: number; startedAt: number; endedAt: number; route: CompactRoute; attempts: number; outcome: CompactOutcome['outcome']; detail: string; tokensBefore?: number; tokensAfter?: number; engine?: string; build: string }
195 submit?: { op: number; session: string; gen: number; at: number; attempts: number; manual: boolean; outcome: 'accepted' | 'dropped' | 'refused' | 'stale'; detail: string; startedAt?: number; engine?: string; build: string }
196}
197let diag: Diag = {}
198let engineVersion: string | undefined
199let startSeen: { op: number; gen: number; at: number } | undefined // the last continuation turn that started
200let lastTouchAt = 0
201let booted = false
202// Usage sharing through the helper. A session's own readings arrive only with its own responses, so one sitting in a
203// long tool call cannot see the account's other sessions spend the shared limit. Every session reports its own
204// readings; while a turn runs, it asks every SHARE_PEEK_MS for the highest reading another session reported for the
205// same windows, and a higher one counts as the account's usage.
206const SHARE_PEEK_MS = 30_000
207let shareTimer: { cancel: () => void } | undefined
208let ownReading: Usage | null = null // this session's latest own reading (the simulated one in test mode)
209let sharedHigh: Win[] = [] // the highest readings other sessions reported for this session's windows
210const shareSent = new Map<string, string>() // per account, the last reading reported: an unchanged one is not resent
211let share: { reportedAt?: number; peekedAt?: number; raised?: { text: string; at: number }; unsupported?: boolean } = {}
212const STAGGER_MS = 20_000
213const MAX_STAGGER_MS = 120_000
214
215let commandReady = false
216async function registerCommand($: any) {
217 if (commandReady) return
218 const spec = {
219 description: 'Quota guard: status, on/off, threshold, pause, cancel, resume, test',
220 argumentHint: '[status|on|off|threshold N|weekly N|ctxmin N|idle [on|off|any|waiting|min N|ttl M|margin S|fail N]|ctx [close]|coord [check|helper [url]|off]|pause [min]|cancel|resume|test on|off|sim ...]',
221 immediate: true as const,
222 }
223 try {
224 await $.command.register({ name: 'quota', ...spec })
225 await $.command.register({ name: 'quota-guard', ...spec })
226 commandReady = true
227 } catch (err) {
228 $.ui.log(PREFIX + `could not register /quota: ${String(err)}`)
229 }
230}
231
232let options: Readonly<Record<string, string | number | boolean | readonly string[]>> = {}
233const num = (k: string, d: number) => (typeof options[k] === 'number' ? (options[k] as number) : d)
234
235async function load($: any): Promise<void> {
236 const gen = epoch
237 await registerCommand($)
238 // read and build everything into locals first; publish only when all of it succeeded, so a failure
239 // part-way leaves nothing half-initialised for the next hook to mistake for a good start
240 const id = await $.session.id()
241 const saved = (await $.store.get('state:' + id)) as State | undefined
242 const o = ((await $.store.get('cfg')) ?? {}) as Overrides
243 const idle = ((await $.store.get('idle:' + id)) as typeof idleStats) ?? undefined
244 const simSaved = ((await $.store.get('sim')) as Sim | undefined) ?? null
245 const diagSaved = ((await $.store.get('diag:' + id)) as Diag | undefined) ?? {}
246
247 const { testMode: tm, dryActions: da, legend: lg, idle: oIdle, helperUrl: oHelper, helperOff: oHelperOff, ...rest } = o
248 const nextCfg: Config = {
249 enabled: typeof options.enabled === 'boolean' ? options.enabled : DEFAULTS.enabled,
250 threshold: num('threshold', DEFAULTS.threshold),
251 weeklyThreshold: num('weeklyThreshold', DEFAULTS.weeklyThreshold),
252 abortThreshold: num('abortThreshold', DEFAULTS.abortThreshold),
253 ceiling: DEFAULTS.ceiling,
254 burnMultiplier: DEFAULTS.burnMultiplier,
255 graceSec: num('graceSeconds', DEFAULTS.graceSec),
256 maxResumeAttempts: num('maxResumeAttempts', DEFAULTS.maxResumeAttempts),
257 weeklyPolicy: options.weeklyPolicy === 'notify' ? 'notify' : 'pause',
258 notifyAt: num('notifyAt', DEFAULTS.notifyAt),
259 compactMinContext: num('compactMinContext', DEFAULTS.compactMinContext),
260 ...rest,
261 }
262 const nextIdle: IdleCfg = {
263 enabled: typeof options.idleCompact === 'boolean' ? options.idleCompact : IDLE_DEFAULTS.enabled,
264 minTokens: num('idleCompactMinTokens', IDLE_DEFAULTS.minTokens),
265 ttlMs: num('cacheTtlMinutes', IDLE_DEFAULTS.ttlMs / 60_000) * 60_000,
266 marginMs: num('idleMarginSeconds', IDLE_DEFAULTS.marginMs / 1000) * 1000,
267 requireWaiting: typeof options.idleRequiresBackground === 'boolean' ? options.idleRequiresBackground : IDLE_DEFAULTS.requireWaiting,
268 ...(oIdle ?? {}),
269 }
270
271 if (gen !== epoch) return // the session ended while this was loading: its state is not ours to publish
272 sid = id
273 cfg = nextCfg
274 idleCfg = nextIdle
275 // Only /quota coord off turns the helper off. Builds before 0.3.6 saved an empty URL for "never configured" with
276 // every settings change, so an empty one means the default too.
277 helperUrl = oHelperOff === true ? '' : typeof oHelper === 'string' && oHelper ? oHelper : DEFAULT_HELPER
278 idleStats = idle
279 diag = diagSaved
280 sim = simSaved
281 testMode = typeof tm === 'boolean' ? tm : typeof options.testMode === 'boolean' ? options.testMode : false
282 if (typeof da === 'boolean') dryActions = da
283 if (typeof lg === 'boolean') legend = lg
284 const blank = initialState()
285 S =
286 saved && saved.v === 1
287 ? { ...blank, ...saved, rec: { ...blank.rec, ...saved.rec }, known: saved.known ?? [], opSeq: saved.opSeq ?? 0 }
288 : blank // last: this is what ensure() takes as "loaded"
289 await touchIndex($)
290}
291
292// Keep the shared store small. Recent sessions stay; older ones are forgotten, EXCEPT records with
293// unresolved recovery (a pause, a resume in flight): those are never discarded. Records written before
294// the index existed are adopted (as the oldest) so they too can age out.
295const INDEX_CAP = 25
296
297async function recordUnresolved($: any, id: string): Promise<boolean> {
298 const st = (await $.store.get('state:' + id)) as State | undefined
299 return !!(st?.rec && st.rec.phase !== 'idle')
300}
301
302async function touchIndex($: any) {
303 try {
304 const now = await $.clock.now()
305 lastTouchAt = now
306 const idx = ((await $.store.get('index')) as { sid: string; at: number }[] | undefined) ?? []
307 const indexed = new Set(idx.map(x => x.sid))
308 let legacy: string[] = []
309 try {
310 legacy = ((await $.store.keys()) as string[])
311 .filter(k => k.startsWith('state:'))
312 .map(k => k.slice('state:'.length))
313 .filter(id => !indexed.has(id) && id !== sid)
314 } catch {
315 /* no key listing available: nothing to migrate */
316 }
317 const entries = [{ sid, at: now }, ...idx.filter(x => x.sid !== sid), ...legacy.map(id => ({ sid: id, at: 0 }))]
318 entries.sort((a, b) => b.at - a.at)
319 const keep = entries.slice(0, INDEX_CAP)
320 for (const old of entries.slice(INDEX_CAP)) {
321 if (await recordUnresolved($, old.sid)) {
322 keep.push(old)
323 continue
324 }
325 // another session may have written a pause since that read: look once more right before deleting
326 if (await recordUnresolved($, old.sid)) {
327 keep.push(old)
328 continue
329 }
330 await $.store.delete('state:' + old.sid)
331 await $.store.delete('idle:' + old.sid)
332 await $.store.delete('resp:' + old.sid)
333 await $.store.delete('idlestate:' + old.sid)
334 await $.store.delete('diag:' + old.sid)
335 }
336 await $.store.set('index', keep)
337 } catch (err) {
338 logOnce($, err)
339 }
340}
341
342// A failure in this mod must never stop prompts or tool calls: hooks catch, log once, and pass through.
343function logOnce($: any, err: unknown) {
344 if (warned) return
345 warned = true
346 try {
347 $.ui.log(PREFIX + `internal error, passing through: ${String(err)}`)
348 } catch {
349 /* nothing more to do */
350 }
351}
352
353async function usable($: any, gen: number): Promise<boolean> {
354 try {
355 await ensure($, gen)
356 return true
357 } catch (err) {
358 if (gen === epoch) logOnce($, err) // a session that has ended is not an internal error
359 return false
360 }
361}
362
363// Headless runs (claude -p, an SDK host with no UI) have no surface attached: never pause those,
364// nobody would be there to resume them. Fails open to "watched" when the engine cannot say.
365async function watched($: any): Promise<boolean> {
366 try {
367 return (await $.session.surfaces()).length > 0
368 } catch {
369 return true
370 }
371}
372
373// Every open session shares the same account windows, so they all pause and wake together.
374// Resume prompts are staggered through the shared store so they do not land in one burst.
375async function claimSlot($: any, wanted: () => boolean) {
376 const session = sid
377 try {
378 if (!wanted()) return
379 const now = await $.clock.now()
380 if (!wanted()) return
381 const last = Number(await $.store.get('lastResume')) || 0
382 if (!wanted()) return
383 let h = 0
384 for (const ch of session) h = (h * 31 + ch.charCodeAt(0)) % 10
385 const at = Math.min(Math.max(now + h * 1000, last + STAGGER_MS), now + MAX_STAGGER_MS)
386 await $.store.set('lastResume', at)
387 if (!wanted()) return
388 if (at > now) await $.clock.sleep(at - now)
389 } catch {
390 /* staggering is best effort */
391 }
392}
393
394
395// `gen` is the session generation the CALLER started in, captured before its first wait. A caller that
396// was overtaken by a session change must stop, even when another load has since filled S for the new one.
397async function ensure($: any, gen: number): Promise<void> {
398 if (gen !== epoch) throw new Error('the session changed')
399 if (!commandReady) void registerCommand($)
400 if (S) return
401 loading ??= load($).catch(err => {
402 loading = undefined
403 throw err
404 })
405 await loading
406 if (gen !== epoch || S === null) throw new Error('the session changed while its state was loading')
407}
408
409async function persist($: any) {
410 try {
411 await $.store.set('state:' + sid, S)
412 if ((await $.clock.now()) - lastTouchAt > 10 * 60_000) await touchIndex($)
413 } catch (err) {
414 logOnce($, err)
415 }
416}
417const saveCfg = ($: any) =>
418 $.store.set('cfg', { ...cfg, testMode, dryActions, legend, idle: idleCfg, helperUrl: helperUrl || DEFAULT_HELPER, helperOff: !helperUrl }).catch(() => {})
419const saveSim = ($: any) => $.store.set('sim', sim).catch(() => {})
420
421// ---------- usage ----------
422
423function simUsage(now: number, probing: boolean): Usage | null {
424 if (!sim || sim.unavailable) return null
425 const f = sim.five
426 if (sim.mode === 'delay' && probing && sim.probeFails > 0) {
427 sim.probeFails--
428 f.percent = 100
429 f.resetsAt = now + 120_000
430 } else if (f.resetsAt <= now && !(sim.mode === 'delay' && sim.probeFails > 0)) {
431 if (sim.mode === 'fail' && !sim.failedOnce) {
432 sim.failedOnce = true
433 f.resetsAt = now + 120_000
434 } else if (sim.mode !== 'fail' || sim.failedOnce) {
435 f.percent = 3
436 f.resetsAt = now + 5 * 3600_000
437 }
438 }
439 const windows: Win[] = [{ kind: FIVE, percent: f.percent, resetsAt: f.resetsAt }]
440 if (sim.week) windows.push({ kind: WEEK, percent: sim.week.percent, resetsAt: sim.week.resetsAt })
441 return { windows, contextPercent: sim.ctx }
442}
443
444function mapUsage(u: any): Usage {
445 const windows: Win[] = (u.rateLimits ?? []).map((r: any) => ({
446 kind: r.kind,
447 percent: r.percentUsed,
448 resetsAt: r.resetsAt ? Date.parse(r.resetsAt) : undefined,
449 }))
450 return { windows, contextPercent: u.context?.percent }
451}
452
453async function readUsage($: any): Promise<Usage | null> {
454 try {
455 if (testMode) {
456 const u = simUsage(await $.clock.now(), S?.rec.phase === 'resuming')
457 if (u && u.contextPercent === undefined) {
458 try {
459 u.contextPercent = (await $.session.usage()).context?.percent
460 } catch {
461 /* none */
462 }
463 }
464 return u
465 }
466 const u = mapUsage(await $.session.usage())
467 return u.windows.length ? u : null
468 } catch {
469 return null
470 }
471}
472
473async function publish($: any, usage: Usage | null, now: number, gen: number) {
474 if (gen !== epoch || S === null) return
475 const st = S as State
476 const five = usage?.windows.find(w => w.kind === FIVE)
477 const week = usage?.windows.find(w => w.kind === WEEK)
478 const rst = (w?: Win) => (w?.resetsAt && w.resetsAt > now ? fmtDur(w.resetsAt - now) : undefined)
479 let ctx = usage?.contextPercent
480 let ctxTokens: number | undefined
481 let ctxWindow: number | undefined
482 let parts: QuotaBar['parts'] = []
483 try {
484 const b = (await $.session.usage({ breakdown: 'summary' })).context
485 ctx ??= b.percent ?? b.breakdown?.percentage
486 ctxTokens = b.tokens ?? b.breakdown?.totalTokens
487 ctxWindow = b.breakdown?.rawMaxTokens ?? b.window
488 const bd = b.breakdown
489 if (bd && gen === epoch) await update($, detail, () => buildDetail(bd, bd.apiUsage))
490 if (bd && bd.rawMaxTokens > 0) {
491 parts = bd.categories
492 .filter((c: any) => c.kind === 'used' && c.tokens > 0)
493 .map((c: any) => ({ name: c.name, pct: (c.tokens / bd.rawMaxTokens) * 100 }))
494 .sort((a: { pct: number }, c: { pct: number }) => c.pct - a.pct)
495 }
496 } catch {
497 /* breakdown is cosmetic */
498 }
499 const v: QuotaBar = {
500 ctx,
501 parts,
502 legend,
503 ctxTokens,
504 ctxWindow,
505 five: five?.percent,
506 fiveReset: rst(five),
507 fiveAt: when(five, now),
508 week: week?.percent,
509 weekReset: rst(week),
510 weekAt: when(week, now),
511 threshold: cfg.threshold,
512 ctxMin: cfg.compactMinContext,
513 phase: st.rec.phase,
514 note:
515 st.rec.phase === 'paused' && st.rec.wakeAt
516 ? `paused until ${fmtClock(st.rec.wakeAt)}`
517 : usage ? undefined : 'waiting for first usage reading',
518 }
519 if (gen !== epoch) return
520 await update($, bar, () => v)
521}
522
523// ---------- dispatch / effects ----------
524
525async function dispatch($: any, ev: Ev, gen: number): Promise<void> {
526 await ensure($, gen)
527 if ((ev.type === 'measure' || ev.type === 'tick' || ev.type === 'forcePause') && !(await watched($))) return
528 if (gen !== epoch || S === null) return
529 const prevPhase = (S as State).rec.phase
530 const prevOp = (S as State).rec.op
531 const { state, fx } = step(S as State, ev, cfg)
532 S = state
533 await persist($)
534 if (gen !== epoch) return // the session ended while persisting: nothing this produced applies any more
535 sync($, gen)
536 if (helperUrl) void helperTrack($, prevPhase, prevOp, gen).catch((err: unknown) => logOnce($, err))
537 for (const f of fx) if (f.t === 'toast') say($, f.text)
538 const rest = fx.filter(f => f.t !== 'toast')
539 if (rest.length) void runEffects($, rest, gen).catch((err: unknown) => logOnce($, err))
540}
541
542function say($: any, text: string) {
543 const t = (testMode ? '[test] ' : '') + text
544 $.ui.toast(t, { timeoutMs: 9000 })
545 $.ui.log(PREFIX + t)
546}
547
548function sync($: any, gen: number) {
549 if (needsHeartbeat(S as State)) {
550 timer ??= $.clock.every(HEARTBEAT_MS, () => void tick($, gen).catch((err: unknown) => logOnce($, err)))
551 } else if (timer) {
552 timer.cancel()
553 timer = undefined
554 }
555}
556
557async function tick($: any, gen: number) {
558 await ensure($, gen)
559 const now = await $.clock.now()
560 const usage = await readUsage($)
561 if (gen !== epoch) return
562 $.ui.status(statusLine(S as State, usage, now))
563 if (helperUrl && helperOp?.confirmed && !helperOp.finished) void hcall($, '/renew', { op: helperOp.id, token: helperOp.token })
564 await dispatch($, { type: 'tick', now, usage }, gen)
565 await publish($, usage, now, gen)
566}
567
568async function runEffects($: any, list: Fx[], gen: number) {
569 for (const f of list) {
570 if (gen !== epoch) return
571 try {
572 if (f.t === 'abort') {
573 // only the turn this pause was armed against, and only while that pause still stands
574 const live = S !== null && S.rec.phase === 'armed' && S.rec.op === f.op
575 if (live && turnId && (f.turnId === undefined || f.turnId === turnId)) await $.turn.abort({ turnId })
576 } else if (f.t === 'compact') {
577 await doCompact($, f.instructions, f.op, gen)
578 } else if (f.t === 'submit') {
579 await doSubmit($, f.text, f.op, gen, f.manual)
580 } else if (f.t === 'fill') {
581 if (gen === epoch) await $.prompt.fill({ text: f.text })
582 }
583 } catch (err) {
584 $.ui.log(PREFIX + `${f.t} failed: ${String(err)}`)
585 }
586 }
587}
588
589// ---------- compaction transport (the quota pause and idle compaction share it) ----------
590// A terminal session compacts through $.session.compact, which answers for itself. An SDK session (Claude Desktop,
591// -p) refuses that call, so there the built-in /compact command is queued instead; core raises session.compact for
592// it through every plugin's hook, this one's included, and the hook recognises the request by the tag in its
593// instructions. The command's answer is never taken as proof: a successful /compact answers no text at all. A queued
594// command cannot be recalled, so the hook refuses one whose operation is no longer wanted when it finally runs.
595type CompactRoute = 'direct' | 'command' | 'dry-run'
596type CompactResult = { outcome: 'ok' | 'vetoed' | 'failed' | 'stale'; detail: string; tokensBefore?: number; tokensAfter?: number; usage?: any }
597type CompactOutcome = { outcome: CompactResult['outcome'] | 'unsupported' | 'busy'; detail: string; route: CompactRoute; attempts: number; tokensBefore?: number; tokensAfter?: number; usage?: any }
598type PendingCompact = { wanted: () => boolean; at: number; abandoned?: boolean; seen?: CompactResult; settle?: (o: CompactResult) => void }
599const pendingCompacts = new Map<string, PendingCompact>()
600let directCompact: 'unknown' | 'supported' | 'unsupported' = 'unknown' // what this session's engine said about the direct API
601let compactSeq = 0
602const HELD_RETRY_MS = 250
603const HELD_TRIES = 40 // 10 s: a hook frame that holds the turn ends when that hook returns
604const TURN_RETRY_MS = 1000
605const TURN_TRIES = 10
606const COMPACT_DEADLINE_MS = 10 * 60_000 // a bound, not an expectation: a real summary of a large session took 99 s
607const errText = (err: unknown) => String(err instanceof Error ? err.message : err).slice(0, 300)
608const routeName = (r: CompactRoute | undefined) => (r === 'command' ? 'the /compact command' : r === 'dry-run' ? 'dry run' : '$.session.compact')
609
610function fromCompacted(r: any): CompactResult {
611 if (r && r.skip !== undefined) return { outcome: 'vetoed', detail: String(r.skip).slice(0, 200) }
612 return { outcome: 'ok', detail: '', tokensBefore: typeof r?.tokensBefore === 'number' ? r.tokensBefore : undefined, tokensAfter: typeof r?.tokensAfter === 'number' ? r.tokensAfter : undefined, usage: r?.usage }
613}
614
615// A call made from inside a hook that holds the turn (a slash command's own hook, say) is refused by the engine
616// until that hook returns. Waiting a fixed time is a guess; this retries exactly that refusal, briefly.
617async function outsideHeldFrame<T>($: any, call: () => Promise<T>, wanted: () => boolean): Promise<{ value: T } | { error: string }> {
618 for (let held = 0; ; held++) {
619 try {
620 return { value: await call() }
621 } catch (err) {
622 const m = errText(err)
623 if (classifyRefusal(m) === 'held' && held < HELD_TRIES && wanted()) {
624 await $.clock.sleep(HELD_RETRY_MS)
625 continue
626 }
627 return { error: m }
628 }
629 }
630}
631
632async function compactNow($: any, instructions: string, wanted: () => boolean): Promise<CompactOutcome> {
633 const now = await $.clock.now()
634 for (const [k, p] of pendingCompacts) if (now - p.at > 3600_000) pendingCompacts.delete(k)
635 let attempts = 0
636 if (directCompact !== 'unsupported') {
637 // The direct call answers for itself, and it runs every session.compact hook but this plugin's own, so it
638 // carries no tag: only a request this plugin's hook will see (the queued command, below) needs one.
639 for (let held = 0, turn = 0; ; ) {
640 if (!wanted()) return { outcome: 'stale', detail: 'no longer wanted', route: 'direct', attempts }
641 attempts++
642 try {
643 const r = await $.session.compact({ instructions })
644 directCompact = 'supported'
645 return { ...fromCompacted(r), route: 'direct', attempts }
646 } catch (err) {
647 const m = errText(err)
648 const kind = classifyRefusal(m)
649 if (kind === 'held' && held++ < HELD_TRIES) {
650 await $.clock.sleep(HELD_RETRY_MS)
651 continue
652 }
653 if (kind === 'turn-running' && turn++ < TURN_TRIES) {
654 await $.clock.sleep(TURN_RETRY_MS)
655 continue
656 }
657 if (kind === 'disabled') return { outcome: 'unsupported', detail: m, route: 'direct', attempts }
658 if (kind === 'held' || kind === 'turn-running') return { outcome: 'busy', detail: m, route: 'direct', attempts }
659 if (kind === 'sdk') directCompact = 'unsupported'
660 // a session that compacted directly before has a real failure here (the summary request failed, say);
661 // one that never has may be refusing in words this plugin does not know, so the command gets one try
662 else if (directCompact === 'supported') return { outcome: 'failed', detail: m, route: 'direct', attempts }
663 $.ui.log(PREFIX + `$.session.compact refused (${m}); using the /compact command`)
664 break
665 }
666 }
667 }
668 return compactByCommand($, instructions, wanted, attempts)
669}
670
671async function compactByCommand($: any, instructions: string, wanted: () => boolean, attempts: number): Promise<CompactOutcome> {
672 const token = `${epoch}.${++compactSeq}`
673 const p: PendingCompact = { wanted, at: await $.clock.now() }
674 pendingCompacts.set(token, p)
675 const args = tagInstructions(instructions, token)
676 const before = await contextTokens($) // only for an answer the hook never saw (see below)
677 return new Promise<CompactOutcome>(resolve => {
678 let done = false
679 let deadline: { cancel: () => void } | undefined
680 const finish = (o: Omit<CompactOutcome, 'route' | 'attempts'>) => {
681 if (done) return
682 done = true
683 deadline?.cancel()
684 resolve({ ...o, route: 'command', attempts })
685 }
686 p.settle = finish
687 deadline = $.clock.after(COMPACT_DEADLINE_MS, () => {
688 p.abandoned = true // if it ever runs now, the hook refuses it: its caller has stopped waiting
689 finish({ outcome: 'failed', detail: 'the queued /compact gave no outcome within 10 minutes' })
690 })
691 void (async () => {
692 if (!wanted()) {
693 pendingCompacts.delete(token)
694 return finish({ outcome: 'stale', detail: 'no longer wanted' })
695 }
696 attempts++
697 const sent = await outsideHeldFrame<any>($, () => $.command.run({ command: 'compact', args }), wanted)
698 if ('error' in sent) {
699 pendingCompacts.delete(token)
700 if (!wanted()) return finish({ outcome: 'stale', detail: 'no longer wanted' })
701 const kind = classifyRefusal(sent.error)
702 return finish({ outcome: kind === 'no-command' || kind === 'disabled' ? 'unsupported' : kind === 'held' ? 'busy' : 'failed', detail: sent.error })
703 }
704 // the command has run. The hook has normally settled the outcome already; if it never saw the compaction (a
705 // hook above it answered or refused, or core refused first), the command's text is all there is to go on.
706 if (p.seen) return finish(p.seen)
707 pendingCompacts.delete(token)
708 const said = readCommandText(sent.value?.text)
709 if (said.outcome === 'vetoed' || said.outcome === 'failed') return finish({ outcome: said.outcome, detail: said.detail })
710 const after = await contextTokens($)
711 if (before !== undefined && after !== undefined && after < before * 0.7) {
712 return finish({ outcome: 'ok', detail: 'seen only through the context size (another hook answered the compaction)', tokensBefore: before, tokensAfter: after })
713 }
714 if (said.outcome === 'claimed') return finish({ outcome: 'ok', detail: `the /compact command reported "${said.detail.slice(0, 80)}"; this plugin's hook did not see it` })
715 return finish({ outcome: 'failed', detail: 'the /compact command ran, but no compaction was observed' })
716 })().catch(err => finish({ outcome: 'failed', detail: errText(err) }))
717 })
718}
719
720async function noteEngine($: any) {
721 if (engineVersion !== undefined) return
722 try {
723 engineVersion = (await $.session.version()).version
724 } catch {
725 engineVersion = 'unknown'
726 }
727}
728
729async function saveDiag($: any, gen: number, patch: Partial<Diag>) {
730 if (gen !== epoch) return
731 diag = { ...diag, ...patch }
732 try {
733 await $.store.set('diag:' + sid, diag)
734 } catch {
735 /* the in-memory record still shows in /quota status */
736 }
737}
738
739async function doCompact($: any, instructions: string, op: number, gen: number) {
740 // this operation of this session, and only this one: a cancel, a takeover, a replacement or the end
741 // of the session makes it stale
742 const wanted = () => gen === epoch && S !== null && S.rec.phase === 'compacting' && S.rec.op === op
743 const startedAt = await $.clock.now()
744 await noteEngine($)
745 let res: CompactOutcome
746 if (testMode && dryActions) {
747 $.ui.log(PREFIX + '[dry-run] would compact the conversation now')
748 res = { outcome: 'ok', detail: 'dry run: nothing was compacted', route: 'dry-run', attempts: 0 }
749 } else res = await compactNow($, instructions, wanted)
750 if (gen !== epoch) return
751 const endedAt = await $.clock.now()
752 $.ui.log(PREFIX + `quota compaction (op ${op}) ${res.outcome} via ${routeName(res.route)} after ${res.attempts} call(s)${res.detail ? ': ' + res.detail : ''}`)
753 const { usage: _u, ...kept } = res
754 await saveDiag($, gen, { compaction: { op, session: sid, gen, startedAt, endedAt, ...kept, engine: engineVersion, build: BUILD } })
755 if (gen !== epoch) return
756 const ok = res.outcome === 'ok'
757 await dispatch($, { type: 'compactDone', now: endedAt, ok, op, detail: ok ? undefined : `${res.outcome}: ${res.detail}` }, gen)
758}
759
760// ---------- account-wide coordination through the helper ----------
761
762type HelperOp = { id: string; token?: string; coreOp: number; confirmed: boolean; finished: boolean }
763let helperOp: HelperOp | null = null
764let helperHealth: { ok: boolean; since: number; detail?: string } | undefined
765let helperFallback = false
766let helperNonce = 0
767
768async function hcall($: any, path: string, body: Record<string, unknown>, base = helperUrl): Promise<any> {
769 const gen = epoch
770 const url = base.replace(/\/+$/, '') + path
771 const t0 = await $.clock.now().catch(() => 0)
772 const mark = (ok: boolean, detail?: string) => {
773 if (gen !== epoch || base !== helperUrl || path === '/cancel' || path === '/complete') return
774 if (helperHealth === undefined || helperHealth.ok !== ok) helperHealth = { ok, since: t0, detail }
775 else helperHealth.detail = detail
776 }
777 try {
778 const res = await Promise.race([
779 $.http.fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }),
780 $.clock.sleep(4000).then(() => Promise.reject(new Error('timed out after 4 s'))),
781 ])
782 const j = JSON.parse(res.text)
783 if (res.status >= 500 && j.reason !== 'busy') {
784 mark(false, `helper answered ${res.status}`)
785 return { ok: false, reason: 'unreachable' }
786 }
787 mark(true)
788 return j
789 } catch (err) {
790 mark(false, String(err instanceof Error ? err.message : err).slice(0, 120))
791 if (base === helperUrl && path !== '/shutdown') void ensureHelper($, gen)
792 return { ok: false, reason: 'unreachable' }
793 }
794}
795
796// ---------- starting the helper ----------
797
798// The helper version this build ships (helper/quota_guard_helper.py VERSION). An older helper that can be asked to stop
799// is replaced by it; one from before version 2 cannot be asked, so it keeps running and /quota status says so.
800const HELPER_VERSION = 2
801const HELPER_RETRY_MS = 10 * 60_000 // after a start that failed, before this session tries again
802const HELPER_RECHECK_MS = 60_000 // after a start that worked, before a helper that is gone again is started again
803// the Windows launcher first: there `python3` is often the Store's stand-in, which only prints how to install Python
804const PYTHONS = [['py', '-3'], ['python'], ['python3']]
805let helperRun: { at?: number; state?: 'started' | 'running' | 'starting' | 'outdated' | 'port-taken' | 'failed'; detail?: string } = {}
806let helperTold = '' // the last state logged: a retry that fails the same way is not logged again
807let helperStarting: Promise<void> | undefined
808
809// Only a helper on this machine, where the helper binds (127.0.0.1), can be started from here: its port, or undefined.
810function localHelper(url: string): string | undefined {
811 return /^http:\/\/(?:127\.0\.0\.1|localhost):(\d{1,5})\/?$/i.exec(url)?.[1]
812}
813
814async function helperAnswer($: any, base: string): Promise<{ up: false } | { up: true; helper: boolean; version: number; stoppable: boolean }> {
815 try {
816 const res = await Promise.race([
817 $.http.fetch(base.replace(/\/+$/, '') + '/health'),
818 $.clock.sleep(4000).then(() => Promise.reject(new Error('timed out after 4 s'))),
819 ])
820 let body: any = {}
821 try {
822 body = JSON.parse(res.text)
823 } catch {
824 /* not JSON */
825 }
826 return { up: true, helper: res.ok === true && body?.service === 'quota-guard-helper', version: Number(body?.version) || 0, stoppable: body?.stoppable === true }
827 } catch {
828 return { up: false }
829 }
830}
831
832async function helperScript($: any): Promise<string | undefined> {
833 const root = String($.plugin.root ?? '').replace(/[\\/]+$/, '')
834 if (!root) return undefined
835 // the plugin's folder; or the one above, should the engine name the folder holding plugin.json
836 for (const dir of [root, root.replace(/[\\/][^\\/]+$/, '')]) {
837 const path = `${dir}/helper/quota_guard_helper.py`
838 try {
839 if (await $.fs.exists(path)) return path
840 } catch {
841 /* not readable from here */
842 }
843 }
844 return undefined
845}
846
847function noteHelper($: any, run: typeof helperRun, text?: string) {
848 helperRun = run
849 if (!text || helperTold === run.state) return
850 helperTold = run.state ?? ''
851 $.ui.log(PREFIX + text)
852}
853
854// Start the bundled helper when none answers, or replace an older one that can be asked to stop. Sessions starting
855// together do not end up with two: the helper takes its port exclusively, and the launcher reports whichever helper
856// answers. The helper runs on its own, so it outlives the session that started it.
857function ensureHelper($: any, gen: number, force = false): Promise<void> {
858 if (force) helperRun = { ...helperRun, at: undefined }
859 helperStarting ??= startHelper($, gen)
860 .catch((err: unknown) => logOnce($, err))
861 .finally(() => {
862 helperStarting = undefined
863 })
864 return helperStarting
865}
866
867async function startHelper($: any, gen: number) {
868 const base = helperUrl
869 const port = localHelper(base)
870 if (!port) return
871 const now = await $.clock.now()
872 // a helper that answers (even an old one) is checked again sooner: once someone stops it, a new one starts within a minute
873 const fine = helperRun.state === 'started' || helperRun.state === 'running' || helperRun.state === 'starting' || helperRun.state === 'outdated'
874 if (helperRun.at !== undefined && now - helperRun.at < (fine ? HELPER_RECHECK_MS : HELPER_RETRY_MS)) return
875 const stale = () => gen !== epoch || base !== helperUrl
876 let h = await helperAnswer($, base)
877 if (stale()) return
878 let at = await $.clock.now()
879 if (h.up && !h.helper) {
880 return noteHelper($, { at, state: 'port-taken', detail: `port ${port} answers, but not as the quota-guard helper` },
881 `port ${port} is held by something that is not the quota-guard helper; coordination uses the shared store (/quota coord helper <url> picks another address)`)
882 }
883 if (h.up && h.version >= HELPER_VERSION) {
884 if (helperRun.state !== 'started') noteHelper($, { at, state: 'running', detail: `version ${h.version}` })
885 else helperRun = { ...helperRun, at }
886 return
887 }
888 if (h.up) {
889 const old = `version ${h.version || 'before 2'}`
890 const res = h.stoppable ? await hcall($, '/shutdown', { version: HELPER_VERSION }, base) : { ok: false }
891 if (stale()) return
892 if (res.ok !== true) {
893 return noteHelper($, { at, state: 'outdated', detail: old },
894 `the helper running at ${base} is an older version (${old}) that cannot be replaced automatically; stop it once and quota-guard starts version ${HELPER_VERSION} in its place`)
895 }
896 $.ui.log(PREFIX + `asked the older helper at ${base} (${old}) to make way for version ${HELPER_VERSION}`)
897 for (let i = 0; i < 20 && h.up; i++) {
898 await $.clock.sleep(250)
899 h = await helperAnswer($, base)
900 if (stale()) return
901 }
902 }
903 const script = await helperScript($)
904 if (stale()) return
905 at = await $.clock.now()
906 if (!script) return noteHelper($, { at, state: 'failed', detail: 'helper/quota_guard_helper.py is not in the plugin folder' }, 'could not start the coordination helper: helper/quota_guard_helper.py is not in the plugin folder; coordination uses the shared store')
907 const tried: string[] = []
908 for (const py of PYTHONS) {
909 let res: any
910 try {
911 res = await $.process.run([...py, script, '--detach', '--port', port], { timeoutMs: 45_000 })
912 } catch (err) {
913 tried.push(`${py.join(' ')}: ${errText(err).slice(0, 100)}`)
914 continue
915 }
916 if (stale()) return
917 let out: any
918 try {
919 out = JSON.parse(String(res.stdout ?? '').trim().split(/\r?\n/).pop() ?? '')
920 } catch {
921 out = undefined
922 }
923 if (!out || typeof out !== 'object') {
924 // not a Python 3 that ran it (the Store's stand-in, Python 2): the next name may be
925 tried.push(`${py.join(' ')}: exit ${res.exitCode}${res.stderr ? ', ' + String(res.stderr).trim().slice(-100) : ''}`)
926 continue
927 }
928 at = await $.clock.now()
929 if (out.ok === true) {
930 // a helper of this version answers: whatever the old one could not do, this one can
931 helperHealth = undefined
932 helperFallback = false
933 share.unsupported = undefined
934 shareSent.clear()
935 if (out.state === 'started') {
936 return noteHelper($, { at, state: 'started', detail: `${py.join(' ')}, pid ${out.pid}` }, `started the coordination helper at ${base} (${py.join(' ')}, pid ${out.pid})`)
937 }
938 return noteHelper($, { at, state: 'running', detail: `version ${out.version}, started by another session` })
939 }
940 if (out.state === 'no-answer') return noteHelper($, { at, state: 'starting', detail: `pid ${out.pid}, not answering after 20 s` })
941 const why = out.state === 'port-taken' ? `something else holds port ${port}` : `it exited (${out.code}): ${String(out.log ?? '').trim().split(/\r?\n/).pop()}`
942 return noteHelper($, { at, state: 'failed', detail: why }, `could not start the coordination helper: ${why}; coordination uses the shared store`)
943 }
944 const why = `no Python 3 ran it (${tried.join('; ')})`
945 noteHelper($, { at, state: 'failed', detail: why }, `could not start the coordination helper: ${why}; coordination uses the shared store`)
946}
947
948function helperLine(): string {
949 if (!localHelper(helperUrl)) return 'Helper: at another address, so quota-guard does not start it'
950 const r = helperRun
951 const at = r.at !== undefined ? fmtClock(r.at) : 'just now'
952 switch (r.state) {
953 case 'started':
954 return `Helper: started by this session at ${at} (${r.detail})`
955 case 'running':
956 return `Helper: running (${r.detail}; checked ${at})`
957 case 'starting':
958 return `Helper: started at ${at} (${r.detail})`
959 case 'outdated':
960 return `Helper: an older one is running (${r.detail}); stop it once and quota-guard starts version ${HELPER_VERSION}`
961 case 'port-taken':
962 case 'failed':
963 return `Helper: could not start it at ${at}: ${r.detail}${r.at !== undefined ? `; tried again after ${fmtClock(r.at + HELPER_RETRY_MS)} if still needed` : ''}`
964 default:
965 return `Helper: started automatically when none answers (this build ships version ${HELPER_VERSION})`
966 }
967}
968
969// Admission of one automatic resume. A missing helper selects the shared-store scheduler for this operation;
970// a reachable helper's pending probe, spacing or quota refusal still governs admission.
971// The operation identity is session id + generation + a unique nonce; the helper's token only authorises it.
972async function helperAdmit($: any, coreOp: number, gen: number, wanted: () => boolean, restarts = 0): Promise<'helper' | 'store' | false> {
973 const ho: HelperOp = { id: `${sid}.${gen}.${coreOp}.${++helperNonce}.${(await $.clock.now()).toString(36)}`, coreOp, confirmed: false, finished: false }
974 if (!wanted()) return false
975 helperOp = ho
976 helperFallback = false
977 const base = helperUrl
978 const call = (path: string, body: Record<string, unknown>) => hcall($, path, body, base)
979 const hold = async () => {
980 if (gen === epoch && wanted()) await dispatch($, { type: 'resumeHold', now: await $.clock.now(), op: coreOp }, gen)
981 }
982 const drop = async (): Promise<false> => {
983 // the operation ended (cancelled, replaced, session ended): release whatever the helper holds for it
984 ho.finished = true
985 if (ho.token) await call('/cancel', { op: ho.id, token: ho.token })
986 if (helperOp === ho) helperOp = null
987 return false
988 }
989 const fallback = (): 'store' | false => {
990 ho.finished = true
991 if (helperOp === ho) helperOp = null
992 // A known reservation is no longer used. Cleanup must not hold up the store fallback if the service is down.
993 if (ho.token) void call('/cancel', { op: ho.id, token: ho.token }).catch(() => undefined)
994 if (!wanted()) return false
995 helperFallback = true
996 say($, 'Using best-effort shared-store spacing for the resume attempt; the optional coordination helper is unavailable.')
997 return 'store'
998 }
999 const busy = async (backoff: number) => {
1000 await hold()
1001 await $.clock.sleep(backoff)
1002 }
1003 const st = S as State
1004 const window = st.rec.expectedReset === undefined ? 'unknown' : String(Math.round(st.rec.expectedReset / 300_000))
1005 // A busy, reachable helper retains admission; an unavailable helper is optional.
1006 for (let backoff = 5000; ; backoff = Math.min(backoff * 2, 60_000)) {
1007 if (!wanted()) return drop()
1008 const res = await call('/reserve', { account: 'default', window, op: ho.id, owner: `${sid}.${gen}` })
1009 if (res.ok === true) {
1010 ho.token = res.token
1011 if (!wanted()) return drop()
1012 const wait = Math.max(0, res.slotAt - res.serverNow)
1013 for (let left = wait; left > 0; left -= 20_000) {
1014 await $.clock.sleep(Math.min(left, 20_000))
1015 if (!wanted()) return drop()
1016 await hold()
1017 const renewed = await call('/renew', { op: ho.id, token: ho.token })
1018 if (renewed.reason === 'unreachable') return fallback()
1019 }
1020 break
1021 }
1022 if (res.reason === 'unreachable') return fallback()
1023 if (res.reason === 'busy') {
1024 await busy(backoff)
1025 continue
1026 }
1027 ho.finished = true
1028 if (gen === epoch && wanted()) await dispatch($, { type: 'resumeBlocked', now: await $.clock.now(), op: coreOp, why: 'coordination refused the reservation: ' + String(res.reason) }, gen)
1029 return false
1030 }
1031 // confirm = admission: the helper checks the lease, the probe's outcome and the spacing in one transaction
1032 for (let backoff = 5000; ; ) {
1033 if (!wanted()) return drop()
1034 const res = await call('/confirm', { op: ho.id, token: ho.token })
1035 if (res.ok === true) {
1036 if (!wanted()) return drop()
1037 ho.confirmed = true
1038 helperFallback = false
1039 return 'helper'
1040 }
1041 if (res.reason === 'unreachable') return fallback()
1042 if (res.reason === 'busy') {
1043 await busy(backoff)
1044 backoff = Math.min(backoff * 2, 60_000)
1045 continue
1046 }
1047 if (res.reason === 'early' || res.reason === 'probe-pending' || res.reason === 'spacing') {
1048 await hold()
1049 await $.clock.sleep(Math.min(30_000, Math.max(1000, Number(res.retryMs) || 2000)))
1050 const renewed = await call('/renew', { op: ho.id, token: ho.token })
1051 if (renewed.reason === 'unreachable') return fallback()
1052 continue
1053 }
1054 if (res.reason === 'probe-failed') {
1055 // the first attempt of this reset window failed: quota is evidently still short, back off and try again
1056 ho.finished = true
1057 if (gen === epoch && wanted()) await dispatch($, { type: 'resumeBlocked', now: await $.clock.now(), op: coreOp, why: 'the probe attempt of this reset window failed' }, gen)
1058 return false
1059 }
1060 // expired / cancelled / unknown / bad token: the reservation is gone; take a fresh one (bounded)
1061 ho.finished = true
1062 if (restarts < 3) return helperAdmit($, coreOp, gen, wanted, restarts + 1)
1063 if (gen === epoch && wanted()) await dispatch($, { type: 'resumeBlocked', now: await $.clock.now(), op: coreOp, why: 'coordination lease kept expiring' }, gen)
1064 return false
1065 }
1066}
1067
1068// Report how the admitted operation ended, from the core's recorded reason, never from the phase: idle after
1069// resuming also happens on a manual takeover or an interrupted turn, which are not quota evidence. Verified
1070// recovery reports success; a genuine failure reports failure (it blocks the cohort behind it); anything else
1071// (cancelled, taken over, interrupted) just releases the reservation, so the followers elect a new probe.
1072async function helperTrack($: any, prevPhase: string, prevOp: number | undefined, gen: number) {
1073 const ho = helperOp
1074 if (!ho || ho.finished || !ho.confirmed || !ho.token || S === null) return
1075 const st = S as State
1076 const r = st.rec
1077 const stillMine = r.phase === 'resuming' && r.op === ho.coreOp
1078 if (stillMine) return
1079 ho.finished = true
1080 helperOp = null
1081 const reason = st.ended && st.ended.op === ho.coreOp ? st.ended.reason : prevPhase === 'resuming' && prevOp === ho.coreOp ? 'cancelled' : 'cancelled'
1082 if (reason === 'verified' || reason === 'completed') await hcall($, '/complete', { op: ho.id, token: ho.token, outcome: 'ok' })
1083 else if (reason === 'failed') await hcall($, '/complete', { op: ho.id, token: ho.token, outcome: 'failed' })
1084 else await hcall($, '/cancel', { op: ho.id, token: ho.token })
1085}
1086
1087// ---------- usage sharing ----------
1088
1089const shareAccount = () => (testMode ? 'test' : 'default') // simulated readings never mix with real ones
1090const wire = (u: Usage) => u.windows.map(w => ({ kind: w.kind, percent: w.percent, resetsAt: w.resetsAt ?? null }))
1091const sameWin = (a: Win, b: Win) => a.kind === b.kind && a.resetsAt !== undefined && b.resetsAt !== undefined && Math.abs(a.resetsAt - b.resetsAt) <= 120_000
1092
1093// this session's own reading, raised to what other sessions reported for the same windows
1094function withShared(u: Usage): Usage {
1095 if (!sharedHigh.length) return u
1096 return {
1097 ...u,
1098 windows: u.windows.map(w => {
1099 const o = sharedHigh.find(x => sameWin(x, w))
1100 return o && o.percent > w.percent ? { ...w, percent: o.percent } : w
1101 }),
1102 }
1103}
1104
1105function setOwn(u: Usage) {
1106 ownReading = { windows: u.windows.map(w => ({ ...w })) }
1107 // a window that reset (or that this session caught up with) needs nothing from the others any more
1108 sharedHigh = sharedHigh.filter(x => u.windows.some(w => sameWin(w, x) && w.percent < x.percent))
1109}
1110
1111function noShare($: any) {
1112 if (share.unsupported) return
1113 share.unsupported = true
1114 $.ui.log(PREFIX + `the helper at ${helperUrl} does not share usage readings (it predates usage sharing); stop it once and quota-guard starts the current one`)
1115}
1116
1117async function reportReading($: any, account: string, u: Usage | null) {
1118 if (!helperUrl || !u?.windows.length || !sid) return
1119 if (share.unsupported) {
1120 // too old to take readings: look again now and then, so the bundled one starts once someone stops it
1121 if (helperRun.state === 'outdated') void ensureHelper($, epoch)
1122 return
1123 }
1124 const windows = wire(u)
1125 const key = JSON.stringify(windows)
1126 if (shareSent.get(account) === key) return
1127 shareSent.set(account, key)
1128 const res = await hcall($, '/usage/report', { account, session: sid, windows })
1129 if (res.reason === 'not-found') noShare($)
1130 else if (res.ok === true) share.reportedAt = await $.clock.now()
1131 else shareSent.delete(account) // not stored: the next reading sends it again
1132}
1133
1134// While a turn runs: has another session of the account seen more of this session's windows used?
1135async function peekShared($: any, gen: number) {
1136 const own = ownReading
1137 // a pause, or a resume being verified, works from its own evidence
1138 const watching = () => gen === epoch && S !== null && S.busy && (S.rec.phase === 'idle' || S.rec.phase === 'armed')
1139 if (!helperUrl || share.unsupported || !own?.windows.length || !watching()) return
1140 const res = await hcall($, '/usage/peek', { account: shareAccount(), session: sid, windows: wire(own) })
1141 if (gen !== epoch) return
1142 if (res.reason === 'not-found') return noShare($)
1143 if (res.ok !== true || !Array.isArray(res.windows)) return
1144 const now = await $.clock.now()
1145 share.peekedAt = now
1146 const raised: Win[] = []
1147 for (const o of res.windows) {
1148 if (typeof o?.kind !== 'string' || typeof o.percent !== 'number' || typeof o.resetsAt !== 'number') continue
1149 const w: Win = { kind: o.kind, percent: o.percent, resetsAt: o.resetsAt }
1150 const mine = own.windows.find(x => sameWin(x, w))
1151 const known = sharedHigh.find(x => sameWin(x, w))
1152 if (!mine || w.percent <= mine.percent || (known && w.percent <= known.percent)) continue
1153 sharedHigh = [...sharedHigh.filter(x => !sameWin(x, w)), w]
1154 raised.push(w)
1155 }
1156 if (!raised.length || !watching() || ownReading !== own) return
1157 const usage = withShared({ windows: own.windows.map(w => ({ ...w })) })
1158 const text = raised.map(w => describeWindow(w, now)).join('; ')
1159 // the status keeps the figure and when it was seen; a countdown to the reset would go stale there
1160 share.raised = { text: raised.map(w => `${w.kind === FIVE ? '5-hour' : w.kind === WEEK ? 'weekly' : w.kind} ${Math.round(w.percent)}%`).join(', '), at: now }
1161 $.ui.log(PREFIX + `another session of this account reports ${text}; this session's own last reading: ${own.windows.map(w => `${Math.round(w.percent)}%`).join(', ')}`)
1162 await dispatch($, { type: 'measure', now, usage, shared: true }, gen)
1163 if (gen !== epoch) return
1164 $.ui.status(statusLine(S as State, usage, now))
1165 await publish($, usage, now, gen)
1166}
1167
1168function shareLine(): string {
1169 if (share.unsupported) return 'Usage sharing: off (the helper predates it; stop it once and quota-guard starts the current one)'
1170 const sent = share.reportedAt !== undefined ? `this session's readings shared, last at ${fmtClock(share.reportedAt)}` : 'nothing shared yet'
1171 const seen = share.raised
1172 ? `another session reported ${share.raised.text} at ${fmtClock(share.raised.at)}`
1173 : share.peekedAt !== undefined
1174 ? `no higher reading from other sessions (checked ${fmtClock(share.peekedAt)})`
1175 : `other sessions' readings checked every ${SHARE_PEEK_MS / 1000} s while a turn runs`
1176 return `Usage sharing: ${sent}; ${seen}`
1177}
1178
1179async function doSubmit($: any, text: string, op: number, gen: number, manual = false) {
1180 const wanted = () => gen === epoch && S !== null && S.rec.phase === 'resuming' && S.rec.op === op
1181 if (testMode && dryActions) {
1182 $.ui.log(PREFIX + `[dry-run] would submit: ${text.split('\n')[0]}`)
1183 await dispatch($, { type: 'resumeDelivered', now: await $.clock.now(), op }, gen)
1184 await dispatch($, { type: 'resumeStarted', now: await $.clock.now(), op }, gen) // no real turn: stand in for its start
1185 $.clock.after(1500, () => void syntheticMeasure($, gen).catch((err: unknown) => logOnce($, err)))
1186 return
1187 }
1188 // An explicit /quota resume bypasses helper admission. A command's own hook frame refuses a submit until it has
1189 // returned; outsideHeldFrame waits for exactly that, so no fixed delay is needed here.
1190 if (helperUrl && !manual) {
1191 // Prefer helper admission, with automatic best-effort fallback if unavailable.
1192 const admission = await helperAdmit($, op, gen, wanted)
1193 if (!admission) return
1194 if (admission === 'store') await claimSlot($, wanted)
1195 } else if (!helperUrl) await claimSlot($, wanted)
1196 let detail = ''
1197 let attempts = 0
1198 const note = async (outcome: NonNullable<Diag['submit']>['outcome'], why: string) => {
1199 // the continuation's turn can start before the submit call returns: keep that start if it was already seen
1200 const startedAt = startSeen?.op === op && startSeen.gen === gen ? startSeen.at : undefinedhooks/core.ts 849 lines1// Pure quota state machine. No engine imports: the adapter (register.ts) feeds
2// it events and executes the effects it returns, so everything here is
3// unit-testable with plain values.
4
5export type Phase = 'idle' | 'armed' | 'compacting' | 'paused' | 'resuming' | 'stopped'
6
7export const FIVE = 'five_hour'
8export const WEEK = 'seven_day'
9
10export type Win = { kind: string; percent: number; resetsAt?: number }
11export type Usage = { windows: Win[]; contextPercent?: number }
12
13export type Config = {
14 enabled: boolean
15 threshold: number // 5-hour compaction/pause threshold, %
16 weeklyThreshold: number // weekly threshold, %
17 abortThreshold: number // abort the running turn at/above this, %
18 ceiling: number // burn-rate ceiling: pause if pct + predicted next jump >= this
19 burnMultiplier: number
20 graceSec: number // wait this long after the reported reset before re-checking
21 maxResumeAttempts: number
22 weeklyPolicy: 'pause' | 'notify'
23 notifyAt: number // one-off heads-up toast at this %, 0 = off
24 compactMinContext: number // compact before pausing only if context is above this %
25}
26
27export const DEFAULTS: Config = {
28 enabled: true,
29 threshold: 98, // compaction itself costs about one point, so this still leaves room for it
30 weeklyThreshold: 97,
31 abortThreshold: 99,
32 ceiling: 99,
33 burnMultiplier: 1.5,
34 graceSec: 30,
35 maxResumeAttempts: 5,
36 weeklyPolicy: 'pause',
37 notifyAt: 80,
38 compactMinContext: 30,
39}
40
41export type Rec = {
42 phase: Phase
43 reason?: string
44 kinds: string[]
45 expectedReset?: number
46 wakeAt?: number
47 task: string
48 pausedAt?: number
49 compactedAt?: number
50 compactFailed?: boolean
51 compactError?: string // why the quota compaction did not happen: the engine's own words
52 usage: Win[]
53 resumeAttempts: number
54 delayCount: number
55 lastResumeAt?: number
56 abortRequested?: boolean
57 op?: number // identity of the compaction / resume in flight; a completion for any other op is stale
58 delivered?: boolean // the session accepted this resume's prompt (accepted is not started)
59 deliveredAt?: number
60 started?: boolean // the continuation's own turn has started: only now has the task actually resumed
61 manual?: boolean // an explicit /quota resume: it does not queue behind account-wide coordination
62 verified?: boolean // quota was seen to have reset (it can be seen before the prompt is delivered)
63 predictive?: boolean // paused on the burn-rate prediction, not on a static limit
64 resets?: Record<string, number> // each window's reset time when the pause began: a reset is THAT window moving on
65 verifiedKinds?: string[] // the windows the quota evidence covered when it was taken
66 olderTurnRunning?: boolean // a turn was already running when this resume began: its completion is not ours
67 olderTurnId?: string // ...and which one
68 turnId?: string // the turn that is this resume's continuation, once it has started
69 foreignTurns?: string[] // turns that started during this resume and are not its continuation
70 causes?: Record<string, 'static' | 'predictive'> // why each window is part of the pause
71 // background-task notices that arrived while automatic prompts were held back: delivered with the continuation
72 // (or beside the person's own prompt when they take over), never simply lost
73 held?: string[]
74}
75
76export type State = {
77 v: 1
78 rec: Rec
79 busy: boolean
80 deltas: number[] // recent 5-hour jumps per measurement, for burn-rate
81 last?: { pct: number; resetsAt?: number }
82 notified: string[]
83 ctx?: number // last known context-window fill, %
84 turnId?: string // the main turn that is running
85 opSeq: number // source of operation identities
86 known: string[] // managed windows ever seen: a resume is only verified if all of them read healthy
87 ended?: { op: number; reason: Ended } // how the most recent resume operation ended (evidence, not just lifecycle)
88}
89
90// Why a resume operation stopped being in flight. Only 'verified' and 'completed' are evidence that quota is back.
91// 'stalled': the prompt was accepted but its turn never started, so nothing was learned about the quota.
92export type Ended = 'verified' | 'completed' | 'takeover' | 'interrupted' | 'cancelled' | 'failed' | 'stalled'
93
94export type Ev =
95 | { type: 'measure'; now: number; usage: Usage; shared?: boolean } // shared: another session's reading of the account
96 | { type: 'turnStart'; turnId?: string; owns?: boolean }
97 | { type: 'turnComplete'; now: number; reason: string; turnId?: string }
98 | { type: 'userPrompt'; now: number; text: string; isUser: boolean }
99 | { type: 'compactDone'; now: number; ok: boolean; op?: number; external?: boolean; detail?: string }
100 | { type: 'tick'; now: number; usage: Usage | null }
101 | { type: 'boot'; now: number; usage: Usage | null }
102 | { type: 'submitFailed'; now: number; text: string; op: number; detail?: string }
103 | { type: 'resumeDelivered'; now: number; op: number }
104 | { type: 'resumeStarted'; now: number; op: number } // dry run only: stands in for the continuation's turn.start
105 | { type: 'held'; text: string } // a background-task notice kept out of the paused session, to deliver later
106 | { type: 'resumeHold'; now: number; op: number } // the adapter is deliberately waiting (coordination): not a stalled resume
107 | { type: 'resumeBlocked'; now: number; op: number; why: string } // coordination refused the attempt: back off and retry
108 | { type: 'forcePause'; now: number; minutes: number }
109 | { type: 'cancel'; now: number }
110 | { type: 'resume'; now: number }
111
112export type Fx =
113 | { t: 'toast'; text: string }
114 | { t: 'abort'; op?: number; turnId?: string }
115 | { t: 'compact'; instructions: string; op: number }
116 | { t: 'submit'; text: string; op: number; manual: boolean }
117 | { t: 'fill'; text: string }
118
119export type Result = { state: State; fx: Fx[] }
120
121export const RESUME_PROMPT =
122 'Usage window has reset. Continue the previous task from the compacted context and persisted recovery state. Do not restart completed work.'
123
124const BACKOFF_SEC = [60, 120, 300, 600, 900]
125const RESUME_WATCHDOG_MS = 180_000
126// A reading arrives only with a response. Long after the expected reset (a session reopened hours later: its process
127// ended during the pause, as when Claude Desktop relaunches itself), waiting for one is waiting for nothing.
128const LONG_PAST_RESET_MS = 10 * 60_000
129// An accepted continuation that has not started its turn after this long, with nothing else running, is stalled.
130// It is not sent again (a late start would then run the continuation twice); the person is told instead.
131export const START_WATCHDOG_MS = 180_000
132
133export function emptyRec(task = ''): Rec {
134 return { phase: 'idle', kinds: [], task, usage: [], resumeAttempts: 0, delayCount: 0 }
135}
136
137export function initialState(): State {
138 return { v: 1, rec: emptyRec(), busy: false, deltas: [], notified: [], opSeq: 0, known: [] }
139}
140
141// ---------- formatting ----------
142
143const pad = (n: number) => (n < 10 ? '0' + n : String(n))
144
145export function fmtClock(ms: number): string {
146 const d = new Date(ms)
147 return `${pad(d.getHours())}:${pad(d.getMinutes())}`
148}
149
150export function fmtDur(ms: number): string {
151 const m = Math.max(0, Math.round(ms / 60000))
152 if (m < 1) return '<1m'
153 const h = Math.floor(m / 60)
154 if (h >= 24) return `${Math.floor(h / 24)}d ${h % 24}h`
155 return h > 0 ? `${h}h ${pad(m % 60)}m`.replace(/ 0(\d)m/, ' $1m') : `${m}m`
156}
157
158const label = (kind: string) => (kind === FIVE ? '5-hour' : kind === WEEK ? 'Weekly' : kind)
159
160export function describeWindow(w: Win, now: number): string {
161 const reset = w.resetsAt === undefined ? '' : w.resetsAt <= now ? ', reset time passed' : `, resets in ${fmtDur(w.resetsAt - now)}`
162 return `${label(w.kind)} usage: ${Math.round(w.percent)}%${reset}`
163}
164
165// ---------- helpers ----------
166
167const clone = (s: State): State => JSON.parse(JSON.stringify(s))
168
169function limitFor(kind: string, cfg: Config): number | undefined {
170 if (kind === FIVE) return cfg.threshold
171 if (kind === WEEK) return cfg.weeklyPolicy === 'pause' ? cfg.weeklyThreshold : undefined
172 return undefined
173}
174
175export function predictedJump(s: State, cfg: Config): number {
176 const m = s.deltas.length ? Math.max(...s.deltas) : 0
177 return Math.min(25, m * cfg.burnMultiplier)
178}
179
180function breaches(u: Usage, s: State, cfg: Config): Win[] {
181 const out: Win[] = []
182 for (const w of u.windows) {
183 const lim = limitFor(w.kind, cfg)
184 if (lim === undefined) continue
185 if (w.percent >= lim || (w.kind === FIVE && w.percent + predictedJump(s, cfg) >= cfg.ceiling)) out.push(w)
186 }
187 return out
188}
189
190const backoffMs = (n: number) => (BACKOFF_SEC[Math.min(n, BACKOFF_SEC.length - 1)] ?? 900) * 1000
191
192export function blocksAutomation(s: State): boolean {
193 return (
194 s.rec.phase === 'paused' ||
195 s.rec.phase === 'stopped' ||
196 s.rec.phase === 'compacting' ||
197 (s.rec.phase === 'resuming' && !s.rec.delivered)
198 )
199}
200
201export function compactInstructions(task: string): string {
202 return (
203 'A usage-limit pause is about to start and work will resume automatically afterwards. ' +
204 'In the summary, state verbatim the current task' +
205 (task ? ` ("${task.slice(0, 600)}")` : '') +
206 ', what is already done, what remains, and the exact next step. Say which commands or background jobs were ' +
207 'still running at this point (with their output files): they may finish during the pause, so they must be ' +
208 'checked, not run again. Do not restart completed work.'
209 )
210}
211
212const HELD_MAX = 8
213const HELD_CHARS = 2000
214
215// The notices a pause held back, as the model reads them with the continuation (or beside the person's prompt).
216export function heldNotices(held: readonly string[]): string {
217 return `Background work reported while the session was paused (these notices were held back until now):\n\n${held.join('\n\n')}`
218}
219
220// Identifies ONE resume operation: the text is not enough, because every operation shares the same instruction.
221export const resumeMarker = (op: number | undefined) => `[quota-guard recovery #${op ?? 0}]`
222
223export function resumePrompt(r: Rec): string {
224 const bits = [RESUME_PROMPT]
225 if (r.task) bits.push(`Task before the pause: ${r.task.slice(0, 1500)}`)
226 if (r.held?.length) bits.push(heldNotices(r.held))
227 bits.push(resumeMarker(r.op))
228 return bits.join('\n\n')
229}
230
231// ---------- the machine ----------
232
233export function step(s0: State, ev: Ev, cfg: Config): Result {
234 const s = clone(s0)
235 const fx: Fx[] = []
236 const toast = (text: string) => fx.push({ t: 'toast', text })
237 const r = s.rec
238 if (!s.known) s.known = []
239 const newOp = () => (s.opSeq = (s.opSeq ?? 0) + 1)
240 // the windows a resume must see healthy: those that caused the pause plus every managed one ever seen
241 const managedKinds = () => {
242 const m = new Set(r.kinds.filter(k => limitFor(k, cfg) !== undefined))
243 for (const k of s.known) if (limitFor(k, cfg) !== undefined) m.add(k)
244 return m
245 }
246 // Why a window is in the pause: over its limit (static), or only predicted to be (burn rate). A
247 // predictive cause is cleared only by THAT window moving on, never by another window's reset.
248 // Records saved before causes existed carry one aggregate flag that cannot describe a mixed pause, so a
249 // window is conservatively predictive unless the snapshot taken when the pause began shows it over its limit.
250 const causeOf = (k: string): 'static' | 'predictive' => {
251 const c = r.causes?.[k]
252 if (c) return c
253 const snap = r.usage.find(x => x.kind === k)
254 if (snap) return snap.percent >= (limitFor(k, cfg) ?? Infinity) ? 'static' : 'predictive'
255 return r.predictive ? 'predictive' : 'static'
256 }
257 const advanced = (k: string, w: Win | undefined) =>
258 w !== undefined && w.resetsAt !== undefined && w.resetsAt > (r.resets?.[k] ?? r.expectedReset ?? 0) + 120_000
259 const predictiveCleared = (u: Usage) => r.kinds.every(k => causeOf(k) !== 'predictive' || advanced(k, u.windows.find(x => x.kind === k)))
260 // a window that breaches after the pause began joins it, with its own cause and baseline
261 const join = (w: Win) => {
262 // a cause is acquired fresh when the window was not part of the pause, or when its earlier cause was
263 // resolved by that window moving on: the baseline (and the reason) belong to the window of THIS breach
264 const was = r.kinds.includes(w.kind)
265 const fresh = !was || advanced(w.kind, w)
266 if (!was) r.kinds.push(w.kind)
267 r.causes ??= {}
268 r.resets ??= {}
269 if (fresh) {
270 r.causes[w.kind] = w.percent >= (limitFor(w.kind, cfg) ?? Infinity) ? 'static' : 'predictive'
271 if (w.resetsAt !== undefined) r.resets[w.kind] = w.resetsAt
272 } else r.causes[w.kind] ??= causeOf(w.kind) // pin what an older record could only imply
273 }
274
275 const endOpAs = (reason: Ended) => {
276 if (r.phase === 'resuming' && r.op !== undefined) s.ended = { op: r.op, reason }
277 }
278 const settle = (task = r.task, reason?: Ended) => {
279 if (reason) endOpAs(reason)
280 s.rec = emptyRec(task)
281 }
282
283 const shouldCompact = () => s.ctx === undefined || s.ctx > cfg.compactMinContext
284
285 const compactOrPause = (now: number) => {
286 if (shouldCompact()) startCompact()
287 else {
288 r.compactedAt = undefined
289 enterPause(now)
290 }
291 }
292
293 const startCompact = () => {
294 r.phase = 'compacting'
295 r.op = newOp()
296 fx.push({ t: 'compact', op: r.op, instructions: compactInstructions(r.task) })
297 }
298
299 const enterPause = (now: number) => {
300 r.phase = 'paused'
301 r.op = undefined
302 r.pausedAt = now
303 const grace = cfg.graceSec * 1000
304 r.wakeAt = r.expectedReset === undefined ? now + backoffMs(r.delayCount) : Math.max(r.expectedReset + grace, now + 5000)
305 if (r.compactFailed) toast(r.compactError ? `Compaction failed (${r.compactError}); pausing anyway.` : 'Compaction failed; pausing anyway.')
306 toast(`Paused until approximately ${fmtClock(r.wakeAt)}.`)
307 }
308
309 const arm = (now: number, wins: Win[], all: Usage | null, reasonOverride?: string) => {
310 const resets = wins.map(w => w.resetsAt).filter((x): x is number => typeof x === 'number')
311 const task = r.task
312 const fresh: Rec = {
313 ...emptyRec(task),
314 phase: 'armed',
315 kinds: wins.map(w => w.kind),
316 reason: reasonOverride ?? wins.map(w => describeWindow(w, now)).join('; '),
317 expectedReset: resets.length ? Math.max(...resets) : undefined,
318 usage: all ? all.windows.map(w => ({ ...w })) : wins.map(w => ({ ...w })),
319 predictive: wins.every(w => w.percent < (limitFor(w.kind, cfg) ?? Infinity)),
320 resets: Object.fromEntries((all ? all.windows : wins).filter(w => w.resetsAt !== undefined).map(w => [w.kind, w.resetsAt as number])),
321 causes: Object.fromEntries(wins.map(w => [w.kind, w.percent >= (limitFor(w.kind, cfg) ?? Infinity) ? 'static' : 'predictive'])) as Rec['causes'],
322 }
323 for (const k of Object.keys(r)) delete (r as Record<string, unknown>)[k]
324 Object.assign(r, fresh)
325 r.op = newOp()
326 // the worst breached window drives the message and the decision to abort a running turn
327 const top = wins.reduce<Win | undefined>((m, w) => (m === undefined || w.percent > m.percent ? w : m), undefined)
328 if (top) {
329 const pct = Math.round(top.percent)
330 toast(
331 shouldCompact()
332 ? `${label(top.kind)} usage reached ${pct}%. Compacting before quota exhaustion.`
333 : `${label(top.kind)} usage reached ${pct}%. Context is only ${Math.round(s.ctx ?? 0)}%, so no compaction needed; waiting for the reset.`,
334 )
335 }
336 if (s.busy) {
337 if (top && top.percent >= cfg.abortThreshold) {
338 r.abortRequested = true
339 fx.push({ t: 'abort', op: r.op, turnId: s.turnId })
340 }
341 } else compactOrPause(now)
342 }
343
344 const resumeNow = (now: number, mode: 'confirmed' | 'assumed' | 'forced') => {
345 if (r.resumeAttempts >= cfg.maxResumeAttempts) {
346 r.phase = 'stopped'
347 r.wakeAt = undefined
348 toast(`Auto-resume gave up after ${r.resumeAttempts} attempts. Use /quota resume or send a prompt.`)
349 return
350 }
351 r.phase = 'resuming'
352 r.op = newOp()
353 r.delivered = false
354 r.deliveredAt = undefined
355 r.started = false
356 r.manual = mode === 'forced'
357 r.verified = false
358 r.verifiedKinds = undefined
359 r.olderTurnRunning = s.busy
360 r.olderTurnId = s.busy ? s.turnId : undefined
361 r.turnId = undefined
362 r.foreignTurns = undefined
363 r.resumeAttempts++
364 r.lastResumeAt = now
365 toast(
366 mode === 'confirmed'
367 ? 'Usage reset confirmed. Preparing to resume task.'
368 : mode === 'assumed'
369 ? 'Reset time passed (usage not re-measured yet). Preparing a resume attempt to verify.'
370 : 'Preparing to resume task.',
371 )
372 fx.push({ t: 'submit', op: r.op, text: resumePrompt(r), manual: r.manual === true })
373 }
374
375 const resumeFailed = (now: number, why: string, nextReset?: number) => {
376 endOpAs('failed')
377 r.op = undefined
378 r.delivered = false
379 r.deliveredAt = undefined
380 r.started = false
381 r.verified = false
382 r.verifiedKinds = undefined
383 r.olderTurnRunning = false
384 r.olderTurnId = undefined
385 r.turnId = undefined
386 r.foreignTurns = undefined
387 r.delayCount++
388 if (r.resumeAttempts >= cfg.maxResumeAttempts) {
389 r.phase = 'stopped'
390 r.wakeAt = undefined
391 toast(`Auto-resume gave up (${why}). Use /quota resume when the limit has reset.`)
392 return
393 }
394 r.phase = 'paused'
395 if (nextReset !== undefined) r.expectedReset = nextReset
396 r.wakeAt = Math.max(nextReset !== undefined ? nextReset + cfg.graceSec * 1000 : 0, now + backoffMs(r.delayCount))
397 toast(`Resume did not take (${why}). Trying again around ${fmtClock(r.wakeAt)}.`)
398 }
399
400 // The task has resumed only when the continuation's own turn starts: an accepted prompt is not a started one.
401 // With the quota already verified the operation is done; otherwise its turn's outcome or a reading decides.
402 const continuationStarted = () => {
403 r.started = true
404 r.delivered = true // a prompt that started was accepted, whichever of the two the adapter reports first
405 if (r.verified && [...managedKinds()].every(k => r.verifiedKinds?.includes(k))) {
406 settle(r.task, 'verified')
407 toast('Quota reset verified; the task is continuing.')
408 } else toast('The resume prompt started; the task is continuing.')
409 }
410
411 // Accepted but never started: sending it again could run the continuation twice if the first one is merely late
412 const stalled = () => {
413 endOpAs('stalled')
414 r.phase = 'stopped'
415 r.op = undefined
416 r.wakeAt = undefined
417 toast('The resume prompt was accepted but its turn never started, so auto-resume stopped instead of sending it twice. Send a prompt or use /quota resume to continue.')
418 }
419
420 const wake = (now: number, usage: Usage | null) => {
421 if (!usage || usage.windows.length === 0) {
422 r.delayCount++
423 const longPast = r.expectedReset !== undefined && now - r.expectedReset >= LONG_PAST_RESET_MS
424 const lateAndBlind = longPast || (r.delayCount >= 3 && (r.expectedReset === undefined || r.expectedReset <= now))
425 if (lateAndBlind) return resumeNow(now, 'assumed')
426 r.wakeAt = now + backoffMs(r.delayCount)
427 if (r.delayCount === 1) toast('Usage data unavailable; will retry shortly.')
428 return
429 }
430 // every managed window counts, not only the ones that caused the pause: another one may have
431 // been exhausted since (or the pause started on a different window)
432 const limited: number[] = []
433 let stale = false
434 const kinds = new Set(r.kinds.filter(k => limitFor(k, cfg) !== undefined))
435 for (const w of usage.windows) if (limitFor(w.kind, cfg) !== undefined) kinds.add(w.kind)
436 for (const k of s.known) if (limitFor(k, cfg) !== undefined) kinds.add(k)
437 for (const k of kinds) {
438 const w = usage.windows.find(x => x.kind === k)
439 const lim = limitFor(k, cfg) ?? cfg.threshold
440 if (!w) {
441 stale = true
442 continue
443 }
444 if (w.percent >= lim) {
445 join(w)
446 if (w.resetsAt !== undefined && w.resetsAt > now) limited.push(w.resetsAt)
447 else stale = true // reading predates the reset; only a fresh response can tell
448 } else if (r.kinds.includes(k) && causeOf(k) === 'predictive' && !advanced(k, w)) {
449 if (w.resetsAt !== undefined && w.resetsAt > now) limited.push(w.resetsAt) // still the window that was about to run out
450 else stale = true
451 }
452 }
453 if (limited.length) {
454 const next = Math.max(...limited)
455 const moved = r.expectedReset === undefined || Math.abs(next - r.expectedReset) > 60_000
456 r.expectedReset = next
457 r.wakeAt = next + cfg.graceSec * 1000
458 r.delayCount++
459 toast(
460 moved
461 ? `Quota not reset yet; reset time moved to about ${fmtClock(next)}.`
462 : `Quota not reset yet; rechecking around ${fmtClock(r.wakeAt)}.`,
463 )
464 return
465 }
466 resumeNow(now, stale ? 'assumed' : 'confirmed')
467 }
468
469 const tickLike = (now: number, usage: Usage | null) => {
470 if (r.phase === 'paused' && cfg.enabled && !s.busy && r.wakeAt !== undefined && now >= r.wakeAt) wake(now, usage)
471 // a turn that is running is the resume prompt being answered (or one ahead of it), however slowly: never time
472 // it out and never queue a second probe behind it. A prompt never accepted is a failed attempt (retried later);
473 // one accepted whose turn never started is stalled (not resent).
474 else if (r.phase === 'resuming' && !s.busy && !r.started) {
475 if (!r.delivered && r.lastResumeAt !== undefined && now - r.lastResumeAt > RESUME_WATCHDOG_MS) resumeFailed(now, 'no response to the resume prompt')
476 else if (r.delivered && now - (r.deliveredAt ?? r.lastResumeAt ?? now) > START_WATCHDOG_MS) stalled()
477 }
478 }
479
480 // Evidence about a resume in flight. Only a reading that is evidence counts. Under the limit in EVERY
481 // managed window we have ever seen (and every predictive cause moved on): the reset happened. Over a
482 // limit with a reset still ahead: it did not. Over it with a reset already past, a window missing, or an
483 // unchanged snapshot of a burn-rate pause: the old reading again, no evidence either way. Later evidence
484 // can contradict earlier evidence, so verification is withdrawn rather than latched.
485 const assessResuming = (now: number, u: Usage, hit: Win[]) => {
486 const managed = managedKinds()
487 const limitedResets: number[] = []
488 let allLow = managed.size > 0
489 let anyHigh = false
490 for (const k of managed) {
491 const w = u.windows.find(x => x.kind === k)
492 const lim = limitFor(k, cfg) ?? cfg.threshold
493 if (!w) {
494 allLow = false
495 continue
496 }
497 if (w.percent >= lim) {
498 allLow = false
499 anyHigh = true
500 if (w.resetsAt !== undefined && w.resetsAt > now) limitedResets.push(w.resetsAt)
501 }
502 }
503 // a window that was fine when the pause began but is exhausted now blocks the resume too
504 for (const w of hit) {
505 if (r.kinds.includes(w.kind) || w.resetsAt === undefined || w.resetsAt <= now) continue
506 join(w)
507 limitedResets.push(w.resetsAt)
508 allLow = false
509 anyHigh = true
510 }
511 if (limitedResets.length) {
512 resumeFailed(now, 'quota still exhausted', Math.max(...limitedResets))
513 } else if (allLow && predictiveCleared(u)) {
514 // quota is verified; the operation is only done once its continuation's turn has actually started
515 if (r.started) {
516 const task = r.task
517 settle(task, 'verified')
518 toast('Quota reset verified.')
519 } else {
520 r.verified = true
521 r.verifiedKinds = [...managed]
522 }
523 } else if (anyHigh) {
524 r.verified = false
525 r.verifiedKinds = undefined
526 }
527 }
528
529 const evaluate = (now: number, usage: Usage) => {
530 const hit = breaches(usage, s, cfg)
531 if (hit.length) arm(now, hit, usage)
532 }
533
534 if (ev.type === 'measure' || ev.type === 'tick' || ev.type === 'boot') {
535 for (const w of ev.usage?.windows ?? []) if (limitFor(w.kind, cfg) !== undefined && !s.known.includes(w.kind)) s.known.push(w.kind)
536 }
537
538 switch (ev.type) {
539 case 'measure': {
540 if (typeof ev.usage.contextPercent === 'number') s.ctx = ev.usage.contextPercent
541 if (!cfg.enabled) break
542 const u = ev.usage
543 const five = u.windows.find(w => w.kind === FIVE)
544 if (five) {
545 // burn-rate history is the growth over the last few measurements of THIS window: a new
546 // window starts it over, and flat measurements age an old spike out
547 const sameWindow = s.last !== undefined && Math.abs((s.last.resetsAt ?? 0) - (five.resetsAt ?? 0)) < 120_000
548 if (!sameWindow) s.deltas = []
549 // other sessions' spending since this one last looked is not this session's burn rate: it moves the
550 // baseline, never the predicted jump
551 else if (s.last && !ev.shared) {
552 s.deltas.push(Math.max(0, five.percent - s.last.pct))
553 s.deltas = s.deltas.slice(-5)
554 }
555 s.last = { pct: five.percent, resetsAt: five.resetsAt }
556 }
557 const hit = breaches(u, s, cfg)
558
559 if (r.phase === 'resuming') {
560 assessResuming(ev.now, u, hit)
561 break
562 }
563 if (r.phase === 'idle') {
564 if (hit.length) {
565 arm(ev.now, hit, u)
566 break
567 }
568 if (cfg.notifyAt > 0) {
569 for (const w of u.windows) {
570 if (limitFor(w.kind, cfg) === undefined && w.kind !== WEEK) continue
571 const key = `${w.kind}@${Math.round((w.resetsAt ?? 0) / 60000)}`
572 if (w.percent >= cfg.notifyAt && !s.notified.includes(key)) {
573 s.notified = [...s.notified, key].slice(-10)
574 toast(describeWindow(w, ev.now))
575 }
576 }
577 }
578 break
579 }
580 if (r.phase === 'armed') {
581 r.usage = u.windows.map(w => ({ ...w }))
582 // a window that is exhausted after arming joins the pause and sets how long it lasts
583 for (const w of hit) {
584 join(w)
585 if (w.resetsAt !== undefined) r.expectedReset = Math.max(r.expectedReset ?? 0, w.resetsAt)
586 }
587 const worst = hit.reduce((m, w) => Math.max(m, w.percent), 0)
588 if (s.busy && !r.abortRequested && worst >= cfg.abortThreshold) {
589 r.abortRequested = true
590 fx.push({ t: 'abort', op: r.op, turnId: s.turnId })
591 }
592 break
593 }
594 if (r.phase === 'paused') {
595 for (const w of hit) join(w)
596 const managed = managedKinds()
597 const blocking: number[] = []
598 let allLow = managed.size > 0
599 for (const k of managed) {
600 const w = u.windows.find(x => x.kind === k)
601 const lim = limitFor(k, cfg) ?? cfg.threshold
602 if (!w || w.percent >= lim) allLow = false
603 if (w && w.percent >= lim && w.resetsAt !== undefined && w.resetsAt > ev.now) blocking.push(w.resetsAt)
604 // a predictive cause that has not moved on keeps blocking until ITS OWN reset, whatever joined it
605 if (w && r.kinds.includes(k) && causeOf(k) === 'predictive' && !advanced(k, w) && w.resetsAt !== undefined && w.resetsAt > ev.now) {
606 blocking.push(w.resetsAt)
607 }
608 }
609 if (blocking.length) {
610 // only a reading that is still blocking can move the wake time
611 const next = Math.max(...blocking)
612 if (r.expectedReset === undefined || Math.abs(next - r.expectedReset) > 60_000) {
613 r.expectedReset = next
614 r.wakeAt = next + cfg.graceSec * 1000
615 toast(`Reset time changed; now paused until approximately ${fmtClock(r.wakeAt)}.`)
616 }
617 } else if (allLow && predictiveCleared(u) && r.wakeAt !== undefined && r.wakeAt > ev.now) {
618 // a fresh reading under every limit, with each burn-rate cause moved on, means the reset already happened
619 r.wakeAt = ev.now
620 }
621 }
622 break
623 }
624
625 case 'turnStart':
626 s.busy = true
627 s.turnId = ev.turnId
628 if (r.phase === 'resuming') {
629 // a turn that begins while resuming is the continuation's only if it is known to be (the adapter
630 // recognises our prompt); with no information, one that starts before delivery cannot be
631 const own = ev.owns ?? r.delivered === true
632 if (own) {
633 r.turnId = ev.turnId
634 if (!r.started) continuationStarted()
635 } else if (ev.turnId !== undefined) r.foreignTurns = [...(r.foreignTurns ?? []), ev.turnId]
636 }
637 break
638
639 case 'turnComplete': {
640 const id = ev.turnId
641 const currentEnds = id === undefined || s.turnId === undefined || id === s.turnId
642 if (!currentEnds) {
643 // a late completion for a turn that is no longer the current one: it ends nothing that is running now
644 if (r.phase === 'resuming' && id === r.olderTurnId) r.olderTurnRunning = false
645 break
646 }
647 s.busy = false
648 s.turnId = undefined
649 if (r.phase === 'armed') {
650 if (r.compactedAt !== undefined) enterPause(ev.now)
651 else compactOrPause(ev.now)
652 } else if (r.phase === 'resuming') {
653 const ours =
654 id === undefined
655 ? !r.olderTurnRunning
656 : r.turnId !== undefined
657 ? id === r.turnId
658 : !(r.foreignTurns ?? []).includes(id) && id !== r.olderTurnId
659 if (!ours) {
660 // the turn that was already running when this resume began, or another turn: not the continuation
661 if (id === undefined || id === r.olderTurnId) r.olderTurnRunning = false
662 } else if (ev.reason === 'error') resumeFailed(ev.now, 'API error')
663 else if (ev.reason === 'aborted') {
664 settle(r.task, 'interrupted')
665 toast('Resume turn was interrupted; auto-resume finished.')
666 } else {
667 settle(r.task, 'completed') // the model answered after the reset: a served request is evidence
668 toast('Quota reset verified.')
669 }
670 }
671 break
672 }
673
674 case 'userPrompt': {
675 if (!ev.isUser) break
676 if (r.phase === 'paused' || r.phase === 'stopped') {
677 settle(r.task)
678 toast('Auto-resume cancelled: you resumed manually.')
679 } else if (r.phase === 'resuming') {
680 settle(r.task, 'takeover')
681 } else if (r.phase === 'armed' || r.phase === 'compacting') {
682 settle(r.task)
683 toast('Quota pause cancelled: you sent a new prompt.')
684 }
685 const t = ev.text.trim()
686 if (t && !t.startsWith('/') && (t.length >= 12 || !s.rec.task)) s.rec.task = t.slice(0, 4000)
687 break
688 }
689
690 case 'compactDone': {
691 if (ev.external) {
692 // anyone's compaction of this conversation (the person's /compact, auto-compact) does the pause's job
693 if (r.phase === 'armed' || r.phase === 'compacting') {
694 r.compactedAt = ev.now
695 r.compactFailed = false
696 r.compactError = undefined
697 if (!s.busy) enterPause(ev.now)
698 }
699 break
700 }
701 if (r.phase === 'compacting' && ev.op === r.op) {
702 r.compactedAt = ev.ok ? ev.now : undefined
703 r.compactFailed = !ev.ok
704 r.compactError = ev.ok ? undefined : ev.detail?.slice(0, 200)
705 enterPause(ev.now)
706 }
707 break
708 }
709
710 case 'tick':
711 if (r.phase === 'resuming' && ev.usage && cfg.enabled) assessResuming(ev.now, ev.usage, breaches(ev.usage, s, cfg))
712 tickLike(ev.now, ev.usage)
713 break
714
715 case 'boot': {
716 s.busy = false
717 if (ev.usage && typeof ev.usage.contextPercent === 'number') s.ctx = ev.usage.contextPercent
718 if (r.phase === 'compacting' || r.phase === 'armed') {
719 if (r.compactedAt !== undefined) {
720 enterPause(ev.now)
721 } else {
722 settle(r.task)
723 if (cfg.enabled && ev.usage) evaluate(ev.now, ev.usage)
724 }
725 } else if (r.phase === 'paused') {
726 toast(
727 r.wakeAt !== undefined && ev.now < r.wakeAt
728 ? `Restored quota pause; checking again around ${fmtClock(r.wakeAt)}.`
729 : 'Restored quota pause; reset time has passed, checking now.',
730 )
731 tickLike(ev.now, ev.usage)
732 } else if (r.phase === 'resuming') {
733 tickLike(ev.now, ev.usage)
734 } else if (r.phase === 'idle' && cfg.enabled && ev.usage) {
735 evaluate(ev.now, ev.usage)
736 }
737 break
738 }
739
740 case 'resumeDelivered': {
741 // accepted, not started: the start watchdog runs from here until the continuation's turn begins
742 if (r.phase !== 'resuming' || ev.op !== r.op) break
743 r.delivered = true
744 r.deliveredAt ??= ev.now
745 break
746 }
747
748 case 'held': {
749 // only while automatic prompts are held back; otherwise the notice reached the session normally
750 if (!blocksAutomation(s)) break
751 r.held = [...(r.held ?? []), ev.text.slice(0, HELD_CHARS)].slice(-HELD_MAX)
752 break
753 }
754
755 case 'resumeStarted': {
756 if (r.phase !== 'resuming' || ev.op !== r.op || r.started) break
757 continuationStarted()
758 break
759 }
760
761 case 'resumeHold': {
762 // waiting for an account-wide slot is not silence: keep the no-response watchdog from timing the attempt out
763 if (r.phase === 'resuming' && ev.op === r.op && !r.delivered) r.lastResumeAt = ev.now
764 break
765 }
766
767 case 'resumeBlocked': {
768 if (r.phase !== 'resuming' || ev.op !== r.op) break
769 resumeFailed(ev.now, ev.why)
770 break
771 }
772
773 case 'submitFailed': {
774 if (r.phase !== 'resuming' || ev.op !== r.op) break
775 r.op = undefined
776 r.phase = 'stopped'
777 r.wakeAt = undefined
778 fx.push({ t: 'fill', text: ev.text })
779 toast(`Could not submit the resume prompt automatically${ev.detail ? ` (${ev.detail.slice(0, 200)})` : ''}. It is in the prompt box: press Enter to continue.`)
780 break
781 }
782
783 case 'forcePause': {
784 if (r.phase !== 'idle' && r.phase !== 'stopped') {
785 toast(`Already ${r.phase}.`)
786 break
787 }
788 const reset = ev.now + ev.minutes * 60_000
789 const task = r.task
790 for (const k of Object.keys(r)) delete (r as Record<string, unknown>)[k]
791 Object.assign(r, {
792 ...emptyRec(task),
793 phase: 'armed',
794 kinds: ['forced'],
795 reason: `forced pause for ${ev.minutes}m (testing)`,
796 expectedReset: reset,
797 })
798 toast(`Forced pause: compacting, then waiting until about ${fmtClock(reset)}.`)
799 if (!s.busy) compactOrPause(ev.now)
800 break
801 }
802
803 case 'cancel': {
804 if (r.phase === 'idle') {
805 toast('Nothing pending to cancel.')
806 break
807 }
808 endOpAs('cancelled')
809 r.phase = 'stopped'
810 r.op = undefined
811 r.wakeAt = undefined
812 toast('Auto-resume cancelled. Use /quota resume or send a prompt to continue.')
813 break
814 }
815
816 case 'resume': {
817 if (r.phase === 'paused' || r.phase === 'stopped') {
818 r.resumeAttempts = 0
819 resumeNow(ev.now, 'forced')
820 } else if (r.phase === 'resuming' && !r.delivered) {
821 // the automatic attempt is still waiting (for a coordination slot, say): replace it with an explicit one.
822 // The old operation is invalidated at once; whoever holds a reservation for it releases it separately.
823 endOpAs('cancelled')
824 resumeNow(ev.now, 'forced')
825 } else if (r.phase === 'resuming' && r.started) toast('The resume prompt was already delivered; it is being answered.')
826 else if (r.phase === 'resuming') toast('The resume prompt was accepted and is waiting to start; it is not sent twice.')
827 else toast('Nothing to resume.')
828 break
829 }
830 }
831
832 return { state: s, fx }
833}
834
835export function needsHeartbeat(s: State): boolean {
836 return s.rec.phase === 'paused' || s.rec.phase === 'resuming'
837}
838
839export function statusLine(s: State, u: Usage | null, now: number): string | undefined {
840 const r = s.rec
841 if (r.phase === 'paused' && r.wakeAt !== undefined) return `quota pause until ${fmtClock(r.wakeAt)}`
842 if (r.phase === 'resuming') return r.started ? 'quota: continuing task' : r.delivered ? 'quota: resume prompt queued' : 'quota: preparing resume'
843 if (r.phase === 'stopped') return 'quota: auto-resume held'
844 if (r.phase === 'compacting' || r.phase === 'armed') return 'quota: compacting'
845 const five = u?.windows.find(w => w.kind === FIVE)
846 if (!five) return undefined
847 return `5h ${Math.round(five.percent)}%${five.resetsAt && five.resetsAt > now ? ` · ${fmtDur(five.resetsAt - now)}` : ''}`
848}
849hooks/idle.ts 123 lines1// Idle compaction planner: pure logic, no engine imports.
2//
3// While a session waits on a background job, the prompt cache keeps ticking down. If the cache
4// expires, the next request re-sends the whole context at full (cache-write) price. Compacting
5// just BEFORE it expires reads the context at the cheap cached rate and leaves a small context
6// for whatever wakes the session up. After expiry compacting saves nothing, so we never do it.
7
8export type Pending = {
9 id: string
10 kind: 'bash' | 'monitor' | 'agent'
11 label: string // what it is, in a few words
12 command?: string
13 at: number // when it was started
14}
15
16export type IdleCfg = {
17 enabled: boolean
18 minTokens: number // only worth it above this many context tokens
19 ttlMs: number // prompt-cache lifetime (5 min or 1 h)
20 marginMs: number // compact this long before the cache expires
21 requireWaiting: boolean // true: only while waiting on background work; false: any idle session
22}
23
24export const IDLE_DEFAULTS: IdleCfg = {
25 enabled: true,
26 minTokens: 200_000,
27 ttlMs: 60 * 60_000,
28 marginMs: 180_000,
29 requireWaiting: false,
30}
31
32export type IdleInput = {
33 now: number
34 lastResponseAt?: number // when the last model response finished (cache last refreshed)
35 tokens?: number // context size the next request would re-send
36 busy: boolean // a turn is running (compaction is refused while one runs)
37 pending: readonly Pending[]
38 quotaPhase: string // the quota state machine's phase; only act while it is 'idle'
39 lastIdleCompactAt?: number
40}
41
42export type IdleDecision = { act: boolean; at?: number; why: string }
43
44const MIN_LEAD_MS = 60_000
45const MAX_PENDING_AGE_MS = 6 * 3600_000
46
47export function freshPending(list: readonly Pending[], now: number): Pending[] {
48 return list.filter(p => now - p.at < MAX_PENDING_AGE_MS)
49}
50
51export function planIdleCompact(cfg: IdleCfg, i: IdleInput): IdleDecision {
52 if (!cfg.enabled) return { act: false, why: 'off' }
53 if (i.busy) return { act: false, why: 'a turn is running' }
54 if (i.quotaPhase !== 'idle') return { act: false, why: `quota state is ${i.quotaPhase}` }
55 if (cfg.requireWaiting && freshPending(i.pending, i.now).length === 0) return { act: false, why: 'not waiting on background work' }
56 if (i.tokens === undefined) return { act: false, why: 'context size unknown' }
57 if (i.tokens < cfg.minTokens) return { act: false, why: 'context below the minimum' }
58 if (i.lastResponseAt === undefined) return { act: false, why: 'no response yet' }
59 if (i.lastIdleCompactAt !== undefined && i.lastIdleCompactAt >= i.lastResponseAt) {
60 return { act: false, why: 'already compacted since the last response' }
61 }
62 const expires = i.lastResponseAt + cfg.ttlMs
63 const trigger = i.lastResponseAt + Math.max(cfg.ttlMs - cfg.marginMs, MIN_LEAD_MS)
64 if (i.now >= expires) return { act: false, why: 'cache already cold, compaction would save nothing' }
65 if (i.now < trigger) return { act: false, at: trigger, why: 'waiting for the cache to near expiry' }
66 return { act: true, why: 'cache about to expire' }
67}
68
69// ---------- recognising background work from a tool call ----------
70
71const short = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + '…' : s)
72
73export function pendingFromTool(tool: string, input: Record<string, unknown>, id: string, now: number): Pending | undefined {
74 const str = (k: string) => (typeof input[k] === 'string' ? (input[k] as string) : undefined)
75 if (tool === 'Bash' || tool === 'PowerShell') {
76 if (input.run_in_background !== true) return undefined
77 const command = str('command')
78 return { id, kind: 'bash', label: short(str('description') ?? command ?? tool, 100), command: command ? short(command, 300) : undefined, at: now }
79 }
80 if (tool === 'Monitor') {
81 const command = str('command')
82 return { id, kind: 'monitor', label: short(str('description') ?? command ?? 'monitor', 100), command: command ? short(command, 300) : undefined, at: now }
83 }
84 if (tool === 'Agent') {
85 if (input.run_in_background === false) return undefined // agents run in the background unless told not to
86 return { id, kind: 'agent', label: short(str('description') ?? 'subagent', 100), at: now }
87 }
88 return undefined
89}
90
91// A background task finished: drop the entry the notification most plausibly names,
92// else the oldest one. Imprecise on purpose; being wrong only skips or delays a compaction.
93export function clearOnNotification(list: readonly Pending[], text: string): Pending[] {
94 if (list.length === 0) return []
95 const t = text.toLowerCase()
96 const hit = list.findIndex(p => (p.label.length > 3 && t.includes(p.label.toLowerCase())) || (p.command !== undefined && p.command.length > 3 && t.includes(p.command.toLowerCase().slice(0, 60))))
97 const drop = hit >= 0 ? hit : 0
98 return list.filter((_, idx) => idx !== drop)
99}
100
101// ---------- what the summary must keep ----------
102
103export function idleInstructions(pending: readonly Pending[], task: string): string {
104 const lines = pending.slice(-6).map(p => `- ${p.kind}: ${p.label}${p.command ? ` (command: ${p.command})` : ''}`)
105 const task_ = task ? `Current task: ${task.slice(0, 600)}\n` : ''
106 if (lines.length === 0) {
107 return (
108 'The session has been idle for a while; compacting now to keep the context small before the prompt cache expires. ' +
109 'Make the summary lead with the current task and its state, and keep verbatim: the file paths, commands, and decisions that matter, ' +
110 'and the exact next step to take when work resumes. Do not restart or redo completed work.\n' +
111 task_
112 )
113 }
114 return (
115 'The session is idle, waiting on background work that will wake it up later; compacting now to keep the context small. ' +
116 'Make the summary lead with what the session is waiting on, and keep verbatim: the task ids, commands, and file paths involved, ' +
117 'where the output will appear, how to tell whether it succeeded, and the exact next step to take when it finishes. ' +
118 'Do not restart or redo completed work.\n' +
119 task_ +
120 `Waiting on:\n${lines.join('\n')}`
121 )
122}
123hooks/transport.ts 49 lines1// Pure helpers for the compaction transport. The adapter (register.tsx) makes the engine calls; this file only says
2// what an answer means, so the classification is testable against the exact text the engine produces. The strings
3// were captured from Claude Code 2.1.299 in an SDK (stream-json) session, which is how Claude Desktop runs it.
4
5export type Refusal =
6 | 'held' // called from inside a hook frame that holds the turn: retry once that hook has returned
7 | 'turn-running' // the direct API refuses while a turn runs: retry between turns
8 | 'sdk' // the direct API does not exist in this session (SDK / -p, so Claude Desktop): use the /compact command
9 | 'disabled' // compaction is switched off in this session, for /compact and plugins alike
10 | 'no-command' // this session has no /compact command
11 | 'stopped' // the person stopped the session and has not typed since: the engine refuses plugin input until then
12 | 'dequeued' // a queued command was removed before it ran, or left the queue as text for the model
13 | 'other'
14
15export function classifyRefusal(message: string): Refusal {
16 if (/called from an? [\w.]+ hook/.test(message)) return 'held'
17 if (/a turn is running/.test(message)) return 'turn-running'
18 if (/not available in a headless|\(-p \/ SDK\) session/.test(message)) return 'sdk'
19 if (/switched off|DISABLE_COMPACT/.test(message)) return 'disabled'
20 if (/no command named \/compact/.test(message)) return 'no-command'
21 if (/session was stopped and nobody has sent input/.test(message)) return 'stopped'
22 if (/removed from the queue|left the queue as text|ended without running the command/.test(message)) return 'dequeued'
23 return 'other'
24}
25
26// The marker that ties one compaction request to the operation that made it. The plugin's own session.compact hook
27// reads it, strips it before the summarizer sees the instructions, and settles exactly that operation; a request
28// whose operation is gone by the time it runs is refused there (a queued command cannot be recalled any other way).
29const TAG = /\s*\[quota-guard compaction ([A-Za-z0-9._-]+)\]\s*$/
30
31export const tagInstructions = (instructions: string, token: string) => `${instructions}\n\n[quota-guard compaction ${token}]`
32
33export function readTag(instructions: unknown): { token: string; clean: string } | undefined {
34 if (typeof instructions !== 'string') return undefined
35 const m = TAG.exec(instructions)
36 return m ? { token: m[1] as string, clean: instructions.slice(0, m.index) } : undefined
37}
38
39// What the /compact command's own answer says, for when the plugin's hook saw nothing (a hook above it answered or
40// vetoed, or core refused before compacting). A successful run may answer no text at all, so silence proves nothing;
41// core's own success line ("Compacted ...", as the transcript shows it) is a claim the caller can check.
42export function readCommandText(text: string | undefined): { outcome: 'vetoed' | 'failed' | 'claimed' | 'silent'; detail: string } {
43 const t = (text ?? '').trim()
44 if (!t) return { outcome: 'silent', detail: 'the /compact command answered nothing' }
45 if (/^not compacted\b/i.test(t)) return { outcome: 'vetoed', detail: t.replace(/^not compacted\W*/i, '') || t }
46 if (/^compacted\b/i.test(t)) return { outcome: 'claimed', detail: t }
47 return { outcome: 'failed', detail: t }
48}
49types/index.d.ts 38 lines1export type QuotaBar = {
2 ctx?: number
3 ctxTokens?: number
4 ctxWindow?: number
5 fiveAt?: string
6 weekAt?: string
7 threshold?: number
8 ctxMin?: number
9 legend?: boolean
10 parts?: { name: string; pct: number }[]
11 five?: number
12 fiveReset?: string
13 week?: number
14 weekReset?: string
15 phase: string
16 note?: string
17}
18
19export type CtxDetail = {
20 model: string
21 total: number
22 window: number
23 percent: number
24 autoAt?: number
25 categories: { name: string; tokens: number; kind: string }[]
26 memory: { path: string; tokens: number }[]
27 mcp: { server: string; tokens: number }[]
28 agents: { name: string; tokens: number }[]
29 skills?: { count: number; total: number; tokens: number; top: { name: string; tokens: number }[] }
30 api?: { input?: number; cacheRead?: number; cacheWrite?: number; output?: number }
31}
32
33declare module 'claude-code' {
34 interface PluginState {
35 'quota-guard': { bar: QuotaBar | null; detail: CtxDetail | null }
36 }
37}
38