Claude Drain Guard
Claude Drain Guard was built for one specific failure mode: a few abnormal Claude Code requests can consume a large part of a five-hour usage window before the user realizes anything changed.
The extension keeps 5h usage and prompt-cache efficiency visible in VS Code, detects unusual fresh-token growth and cache rebuilds, and records enough local evidence to explain what happened. Its purpose is not merely to display quota; it is to warn when the rate and shape of consumption stop looking normal.
It is a local-first VS Code extension with no runtime npm dependencies. Transcript content is parsed in memory to extract counters; prompt text, response text, source code, credentials, and tool arguments are not persisted in metrics or reports. The optional Unix live bridge requires jq.

Screenshots illustrate the existing UI with example data; they predate the latest connection-label fixes. Current behavior is described below and in the feature guides.
What it tells you
Claude Drain Guard separates three questions that are easy to confuse:
| Question |
Signal |
Source |
| How much subscription capacity is left? |
5h and optional 7d utilization |
Official account usage |
| Is this session reusing context efficiently? |
Cache hit, cache read/write, warm/cold state |
Claude JSONL and optional status-line telemetry |
| Is something abnormal happening now? |
Blue, yellow, or red anomaly indicator |
Local statistical detector |
The colored dot is an anomaly signal, not a quota threshold. A 96% cache hit does not become critical merely because usage is high, and 100% 5h usage does not by itself mean the detector found a cache problem.
Quick start
- Install Claude Drain Guard from the Visual Studio Marketplace, or use Extensions: Install from VSIX... for the local 0.9.4 connection-fix build. The local build is not automatically published to Marketplace.
- Reload VS Code. The compact item appears on the right side of the status bar.
- Run Claude Code normally. Completed responses are read incrementally from the local Claude JSONL files.
- Click the status item to open the Dashboard.
- If 5h usage is unavailable, select Check usage in the Dashboard (Command Palette: Connect Live Usage). It attempts a real read first. If credentials are unavailable, choose Sign in to Claude, complete login, then Check usage again; closing the login terminal is not required. Errors and the last sample time remain visible. Repeated checks have a ten-second minimum interval and respect server retry instructions.
- Optionally connect Claude Live Bridge for event-driven status-line updates. This is a separate integration, not a prerequisite for OAuth usage or JSONL monitoring.
Marketplace versions are immutable. Always increment version before uploading a replacement package.
Reliability build notes
Usage, cache efficiency, and anomaly severity are separate measurements. A normal 3-point quota increase does not create a popup. The detector looks at cumulative changes within 15 minutes and stronger evidence before interrupting you; its thresholds are heuristics, not a guarantee that every expensive task is abnormal.
Historical charts use fixed five-minute storage bins, with 5m/30m/1h display choices. Session totals survive the 500-response detail limit; the chart identifies retained detail separately. On upgrade, legacy metrics are backed up as metrics.json.pre-v2.json, ambiguous old quota samples are re-baselined, and incomplete reconstructed history is identified as partial.
See Claude Code compatibility for source fields and development checks for verification and remaining limits.
Status bar
The persistent item is intentionally compact:
| State |
Example |
Meaning |
| Normal |
5h:31% 7d:62% · cache:97% + blue dot |
No drain anomaly detected |
| Elevated |
same metrics + yellow dot |
A change deserves inspection |
| Critical |
same metrics + red dot and Alert |
Stop before sending another prompt |
| 5h-only plan |
5h:31% · cache:97% |
No 7d window was returned |
| Waiting |
5h — · cache — |
No usable sample yet |

Hover for:
- current 5h/7d usage and reset times
- observed session duration and completed responses
- session-average and recent-one-hour burn rate
- estimated time to the limit, compared with the reset time
- the largest local model/traffic contributor
- rolling cache read, uncached input, and cache-write totals
Click the item to open the Dashboard. The refresh interval is configurable from 1–60 seconds; 15 seconds is the default. File changes still trigger an immediate incremental read.
Usage audit
The Usage audit answers “where did this session go?” rather than showing another isolated percentage.
| Metric |
Definition |
| Observed 5h use |
Positive change in official 5h utilization during the observed session |
| Average burn |
Observed percentage-point change divided by session hours |
| Recent burn |
Same calculation over the latest 60 minutes |
| Per response |
Observed session change divided by completed API responses |
| API-equivalent rate |
Reported or estimated token cost per hour; not Claude Max billing |
| Estimated module share |
Allocation across model and main, subagent, or workflow traffic |
“7.3 pts/h” means the 5h meter is increasing by approximately 7.3 percentage points per hour. It does not mean 7.3% of the remaining balance.
Anthropic exposes account-wide 5h usage, not an exact per-model or per-agent charge. Module rows are therefore marked estimated. Drain Guard uses API-equivalent cost weights when all responses have comparable cost data; otherwise it uses a stable token-workload proxy. Concurrent sessions and other devices can affect the official total.
Use Export usage report for a local Markdown record of the session, burn rates, forecast, and module table.
Read the Usage audit guide
Dashboard
Read the Dashboard from top to bottom:
- Ongoing session — what the current JSONL session has produced.
- Usage audit — how quickly official 5h utilization changed and which local traffic dominated.
- Cache detail — current-response counters, JSONL cache history, and official
prompt_cache fields when present.
- 24-hour chart — when fresh-token activity occurred. Choose a 1h, 6h, or 24h range and 5m, 30m, or 1h bins.
- Recent activity — grouped incidents or every completed response.
Every chart bar has exact hover data. The vertical scale is logarithmic so a large spike does not flatten normal traffic into an unreadable line.
Read the Dashboard and reports guide
Anomaly detection
A cache percentage is not judged in isolation. The detector combines:
- absolute fresh-input and cache-rewrite size
- cache cliffs relative to the preceding comparable response
- a personal median/MAD baseline resistant to outliers
- short EWMA acceleration
- Page-Hinkley and one-sided CUSUM change detection
- multivariate pressure across fresh input, cache write, output, and cache deficit
- separate baselines for session, model, context size, and main/subagent/workflow traffic
- unexpected misses when official
prompt_cache telemetry provides them
A statistical shift alone is elevated. Critical requires strong absolute evidence, such as an unusually large fresh-input event, an authoritative quota jump, or repeated large cache rewrites. New sessions and responses after an idle/cache-expiry boundary receive warm-up handling to suppress misleading 0% cache alerts.

Read how cache and anomaly decisions work
Claude live bridge
Claude Code's documented status-line payload provides current-response counters, rate limits, and optional prompt_cache statistics including warm/cold, TTL, misses, and expected rebuilds. Drain Guard checks field presence; missing values stay unknown. JSONL remains the source for per-response history and subagents. See the compatibility notes.
The connection states are deliberately explicit:
| State |
What has been verified |
| Configured |
The Claude statusLine setting points to Drain Guard |
| Waiting for first signal |
The helper passed its self-test, but Claude has not invoked it |
| Restart required |
Settings and helper are ready; Claude Code must restart and accept its trust prompt |
| Live |
A recent real Claude payload containing documented counters was parsed |
| Stale |
A payload exists but is no longer recent |
| Self-test failed |
The copied helper could not produce a valid local probe |
“Configured” is not treated as “Live.” If it remains waiting after restarting Claude Code, accepting trust, and completing a response, check disableAllHooks and the selected Claude data directory. JSONL monitoring and OAuth usage continue independently.
Read the telemetry and data-source guide
Cost
Cost follows an auto strategy similar to mature Claude usage tools:
- Prefer Claude Code's reported per-entry
costUSD when present.
- Otherwise calculate API-equivalent cost from input, output, cache-read, 5-minute cache-write, and 1-hour cache-write tokens using the matched model family.
- Leave the value unavailable when a safe first-party estimate cannot be made, including unsupported models and some provider/fast-mode combinations.
This is an impact estimate for comparing requests. It is not a Claude Max invoice and is never converted directly into 5h quota.
| Layer |
Responsibility |
Frequency |
| Claude JSONL |
Responses, tokens, models, subagents, charts, incidents |
Incremental read on file change; active-file fallback timer |
| OAuth usage |
Authoritative 5h/7d reconciliation |
At most once per five minutes unless manually refreshed |
| Optional status line |
Immediate current-response counters and account rate limits |
When Claude emits a status-line payload |
Performance safeguards:
- changed JSONL files are opened read-only and scanned from the previous byte offset
- incomplete JSONL tails are retained until the next append
- high-frequency fallback checks are limited to the 64 most recently active session files
- full discovery runs once per minute
- state writes are asynchronous, atomic, and coalesced
- Dashboard refresh bursts are coalesced, hidden panels are skipped, and unchanged state is not reloaded
- concurrent live-telemetry events share one read/parse operation
- rolling windows use one aggregation pass; current bins and bounded histories update in place
- detector baselines retain only the 256 most recently observed session/model/context/traffic groups
- alert dialogs are serialized through one coalescing queue
- reports are generated asynchronously
- no proxy, certificate change, prompt interception, or long-running helper process is installed
The optional connection self-test runs the copied helper once with synthetic counters and a five-second timeout. It does not send a model request, and Claude settings are changed only after the test succeeds.
Feature guides
Requirements and compatibility
- VS Code 1.85 or newer
- Claude Code sessions with local JSONL history for token/cache analysis
- Claude.ai OAuth credentials for authoritative 5h/7d percentages
- a compatible Claude Code status-line surface for the optional live bridge
API-key and AWS Bedrock users retain local token/cache monitoring and supported cost estimates, but do not receive Claude.ai subscription percentages.
Commands
Open the Command Palette and search for Claude Drain Guard:
| Command |
Result |
| Open Dashboard |
Opens or reveals the single Dashboard panel |
| Show Details |
Opens recent activity and report actions |
| Connect Live Usage |
Checks usage immediately; offers sign-in for credential failures and verifies data separately from login |
| Connect Claude Live Bridge |
Installs and self-tests the optional status-line helper; Claude restart and trust are still required |
| Disconnect Claude Live Bridge |
Removes only a status-line entry owned by Drain Guard |
| Generate Usage Report |
Exports session pace and estimated module attribution |
| Generate Incident Report |
Exports anomaly evidence and recent slices |
| Mute Alerts for 15 Minutes |
Temporarily suppresses notifications |
| Reset Baseline |
Resets learned detector baselines; preserves usage totals and recorded history |
Settings
| Setting |
Default |
Purpose |
claudeDrainGuard.refreshIntervalSeconds |
15 |
Active-file fallback refresh, 1–60 seconds |
claudeDrainGuard.sliceMinutes |
5 |
Rolling cache/fresh summary window |
claudeDrainGuard.statusBarAlignment |
right |
Status-bar side |
claudeDrainGuard.notifications |
true |
Enable anomaly notifications |
claudeDrainGuard.modalCriticalAlerts |
true |
Require acknowledgement for critical alerts |
claudeDrainGuard.authoritativeQuota.enabled |
true |
Enable read-only 5h/7d usage reconciliation |
claudeDrainGuard.authoritativeQuota.warningSpikePercent |
5 |
Yellow state for a comparable rapid 5h increase; no popup |
claudeDrainGuard.authoritativeQuota.criticalSpikePercent |
10 |
Critical candidate requiring confirmation or short time-to-limit |
claudeDrainGuard.authoritativeQuota.emergencySpikePercent |
15 |
Emergency increase that may notify without a second signal |
claudeDrainGuard.cost.fallbackCacheTtl |
auto |
Pricing fallback for cache writes lacking TTL detail |
Advanced detector thresholds are available in VS Code Settings. Defaults are combined with personal baselines; lowering a single threshold can increase false positives.
Privacy and security
See PRIVACY.md and SECURITY.md.
Drain Guard stores counters, timestamps, model/traffic labels, anomaly evidence, and generated reports locally. It does not store prompt or response content. This is a community project and is not affiliated with or endorsed by Anthropic.
Development
git clone https://github.com/Rainday2425/claude-drain-guard.git
cd claude-drain-guard
pnpm install
pnpm check
npx @vscode/vsce package --no-dependencies
Open the folder in VS Code and press F5 to launch an Extension Development Host. Increment the package version before every Marketplace upload.
See CHANGELOG.md for release notes.