Automatic context window management for Claude Code sessions.
When your Claude Code session approaches the context limit, this tool automatically saves your progress (goals, tasks, file changes) and seamlessly restarts with a fresh session that continues from where you left off.
Claude Code has a 200k token context window. During long coding sessions, you can hit this limit, causing:
- Loss of conversation context
- Need to manually re-explain what you were working on
- Interrupted workflows
Context Monitor wraps Claude Code to:
- Track context window usage in real-time
- Save session state when approaching the threshold (default: 50%)
- Restart automatically with a new session
- Resume seamlessly with preserved context
┌─────────────────────────────────────────────────┐
│ Context Monitor Wrapper │
├─────────────────────────────────────────────────┤
│ TokenTracker StateManager SessionController
│ │ │ │ │
│ └───────────────┴────────────────┘ │
│ │ │
│ Claude Code SDK │
├─────────────────────────────────────────────────┤
│ .claude/session-state.json │
└─────────────────────────────────────────────────┘
- Node.js 18+
- Claude Code CLI installed (
npm install -g @anthropic-ai/claude-code) - Valid Anthropic API key configured
npm install -g claude-context-monitorgit clone https://github.com/younann/context-free.git
cd claude-context-monitor
npm install
npm run build
npm link# Run with context monitoring
context-monitor "Build a REST API with authentication"
# With custom threshold (60%)
context-monitor -t 60 "Refactor the database layer"
# Verbose mode
context-monitor -v "Debug the payment system"Add to your ~/.zshrc or ~/.bashrc:
# Claude Code Context Monitor
export CLAUDE_REAL_PATH="$(which claude)"
export CLAUDE_CONTEXT_THRESHOLD=50
alias claude="claude-monitored"Then reload your shell:
source ~/.zshrc # or ~/.bashrcNow use claude normally - monitoring is automatic!
| Variable | Default | Description |
|---|---|---|
CLAUDE_CONTEXT_THRESHOLD |
50 |
Restart threshold (% of context window) |
CLAUDE_CONTEXT_WARNING |
45 |
Warning threshold (% of context window) |
CLAUDE_CONTEXT_SIZE |
200000 |
Context window size in tokens |
CLAUDE_CONTEXT_MONITOR |
true |
Set to false to disable monitoring |
CLAUDE_REAL_PATH |
auto-detect | Path to real claude executable |
Usage: context-monitor [options] <prompt>
Options:
-t, --threshold <n> Context usage threshold percentage (default: 50)
-c, --context-size <n> Context window size in tokens (default: 200000)
-d, --cwd <path> Working directory for the session
--no-resume Don't resume from previous saved state
-v, --verbose Enable verbose output
-h, --help Show help message
--version Show version
When the context threshold is reached, the monitor saves:
{
"version": "1.0",
"savedAt": "2024-01-15T10:30:00Z",
"previousSessionId": "session-abc123",
"contextAtSave": {
"usedPercentage": 50.2,
"inputTokens": 100400
},
"currentGoal": "Implement user authentication",
"completedTasks": [
{ "id": "task-001", "subject": "Create user model", "status": "completed" }
],
"pendingTasks": [
{ "id": "task-002", "subject": "Implement login endpoint", "status": "pending" }
],
"fileChanges": [
{ "path": "src/models/User.ts", "action": "created" }
],
"resumeInstructions": "Continue implementing login endpoint..."
}When a new session starts, it receives a structured resume prompt:
## Resuming Previous Session
**Previous Session:** session-abc123
**Saved At:** 2024-01-15T10:30:00Z
### Current Goal
Implement user authentication
### Completed Tasks
- [x] Create user model
### Pending Tasks
- ⏳ Implement login endpoint
### File Changes Made
- ✨ src/models/User.ts (created)
### Resume Instructions
Continue implementing login endpoint...
---
Please continue from where we left off.If you prefer using Claude Code hooks (warnings only, no auto-restart):
- Copy the hook script:
cp hooks/context-monitor-hook.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/context-monitor-hook.sh- Add to
~/.claude/settings.json:
{
"hooks": {
"PostToolUse": [{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/context-monitor-hook.sh"
}]
}]
}
}Note: Hooks cannot restart sessions programmatically - they can only warn and save state.
import { SessionController, TokenTracker, StateManager } from 'claude-context-monitor';
const controller = new SessionController({
config: {
thresholdPercentage: 50,
contextWindowSize: 200000,
},
onThresholdReached: (percentage) => {
console.log(`Context at ${percentage}%, restarting...`);
},
onSessionRestart: (sessionNumber) => {
console.log(`Starting session #${sessionNumber}`);
},
});
await controller.runWithMonitoring("Build a todo app with React");| Feature | Wrapper | Hooks |
|---|---|---|
| Auto-restart at threshold | ✅ Yes | ❌ No |
| State preservation | ✅ Yes | ✅ Yes |
| Seamless resume | ✅ Automatic | |
| Interactive mode support | ✅ Full | |
| Zero config after install | ✅ Yes | ❌ No |
Ensure Claude Code CLI is installed:
npm install -g @anthropic-ai/claude-codeYour threshold may be too low. Increase it:
export CLAUDE_CONTEXT_THRESHOLD=60Check write permissions for .claude/ directory in your project.
Verify the monitor is active:
CLAUDE_CONTEXT_MONITOR=true context-monitor -v "test"Contributions are welcome! Please read our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Younan Nwesre - @younann
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with the Claude Agent SDK
- Inspired by the need for seamless long-running coding sessions
Created by Younan Nwesre