Writes the account's rate-limit windows (five_hour, seven_day) and the account they belong to into ~/.claude/local/rate-limits.json on every measurement, for…

A hooks-only mod that writes the account's rate-limit windows, and which account they belong to, to ~/.claude/local/rate-limits.json on every measurement, so scripts/fleet-launch.sh can print the active account's burst (five_hour) and weekly (seven_day) readings before it dispatches, and scripts/fleet-headroom.sh can park a fleet session on the same meter. Nothing at launch reported weekly use before it: the 2026-10-10 fleet (3 sessions, 12h) was launched on an account 5.75h from its weekly limit and lost 18.75 of its 36 session-hours. On a machine that rotates accounts it also pins the active account and its windows under the prompt.
session.measure fires after each main-thread turn and whenever a window moves a whole point. When its rateLimits carries a reading the whole file is rewritten — last writer wins, so the file names whichever account the latest session on this machine ran on, and measured_at dates it. A measurement with no windows (off a subscription, or before the first response) writes nothing, so an empty reading never overwrites a dated one.
account is the live login's email as Claude Code records it in ~/.claude.json ($CLAUDE_CONFIG_DIR/.claude.json in a cswap run profile), the file cswap rewrites on every switch. It is read at session start and again whenever the reading's weekly reset moves — a switch, or the week rolling over — since that reset is stable within one account's week and differs between accounts; a steady-state turn costs no file read. Absent when the file is missing or carries no login.
{
"measured_at": "2026-10-10T20:15:03.000Z",
"session": "8c16860d-d02b-4364-af52-2d5a27d9dd9c",
"account": "claude-bfp@drinkto.me",
"windows": [
{ "kind": "five_hour", "percentUsed": 12.5, "resetsAt": "2026-10-11T00:00:00.000Z" },
{ "kind": "seven_day", "percentUsed": 71, "resetsAt": "2026-10-13T22:00:00.000Z" }
]
}
~/.claude/local/ is the directory ~/.claude/CLAUDE.md reserves for machine-local state kept across sessions; the write creates it. The home directory comes from HOME, or USERPROFILE where only that is set.
Each session also keeps a history, ~/.claude/local/rate-limits/<session-id>.jsonl, one line per measurement in which a window moved ({"measured_at", "account", "windows"}, the same windows as above) and one for every login that moved under the session, carrying the account left as switched_from — the moment cswap's auto-switch landed on a running session, dated from the session's own traffic. The snapshot cannot say how full the 5-hour window got while a fleet ran — the 2026-10-12 retro had only a reading from two days earlier to estimate headroom from — and one file per session means concurrent sessions never race a shared file. scripts/fleet-metrics.py reads a fleet's files for each session's peak five_hour reading, and scripts/fleet-headroom.sh --session <id> reads a session's last line as its account's current 5h reading at pick time (the account it is on, switch or no switch), falling back to the snapshot. Both read windows and ignore the other keys. A reload resumes the session's file rather than starting it over. Nothing prunes these files (the mod API has no delete); each holds at most a few hundred short lines.
Where cswap's backup directory exists (~/.claude-swap-backup, or $XDG_DATA_HOME/claude-swap on Linux) the mod pins ⇄ <account> · 5h <pct>% · 7d <pct>% under the prompt through $.ui.status, updated on every measurement, so the account a session is on is visible while the engine moves the login underneath it. Everywhere else it pins nothing. This is deliberately not a statusLine command in the shared settings: configuring one removes the footer's keyboard hints for every user of this repo, rotating or not, and a command that prints nothing still does that.
A headless claude -p --plugin-dir ~/.claude/mods/rate-limits --model haiku run on a subscription account wrote the file on its one turn, carrying both windows: five_hour at 28% resetting in 3.5h and seven_day at 7% resetting Oct 13 22:00Z, the same reset the morning's weekly-limit message had named. The file did not exist before the run. Not yet measured: a cswap switch landing on a running interactive session — the switched_from line is what records it when it does.
userConfig: enabled (kill switch: writes nothing, pins nothing), status (the pin alone; off still records the account).
Installed user-wide by update.sh from the repo's marketplace and loaded in place from this folder. fleet-launch.sh never requires it: without a reading it prints Weekly: no reading (<why>) and launches.
claude plugin validate mods/rate-limits && claude plugin test mods/rate-limits && mods/typecheck.sh mods/rate-limitshooks/register.ts 94 lines1import type { Register } from 'claude-code'
2import { accountOf, configPath, historyLine, historyPath, readOptions, readingOf, readingPath, rotationDirs, statusText, weeklyResetOf } from './limits'
3
4let sessionId = ''
5let path: string | null = null
6let historyFile: string | null = null
7let history: string[] = []
8let configFile: string | null = null
9let rotating = false
10let account: string | null = null
11let weeklyReset: string | null = null
12
13type Host = { fs: { exists(p: string): Promise<boolean>; read(p: string): Promise<string> } }
14
15async function readAccount($: Host): Promise<string | null> {
16 if (configFile === null) return null
17 try {
18 return (await $.fs.exists(configFile)) ? accountOf(await $.fs.read(configFile)) : null
19 } catch {
20 return null
21 }
22}
23
24export const register: Register = (on, options) => {
25 const opts = readOptions(options)
26
27 on('session.start', async ($, e, next) => {
28 sessionId = await $.session.id()
29 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
30 path = readingPath(home)
31 historyFile = historyPath(home, sessionId)
32 configFile = configPath(home, await $.env.get('CLAUDE_CONFIG_DIR'))
33 // A reload starts the module over; the session's file is where its earlier readings live.
34 history = []
35 if (historyFile !== null && (await $.fs.exists(historyFile))) {
36 history = (await $.fs.read(historyFile)).split('\n').filter((line) => line !== '')
37 }
38 rotating = false
39 for (const dir of rotationDirs(home, await $.env.get('XDG_DATA_HOME'))) {
40 if (await $.fs.exists(dir)) {
41 rotating = true
42 break
43 }
44 }
45 account = await readAccount($)
46 weeklyReset = null
47 if (opts.enabled && opts.status && rotating) $.ui.status(statusText(account, []))
48 return next(e)
49 })
50
51 // Fires after each main-thread turn and whenever a window moves a whole point. The whole file is rewritten each time, last writer
52 // wins, so it names whichever account the latest session on this machine ran on and `measured_at` dates it. The session's history
53 // gains a line only when a window moved, or when the login moved under the session. A failed write is dropped: a readout never
54 // touches the session, and the launch line says when the file is stale or missing.
55 on('session.measure', async ($, e, next) => {
56 if (opts.enabled && path !== null) {
57 const now = await $.clock.now()
58 let switchedFrom: string | null = null
59 if (e.rateLimits.length > 0) {
60 // The identity file is re-read only when the reading's weekly reset moved (a switch, or the week rolling over) or no
61 // identity is known yet, so a turn costs no file read in the steady state.
62 const reset = weeklyResetOf(e.rateLimits)
63 if (reset !== weeklyReset || account === null) {
64 const seen = await readAccount($)
65 if (seen !== null && account !== null && seen !== account) switchedFrom = account
66 if (seen !== null) account = seen
67 weeklyReset = reset
68 }
69 }
70 const text = readingOf(e.rateLimits, sessionId, now, account)
71 if (text !== null) {
72 try {
73 await $.fs.write(path, text)
74 } catch {
75 // see above
76 }
77 }
78 const line = e.changed.includes('rateLimits') || switchedFrom !== null ? historyLine(e.rateLimits, now, account, switchedFrom) : null
79 if (line !== null && historyFile !== null) {
80 history.push(line)
81 try {
82 await $.fs.write(historyFile, `${history.join('\n')}\n`)
83 } catch {
84 // see above
85 }
86 }
87 // Pinned under the prompt only on a machine that rotates accounts; everywhere else the mod stays silent, so a single-account
88 // user sees no change. Not a statusLine command: configuring one of those removes the footer's keyboard hints for everyone.
89 if (opts.status && rotating && e.rateLimits.length > 0) $.ui.status(statusText(account, e.rateLimits))
90 }
91 return next(e)
92 })
93}
94hooks/limits.ts 92 lines1export type RateLimit = { readonly kind: string; readonly percentUsed: number; readonly resetsAt?: string }
2export type Options = { readonly enabled: boolean; readonly status: boolean }
3
4export function readOptions(raw: Readonly<Record<string, unknown>>): Options {
5 return { enabled: raw.enabled !== false, status: raw.status !== false }
6}
7
8function trimDir(p: string | undefined): string {
9 return (p ?? '').trim().replace(/[\\/]+$/, '')
10}
11
12// One machine-wide file under ~/.claude/local/, the directory ~/.claude/CLAUDE.md reserves for state kept across sessions, read by
13// scripts/fleet-launch.sh. Null without a home directory, and then nothing is written.
14export function readingPath(home: string | undefined): string | null {
15 const h = trimDir(home)
16 return h === '' ? null : `${h}/.claude/local/rate-limits.json`
17}
18
19// Where Claude Code records the live login's identity. The file sits beside ~/.claude, not inside it, unless CLAUDE_CONFIG_DIR names
20// a profile directory (a `cswap run` session), where it sits inside that directory. cswap rewrites it on every switch, which is what
21// makes it the account the session is on rather than the one it started on.
22export function configPath(home: string | undefined, configDir: string | undefined): string | null {
23 const dir = trimDir(configDir)
24 if (dir !== '') return `${dir}/.claude.json`
25 const h = trimDir(home)
26 return h === '' ? null : `${h}/.claude.json`
27}
28
29export function accountOf(configText: string): string | null {
30 try {
31 const parsed: unknown = JSON.parse(configText)
32 const email = (parsed as { oauthAccount?: { emailAddress?: unknown } } | null)?.oauthAccount?.emailAddress
33 return typeof email === 'string' && email !== '' ? email : null
34 } catch {
35 return null
36 }
37}
38
39// cswap's backup root marks a machine that rotates accounts: ~/.claude-swap-backup on macOS and Windows, $XDG_DATA_HOME/claude-swap
40// (default ~/.local/share/claude-swap) on Linux. Its presence, not the binary's, is the test: the binary sits in a PATH the plugin
41// environment cannot search.
42export function rotationDirs(home: string | undefined, xdgDataHome: string | undefined): string[] {
43 const h = trimDir(home)
44 if (h === '') return []
45 const xdg = trimDir(xdgDataHome)
46 return [`${h}/.claude-swap-backup`, `${xdg !== '' ? xdg : `${h}/.local/share`}/claude-swap`]
47}
48
49// The weekly window's reset is stable for the life of an account's week and differs between accounts, so a change in it is the one
50// signal in the reading itself that the login may have moved; the identity is then re-read rather than inferred.
51export function weeklyResetOf(windows: readonly RateLimit[]): string | null {
52 return windows.find((w) => w.kind === 'seven_day')?.resetsAt ?? null
53}
54
55export function statusText(account: string | null, windows: readonly RateLimit[]): string {
56 const parts = windows
57 .filter((w) => w.kind === 'five_hour' || w.kind === 'seven_day')
58 .map((w) => `${w.kind === 'five_hour' ? '5h' : '7d'} ${w.percentUsed}%`)
59 return [`⇄ ${account ?? 'account ?'}`, ...parts].join(' · ')
60}
61
62function windowsOf(windows: readonly RateLimit[]) {
63 return windows.map((w) => (w.resetsAt === undefined ? { kind: w.kind, percentUsed: w.percentUsed } : { kind: w.kind, percentUsed: w.percentUsed, resetsAt: w.resetsAt }))
64}
65
66// The file's text: the windows as the engine reported them, dated, and the account they belong to when it is known; null when the
67// measurement carried none (off a subscription, or before the first response), so an empty reading never overwrites a dated one.
68export function readingOf(windows: readonly RateLimit[], session: string, nowMs: number, account: string | null = null): string | null {
69 if (windows.length === 0) return null
70 const reading = { measured_at: new Date(nowMs).toISOString(), session, ...(account === null ? {} : { account }), windows: windowsOf(windows) }
71 return `${JSON.stringify(reading, null, 2)}\n`
72}
73
74// The snapshot above keeps only the latest writer, so it cannot say how full a window got while a fleet ran. Each session also keeps
75// its own history, one file per session so concurrent sessions never race a shared one; fleet-metrics.py reads a fleet's files for
76// the peak five_hour reading. A line that records a switch names the account left as `switched_from`. Null without a home directory
77// or a session id.
78export function historyPath(home: string | undefined, session: string): string | null {
79 const h = trimDir(home)
80 return h === '' || session === '' ? null : `${h}/.claude/local/rate-limits/${session}.jsonl`
81}
82
83export function historyLine(windows: readonly RateLimit[], nowMs: number, account: string | null = null, switchedFrom: string | null = null): string | null {
84 if (windows.length === 0) return null
85 return JSON.stringify({
86 measured_at: new Date(nowMs).toISOString(),
87 ...(account === null ? {} : { account }),
88 ...(switchedFrom === null ? {} : { switched_from: switchedFrom }),
89 windows: windowsOf(windows),
90 })
91}
92