Expose context window token count to hooks and environment

Resolved 💬 3 comments Opened Apr 7, 2026 by williamsommers-hmq Closed Apr 7, 2026

Summary

Expose the current context window token usage as an environment variable (e.g., $CLAUDE_CONTEXT_TOKENS) available to hooks and cron prompts. This enables users to build context-aware workflows like auto-compaction at a threshold.

Motivation

With 1M token context windows, a common best practice is to compact or reset sessions at 30-50% usage rather than letting context grow to the limit. From the community:

"The alternative, and my preference, is to keep the 1M token limit, but manually pay attention to your context window and reset sessions at ~30-50% usage. You get most of the benefit of the increased context window while minimizing inference with 800K token contexts."

Today there's no way to automate this because:

  • Current token usage isn't exposed to any programmatic interface
  • Hooks can't read context size
  • Cron prompts can't read context size
  • Users must manually watch the context indicator and remember to compact

Proposed Behavior

Expose context metrics as environment variables available to hooks:

$CLAUDE_CONTEXT_TOKENS      # current tokens in context (e.g., 423000)
$CLAUDE_CONTEXT_MAX          # max context window size (e.g., 1000000)
$CLAUDE_CONTEXT_PERCENT      # convenience: usage as integer percent (e.g., 42)

Example: warn at 40% usage

// settings.json
{
  "hooks": {
    "PostToolCall": [{
      "command": "[ \"$CLAUDE_CONTEXT_PERCENT\" -gt 40 ] && echo 'Context at ${CLAUDE_CONTEXT_PERCENT}% — consider /compact'"
    }]
  }
}

Example: auto-compact at 50% (if #44789 is also implemented)

{
  "hooks": {
    "PostToolCall": [{
      "command": "[ \"$CLAUDE_CONTEXT_PERCENT\" -gt 50 ] && echo '/compact'"
    }]
  }
}

Alternatives Considered

  • Estimate tokens from tool call logs: Possible but inaccurate — misses conversation text, system prompts, and internal overhead. Rough estimate at best.
  • Periodic cron check: Adds context on each fire, and still can't read actual usage without this feature.
  • Status bar only: The context indicator exists in the UI but isn't programmatically accessible.

Related

  • #44789 — Auto-compact sessions after idle timeout (complementary feature)

Additional Context

This is a low-cost, high-leverage addition. The runtime already tracks token count for the status bar — exposing it to the hook environment is likely minimal implementation effort but unlocks a whole class of context-management workflows.

View original on GitHub ↗

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