Expose context token count to hooks via environment variable
Resolved 💬 3 comments Opened Apr 13, 2026 by sacdizzle Closed Apr 17, 2026
Problem
Hooks (UserPromptSubmit, PreToolUse, etc.) have no way to know the current context window usage. This makes it impossible to build smart automation around context management — for example, triggering a manual /compact with custom instructions before auto-compaction fires.
Requested behavior
Expose the current context token usage as environment variables available to hooks:
CLAUDE_CONTEXT_USED_TOKENS— current token count in the context windowCLAUDE_CONTEXT_MAX_TOKENS— total available tokens for the current modelCLAUDE_CONTEXT_PERCENT— percentage used (convenience)
These should be set before each hook invocation so hooks can make informed decisions.
Use cases
- Preemptive compaction: A UserPromptSubmit hook could warn the user (or the model) when context is approaching the compaction threshold, giving time to run
/compactwith custom instructions - Session management: Long-running agent sessions could gracefully wrap up work before context runs out
- Cost monitoring: Hooks could track token consumption over time
- Adaptive behavior: Tools and workflows could adjust their verbosity based on remaining context
Current workaround
The only proxy available is checking the session's JSONL file size, which doesn't correlate well with actual context window usage (JSONL grows monotonically, context gets trimmed on compaction).
Environment
- Claude Code 2.1.101
- Heavy hook usage (UserPromptSubmit, PreToolUse, PreCompact, PostToolUse, SessionStart)
This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗