Expose context window usage percentage to hooks

Resolved 💬 3 comments Opened Feb 23, 2026 by Streadz Closed Feb 27, 2026

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:

  1. PreCompact hooks — fire right before compaction but cannot block it, so by the time the user sees a warning, compaction has already happened
  2. Message counting (e.g. UserPromptSubmit with 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 UserPromptSubmit hook that warns at 70% and strongly recommends /clear at 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

  • PreCompact with decision: "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

View original on GitHub ↗

This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗