[FEATURE] Proactive token cost transparency & anomaly detection across all surfaces
Preflight Checklist
- [x] I have searched existing requests and this feature hasn't been requested yet
- [x] This is a single feature request (not multiple features)
Problem Statement
A single unified feature: users should never be surprised by token consumption. Surprises cause complaints, wasted budgets, and in agentic contexts can cause runaway consumption that empties daily/hourly limits in seconds.
The principle: before executing any action with non-trivial, estimable token cost, show the user what they are about to spend and require confirmation if it exceeds their configured threshold.
This applies to Claude Code, the claude.ai web UI, Cowork, and any other surface where token consumption occurs.
The failure modes this addresses, in increasing severity:
User resumes a stale session, cache has expired, 400k tokens reload uncached. They had no idea.
User asks Claude to ingest a 200MB PDF. Full ingest begins. Tokens gone before they understood the cost.
A bug in a harness or agent causes 50 parallel Claude Code sessions to spawn. Each costs 40k tokens at startup. 2 million tokens gone in 30 seconds. No warning raised.
A runaway agentic loop iterates at high token burn rate. Silently exhausts hourly limits.
All of these are preventable with pre-operation estimation and burn rate monitoring. None require perfect token counting — ballpark estimates are sufficient because the anomalies are orders of magnitude, not marginal differences.
Design principles for all cases:
Fail loudly. Silent failures are the worst kind. They let bad states compound. A visible anomaly caught immediately is a minor incident. The same anomaly noticed 10 minutes later is a disaster.
The loudness of the failure should scale with the cost of missing it.
Always offer a "do less" path, not just confirm/abort. Compact first, summarize instead of full ingest, reduce scope. Friction without an escape hatch is just friction.
Thresholds must be user-configurable and disable-able entirely for power users who have their own monitoring.
Cross-surface consistency. Threshold settings should live at the account level and propagate to all surfaces.
Specific Cases(non-exhaustive):
#1 Stale cache resume warning
#2 Large file / high-cost ingestion warning
#3 Recursive / runaway spawn detector
#4 Token burn rate anomaly detector(this covers all the above but only after the fact. Better to warn BEFORE hand but this is the catch all case)
Proposed Solution
Example Case 1:
Problem:
Users resume sessions after cache TTL expiry (5 min default, 1 hr extended) with no awareness that their entire context will reload as uncached tokens. A session with 400k tokens of context costs 400k uncached tokens on resume. This is the single most common source of "why did I use all my tokens" complaints.
Proposed behavior:
When --resume or --continue is invoked:
Read the JSONL transcript to estimate context token count (character-count heuristic is sufficient)
Compare last message timestamp against cache TTL thresholds
If TTL has expired AND estimated token count exceeds user-configured threshold, show a blocking prompt before any tokens are consumed:
⚠️ Cache Expired — Resume Cost Warning
This session's context is approximately 340k tokens.
Cache expired 4 hours ago. Resuming will reload the full context as uncached tokens.
Estimated cost: ~340k tokens (~12% of your 5 hour limit)
[C] Continue anyway
[S] Compact first, then resume ← recommended
[A] Abort
Options on the block:
Continue — proceed as normal
Compact first — run /compact against the transcript, then resume with the summary. Dramatically reduces reload cost.
Abort — exit cleanly
Configuration:
json// .claude/settings.json
{
"tokenWarnings": {
"resumeWarningThreshold": 0.10, // warn if resume would cost >10% of 5 hour limit
"disabled": false
}
}
**Notes:**
- Token estimate does not need to be precise. Order-of-magnitude accuracy is sufficient.
- Should display both absolute token estimate AND percentage of current rate limit tier.
- The "Compact first" path is the real value — it turns the warning into a solution, not just friction.
- Applies to claude.ai web UI session continuation as well, not only Claude Code.
---
## Example Case 2 — Large File / High-Cost Ingestion Warning
**Problem:**
When a user asks Claude to read a large file — a 200MB PDF, a 50k line codebase, a large log dump — ingestion begins immediately with no indication of token cost. By the time the user understands what happened, the tokens are spent.
File size is known *before* ingestion starts. There is no reason this cannot be a hard block.
**Proposed behavior:**
Before ingesting any file or content source:
1. Estimate token cost from file size (simple heuristic: ~1 token per 4 bytes of text, adjust for binary/PDF)
2. If estimated cost exceeds user-configured threshold, show a blocking prompt:
⚠️ Large File Warning
You are about to ingest: report.pdf (214 MB)
Estimated token cost: ~180k tokens (~11% of your 5 hour limit)
[C] Continue — full ingest
[S] Summarize instead ← recommended
[P] Ingest first N pages only
[A] Abort
Triggers (non-exhaustive):
Single file exceeding size threshold
/add of a directory whose estimated total exceeds threshold
Web research task with broad scope (harder to estimate, but a ceiling estimate is still useful)
Any tool call whose inputs suggest high token cost before execution
Configuration:
json{
"tokenWarnings": {
"fileIngestionWarningThreshold": 0.15,
"disabled": false
}
}
**Notes:**
- The "Summarize instead" and "first N pages" options are critical — they make the warning actionable.
- Applies across Claude Code, claude.ai web UI, and Cowork.
- The same pattern should apply to any estimable high-cost operation, not just file reads.
---
## Example Case 3 — Recursive / Parallel Spawn Detector
**Problem:**
Claude Code can spawn child Claude Code sessions for subagent or maintenance tasks. If a harness bug causes a session to recursively spawn itself, or to fan out to an unexpected number of parallel sessions, the cost compounds extremely rapidly before any per-operation warning could fire.
This is catchable at spawn time with session tree awareness, before burn rate even becomes visible.
**Proposed behavior:**
When any Claude Code session attempts to spawn a child session:
1. Check current session tree depth
2. Check total number of active sessions under the account
3. If either exceeds threshold, block and warn:
⚠️ Session Spawn Warning
A Claude Code session is attempting to spawn a new Claude Code session.
Current session tree depth: 3
Total active sessions: 12
Estimated startup token cost: ~40k tokens
Recursive spawning may indicate a configuration error.
[C] Continue — spawn the session
[A] Abort spawn
[K] Abort spawn and kill all sessions
Specific triggers:
Session depth exceeding N (suggest default: 3)
Total active session count exceeding N (suggest default: 5)
Spawn rate exceeding N sessions per minute (catches gradual runaway)
A session spawning a child that shares the same task/prompt as itself (direct recursion detection)
Configuration:
json{
"tokenWarnings": {
"maxSessionDepth": 3,
"maxActiveSessions": 5,
"spawnWarningEnabled": true
}
}
Notes:
This is complementary to burn rate detection (Example Case #4) — spawn detection fires earlier, before the financial damage is done.
The "Kill all sessions" option on this prompt is important. If the user sees depth=3 and count=12, they may want to nuke everything immediately.
False positive cost is one unnecessary confirmation click. False negative cost is millions of tokens in seconds. Err hard toward warning.
Applies specifically to Claude Code and Cowork or any surface that supports session spawning.
---
Example Case 4 — Token Burn Rate Anomaly Detector
Problem:
Per-operation cost estimation cannot catch runaway scenarios where the problem is the rate of individually normal-cost operations. Example: a bug causes an agentic loop to iterate continuously. Each iteration is a normal-cost operation. The problem is only visible in aggregate rate over time.
Real incident: a misconfigured harness spawned ~50 parallel Claude Code sessions. Each session startup cost ~40k tokens. Approximately 2 million tokens were consumed in roughly 30 seconds. No warning was raised at any point. The failure was only discovered by checking the usage dashboard.
Proposed behavior:
Maintain a rolling token consumption rate across all active sessions under the same account:
- Track tokens consumed per minute over a sliding window (e.g. last 5 minutes)
- Compare against a baseline for the current workload type
- If rate exceeds user-configured threshold (absolute or % of limit per minute), immediately interrupt all active sessions and surface a loud, blocking alert:
🚨 Anomalous Token Burn Rate Detected
Token consumption in the last 60 seconds: 1,840,000 tokens
Active sessions: 47
At this rate your hourly limit will be exhausted in: ~2 minutes
This may indicate a runaway loop, recursive spawn, or other error.
[K] Kill all sessions immediately
[P] Pause all sessions and review
[C] Continue — this is expected
Critical requirements:
Cross-session awareness. The monitor must aggregate across ALL active sessions under the account, not just the current process. A per-session monitor would have missed the incident described above.
Interrupt must be aggressive. This is not a statusline update. It is a full stop across all surfaces. Fail loudly.
"Kill all" must be one keypress. Do not require the user to hunt down and terminate 47 individual sessions.
The "Continue — this is expected" path must exist. Legitimate parallel workloads are real. The goal is confirmation, not unconditional blocking.
Configuration:
json{
"tokenWarnings": {
"burnRateWarningThreshold": 100000, // tokens/minute absolute
"burnRateWarningPercent": 0.10, // or % of hourly limit per minute
"disabled": false
}
}
Notes:
- Ballpark rate estimates are sufficient. The anomalies this targets are orders of magnitude above normal, not marginal differences.
- This is also a powerful bug detection tool beyond just cost protection. If expected burn rate is ~5k tokens/min and actual is 200k/min, something is wrong regardless of whether the user cares about cost.
- The post-operation token delta display (already implemented by some users via hooks) is complementary — it answers "what did that just cost?" This answers "what is this costing right now?"
Alternative Solutions
_No response_
Priority
High - Significant impact on productivity
Feature Category
Interactive mode (TUI)
Use Case Example
I think I've explained the use case more than sufficiently.
Preventing every Claude related Reddit from getting spammed by hundreds of "My Usage Limits..." messages DAILY and trashing Anthropic's reputation seems to me more than enough REASON TO IMPLEMENT, don't you think?
Additional Context
_No response_
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗