Expose context window usage to hooks via environment variable

Resolved 💬 6 comments Opened Mar 14, 2026 by nguyenhoanglong-tech Closed May 24, 2026

Problem

Hooks (PreToolUse, PostToolUse, Stop) have no way to know how much of the context window is consumed. The only context-related env vars available are CLAUDE_TOOL_NAME, CLAUDECODE, and CLAUDE_CODE_SSE_PORT — none expose token usage or context percentage.

Use Case

I run a PreToolUse hook (strategic-compact.sh) that warns the agent to run /compress and suggest starting a new conversation when context is getting full. Currently it approximates context usage by counting heavy tool calls (Read, Bash, WebFetch, WebSearch, Agent) and firing at a hardcoded threshold.

This breaks when the context window size changes. I recently got upgraded from 200K to 1M context (Opus 4.6) and my hook started firing at ~25% instead of ~60% because the threshold was calibrated for the old window size. I had to manually bump the counter from 40 to 200 — a crude guess.

Proposed Solution

Expose context window usage as environment variables available to all hook types:

# Absolute values
CLAUDE_CONTEXT_USED=268000        # tokens currently in context
CLAUDE_CONTEXT_MAX=1000000        # total context window size

# Convenience
CLAUDE_CONTEXT_PERCENT=27         # integer percentage (0-100)

This would allow hooks to make context-aware decisions:

# Fire compress warning at 60% regardless of window size
if (( CLAUDE_CONTEXT_PERCENT >= 60 )); then
  echo "Context at ${CLAUDE_CONTEXT_PERCENT}%. Run /compress and start a new conversation."
fi

Alternative: PreCompact Hook Event

A complementary solution would be a new hook event that fires when Claude Code is about to auto-compact the conversation:

{
  "PreCompact": [{
    "matcher": ".*",
    "hooks": [{
      "type": "command",
      "command": "bash ~/.claude/hooks/scripts/pre-compact-save.sh"
    }]
  }]
}

This would let users save full session state to external systems (vault, Obsidian, etc.) right before context is truncated — preventing information loss at compaction boundaries.

Current Workaround

Counting tool calls as a proxy for context consumption. This is:

  • Fragile — breaks when context window size changes
  • Imprecise — a Read of a 10-line file vs a 2000-line file consume very different amounts of context
  • Non-portable — threshold must be manually recalibrated per model/plan

Environment

  • Claude Code CLI (latest)
  • Model: Opus 4.6 (1M context)
  • macOS

View original on GitHub ↗

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