Feature Request: Add context usage percentage to hooks and enable automatic /compact execution
Summary
Request to add context usage monitoring capabilities to hooks, enabling automatic /compact execution when context usage reaches a threshold.
Problem
Currently, when working with Claude Code:
- No programmatic access to context usage - There's no API, environment variable, or hook input field that provides the current context usage percentage
- Cannot execute
/compactfrom hooks - Slash commands cannot be invoked from bash commands in hooks - No context-specific hook events - No
ContextWarningor similar event exists
This makes it impossible to automatically monitor and compress context before hitting the 95% auto-compact threshold, which often results in:
- Loss of important context from the beginning of the conversation (requirements, goals)
- Loss of recent progress information
- The "Conversation too long" error when trying to run
/compactmanually
Proposed Solution
Option 1: Add context usage to hook environment variables
# Available in hook scripts
$CONTEXT_USAGE_PERCENT # e.g., "78"
$CONTEXT_USAGE_TOKENS # e.g., "156000"
$CONTEXT_MAX_TOKENS # e.g., "200000"
Option 2: Add context usage to hook input JSON
{
"tool_name": "Bash",
"tool_input": {...},
"context_usage": {
"percent": 78,
"tokens_used": 156000,
"tokens_max": 200000
}
}
Option 3: Add a ContextWarning hook event
{
"hooks": {
"ContextWarning": [
{
"matcher": "threshold:75",
"hooks": [
{
"type": "command",
"command": "echo 'Context at 75%'"
}
]
}
]
}
}
Option 4: Enable /compact execution from hooks
Allow hooks to trigger slash commands like /compact with custom instructions:
{
"hooks": {
"PostToolUse": [
{
"hooks": [
{
"type": "slash-command",
"command": "/compact",
"args": "Preserve initial requirements and latest progress"
}
]
}
]
}
}
Use Case
As a user working on complex, multi-step tasks:
- I want to automatically monitor context usage
- When it reaches 75-80%, automatically run
/compactwith custom instructions - Preserve initial requirements (beginning of conversation) and recent progress (end of conversation)
- Avoid the "Conversation too long" error that prevents manual compaction
Current Workaround
Using a combination of:
PostToolUsehook with a bash script that estimates context from transcript file sizeStophook with a prompt that asks Claude to estimate context usage
This is imprecise and cannot actually execute /compact automatically.
Environment
- Claude Code version: latest
- OS: macOS
Additional Context
This would significantly improve the user experience for long-running sessions and complex tasks, especially when using parallel agents (Task tool) which consume context quickly.
This issue has 4 comments on GitHub. Read the full discussion on GitHub ↗