SLOPSHOPPER

rate-limit-guard

Shared rate-limit guard for loop lanes and Claude: a hooks module writes the subscription rate-limit windows to a fixed machine-scope file and toasts window…

bandguardcommandtoastprompttool
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · rate-limit-guard
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /rate-limit-guard ⎿ rate-limit-guard: From the last API response: ⎿ rate-limit-guard: 5-hour window: 31% used, below 95%, resets at 2025-10-09 09:53 UTC ⎿ rate-limit-guard: 7-day window: no reading ⎿ rate-limit-guard: Line threshold 95%, approach mark 90%. ⎿ rate-limit-guard: Band row off, window-change toast on. Set the row with /rate-limit-guard band [on|off]. ⎿ rate-limit-guard: Snapshot: /Users/dev/.claude/rate-limit-guard/rate-limits.json ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

rate-limit-guard

A Claude Code plugin that tells Claude, and every session on the machine that reads its file, where the account's shared subscription rate-limit windows stand, so Claude can plan around a limit before it hits one, and so autonomous loop lanes can report it and, where the operator opted in, pause before a limit and resume on their own after the reset. Three parts:

  • Hooks module (hooks/register.tsx), a mod that Claude Code runs in its own process. It shows you a toast when a window approaches or reaches the line threshold and when it resets, tells Claude the same at those boundaries when you turn on model_notices (off by default), can draw the figures in a band row (off by default), answers a status tool, and writes the windows to the fixed machine-scope file ~/.claude/rate-limit-guard/rate-limits.json in interactive and headless sessions alike. It needs a Claude Code build that can run mods; older builds are unsupported. Pointer: when deciding which build that is, fetch mods overview: turn mods on or off live. As of: 2026-10-11. Recheck trigger: the terminal version that section names for mods changes.
  • StopFailure hook (hooks/record-rate-limit-stop.sh), the reactive fallback. When a turn ends on a rate-limit API error, it appends a detection record to ~/.claude/rate-limit-guard/stop-events.jsonl. The hook is side-effect-only by design: the record is its one output, and it returns no decision. Pointer: when deciding whether a StopFailure hook's output can do anything, fetch hooks: StopFailure live. As of: 2026-10-11. Recheck trigger: the StopFailure section gives the event decision control.
  • Reader contract (reference/reader-contract.md), the authoritative consumer contract: the fixed file path, the opt-in 95%-of-either-window pause threshold, the staleness rule, pause-end semantics, capability-detect fail-open, and drain-then-pause.

The module

The module tells Claude where the account stands against its rate limits, tells you when a window changes, can draw the figures in a band row, answers a status tool, and writes the contract file, in interactive, -p, --bg and /loop sessions alike. Tested with claude plugin test and live on Claude Code 2.1.288: interactive terminal sessions, -p runs, --bg and /loop lanes, side by side with the retired tee, a mods-off session, and native Windows. The Desktop app and VS Code were not run.

Lines to Claude

Lines go to Claude only with model_notices set to true; it is off by default, and then nothing from this plugin enters Claude's context. Claude can still read the windows from the status tool. With it on, a line goes to Claude only at a boundary, appended to the context of a main-thread tool result or of a prompt; a crossing seen when a turn ends reaches Claude with the next prompt. Per window (5-hour and 7-day), with the default options:

WhenLine
The window reaches the approach mark (90%)once per window, "at or above 90%", with the reset time
The window reaches the line threshold (95%)once per window, "at or above 95%", with the reset time
The window resets (its reset time passes, or it leaves the reading) after reaching the thresholdonce; the approach and threshold lines can then fire again
After a compaction (not the precompute kind), and after /resume or /branchthe verdict for each window at or above the approach mark, once; nothing when none is
After /clear, and when the module loads into a session that already has turns (a --resume launch, a reload after an options change, a hooks-worker restart)the verdict for each window at or above the threshold, once; nothing when none is
The signed-in account changes while a window is past quiet or a line is still dueonce, that earlier lines no longer apply, with each window's current reading, or "No reading yet for this account" before the new account's first response
A window's reset time reads more than a minute earlier than the recorded one while that window is past quiet or a line about it is still dueonce, that earlier lines for that window no longer apply, with its current reading

Use only rises within a window, so a reading that dips below a mark sends nothing and does not re-arm that mark's line. A restatement states the current reading, and none is made while that reading is below the restated mark. The account is the one in .claude.json, keyed on .oauthAccount.accountUuid, or on .oauthAccount.emailAddress when no UUID is there. When it changes, or a window's reset time moves earlier (which catches a switch the state file does not show, when the new account's window resets sooner), the module drops what it latched for the old account or window: levels, lines not yet sent, suggestions not yet handed to Claude, and toasts not yet shown. The reading held at an account change is the old account's, so it sets no level; the next reading that differs does. No other tool call or prompt carries a line. Each window gets its own line, for example rate-limit-guard: 5-hour window at or above 95% (96% used), resets at 2026-10-03 21:00 UTC. A line states the window, the threshold crossed, and the use and reset time the line data selects. After the approach and threshold lines at a carrier comes one options line:

rate-limit-guard: options: continue at the same model, effort and review depth; the user can switch accounts (https://github.com/melodic-software/claude-code-account-rotation); or schedule work for after the reset. Usage never calls for lowering model, effort or review depth; whether to stop or pause is the user's call, or an opted-in loop lane's floor.

Facts alone led Claude to stop launching agents and to move work to a smaller model (#7118), so the line names the options and rules out trading quality for usage. A reset line carries no options line. Every line carries its verdict; rate_limit_line_data chooses what goes with it: the window's name (window), its use (percent) and its reset time (reset). Without window the line says "a rate-limit window". A line never carries the account email or the session name. Subagents get no line. Each line sent to Claude is also written as sent to the debug log (claude --debug). The line threshold is a line setting only: an opted-in loop lane's pause threshold stays 95% (see the reader contract).

Window changes shown to you

When a window rises from an earlier reading to the approach mark or the line threshold, or resets after reaching the threshold, the module shows a toast for 4 seconds, such as 5h at the 95% line threshold · resets 21:00 UTC, and writes one transcript line Claude does not read, ending · more: /rate-limit-guard. A window's first reading since the module loaded or the window reset is never toasted, and neither is a restatement after a compaction, a resume, /clear or a reload: those only restate the verdict to Claude. Windows belong to the account, so a rise across /clear or a resume is a change and is toasted. The toast does not depend on model_notices. rate_limit_guard_toast set to false drops the toast and keeps the transcript line. Outside the terminal (the Desktop app, VS Code, mobile), where toast drawing is unverified, the change also shows as a single row above the prompt, covering every window that changed, until your next prompt.

Operator mode

With rate_limit_report_mode set to operator, a turn a person started by typing (or through the Remote Control bridge) gets no line. When that turn ends, the line is offered as the prompt box's suggestion (Tab takes it) and shown as a notice row above the prompt, on every surface, wrapped rather than cut off. With text in the box, only the notice row shows, and the suggestion is offered again once the box is empty. Where nobody can take a suggestion, the line goes to Claude as in automatic mode: -p and SDK turns, /loop and scheduled turns, task notifications and other non-typed turns, a session with no drawing surface (such as the VS Code panel), and a suggestion the session reports it cannot show. The row and a shown suggestion are your channel for a held line, so it gets a toast and a transcript line only when you never had either: its first offer could not show, or a survey hid the row until the line went to Claude. A suggestion that showed but was not taken goes to Claude as the automatic line at the next turn no person started; a turn a person starts drops it unsent.

Which apps draw the band's site, AbovePrompt, is upstream's render-sites table to say. No probe of this plugin ran in the Desktop app or VS Code, so the band, the notice rows, the toast and the suggestion there are untested.

  • Pointer: mods reference: render sites.
  • As of: 2026-10-03, Claude Code 2.1.288.
  • Recheck trigger: the AbovePrompt row changes the apps it lists, or a Desktop run of this plugin is made.

A --bg session reports its first prompt as typed, so in operator mode a --bg lane gets no line from that turn; its line reaches Claude at the lane's next turn no person started. A lane that wants the lines at once may start its session with its own options through --settings, which can set any key user settings can, including the plugin's pluginConfigs entry: {"pluginConfigs": {"rate-limit-guard@<marketplace>": {"options": {"rate_limit_report_mode": "automatic"}}}} (a --plugin-dir copy is keyed <name>@inline).

The /rate-limit-guard command, band row and status tool

/rate-limit-guard with no argument prints each window's use, verdict and reset time, the line threshold and approach mark, whether the band row and the toast are on, the snapshot path and a link to this README.

The band row above the prompt is off by default. When on, it shows rate-limit-guard: 5h <x>% | 7d <y>%, with - for a window that has no reading yet. Context use is context-guard's row, not this one. rate_limit_guard_band set to true turns it on for every session; /rate-limit-guard band on, band off, or a bare band (toggle) changes it for the current session. Claude can call mcp__rate-limit-guard__status for the exact figures from the last API response: every window the response reported, with its verdict, and, behind a Claude gateway, the spend_limit window, which is never written to the contract file.

Snapshot writes

The module writes ~/.claude/rate-limit-guard/rate-limits.json through lib/write-snapshot.mjs, run with node, so the file is replaced atomically on Linux, macOS and native Windows. It writes at once when a window moves a whole point, appears, leaves or resets, and otherwise at most once every 300 seconds across the machine, checked from main-thread tool results, each measurement after a turn, a 60-second timer that runs only while a turn runs, and the session's end. It never writes from a turn a task notification started (a paused lane's own Monitor tick), and it follows the plugin's on/off switch and rate_limit_guard_enabled. The body carries captured_at, session_id, the windows, and account.email only when the account in the state file at the write is the one it held at the last API response (a startup quota check counts); it never carries session_name or spend_limit. A session with no windows writes a windowless body, which never replaces a file that has windows.

Process cost: an event that writes nothing starts no process; each write starts one node process. Mods can start host processes in the CLI only; where they cannot, the module writes nothing and logs that once to the debug log.

Where mods are off

Wherever mods are off for a session, whether the build is too old for mods or a setting, flag, policy or Claude Code itself turned them off, the module does not run: no lines, no band, no status tool, no module writes. The StopFailure hook still records, and readers fall back to reactive-only as the reader contract says. /rate-limit-guard:check and /rate-limit-guard:setup check report "mods off" in that case. A hook that throws passes its event through unchanged.

Behavior

  • Atomic, last-writer-wins snapshot. Concurrent sessions write one path; readers never see torn JSON (temp file + rename, with a brief retry for the Windows rename-over-open-target case). The helper takes a short lock, refuses an older captured_at over a newer one, and keeps a windowless body from replacing windows. Last-writer-wins still applies between sessions: a session whose last API response is minutes old can write its older reading over a newer one, until the next write from a session with a fresher response.
  • Fail-open capability detection. Sessions whose auth exposes no subscription windows write an honest snapshot without rate_limits; consumers treat that as unknown and run reactive-only rather than throttling on fabricated data. Cloud / remote sessions typically have no file a consumer can read. That is the same unknown → reactive-only classification, documented as the expected degraded mode in reference/reader-contract.md ("Cloud / remote sessions"), with a documented residual that a live cloud producer is out of scope until one exists.
  • An unchanged reading costs no process. The module compares each reading with the last one it wrote and with the captured_at on disk, in process, so an unchanged reading inside the 300-second floor starts nothing. That floor is half the reader contract's 10-minute staleness budget, so a session whose windows sit still refreshes captured_at well before a reader could call it stale.
  • Multi-account operation is a narrowed gap. The snapshot names the account whose windows it carries in an account.email field, so a machine switching accounts is visible to a reader that checks it. Lanes drop a latched pause on an account change: while paused they read .oauthAccount.emailAddress from .claude.json directly and re-evaluate against the new account's windows. The gap that remains is attribution: the field is absent whenever the module could not attribute the observation, which covers an unreadable state file, no email-shaped value, and an account that changed between the last API response and the write. A lane that cannot attribute keeps its latch. The loop-lane convention §6 owns that framing; the reader contract states the absence cases and the untrusted-value rule (reference/reader-contract.md, "Snapshot file shape").

Tests and their budgets

claude plugin test plugins/rate-limit-guard runs the module's suite (hooks/rate-limit-guard.test.ts) with stubbed Claude Code calls; lib/write-snapshot.test.mjs covers the helper. The module's process budget, counted in the hook-budget convention's unit (one process start): 0 processes on a tool result, prompt, measurement or timer tick that writes nothing, and 1 (the node helper) per write, with writes at most once per changed reading and no more often than every 300 seconds when unchanged. The budget: test pins it: 50 unchanged tool results start no process, and one change starts exactly one.

The tests retired with the statusline tee, and what holds their property now:

Retired testReplacement
The tee suite: snapshot shape, account, no-change floor, enablementthe snapshot:, account:, floor: and switch: tests in hooks/rate-limit-guard.test.ts
The tee suite: atomic write, windowless preservation, lockslib/write-snapshot.test.mjs
The tee suite: the zero-fork render tracethe budget: test, at the budget above
The bench lanes and their recorded process countsthe budget: test, at the budget above
The tee suite: transparency, spool and drain, async writes, the disabled markernone: the plugin no longer wraps a status line or spools
The shim and compose-script suitesnone: no shim ships; the setup skill's evals cover removing an old one

Install

/plugin marketplace add melodic-software/claude-code-plugins
/plugin install rate-limit-guard@<marketplace>

The module and the StopFailure hook are active once the plugin loads (the next session, or /reload-plugins in an open one); nothing needs wiring. /rate-limit-guard:setup check verifies the result.

Requirements

  • A Claude Code build at or above the terminal version mods need, with mods on, for the module. Below that floor, or with mods off, only the StopFailure hook runs. prerequisites.json holds the floor as data, in detect.version.min of the entry with "id": "claude", which the check skill compares against (relayed 2026-10-11; recheck when that key moves); the pointer below is where to re-derive it.
  • Node.js on PATH, installed on its own: the StopFailure hook launches through node hooks/exec-bash.mjs, and the module writes the file by running node, and we never count on Claude Code's install to provide it. Without it the hook records nothing and the module writes nothing, while its lines and band row still work.
  • Bash for the StopFailure hook: on native Windows, Git for Windows, which hooks/exec-bash.mjs finds.
  • Auth that exposes subscription windows, for proactive window data. On other auth the guard is reactive-only.
  • Pointer: when deciding which Claude Code version mods need, fetch mods overview: turn mods on or off live; when deciding whether a Claude Code install brings a Node.js the plugin could use, fetch advanced setup: install with npm live; when deciding which auth exposes subscription windows, fetch status line: rate limit usage live.
  • As of: 2026-10-11.
  • Recheck trigger: the terminal version that section names for mods changes, the setup page says the installed binary runs on Node.js, or the rate limit usage section changes which accounts or gateways the rate_limits object appears for.

/rate-limit-guard:check reports whether node resolves and whether the module can load, read-only. It installs nothing.

Configuration

The userConfig options:

OptionWhat it controls
rate_limit_guard_enabledKill switch for the StopFailure detection hook and the module's snapshot writes (default true). It does not stop the module's lines.
model_noticesThe module's lines to Claude, and the operator-mode suggestions (default false). Off, nothing from this plugin enters Claude's context; the toast, transcript line, band row, status tool and snapshot are unchanged.
rate_limit_report_modeautomatic (default) or operator, only with model_notices on; see Operator mode.
rate_limit_line_thresholdWindow use for the threshold line (default 95).
rate_limit_approach_pctWindow use for the one approach line (default 90).
rate_limit_line_dataWhat a line carries beside its verdict: percent, window, reset (default verdict,percent,window,reset).
rate_limit_guard_bandThe band row (default false).
rate_limit_guard_toastThe toast when a window nears or reaches the threshold or resets (default true); the transcript line stays either way.

Two settings live outside userConfig:

SettingWhereDefaultWhat it controls
Snapshot file a status line can read~/.claude/rate-limit-guard/rate-limits.json, written under rate_limit_guard_enabledonA status-line command that reads this file keeps working with every other option at its default.
LOOP_LANE_RATE_LIMIT_PAUSEthe loop lane session's environmentunset (off)1 makes an unattended loop lane pause at 95% of either window; see the reader contract.

A threshold or approach mark outside 1 to 100, or line data with an unknown item, reads as that option's default with one transcript line naming it. The thresholds declare no range in userConfig; the module judges a value outside 1 to 100 itself. A value of the wrong type (text for a number, a number for a switch) is Claude Code's to handle before the module sees it.

The module reads its options when it loads. Claude Code reloads a module when its options change, so a switch turned off takes effect from the next event, with no restart. The StopFailure hook receives rate_limit_guard_enabled as CLAUDE_PLUGIN_OPTION_RATE_LIMIT_GUARD_ENABLED at session start.

  • Pointer: the doc comment on Register in the claude-code/index.d.ts types Claude Code writes for its build (see create: get the types for your build).
  • As of: 2026-10-03, Claude Code 2.1.288.
  • Recheck trigger: that doc comment stops saying an options change reloads the plugin.

Set it with /plugin configure rate-limit-guard@<marketplace>, or headless via claude plugin install rate-limit-guard@<marketplace> -s <scope> --config rate_limit_guard_enabled=false, against an already-installed plugin that prints already installed and still writes the value. Never uninstall to reconfigure: that drops the whole stored pluginConfigs entry and resets every option to its manifest default. The verified-version record lives in the plugin-reconfiguration convention.

The file path and the 95% pause threshold an opted-in lane applies are deliberately not configurable: they are contract constants that cross-plugin consumers inline from the reader contract; a per-user override would silently split the writer from its readers. The kill switch stops this plugin's writes and records; turning the plugin off for a project is enabledPlugins, and removing it is

Source 1 files
hooks/register.tsx 855 lines
1import type { EngineInterface, PromptOrigin, Register, SessionRateLimit, Timer } from 'claude-code'
2
3// The contract directory under the home directory. make-probe-copy.sh rewrites this one line.
4const CONTRACT_DIR = 'rate-limit-guard'
5const SNAPSHOT_FILE = 'rate-limits.json'
6const HELPER = 'lib/write-snapshot.mjs'
7const PAUSE_EDGE = 95
8const FLOOR_MS = 300_000
9const WRITE_TIMER_MS = 60_000
10const REOFFER_MS = 5_000
11// A reset time read this much earlier than the recorded one belongs to another window.
12const RESET_SLACK_MS = 60_000
13const WINDOWS = [
14  { kind: 'five_hour', name: '5-hour', short: '5h' },
15  { kind: 'seven_day', name: '7-day', short: '7d' },
16] as const
17// The verdict is always in a line; these add to it.
18const DATA_ITEMS = ['verdict', 'percent', 'window', 'reset']
19const DEFAULT_DATA = ['verdict', 'percent', 'window', 'reset']
20const RANK = { quiet: 0, approach: 1, edge: 2 } as const
21const PERSON_ORIGINS = ['composer', 'bridge']
22const COMMAND = 'rate-limit-guard'
23// Command replies carry no plugin prefix: Claude Code shows each under the plugin's name.
24const USAGE = `Usage: /${COMMAND} [band [on|off]]`
25const README = 'https://github.com/melodic-software/claude-code-plugins/blob/main/plugins/rate-limit-guard/README.md'
26
27type Level = 'quiet' | 'approach' | 'edge'
28type Event = Level | 'reset'
29type Reading = Map<string, SessionRateLimit>
30// An event and the reading that produced it, so a late line states both from one reading.
31type Due = { event: Event; limit: SessionRateLimit | undefined }
32// The signed-in account in the state file: its UUID, and its email for a file with no UUID.
33type Identity = { uuid?: string; email?: string }
34// A change that voids the lines sent before it: the account, or the windows whose reset time moved earlier.
35type Voided = { cause: 'account' | 'reset'; kinds: string[] }
36type Config = {
37  bad: string[]
38  writes: boolean
39  lines: boolean
40  operator: boolean
41  threshold: number
42  approach: number
43  data: Set<string>
44  band: boolean
45  toast: boolean
46}
47// An operator notice offers held lines and shows on every surface; a crossing notice stands in for
48// the toast where toasts may not draw, so it shows only off the terminal.
49type Notice = { text: string; kind: 'crossing' | 'operator' }
50type Body = {
51  captured_at: string
52  session_id: string
53  rate_limits?: Record<string, { used_percentage: number; resets_at?: number }>
54  account?: { email: string }
55}
56type State = {
57  reading: Reading | undefined
58  spend: SessionRateLimit | undefined
59  levels: Map<string, { level: Level; resetsMs: number; limit: SessionRateLimit }>
60  limits: readonly SessionRateLimit[]
61  pending: Map<string, Due>
62  // Rises from a known level and resets not yet shown to the person.
63  toastQueue: [string, Event][]
64  // Operator mode: the changes the operator notice offers, and whether its row has been drawn.
65  // The row and a shown suggestion are the person's channel, so a change either reached is never toasted.
66  heldToasts: [string, Event][]
67  rowSeen: boolean
68  // Operator mode: events a shown suggestion offered, handed to Claude if no person takes them.
69  handoff: Map<string, Due>
70  handoffVoided: Voided | undefined
71  // The account the latched state belongs to; a reading taken before it changed, until a new one arrives.
72  account: Identity | undefined
73  staleSig: string | undefined
74  voided: Voided | undefined
75  refreshSeq: number
76  appliedSeq: number
77  restate: boolean
78  restateIfLoud: boolean
79  // An in-process /resume or /branch ended the last session; cleared by the first decided write.
80  branched: boolean
81  forceAutomatic: boolean
82  origin: PromptOrigin | undefined
83  notice: Notice | undefined
84  bandShown: boolean
85  lastResponseAtMs: number | undefined
86  responseEmail: string | undefined
87  identityCache: { key: string; identity: Identity } | undefined
88  lastAttempt: { sig: string; at: number } | undefined
89  loggedOnce: Set<string>
90  writing: Promise<void>
91  writeTimer: Timer | undefined
92  reofferTimer: Timer | undefined
93}
94
95// A bad value reads as the option's default and adds one line to `bad`: the engine refuses the whole
96// module for a value outside a declared range, so the ranges are checked here instead.
97export const parseConfig = (options: Record<string, unknown>): Config => {
98  const bad: string[] = []
99  const reject = (key: string, kind: string, fallback: string) =>
100    bad.push(`option ${key} is ${kind}; using the default, ${fallback}`)
101  const number = (key: string, fallback: number) => {
102    const value = options[key]
103    if (value === undefined) return fallback
104    if (typeof value === 'number' && value >= 1 && value <= 100) return value
105    reject(key, typeof value === 'number' ? `${value}, outside 1 to 100` : `a ${typeof value}, not a number`, String(fallback))
106    return fallback
107  }
108  const raw = options.rate_limit_line_data
109  const items = String(raw ?? '')
110    .split(',')
111    .map(s => s.trim().toLowerCase())
112    .filter(s => s !== '')
113  const known = items.length > 0 && items.every(s => DATA_ITEMS.includes(s))
114  // An empty value reads as the default silently, as an unset one does.
115  if (raw !== undefined && String(raw).trim() !== '' && !known) {
116    const shown = typeof raw === 'string' ? JSON.stringify(raw.slice(0, 40)) : `a ${typeof raw}`
117    reject('rate_limit_line_data', `${shown}, not a list of ${DATA_ITEMS.join(', ')}`, DEFAULT_DATA.join(','))
118  }
119  const data = new Set(known ? items : DEFAULT_DATA)
120  return {
121    bad,
122    writes: options.rate_limit_guard_enabled !== false,
123    lines: options.model_notices === true,
124    operator: options.rate_limit_report_mode === 'operator',
125    threshold: number('rate_limit_line_threshold', PAUSE_EDGE),
126    approach: number('rate_limit_approach_pct', 90),
127    data,
128    band: options.rate_limit_guard_band === true,
129    toast: options.rate_limit_guard_toast !== false,
130  }
131}
132
133// The status line drops a window once its reset time has passed; so does this reading.
134export const liveWindows = (limits: readonly SessionRateLimit[], nowMs: number): Reading => {
135  const reading: Reading = new Map()
136  for (const { kind } of WINDOWS) {
137    const limit = limits.find(l => l.kind === kind)
138    if (limit === undefined) continue
139    const resetsMs = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt)
140    if (Number.isFinite(resetsMs) && resetsMs <= nowMs) continue
141    reading.set(kind, limit)
142  }
143  return reading
144}
145
146const levelOf = (percent: number, cfg: Config): Level =>
147  percent >= cfg.threshold ? 'edge' : percent >= cfg.approach ? 'approach' : 'quiet'
148
149const edgeName = (cfg: Config) => `${cfg.threshold}% line threshold`
150
151const resetLabel = (iso: string) => {
152  const at = new Date(iso)
153  return Number.isNaN(at.getTime()) ? iso : `${at.toISOString().slice(0, 16).replace('T', ' ')} UTC`
154}
155
156// The person's wording; Claude's names the threshold crossed and nothing else.
157const verdictText = (event: Event, cfg: Config) =>
158  ({ edge: 'at', approach: 'nearing', quiet: 'below', reset: 'reset and below' })[event] + ` the ${edgeName(cfg)}`
159
160const modelVerdict = (event: Event, cfg: Config) =>
161  ({
162    edge: `at or above ${cfg.threshold}%`,
163    approach: `at or above ${cfg.approach}%`,
164    quiet: `below ${cfg.threshold}%`,
165    reset: `reset, now below ${cfg.threshold}%`,
166  })[event]
167
168const windowOf = (kind: string) => WINDOWS.find(w => w.kind === kind)
169
170const clause = (kind: string, event: Event, limit: SessionRateLimit | undefined, cfg: Config) => {
171  const subject = cfg.data.has('window') ? `${windowOf(kind)?.name ?? kind} window` : 'a rate-limit window'
172  const percent = limit !== undefined && cfg.data.has('percent') ? `${limit.percentUsed}% used` : undefined
173  let text = `${subject} ${modelVerdict(event, cfg)}${percent ? ` (${percent})` : ''}`
174  if (event !== 'reset' && cfg.data.has('reset') && limit?.resetsAt !== undefined) {
175    text += `, resets at ${resetLabel(limit.resetsAt)}`
176  }
177  return text
178}
179
180// The person's short form: the 5-hour window resets within the day, so its time alone is enough.
181const toastBody = (kind: string, event: Event, limit: SessionRateLimit | undefined, cfg: Config) => {
182  if (event === 'reset') return `${windowOf(kind)?.short ?? kind} reset, below the ${edgeName(cfg)}`
183  const text = `${windowOf(kind)?.short ?? kind} ${verdictText(event, cfg)}`
184  if (limit?.resetsAt === undefined) return text
185  const label = resetLabel(limit.resetsAt)
186  return `${text} · resets ${kind === 'five_hour' ? label.replace(/^\d{4}-\d{2}-\d{2} /, '') : label}`
187}
188
189const order = (kind: string) => WINDOWS.findIndex(w => w.kind === kind)
190
191// Records crossings since the last check as pending events, one per window, the newest kept.
192// Use only rises within a window, so a dip is reporting noise: a window's level falls, and its
193// lines re-arm, only when the window resets (its reset time passes) or leaves the reading.
194// Returns the events the person is told of: a rise from a known level, or a reset from the edge.
195// A window's first reading is never one, so a fresh load or the reading after a reset stays quiet.
196// A window whose reset time reads earlier than the recorded one is taken as a new window, as after
197// an account change: its latched state is dropped, and a line voids what Claude was told of it.
198export const recordCrossings = (st: State, reading: Reading, cfg: Config, nowMs: number) => {
199  const changes: [string, Event][] = []
200  const moved: string[] = []
201  for (const { kind } of WINDOWS) {
202    const limit = reading.get(kind)
203    let prev = st.levels.get(kind)
204    if (prev !== undefined && (limit === undefined || prev.resetsMs <= nowMs)) {
205      if (prev.level === 'edge') {
206        st.pending.set(kind, { event: 'reset', limit })
207        changes.push([kind, 'reset'])
208      } else st.pending.delete(kind)
209      st.levels.delete(kind)
210      prev = undefined
211    }
212    if (limit === undefined) continue
213    const level = levelOf(limit.percentUsed, cfg)
214    const resetsMs = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt)
215    if (prev !== undefined && Number.isFinite(prev.resetsMs) && resetsMs < prev.resetsMs - RESET_SLACK_MS) {
216      if (prev.level !== 'quiet' || st.pending.has(kind) || st.handoff.has(kind)) moved.push(kind)
217      dropWindows(st, [kind])
218      prev = undefined
219    }
220    if (prev !== undefined && RANK[level] <= RANK[prev.level]) continue
221    st.levels.set(kind, { level, resetsMs: Number.isFinite(resetsMs) ? resetsMs : Infinity, limit })
222    if (level === 'quiet') continue
223    st.pending.set(kind, { event: level, limit })
224    if (prev !== undefined) changes.push([kind, level])
225  }
226  if (moved.length > 0) st.voided = mergeVoided(st.voided, { cause: 'reset', kinds: moved })
227  return changes
228}
229
230// An account change voids every window, so it outranks a moved reset time.
231const mergeVoided = (a: Voided | undefined, b: Voided | undefined): Voided | undefined =>
232  a === undefined || b === undefined
233    ? (a ?? b)
234    : a.cause === 'account'
235      ? a
236      : b.cause === 'account'
237        ? b
238        : { cause: 'reset', kinds: [...new Set([...a.kinds, ...b.kinds])] }
239
240// Drops what is latched for these windows: levels, pending and handed-off events, and queued toasts.
241const dropWindows = (st: State, kinds: readonly string[]) => {
242  for (const kind of kinds) {
243    st.levels.delete(kind)
244    st.pending.delete(kind)
245    st.handoff.delete(kind)
246  }
247  st.toastQueue = st.toastQueue.filter(([kind]) => !kinds.includes(kind))
248  st.heldToasts = st.heldToasts.filter(([kind]) => !kinds.includes(kind))
249}
250
251// The windows a reading reports, so an unchanged reading compares equal.
252const windowSig = (limits: readonly SessionRateLimit[]) =>
253  JSON.stringify(WINDOWS.map(({ kind }) => limits.find(l => l.kind === kind)).map(l => l && [l.percentUsed, l.resetsAt ?? null]))
254
255// The events due now, one per window, without consuming them. A window a voiding line covers is left to it.
256const dueEvents = (st: State, cfg: Config): [string, Due][] => {
257  // After /clear or a fresh load mid-session, only a window at the edge is restated; after a
258  // compaction, a resume or a /branch, each window past quiet. A quiet window is never restated.
259  // A restatement states the current reading, and none is made once that reading is below the level.
260  const restated = (edgeOnly: boolean): [string, Due][] =>
261    [...st.levels].flatMap(([kind, w]): [string, Due][] => {
262      const limit = st.reading?.get(kind)
263      if (w.level === 'quiet' || (edgeOnly && w.level !== 'edge') || limit === undefined) return []
264      return RANK[levelOf(limit.percentUsed, cfg)] < RANK[w.level] ? [] : [[kind, { event: w.level, limit }]]
265    })
266  const due = st.restate ? restated(false) : [...new Map<string, Due>([...st.pending.entries(), ...(st.restateIfLoud ? restated(true) : [])])]
267  return due.filter(([kind]) => !st.voided?.kinds.includes(kind))
268}
269
270// One line saying the account or a window changed and what Claude was told before no longer
271// applies, with the current reading; undefined when nothing was voided.
272const voidedLine = (st: State, cfg: Config): { line: string; levels: Level[] } | undefined => {
273  if (st.voided === undefined) return undefined
274  const { cause, kinds } = st.voided
275  const current = WINDOWS.flatMap(({ kind }): [string, SessionRateLimit, Level][] => {
276    const limit = st.staleSig === undefined && kinds.includes(kind) ? st.reading?.get(kind) : undefined
277    return limit === undefined ? [] : [[kind, limit, levelOf(limit.percentUsed, cfg)]]
278  })
279  const head =
280    cause === 'account'
281      ? 'the signed-in account changed, so earlier rate-limit lines in this session no longer apply.'
282      : "a window's reset time moved earlier than recorded, so earlier rate-limit lines for that window no longer apply."
283  const tail =
284    current.length > 0
285      ? `Current reading: ${current.map(([kind, limit, level]) => clause(kind, level, limit, cfg)).join('; ')}.`
286      : `No reading yet for this ${cause === 'account' ? 'account' : 'window'}.`
287  return { line: `rate-limit-guard: ${head} ${tail}`, levels: current.map(([, , level]) => level) }
288}
289
290// Follows any approach or edge line, once per carrier. Facts alone led Claude to stop launching agents
291// and to move work to a smaller model, so the options are stated and lowering quality is not one of them.
292const OPTIONS =
293  "rate-limit-guard: options: continue at the same model, effort and review depth; the user can switch accounts (https://github.com/melodic-software/claude-code-account-rotation); or schedule work for after the reset. Usage never calls for lowering model, effort or review depth; whether to stop or pause is the user's call, or an opted-in loop lane's floor."
294
295const dueLines = (st: State, cfg: Config): string[] => {
296  const due = dueEvents(st, cfg).sort(([a], [b]) => order(a) - order(b))
297  const voided = voidedLine(st, cfg)
298  const lines = [...(voided ? [voided.line] : []), ...due.map(([kind, d]) => `rate-limit-guard: ${clause(kind, d.event, d.limit, cfg)}.`)]
299  const events: Event[] = [...(voided?.levels ?? []), ...due.map(([, d]) => d.event)]
300  return events.some(e => e === 'approach' || e === 'edge') ? [...lines, OPTIONS] : lines
301}
302
303// Appends lines to what Claude reads and writes each to the debug log, so the log holds what Claude was told.
304const withLines = <T extends { context?: readonly string[] }>($: EngineInterface, e: T, lines: readonly string[]): T => {
305  for (const line of lines) $.ui.log(line, { to: 'debug' })
306  return lines.length === 0 ? e : { ...e, context: [...(e.context ?? []), ...lines] }
307}
308
309const consume = (st: State) => {
310  st.pending.clear()
311  st.voided = undefined
312  st.restate = false
313  st.restateIfLoud = false
314  st.forceAutomatic = false
315}
316
317const isPersonTurn = (st: State) => st.origin !== undefined && PERSON_ORIGINS.includes(st.origin.kind)
318
319async function operatorHolds($: EngineInterface, st: State, cfg: Config) {
320  if (!cfg.operator || st.forceAutomatic || !isPersonTurn(st)) return false
321  return (await $.session.surfaces()).length > 0
322}
323
324// Whether two identities are one account: by UUID when both have one, else by email; undefined when neither can tell.
325const sameAccount =(a: Identity, b: Identity) =>
326  a.uuid !== undefined && b.uuid !== undefined
327    ? a.uuid === b.uuid
328    : a.email !== undefined && b.email !== undefined
329      ? a.email === b.email
330      : undefined
331
332// The signed-in account changed: everything latched was the old account's. The reading held now
333// is the old account's too until a different one arrives, so it is kept out of the levels.
334function switchAccount($: EngineInterface, st: State) {
335  const told =
336    st.voided !== undefined ||
337    st.handoffVoided !== undefined ||
338    st.pending.size > 0 ||
339    st.handoff.size > 0 ||
340    [...st.levels.values()].some(w => w.level !== 'quiet')
341  dropWindows(st, WINDOWS.map(w => w.kind))
342  st.handoffVoided = undefined
343  st.voided = told ? { cause: 'account', kinds: WINDOWS.map(w => w.kind) } : undefined
344  st.staleSig = windowSig(st.limits)
345  clearNotice($, st)
346}
347
348async function currentIdentity($: EngineInterface, st: State) {
349  const home = await homeDir($)
350  const identity = home ? await readIdentity($, st, home) : undefined
351  return identity?.uuid === undefined && identity?.email === undefined ? undefined : identity
352}
353
354async function refresh($: EngineInterface, st: State, cfg: Config, limits?: readonly SessionRateLimit[]) {
355  const seq = ++st.refreshSeq
356  const [now, rateLimits, identity] = await Promise.all([
357    $.clock.now(),
358    limits ?? $.session.usage().then(u => u.rateLimits),
359    currentIdentity($, st).catch(() => undefined),
360  ])
361  // A refresh that started before the last one applied holds an older reading and identity.
362  if (seq < st.appliedSeq) return
363  st.appliedSeq = seq
364  // An unreadable identity is no evidence either way, so the recorded one stands; a field one
365  // read lacks is kept from the last, so a UUID that drops out and returns is still compared.
366  if (identity !== undefined) {
367    const same = st.account === undefined ? undefined : sameAccount(st.account, identity)
368    if (same === false) switchAccount($, st)
369    st.account = same === false ? identity : { ...st.account, ...identity }
370  }
371  const hasWindows = rateLimits.some(l => WINDOWS.some(w => w.kind === l.kind))
372  if (hasWindows && st.staleSig !== undefined && windowSig(rateLimits) !== st.staleSig) st.staleSig = undefined
373  const reading = liveWindows(rateLimits, now)
374  const changed = bandText(reading) !== bandText(st.reading)
375  st.reading = reading
376  st.limits = rateLimits
377  st.spend = rateLimits.find(l => l.kind === 'spend_limit')
378  if (changed) $.ui.invalidate('ui.render')
379  // No window reported is no reading, never a reset: the levels wait for the next reading.
380  if (hasWindows && st.staleSig === undefined) st.toastQueue.push(...recordCrossings(st, reading, cfg, now))
381}
382
383function clearNotice($: EngineInterface, st: State, kind?: Notice['kind']) {
384  if (st.notice === undefined || (kind !== undefined && st.notice.kind !== kind)) return
385  st.notice = undefined
386  st.reofferTimer = stopTimer(st.reofferTimer)
387  $.ui.invalidate('ui.render')
388}
389
390// The lines a carrier attaches now, consumed; none when none is due or operator mode holds them.
391// Lines sent to Claude supersede any notice still offering them to the person.
392async function takeLines($: EngineInterface, st: State, cfg: Config): Promise<string[]> {
393  if (!cfg.lines) {
394    consume(st)
395    return []
396  }
397  if (await operatorHolds($, st, cfg)) return []
398  const lines = dueLines(st, cfg)
399  // A restatement with no reading to restate waits for the first carrier that has one.
400  if ((st.restate || st.restateIfLoud) && (st.reading?.size ?? 0) === 0) return []
401  consume(st)
402  if (lines.length > 0 && st.notice?.kind === 'operator') {
403    releaseHeld(st, st.rowSeen)
404    clearNotice($, st)
405  }
406  return lines
407}
408
409// Ends the operator notice's hold on its changes: dropped when the person saw them, otherwise
410// queued for the next flush.
411function releaseHeld(st: State, seen: boolean) {
412  if (!seen) st.toastQueue.unshift(...st.heldToasts)
413  st.heldToasts = []
414}
415
416// Tells the person of each queued window change: a transcript line always, a toast when the option
417// allows. Run after a carrier's lines are built and never throws, so a failing toast drops no line.
418// While operator mode holds the lines the queue waits: a shown suggestion or the person's next
419// prompt drops it, and a suggestion that cannot show leaves it for the carrier that sends the line.
420// `held` is the carrier's answer from before its lines were taken, which may end a forced turn.
421async function flushToasts($: EngineInterface, st: State, cfg: Config, held?: boolean) {
422  try {
423    if (st.toastQueue.length === 0) return
424    if (held ?? (cfg.lines && (await operatorHolds($, st, cfg)))) return
425    const changes = st.toastQueue.splice(0).sort(([a], [b]) => order(a) - order(b))
426    const bodies: string[] = []
427    for (const [kind, event] of changes) {
428      const body = toastBody(kind, event, st.reading?.get(kind), cfg)
429      bodies.push(body)
430      $.ui.log(`rate-limit-guard: ${body} · more: /${COMMAND}`, { to: 'transcript' })
431      if (cfg.toast) $.ui.toast(body)
432    }
433    if (st.notice?.kind !== 'operator') {
434      st.notice = { text: `rate-limit-guard: ${bodies.join('; ')} · more: /${COMMAND}`, kind: 'crossing' }
435      $.ui.invalidate('ui.render')
436    }
437  } catch (error) {
438    logOnce($, st, 'flush-failed', `window change not shown: ${error instanceof Error ? error.message : String(error)}`)
439  }
440}
441
442const noticeShows = (st: State, surface: string) =>
443  st.notice !== undefined && (st.notice.kind === 'operator' || surface !== 'terminal')
444
445// The module's band row: rate-limit-guard: 5h <x>% | 7d <y>%, led by the plugin's name so the row says whose it is.
446export const bandText = (reading: Reading | undefined) =>
447  `rate-limit-guard: ${WINDOWS.map(({ kind, short }) => {
448    const limit = reading?.get(kind)
449    return `${short} ${limit === undefined ? '-' : `${limit.percentUsed}%`}`
450  }).join(' | ')}`
451
452// What /rate-limit-guard with no argument prints.
453async function statusText($: EngineInterface, st: State, cfg: Config) {
454  await refresh($, st, cfg)
455  const windows = WINDOWS.map(({ kind, name }) => {
456    const limit = st.reading?.get(kind)
457    if (limit === undefined) return `${name} window: no reading`
458    const reset = limit.resetsAt === undefined ? '' : `, resets at ${resetLabel(limit.resetsAt)}`
459    return `${name} window: ${limit.percentUsed}% used, ${modelVerdict(levelOf(limit.percentUsed, cfg), cfg)}${reset}`
460  })
461  const home = await homeDir($)
462  const snapshot = !cfg.writes
463    ? 'off (rate_limit_guard_enabled is false)'
464    : home
465      ? `${home}/.claude/${CONTRACT_DIR}/${SNAPSHOT_FILE}`
466      : 'no home directory to write under'
467  return [
468    'From the last API response:',
469    ...windows,
470    ...(st.spend ? [`Spend limit: ${st.spend.percentUsed}% used`] : []),
471    `Line threshold ${cfg.threshold}%, approach mark ${cfg.approach}%.`,
472    `Band row ${st.bandShown ? 'on' : 'off'}, window-change toast ${cfg.toast ? 'on' : 'off'}. Set the row with /${COMMAND} band [on|off].`,
473    `Snapshot: ${snapshot}`,
474    `README: ${README}`,
475  ].join('\n')
476}
477
478const isoSeconds = (ms: number) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, 'Z')
479
480export const isEmailShaped = (value: unknown): value is string => {
481  if (typeof value !== 'string') return false
482  const points = [...value].map(c => c.codePointAt(0) ?? 0)
483  return points.length >= 3 && points.length <= 254 && value.includes('@') && !points.some(p => p < 32 || p === 34 || p === 92 || p === 127)
484}
485
486const homeDir = async ($: EngineInterface) => (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
487
488const isIdShaped = (value: unknown): value is string => typeof value === 'string' && /^[A-Za-z0-9-]{1,128}$/.test(value)
489
490// The account in the state file, undefined when unreadable; a field is left out when missing or
491// malformed. The file is large and rewritten often, so a parse is kept until its mtime or size changes.
492async function readIdentity($: EngineInterface, st: State, home: string): Promise<Identity | undefined> {
493  const path = `${(await $.env.get('CLAUDE_CONFIG_DIR')) || home}/.claude.json`
494  const stat = await $.fs.stat(path).catch(() => undefined)
495  if (stat === undefined || stat.kind !== 'file') return undefined
496  const key = `${path}|${stat.mtimeMs}|${stat.size}`
497  if (st.identityCache?.key === key) return st.identityCache.identity
498  const text = await $.fs.read(path).catch(() => undefined)
499  if (typeof text !== 'string') return undefined
500  const identity: Identity = {}
501  try {
502    const account = JSON.parse(text)?.oauthAccount
503    if (isIdShaped(account?.accountUuid)) identity.uuid = account.accountUuid
504    if (isEmailShaped(account?.emailAddress)) identity.email = account.emailAddress
505  } catch {}
506  st.identityCache = { key, identity }
507  return identity
508}
509
510// An API response: its time, and the account it was for.
511async function recordResponse($: EngineInterface, st: State, cfg: Config) {
512  st.lastResponseAtMs = await $.clock.now()
513  st.responseEmail = undefined
514  const home = await homeDir($)
515  if (cfg.writes && home) st.responseEmail = (await readIdentity($, st, home))?.email
516}
517
518// Omit rather than guess: attribute only when the account now is the one read at the last response.
519async function accountEmail($: EngineInterface, st: State, home: string) {
520  if (st.responseEmail === undefined) return undefined
521  const email = (await readIdentity($, st, home))?.email
522  return email !== undefined && email === st.responseEmail ? email : undefined
523}
524
525export const snapshotBody = (capturedAt: string, sessionId: string, reading: Reading, email?: string): Body => {
526  const windows = [...reading.entries()].map(([kind, l]) => {
527    const resetsMs = l.resetsAt === undefined ? NaN : Date.parse(l.resetsAt)
528    const resets = Number.isFinite(resetsMs) ? { resets_at: Math.floor(resetsMs / 1000) } : {}
529    return [kind, { used_percentage: l.percentUsed, ...resets }] as const
530  })
531  return {
532    captured_at: capturedAt,
533    session_id: sessionId,
534    ...(windows.length > 0 ? { rate_limits: Object.fromEntries(windows) } : {}),
535    ...(email ? { account: { email } } : {}),
536  }
537}
538
539const wholePoints = (body: Partial<Body> | undefined) =>
540  JSON.stringify(
541    Object.entries(body?.rate_limits ?? {})
542      .sort(([a], [b]) => a.localeCompare(b))
543      .map(([kind, w]) => [kind, Math.floor(Number(w?.used_percentage)), w?.resets_at ?? null]),
544  )
545
546const logOnce = ($: EngineInterface, st: State, key: string, text: string, to: 'debug' | 'transcript' = 'debug') => {
547  if (st.loggedOnce.has(key)) return
548  st.loggedOnce.add(key)
549  $.ui.log(`rate-limit-guard: ${text}`, { to })
550}
551
552// A bad option is the person's to fix, so its line goes to the transcript, once per load.
553const reportOptions = ($: EngineInterface, st: State, cfg: Config) => {
554  for (const line of cfg.bad) logOnce($, st, line, line, 'transcript')
555}
556
557// Decides in memory whether to write, so an event that writes nothing starts no process.
558async function writeSnapshot($: EngineInterface, st: State, cfg: Config, trigger: 'event' | 'timer') {
559  if (!cfg.writes || st.origin?.kind === 'task-notification' || st.reading === undefined) return
560  const home = await homeDir($)
561  if (!home) return
562  const target = `${home}/.claude/${CONTRACT_DIR}/${SNAPSHOT_FILE}`
563  const [now, sessionId] = await Promise.all([$.clock.now(), $.session.id()])
564  const email = await accountEmail($, st, home)
565  const body = snapshotBody(isoSeconds(now), sessionId, st.reading, email)
566  const onDisk = await $.fs
567    .read(target)
568    .then(text => JSON.parse(String(text)) as Partial<Body>)
569    .catch(() => undefined)
570  const diskAt = onDisk?.captured_at === undefined ? NaN : Date.parse(onDisk.captured_at)
571  if (trigger === 'timer' && onDisk !== undefined && onDisk.session_id !== sessionId && !(diskAt < (st.lastResponseAtMs ?? 0))) {
572    return
573  }
574  // After a branch the file takes the new session id at once: the id is part of what a reader trusts.
575  const moved =
576    onDisk === undefined || wholePoints(onDisk) !== wholePoints(body) || (st.branched && onDisk.session_id !== sessionId)
577  if (!moved && Number.isFinite(diskAt) && now - diskAt < FLOOR_MS) return
578  const sig = JSON.stringify({ ...body, captured_at: undefined })
579  if (st.lastAttempt !== undefined && st.lastAttempt.sig === sig && now - st.lastAttempt.at < FLOOR_MS) return
580  const argv = ['node', `${$.plugin.root}/${HELPER}`, target, '--preserve-key', 'rate_limits', ...(moved ? [] : ['--floor', '300'])]
581  // Only a write the helper decided (written, or skipped by rule) dedupes; a failed one is tried at the next carrier.
582  try {
583    const run = await $.process.run(argv, { stdin: JSON.stringify(body), timeoutMs: 10_000 })
584    if (run.exitCode === 0 || run.exitCode === 3) {
585      st.lastAttempt = { sig, at: now }
586      st.branched = false
587    }
588    else logOnce($, st, 'write-failed', `snapshot write failed (exit ${run.exitCode}): ${run.stderr.trim()}`)
589  } catch (error) {
590    logOnce($, st, 'write-threw', `snapshot write did not run: ${error instanceof Error ? error.message : String(error)}`)
591  }
592}
593
594function queueWrite($: EngineInterface, st: State, cfg: Config, trigger: 'event' | 'timer') {
595  st.writing = st.writing.then(() => writeSnapshot($, st, cfg, trigger)).catch(() => undefined)
596  return st.writing
597}
598
599async function statusJson($: EngineInterface, st: State, cfg: Config) {
600  await refresh($, st, cfg)
601  // Every window the response reported except a gateway's spend limit, which has its own entry.
602  const now = await $.clock.now()
603  const live = st.limits.filter(l => l.kind !== 'spend_limit' && !(Date.parse(l.resetsAt ?? '') <= now))
604  const windows = Object.fromEntries(
605    live.map(l => [l.kind, { used_percentage: l.percentUsed, resets_at: l.resetsAt ?? null, verdict: levelOf(l.percentUsed, cfg) }]),
606  )
607  const levels = live.map(l => levelOf(l.percentUsed, cfg))
608  return JSON.stringify({
609    source: 'the last API response',
610    windows,
611    verdict: levels.length === 0 ? 'unknown' : levels.includes('edge') ? 'edge' : levels.includes('approach') ? 'approach' : 'quiet',
612    line_threshold: cfg.threshold,
613    approach_pct: cfg.approach,
614    lanes_pause_edge: PAUSE_EDGE,
615    ...(st.spend ? { spend_limit: { used_percentage: st.spend.percentUsed, resets_at: st.spend.resetsAt ?? null } } : {}),
616  })
617}
618
619// Operator mode: offer the line as the prompt box's suggestion; with text in the box, show the
620// notice row and offer again once the box is empty; where it cannot show, the line goes to Claude.
621// A first offer that cannot show leaves the changes to be toasted with the automatic line; a
622// re-offer comes after the row was up, so the person has seen them unless a survey hid the row.
623async function offer($: EngineInterface, st: State, cfg: Config, first = false) {
624  if (st.notice?.kind !== 'operator') return true
625  const { text } = st.notice
626  const box = await $.prompt.read()
627  if (box.text.trim() !== '') return false
628  const { isShown } = await $.prompt.suggest({ text })
629  if (isShown) {
630    st.handoff = new Map([...st.handoff, ...dueEvents(st, cfg)])
631    st.handoffVoided = mergeVoided(st.handoffVoided, st.voided)
632    consume(st)
633    releaseHeld(st, true)
634  } else {
635    releaseHeld(st, !first && st.rowSeen)
636    st.notice = undefined
637    st.forceAutomatic = true
638  }
639  $.ui.invalidate('ui.render')
640  return true
641}
642
643function stopTimer(timer: Timer | undefined) {
644  timer?.cancel()
645  return undefined
646}
647
648export const register: Register = (on, options) => {
649  const cfg = parseConfig(options)
650  const st: State = {
651    reading: undefined,
652    spend: undefined,
653    levels: new Map(),
654    limits: [],
655    pending: new Map(),
656    toastQueue: [],
657    heldToasts: [],
658    rowSeen: false,
659    handoff: new Map(),
660    handoffVoided: undefined,
661    account: undefined,
662    staleSig: undefined,
663    voided: undefined,
664    refreshSeq: 0,
665    appliedSeq: 0,
666    restate: false,
667    restateIfLoud: false,
668    branched: false,
669    forceAutomatic: false,
670    origin: undefined,
671    notice: undefined,
672    bandShown: cfg.band,
673    lastResponseAtMs: undefined,
674    responseEmail: undefined,
675    identityCache: undefined,
676    lastAttempt: undefined,
677    loggedOnce: new Set(),
678    writing: Promise.resolve(),
679    writeTimer: undefined,
680    reofferTimer: undefined,
681  }
682
683  on('session.start', async ($, e, next) => {
684    reportOptions($, st, cfg)
685    const [tool] = await Promise.allSettled([
686      $.tool.register({
687        name: 'status',
688        description:
689          "Returns this session's plan rate-limit usage as JSON, from the last API response: `windows` keyed by kind (five_hour, seven_day, and any other window reported except the spend limit), each with `used_percentage`, `resets_at` and `verdict`; an overall `verdict`, the worst window's (`quiet`, `approach` at or above `approach_pct`, `edge` at or above `line_threshold`, or `unknown` when no window is reported); those two thresholds and `lanes_pause_edge`, where a loop lane that opted in to pausing pauses; and `spend_limit` when a gateway reports one. A window whose reset time has passed is left out. The figures change only when an API response arrives. With the model_notices option on (off by default), rate-limit-guard also adds a line to the next prompt or tool result when the 5-hour or 7-day window rises to approach or edge, or resets from edge, and one line saying earlier lines no longer apply when the signed-in account changes. Read-only.",
690        inputSchema: { type: 'object', properties: {}, additionalProperties: false },
691      }),
692      $.command.register({
693        name: 'rate-limit-guard',
694        description: 'Rate-limit windows and verdicts; band on or off sets the band row for this session',
695        argumentHint: '[band [on|off]]',
696      }),
697    ])
698    if (tool.status === 'rejected') {
699      const reason = tool.reason instanceof Error ? tool.reason.message : String(tool.reason)
700      logOnce($, st, 'tool-register', `the status pull tool could not register: ${reason}`)
701    }
702    await refresh($, st, cfg)
703    // A fresh load mid-session (a reload, a worker respawn, an enable, a --resume launch): the
704    // earlier lines already reached Claude, so only a window at the edge is restated.
705    if ((await $.session.turns()) > 0) {
706      st.pending.clear()
707      st.restateIfLoud = true
708    }
709    return next(e)
710  }).catch(($, e, next) => next(e))
711
712  on('session.end', async ($, e, next) => {
713    st.writeTimer = stopTimer(st.writeTimer)
714    st.reofferTimer = stopTimer(st.reofferTimer)
715    await queueWrite($, st, cfg, 'event')
716    if (e.reason === 'resume') st.restate = st.branched = true
717    if (e.reason === 'clear') st.restateIfLoud = true
718    st.origin = undefined
719    return next(e)
720  }).catch(($, e, next) => next(e))
721
722  on('session.compact', async ($, e, next) => {
723    const result = await next(e)
724    if (e.agentId === undefined && e.trigger !== 'precompute' && !('skip' in result && result.skip)) st.restate = true
725    return result
726  }).catch(($, e, next) => next(e))
727
728  on('session.measure', async ($, e, next) => {
729    reportOptions($, st, cfg)
730    await recordResponse($, st, cfg).catch(() => undefined)
731    await refresh($, st, cfg, e.rateLimits)
732    await queueWrite($, st, cfg, 'event')
733    await flushToasts($, st, cfg)
734    return next(e)
735  }).catch(($, e, next) => next(e))
736
737  on('turn.step', async function* ($, e, next) {
738    const result = yield* next(e)
739    await recordResponse($, st, cfg).catch(() => undefined)
740    return result
741  }).catch(async function* ($, e, next) {
742    return yield* next(e)
743  })
744
745  on('prompt.submit', async ($, e, next) => {
746    reportOptions($, st, cfg)
747    if (e.turnId === undefined) {
748      st.origin = e.origin
749      // An untaken suggestion goes to Claude at the next turn no person started; a person's turn drops it.
750      const handingOff = !isPersonTurn(st) && (st.handoff.size > 0 || st.handoffVoided !== undefined)
751      if (handingOff) {
752        for (const [kind, due] of st.handoff) {
753          if (!st.pending.has(kind) && (due.event === 'reset' || st.levels.has(kind))) st.pending.set(kind, due)
754        }
755        st.voided = mergeVoided(st.voided, st.handoffVoided)
756      }
757      st.handoff.clear()
758      st.handoffVoided = undefined
759      if (isPersonTurn(st) && st.notice?.kind === 'operator') releaseHeld(st, st.rowSeen)
760      if (isPersonTurn(st) || handingOff) clearNotice($, st)
761    }
762    await refresh($, st, cfg)
763    const held = cfg.lines && (await operatorHolds($, st, cfg))
764    const lines = await takeLines($, st, cfg)
765    await flushToasts($, st, cfg, held)
766    return next(withLines($, e, lines))
767  }).catch(($, e, next) => next(e))
768
769  on('turn.start', async ($, e, next) => {
770    st.reofferTimer = stopTimer(st.reofferTimer)
771    st.writeTimer ??= $.clock.every(WRITE_TIMER_MS, () => {
772      void queueWrite($, st, cfg, 'timer')
773    })
774    return next(e)
775  }).catch(($, e, next) => next(e))
776
777  on('turn.complete', async ($, e, next) => {
778    if (e.agentId !== undefined) return next(e)
779    st.writeTimer = stopTimer(st.writeTimer)
780    if (cfg.lines && (await operatorHolds($, st, cfg))) {
781      await refresh($, st, cfg)
782      await flushToasts($, st, cfg)
783      const lines = dueLines(st, cfg)
784      if (lines.length > 0) {
785        // One row, one prefix, however many windows it offers.
786        st.notice = { text: `FYI, rate-limit-guard: ${lines.map(l => l.replace(/^rate-limit-guard: /, '')).join(' ')}`, kind: 'operator' }
787        st.heldToasts.push(...st.toastQueue.splice(0))
788        st.rowSeen = false
789        $.ui.invalidate('ui.render')
790        if (!(await offer($, st, cfg, true))) {
791          st.reofferTimer ??= $.clock.every(REOFFER_MS, () => {
792            void offer($, st, cfg)
793              .then(done => {
794                if (done) st.reofferTimer = stopTimer(st.reofferTimer)
795              })
796              .catch(() => undefined)
797          })
798        }
799      }
800    }
801    return next(e)
802  }).catch(($, e, next) => next(e))
803
804  on('tool.call', async ($, e, next) => {
805    if (e.tool === `mcp__${$.plugin.name}__status`) {
806      const json = await statusJson($, st, cfg)
807      await flushToasts($, st, cfg)
808      return { result: json }
809    }
810    reportOptions($, st, cfg)
811    const result = await next(e)
812    if (e.agentId !== undefined) return result
813    await refresh($, st, cfg)
814    await queueWrite($, st, cfg, 'event')
815    if (result.deny !== undefined || result.isError) return result
816    const held = cfg.lines && (await operatorHolds($, st, cfg))
817    const lines = await takeLines($, st, cfg)
818    await flushToasts($, st, cfg, held)
819    return withLines($, result, lines)
820  }).catch(($, e, next) => next(e))
821
822  on('command.run', { command: 'rate-limit-guard' }, async ($, e, next) => {
823    const words = (e.args ?? '').trim().toLowerCase().split(/\s+/).filter(w => w !== '')
824    if (words.length === 0) {
825      const text = await statusText($, st, cfg)
826      await flushToasts($, st, cfg)
827      return { text }
828    }
829    const [word, arg, ...rest] = words
830    if (word !== 'band' || rest.length > 0 || (arg !== undefined && arg !== 'on' && arg !== 'off')) return { text: USAGE }
831    st.bandShown = arg === undefined ? !st.bandShown : arg === 'on'
832    $.ui.invalidate('ui.render')
833    return { text: `Band row ${st.bandShown ? 'on' : 'off'} for this session` }
834  }).catch(($, e, next) => next(e))
835
836  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
837    const theirs = await next(e)
838    const notice = noticeShows(st, e.surface) ? st.notice : undefined
839    if (e.props.hasSurvey || (!st.bandShown && notice === undefined)) return theirs
840    if (notice?.kind === 'operator') st.rowSeen = true
841    const { Box, Text } = $.ui.resolve(e)
842    return (
843      <Box flexDirection="column">
844        {st.bandShown ? (
845          <Text dimColor wrap="truncate">
846            {bandText(st.reading)}
847          </Text>
848        ) : null}
849        {notice !== undefined ? <Text wrap="wrap">{notice.text}</Text> : null}
850        {theirs}
851      </Box>
852    )
853  }).catch(($, e, next) => next(e))
854}
855