Expose context window usage percentage to hooks
Feature Request
Expose the current context window usage (as a percentage or token count) to hook scripts via an environment variable, e.g. $CLAUDE_CONTEXT_PERCENT or $CLAUDE_CONTEXT_TOKENS_USED / $CLAUDE_CONTEXT_TOKENS_MAX.
Motivation
There's currently no way for hooks to know how full the context window is. This makes it impossible to build reliable "save state before compaction" workflows. The only options today are:
PreCompacthooks — fire right before compaction but cannot block it, so by the time the user sees a warning, compaction has already happened- Message counting (e.g.
UserPromptSubmitwith a counter file) — a rough heuristic, but wildly inaccurate since a single turn with large file reads or agent launches can consume 10x more context than a simple question
Proposed Solution
Inject context usage into the hook environment for all hook events:
# Available in all hook scripts:
CLAUDE_CONTEXT_PERCENT=73 # 0-100
CLAUDE_CONTEXT_TOKENS_USED=148200
CLAUDE_CONTEXT_TOKENS_MAX=200000
This would enable:
- Proactive warnings — A
UserPromptSubmithook that warns at 70% and strongly recommends/clearat 85% - Auto-save triggers — Save working state at a configurable threshold, not just at the last moment before compaction
- Smarter agent decisions — Avoid launching expensive background agents when context is already tight
Context
The context percentage is already computed and displayed in the Claude Code UI (visible in the status bar). This request is just about piping that same value into the hook environment so scripts can act on it.
Alternatives Considered
PreCompactwithdecision: "block"— Not supported; PreCompact hooks are notification-only- Message counting — Too imprecise; doesn't account for variable message sizes
- Token counting via external tools — Would require duplicating the tokenizer and tracking all messages externally, which is fragile and expensive
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗