@echo off
:: Disconnect any existing mapping (stale or otherwise)
net use S: /delete /y 2>nul

:: Map with current session credentials (will prompt if needed)
net use S: \\SAGE-SQL\SAGE /persistent:no

if errorlevel 1 (
    echo Failed to connect to SAGE share. Please check your credentials.
    echo If you recently changed your password, log off and back on.
    pause
    exit /b 1
)

S:
cd "\sbt\ACCPAC Query"
sfquery.exe


The user has shared a Windows batch file with me. Let me analyze what this script does:

1. `@echo off` - Suppresses command echoing
2. `net use S: /delete /y 2>nul` - Disconnects any existing S: drive mapping, suppressing errors
3. `net use S: \\SAGE-SQL\SAGE /persistent:no` - Maps S: drive to a network share on SAGE-SQL server
4. Error handling - If the mapping fails, shows an error message and exits
5. `S:` - Switches to the S: drive
6. `cd "\sbt\ACCPAC Query"` - Changes to a specific directory
7. `sfquery.exe` - Runs an executable

This appears to be a script for connecting to a Sage accounting software network share and running a query tool.

The user hasn't asked me a specific question - they've just shared the script. I should ask what they'd like help with, or if they're showing me context for something.


This is a Windows batch script that:

1. **Disconnects** any existing S: drive mapping (silently ignoring errors)
2. **Maps S: drive** to `\\SAGE-SQL\SAGE` network share using current session credentials
3. **Checks for errors** - if the mapping fails, it displays a helpful message about credentials/password and exits
4. **Navigates** to `S:\sbt\ACCPAC Query`
5. **Launches** `sfquery.exe` (likely a Sage/ACCPAC query tool)

What would you like help with? For example:
- Troubleshooting connection issues
- Modifying the script behavior
- Adding logging or additional error handling
- Converting to PowerShell


In that batch, I'd prefer it check for access to S:  If S: exists, launch the app, if not, map the drive.


The user wants to modify the batch script to:
1. First check if S: drive already exists and is accessible
2. If it exists, just launch the app directly
3. If it doesn't exist, then map the drive and launch the app

This is a reasonable optimization to avoid unnecessary disconnect/reconnect cycles when the drive is already mapped correctly.

I can use `if exist S:\` to check if the drive is accessible, or use `net use S:` to check the status. The `if exist` approach is simpler and more direct for checking accessibility.


Here's the modified script:

```batch
@echo off
:: Check if S: is already accessible
if exist S:\sbt\ACCPAC Query\sfquery.exe goto launch

:: Not accessible - disconnect any stale mapping and remap
net use S: /delete /y 2>nul
net use S: \\SAGE-SQL\SAGE /persistent:no

if errorlevel 1 (
    echo Failed to connect to SAGE share. Please check your credentials.
    echo If you recently changed your password, log off and back on.
    pause
    exit /b 1
)

:launch
S:
cd "\sbt\ACCPAC Query"
sfquery.exe
```

**Changes:**
- Checks if the target executable is already accessible on S:
- If yes, skips straight to launching
- If no, performs the disconnect/reconnect as before

I checked for the actual executable rather than just `S:\` to ensure the share is properly mapped to the right location, not just that some S: drive exists.


Same changes to this one: @echo off
:: Disconnect any existing mapping (stale or otherwise)
net use S: /delete /y 2>nul

:: Map with current session credentials (will prompt if needed)
net use S: \\SAGE-SQL\SAGE /persistent:no

if errorlevel 1 (
    echo Failed to connect to SAGE share. Please check your credentials.
    echo If you recently changed your password, log off and back on.
    pause
    exit /b 1
)

S:
cd \sbt
sbtw.exe


The user wants me to apply the same changes to this similar batch script. This one launches sbtw.exe from \sbt instead of sfquery.exe from "\sbt\ACCPAC Query". I'll follow the same pattern.


```batch
@echo off
:: Check if S: is already accessible
if exist S:\sbt\sbtw.exe goto launch

:: Not accessible - disconnect any stale mapping and remap
net use S: /delete /y 2>nul
net use S: \\SAGE-SQL\SAGE /persistent:no

if errorlevel 1 (
    echo Failed to connect to SAGE share. Please check your credentials.
    echo If you recently changed your password, log off and back on.
    pause
    exit /b 1
)

:launch
S:
cd \sbt
sbtw.exe
```


Can we make eit so the cmd window closes after it launches the app?


The user wants the command window to close after launching the application. Currently the script runs the exe directly, which keeps the cmd window open until the app closes.

To launch the app and close the cmd window, I can use:
- `start "" sbtw.exe` - this launches the app in a separate process and allows the batch file to continue/exit
- Then the batch file ends and the window closes

The `start` command with empty quotes for the title is the standard approach.


```batch
@echo off
:: Check if S: is already accessible
if exist S:\sbt\sbtw.exe goto launch

:: Not accessible - disconnect any stale mapping and remap
net use S: /delete /y 2>nul
net use S: \\SAGE-SQL\SAGE /persistent:no

if errorlevel 1 (
    echo Failed to connect to SAGE share. Please check your credentials.
    echo If you recently changed your password, log off and back on.
    pause
    exit /b 1
)

:launch
S:
cd \sbt
start "" sbtw.exe
```

**Change:** Replaced `sbtw.exe` with `start "" sbtw.exe`

The `start` command launches the app in a separate process, allowing the batch script to finish and close the window immediately. The empty quotes `""` are for the window title (required when the path might contain spaces).


There's a special character before @ech off, should that be there?


The user is saying there's a special character before @echo off in what I provided. Let me look at what I wrote... I don't see any special character in my response, but they might be seeing something when they copy/paste it. This could be:

1. A BOM (Byte Order Mark) that got inserted
2. Some invisible Unicode character
3. A rendering issue on their end

I should acknowledge this and provide a clean version. The script should start with just `@echo off` with nothing before it.


No, there shouldn't be anything before `@echo off`. That might be a hidden character (like a BOM or invisible Unicode) that snuck in during copy/paste.

Here's a clean version:

```
@echo off
:: Check if S: is already accessible
if exist S:\sbt\sbtw.exe goto launch

:: Not accessible - disconnect any stale mapping and remap
net use S: /delete /y 2>nul
net use S: \\SAGE-SQL\SAGE /persistent:no

if errorlevel 1 (
    echo Failed to connect to SAGE share. Please check your credentials.
    echo If you recently changed your password, log off and back on.
    pause
    exit /b 1
)

:launch
S:
cd \sbt
start "" sbtw.exe
```

If you still see it after pasting, try opening the .bat file in Notepad, delete everything, and manually retype or paste fresh.


same changes to the first script


The user wants me to apply the same changes (adding start "" and ensuring no special characters) to the first script that launched sfquery.exe.


```
@echo off
:: Check if S: is already accessible
if exist S:\sbt\ACCPAC Query\sfquery.exe goto launch

:: Not accessible - disconnect any stale mapping and remap
net use S: /delete /y 2>nul
net use S: \\SAGE-SQL\SAGE /persistent:no

if errorlevel 1 (
    echo Failed to connect to SAGE share. Please check your credentials.
    echo If you recently changed your password, log off and back on.
    pause
    exit /b 1
)

:launch
S:
cd "\sbt\ACCPAC Query"
start "" sfquery.exe
```


How do I use this? D:\Users\MikeSwanson\Downloads\Claude-Code-Usage-Monitor-main


The user is asking how to use something they downloaded called "Claude-Code-Usage-Monitor-main". This appears to be a GitHub repo they downloaded to their Downloads folder. I should explore this directory to understand what it is and how to use it.


Let me take a look at what's in that folder.


This is a Python project with a README.md. Let me read the README to understand what this tool does and how to use it.


     1→# 🎯 Claude Code Usage Monitor
     2→[![PyPI Version](https://img.shields.io/pypi/v/claude-monitor.svg)](https://pypi.org/project/claude-monitor/)
     3→[![Python Version](https://img.shields.io/badge/python-3.9+-blue.svg)](https://python.org)
     4→[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
     5→[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com)
     6→[![codecov](https://codecov.io/gh/Maciek-roboblog/Claude-Code-Usage-Monitor/branch/main/graph/badge.svg)](https://codecov.io/gh/Maciek-roboblog/Claude-Code-Usage-Monitor)
     7→
     8→A beautiful real-time terminal monitoring tool for Claude AI token usage with advanced analytics, machine learning-based predictions, and Rich UI. Track your token consumption, burn rate, cost analysis, and get intelligent predictions about session limits.
     9→
    10→![Claude Token Monitor Screenshot](https://raw.githubusercontent.com/Maciek-roboblog/Claude-Code-Usage-Monitor/main/doc/scnew.png)
    11→
    12→---
    13→
    14→## 📑 Table of Contents
    15→
    16→- [✨ Key Features](#-key-features)
    17→- [🚀 Installation](#-installation)
    18→  - [⚡ Modern Installation with uv (Recommended)](#-modern-installation-with-uv-recommended)
    19→  - [📦 Installation with pip](#-installation-with-pip)
    20→  - [🛠 Other Package Managers](#-other-package-managers)
    21→- [📖 Usage](#-usage)
    22→  - [Get Help](#get-help)
    23→  - [Basic Usage](#basic-usage)
    24→  - [Configuration Options](#configuration-options)
    25→  - [Available Plans](#available-plans)
    26→- [🙏 Please Help Test This Release!](#-please-help-test-this-release)
    27→- [✨ Features & How It Works](#-features--how-it-works)
    28→  - [Current Features](#current-features)
    29→  - [Understanding Claude Sessions](#understanding-claude-sessions)
    30→  - [Token Limits by Plan](#token-limits-by-plan)
    31→  - [Smart Detection Features](#smart-detection-features)
    32→- [🚀 Usage Examples](#-usage-examples)
    33→  - [Common Scenarios](#common-scenarios)
    34→  - [Best Practices](#best-practices)
    35→- [🔧 Development Installation](#-development-installation)
    36→- [Troubleshooting](#troubleshooting)
    37→  - [Installation Issues](#installation-issues)
    38→  - [Runtime Issues](#runtime-issues)
    39→- [📞 Contact](#-contact)
    40→- [📚 Additional Documentation](#-additional-documentation)
    41→- [📝 License](#-license)
    42→- [🤝 Contributors](#-contributors)
    43→- [🙏 Acknowledgments](#-acknowledgments)
    44→
    45→
    46→
    47→## ✨ Key Features
    48→
    49→### 🚀 **v3.0.0 Major Update - Complete Architecture Rewrite**
    50→
    51→- **🔮 ML-based predictions** - P90 percentile calculations and intelligent session limit detection
    52→- **🔄 Real-time monitoring** - Configurable refresh rates (0.1-20 Hz) with intelligent display updates
    53→- **📊 Advanced Rich UI** - Beautiful color-coded progress bars, tables, and layouts with WCAG-compliant contrast
    54→- **🤖 Smart auto-detection** - Automatic plan switching with custom limit discovery
    55→- **📋 Enhanced plan support** - Updated limits: Pro (44k), Max5 (88k), Max20 (220k), Custom (P90-based)
    56→- **⚠ Advanced warning system** - Multi-level alerts with cost and time predictions
    57→- **💼 Professional Architecture** - Modular design with Single Responsibility Principle (SRP) compliance
    58→- **🎨 Intelligent theming** - Scientific color schemes with automatic terminal background detection
    59→- **⏰ Advanced scheduling** - Auto-detected system timezone and time format preferences
    60→- **📈 Cost analytics** - Model-specific pricing with cache token calculations
    61→- **🔧 Pydantic validation** - Type-safe configuration with automatic validation
    62→- **📝 Comprehensive logging** - Optional file logging with configurable levels
    63→- **🧪 Extensive testing** - 100+ test cases with full coverage
    64→- **🎯 Error reporting** - Optional Sentry integration for production monitoring
    65→- **⚡ Performance optimized** - Advanced caching and efficient data processing
    66→
    67→### 📋 Default Custom Plan
    68→
    69→The **Custom plan** is now the default option, specifically designed for 5-hour Claude Code sessions. It monitors three critical metrics:
    70→- **Token usage** - Tracks your token consumption
    71→- **Messages usage** - Monitors message count
    72→- **Cost usage** - The most important metric for long sessions
    73→
    74→The Custom plan automatically adapts to your usage patterns by analyzing all your sessions from the last 192 hours (8 days) and calculating personalized limits based on your actual usage. This ensures accurate predictions and warnings tailored to your specific workflow.
    75→
    76→
    77→## 🚀 Installation
    78→### ⚡ Modern Installation with uv (Recommended)
    79→
    80→**Why uv is the best choice:**
    81→- ✅ Creates isolated environments automatically (no system conflicts)
    82→- ✅ No Python version issues
    83→- ✅ No "externally-managed-environment" errors
    84→- ✅ Easy updates and uninstallation
    85→- ✅ Works on all platforms
    86→
    87→The fastest and easiest way to install and use the monitor:
    88→
    89→[![PyPI](https://img.shields.io/pypi/v/claude-monitor.svg)](https://pypi.org/project/claude-monitor/)
    90→
    91→#### Install from PyPI
    92→
    93→```bash
    94→# Install directly from PyPI with uv (easiest)
    95→uv tool install claude-monitor
    96→
    97→# Run from anywhere
    98→claude-monitor  # or cmonitor, ccmonitor for short
    99→```
   100→
   101→
   102→#### Install from Source
   103→
   104→```bash
   105→# Clone and install from source
   106→git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git
   107→cd Claude-Code-Usage-Monitor
   108→uv tool install .
   109→
   110→# Run from anywhere
   111→claude-monitor
   112→```
   113→
   114→
   115→#### First-time uv users
   116→If you don't have uv installed yet, get it with one command:
   117→
   118→```bash
   119→# On Linux/macOS:
   120→curl -LsSf https://astral.sh/uv/install.sh | sh
   121→
   122→# On Windows:
   123→powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
   124→
   125→# After installation, restart your terminal
   126→```
   127→
   128→
   129→### 📦 Installation with pip
   130→
   131→```bash
   132→# Install from PyPI
   133→pip install claude-monitor
   134→
   135→# If claude-monitor command is not found, add ~/.local/bin to PATH:
   136→echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
   137→source ~/.bashrc  # or restart your terminal
   138→
   139→# Run from anywhere
   140→claude-monitor  # or cmonitor, ccmonitor for short
   141→```
   142→
   143→
   144→>
   145→> **⚠ PATH Setup**: If you see WARNING: The script claude-monitor is installed in '/home/username/.local/bin' which is not on PATH, follow the export PATH command above.
   146→>
   147→> **⚠ Important**: On modern Linux distributions (Ubuntu 23.04+, Debian 12+, Fedora 38+), you may encounter an "externally-managed-environment" error. Instead of using --break-system-packages, we strongly recommend:
   148→> 1. **Use uv instead** (see above) - it's safer and easier
   149→> 2. **Use a virtual environment** - python3 -m venv myenv && source myenv/bin/activate
   150→> 3. **Use pipx** - pipx install claude-monitor
   151→>
   152→> See the Troubleshooting section for detailed solutions.
   153→
   154→### 🛠 Other Package Managers
   155→
   156→#### pipx (Isolated Environments)
   157→```bash
   158→# Install with pipx
   159→pipx install claude-monitor
   160→
   161→# Run from anywhere
   162→claude-monitor  # or claude-code-monitor, cmonitor, ccmonitor, ccm for short
   163→```
   164→
   165→
   166→#### conda/mamba
   167→```bash
   168→# Install with pip in conda environment
   169→pip install claude-monitor
   170→
   171→# Run from anywhere
   172→claude-monitor  # or cmonitor, ccmonitor for short
   173→```
   174→
   175→
   176→## 📖 Usage
   177→
   178→### Get Help
   179→
   180→```bash
   181→# Show help information
   182→claude-monitor --help
   183→```
   184→
   185→#### Available Command-Line Parameters
   186→
   187→| Parameter | Type | Default | Description |
   188→|-----------|------|---------|-------------|
   189→| --plan | string | custom | Plan type: pro, max5, max20, or custom |
   190→| --custom-limit-tokens | int | None | Token limit for custom plan (must be > 0) |
   191→| --view | string | realtime | View type: realtime, daily, or monthly |
   192→| --timezone | string | auto | Timezone (auto-detected). Examples: UTC, America/New_York, Europe/London |
   193→| --time-format | string | auto | Time format: 12h, 24h, or auto |
   194→| --theme | string | auto | Display theme: light, dark, classic, or auto |
   195→| --refresh-rate | int | 10 | Data refresh rate in seconds (1-60) |
   196→| --refresh-per-second | float | 0.75 | Display refresh rate in Hz (0.1-20.0) |
   197→| --reset-hour | int | None | Daily reset hour (0-23) |
   198→| --log-level | string | INFO | Logging level: DEBUG, INFO, WARNING, ERROR, CRITICAL |
   199→| --log-file | path | None | Log file path |
   200→| --debug | flag | False | Enable debug logging |
   201→| --version, -v | flag | False | Show version information |
   202→| --clear | flag | False | Clear saved configuration |
   203→
   204→#### Plan Options
   205→
   206→| Plan | Token Limit | Cost Limit       | Description |
   207→|------|-------------|------------------|-------------|
   208→| pro | 19,000 | $18.00           | Claude Pro subscription |
   209→| max5 | 88,000 | $35.00           | Claude Max5 subscription |
   210→| max20 | 220,000 | $140.00          | Claude Max20 subscription |
   211→| custom | P90-based | (default) $50.00 | Auto-detection with ML analysis |
   212→
   213→#### Command Aliases
   214→
   215→The tool can be invoked using any of these commands:
   216→- claude-monitor (primary)
   217→- claude-code-monitor (full name)
   218→- cmonitor (short)
   219→- ccmonitor (short alternative)
   220→- ccm (shortest)
   221→
   222→#### Save Flags Feature
   223→
   224→The monitor automatically saves your preferences to avoid re-specifying them on each run:
   225→
   226→**What Gets Saved:**
   227→- View type (--view)
   228→- Theme preferences (--theme)
   229→- Timezone settings (--timezone)
   230→- Time format (--time-format)
   231→- Refresh rates (--refresh-rate, --refresh-per-second)
   232→- Reset hour (--reset-hour)
   233→- Custom token limits (--custom-limit-tokens)
   234→
   235→**Configuration Location:** ~/.claude-monitor/last_used.json
   236→
   237→**Usage Examples:**
   238→```bash
   239→# First run - specify preferences
   240→claude-monitor --plan pro --theme dark --timezone "America/New_York"
   241→
   242→# Subsequent runs - preferences automatically restored
   243→claude-monitor --plan pro
   244→
   245→# Override saved settings for this session
   246→claude-monitor --plan pro --theme light
   247→
   248→# Clear all saved preferences
   249→claude-monitor --clear
   250→```
   251→
   252→**Key Features:**
   253→- ✅ Automatic parameter persistence between sessions
   254→- ✅ CLI arguments always override saved settings
   255→- ✅ Atomic file operations prevent corruption
   256→- ✅ Graceful fallback if config files are damaged
   257→- ✅ Plan parameter never saved (must specify each time)
   258→
   259→### Basic Usage
   260→
   261→#### With uv tool installation (Recommended)
   262→```bash
   263→# Default (Custom plan with auto-detection)
   264→claude-monitor
   265→
   266→# Alternative commands
   267→claude-code-monitor  # Full descriptive name
   268→cmonitor             # Short alias
   269→ccmonitor            # Short alternative
   270→ccm                  # Shortest alias
   271→
   272→# Exit the monitor
   273→# Press Ctrl+C to gracefully exit
   274→```
   275→
   276→#### Development mode
   277→If running from source, use python -m claude_monitor from the src/ directory.
   278→
   279→### Configuration Options
   280→
   281→#### Specify Your Plan
   282→
   283→```bash
   284→# Custom plan with P90 auto-detection (Default)
   285→claude-monitor --plan custom
   286→
   287→# Pro plan (~44,000 tokens)
   288→claude-monitor --plan pro
   289→
   290→# Max5 plan (~88,000 tokens)
   291→claude-monitor --plan max5
   292→
   293→# Max20 plan (~220,000 tokens)
   294→claude-monitor --plan max20
   295→
   296→# Custom plan with explicit token limit
   297→claude-monitor --plan custom --custom-limit-tokens 100000
   298→```
   299→
   300→#### Custom Reset Times
   301→
   302→```bash
   303→# Reset at 3 AM
   304→claude-monitor --reset-hour 3
   305→
   306→# Reset at 10 PM
   307→claude-monitor --reset-hour 22
   308→```
   309→
   310→#### Usage View Configuration
   311→
   312→```bash
   313→# Real-time monitoring with live updates (Default)
   314→claude-monitor --view realtime
   315→
   316→# Daily token usage aggregated in table format
   317→claude-monitor --view daily
   318→
   319→# Monthly token usage aggregated in table format
   320→claude-monitor --view monthly
   321→
   322→```
   323→
   324→#### Performance and Display Configuration
   325→
   326→```bash
   327→# Adjust refresh rate (1-60 seconds, default: 10)
   328→claude-monitor --refresh-rate 5
   329→
   330→# Adjust display refresh rate (0.1-20 Hz, default: 0.75)
   331→claude-monitor --refresh-per-second 1.0
   332→
   333→# Set time format (auto-detected by default)
   334→claude-monitor --time-format 24h  # or 12h
   335→
   336→# Force specific theme
   337→claude-monitor --theme dark  # light, dark, classic, auto
   338→
   339→# Clear saved configuration
   340→claude-monitor --clear
   341→```
   342→
   343→#### Timezone Configuration
   344→
   345→The default timezone is **auto-detected from your system**. Override with any valid timezone:
   346→
   347→```bash
   348→# Use US Eastern Time
   349→claude-monitor --timezone America/New_York
   350→
   351→# Use Tokyo time
   352→claude-monitor --timezone Asia/Tokyo
   353→
   354→# Use UTC
   355→claude-monitor --timezone UTC
   356→
   357→# Use London time
   358→claude-monitor --timezone Europe/London
   359→```
   360→
   361→#### Logging and Debugging
   362→
   363→```bash
   364→# Enable debug logging
   365→claude-monitor --debug
   366→
   367→# Log to file
   368→claude-monitor --log-file ~/.claude-monitor/logs/monitor.log
   369→
   370→# Set log level
   371→claude-monitor --log-level WARNING  # DEBUG, INFO, WARNING, ERROR, CRITICAL
   372→```
   373→
   374→### Available Plans
   375→
   376→| Plan | Token Limit     | Best For |
   377→|------|-----------------|----------|
   378→| **custom** | P90 auto-detect | Intelligent limit detection (default) |
   379→| **pro** | ~19,000         | Claude Pro subscription |
   380→| **max5** | ~88,000         | Claude Max5 subscription |
   381→| **max20** | ~220,000        | Claude Max20 subscription |
   382→
   383→#### Advanced Plan Features
   384→
   385→- **P90 Analysis**: Custom plan uses 90th percentile calculations from your usage history
   386→- **Cost Tracking**: Model-specific pricing with cache token calculations
   387→- **Limit Detection**: Intelligent threshold detection with 95% confidence
   388→
   389→
   390→## 🚀 What's New in v3.0.0
   391→
   392→### Major Changes
   393→
   394→#### **Complete Architecture Rewrite**
   395→- Modular design with Single Responsibility Principle (SRP) compliance
   396→- Pydantic-based configuration with type safety and validation
   397→- Advanced error handling with optional Sentry integration
   398→- Comprehensive test suite with 100+ test cases
   399→
   400→#### **Enhanced Functionality**
   401→- **P90 Analysis**: Machine learning-based limit detection using 90th percentile calculations
   402→- **Updated Plan Limits**: Pro (44k), Max5 (88k), Max20 (220k) tokens
   403→- **Cost Analytics**: Model-specific pricing with cache token calculations
   404→- **Rich UI**: WCAG-compliant themes with automatic terminal background detection
   405→
   406→#### **New CLI Options**
   407→- --refresh-per-second: Configurable display refresh rate (0.1-20 Hz)
   408→- --time-format: Automatic 12h/24h format detection
   409→- --custom-limit-tokens: Explicit token limits for custom plans
   410→- --log-file and --log-level: Advanced logging capabilities
   411→- --clear: Reset saved configuration
   412→- Command aliases: claude-code-monitor, cmonitor, ccmonitor, ccm for convenience
   413→
   414→#### **Breaking Changes**
   415→- Package name changed from claude-usage-monitor to claude-monitor
   416→- Default plan changed from pro to custom (with auto-detection)
   417→- Minimum Python version increased to 3.9+
   418→- Command structure updated (see examples above)
   419→
   420→
   421→## ✨ Features & How It Works
   422→
   423→### v3.0.0 Architecture Overview
   424→
   425→The new version features a complete rewrite with modular architecture following Single Responsibility Principle (SRP):
   426→
   427→### 🖥 User Interface Layer
   428→
   429→| Component            | Description           |
   430→| -------------------- | --------------------- |
   431→| **CLI Module**       | Pydantic-based        |
   432→| **Settings/Config**  | Type-safe             |
   433→| **Error Handling**   | Sentry-ready          |
   434→| **Rich Terminal UI** | Adaptive Theme        |
   435→
   436→---
   437→
   438→### 🎛 Monitoring Orchestrator
   439→
   440→| Component                | Key Responsibilities                                             |
   441→| ------------------------ | ---------------------------------------------------------------- |
   442→| **Central Control Hub**  | Session Mgmt · Real-time Data Flow · Component Coordination      |
   443→| **Data Manager**         | Cache Mgmt · File I/O · State Persist                           |
   444→| **Session Monitor**      | Real-time · 5 hr Windows · Token Track                           |
   445→| **UI Controller**        | Rich Display · Progress Bars · Theme System                     |
   446→| **Analytics**            | P90 Calculator · Burn Rate · Predictions                        |
   447→
   448→---
   449→
   450→### 🏗 Foundation Layer
   451→
   452→| Component           | Core Features                                           |
   453→| ------------------- | ------------------------------------------------------- |
   454→| **Core Models**     | Session Data · Config Schema · Type Safety             |
   455→| **Analysis Engine** | ML Algorithms · Statistical · Forecasting              |
   456→| **Terminal Themes** | Auto-detection · WCAG Colors · Contrast Opt            |
   457→| **Claude API Data** | Token Tracking · Cost Calculator · Session Blocks      |
   458→
   459→---
   460→
   461→**🔄 Data Flow:**
   462→Claude Config Files → Data Layer → Analysis Engine → UI Components → Terminal Display
   463→
   464→
   465→### Current Features
   466→
   467→#### 🔄 Advanced Real-time Monitoring
   468→- Configurable update intervals (1-60 seconds)
   469→- High-precision display refresh (0.1-20 Hz)
   470→- Intelligent change detection to minimize CPU usage
   471→- Multi-threaded orchestration with callback system
   472→
   473→#### 📊 Rich UI Components
   474→- **Progress Bars**: WCAG-compliant color schemes with scientific contrast ratios
   475→- **Data Tables**: Sortable columns with model-specific statistics
   476→- **Layout Manager**: Responsive design that adapts to terminal size
   477→- **Theme System**: Auto-detects terminal background for optimal readability
   478→
   479→#### 📈 Multiple Usage Views
   480→- **Realtime View** (Default): Live monitoring with progress bars, current session data, and burn rate analysis
   481→- **Daily View**: Aggregated daily statistics showing Date, Models, Input/Output/Cache tokens, Total tokens, and Cost
   482→- **Monthly View**: Monthly aggregated data for long-term trend analysis and budget planning
   483→
   484→#### 🔮 Machine Learning Predictions
   485→- **P90 Calculator**: 90th percentile analysis for intelligent limit detection
   486→- **Burn Rate Analytics**: Multi-session consumption pattern analysis
   487→- **Cost Projections**: Model-specific pricing with cache token calculations
   488→- **Session Forecasting**: Predicts when sessions will expire based on usage patterns
   489→
   490→#### 🤖 Intelligent Auto-Detection
   491→- **Background Detection**: Automatically determines terminal theme (light/dark)
   492→- **System Integration**: Auto-detects timezone and time format preferences
   493→- **Plan Recognition**: Analyzes usage patterns to suggest optimal plans
   494→- **Limit Discovery**: Scans historical data to find actual token limits
   495→
   496→### Understanding Claude Sessions
   497→
   498→#### How Claude Code Sessions Work
   499→
   500→Claude Code operates on a **5-hour rolling session window system**:
   501→
   502→1. **Session Start**: Begins with your first message to Claude
   503→2. **Session Duration**: Lasts exactly 5 hours from that first message
   504→3. **Token Limits**: Apply within each 5-hour session window
   505→4. **Multiple Sessions**: Can have several active sessions simultaneously
   506→5. **Rolling Windows**: New sessions can start while others are still active
   507→
   508→#### Session Reset Schedule
   509→
   510→**Example Session Timeline:**
   511→10:30 AM - First message (Session A starts at 10 AM)
   512→03:00 PM - Session A expires (5 hours later)
   513→
   514→12:15 PM - First message (Session B starts 12PM)
   515→05:15 PM - Session B expires (5 hours later 5PM)
   516→
   517→
   518→#### Burn Rate Calculation
   519→
   520→The monitor calculates burn rate using sophisticated analysis:
   521→
   522→1. **Data Collection**: Gathers token usage from all sessions in the last hour
   523→2. **Pattern Analysis**: Identifies consumption trends across overlapping sessions
   524→3. **Velocity Tracking**: Calculates tokens consumed per minute
   525→4. **Prediction Engine**: Estimates when current session tokens will deplete
   526→5. **Real-time Updates**: Adjusts predictions as usage patterns change
   527→
   528→### Token Limits by Plan
   529→
   530→#### v3.0.0 Updated Plan Limits
   531→
   532→| Plan | Limit (Tokens) | Cost Limit       | Messages | Algorithm |
   533→|------|----------------|------------------|----------|-----------|
   534→| **Claude Pro** | 19,000         | $18.00           | 250 | Fixed limit |
   535→| **Claude Max5** | 88,000         | $35.00           | 1,000 | Fixed limit |
   536→| **Claude Max20** | 220,000        | $140.00          | 2,000 | Fixed limit |
   537→| **Custom** | P90-based      | (default) $50.00 | 250+ | Machine learning |
   538→
   539→#### Advanced Limit Detection
   540→
   541→- **P90 Analysis**: Uses 90th percentile of your historical usage
   542→- **Confidence Threshold**: 95% accuracy in limit detection
   543→- **Cache Support**: Includes cache creation and read token costs
   544→- **Model-Specific**: Adapts to Claude 3.5, Claude 4, and future models
   545→
   546→### Technical Requirements
   547→
   548→#### Dependencies (v3.0.0)
   549→
   550→```toml
   551→# Core dependencies (automatically installed)
   552→pytz>=2023.3                # Timezone handling
   553→rich>=13.7.0                # Rich terminal UI
   554→pydantic>=2.0.0             # Type validation
   555→pydantic-settings>=2.0.0    # Configuration management
   556→numpy>=1.21.0               # Statistical calculations
   557→sentry-sdk>=1.40.0          # Error reporting (optional)
   558→pyyaml>=6.0                 # Configuration files
   559→tzdata                      # Windows timezone data
   560→```
   561→
   562→#### Python Requirements
   563→
   564→- **Minimum**: Python 3.9+
   565→- **Recommended**: Python 3.11+
   566→- **Tested on**: Python 3.9, 3.10, 3.11, 3.12, 3.13
   567→
   568→### Smart Detection Features
   569→
   570→#### Automatic Plan Switching
   571→
   572→When using the default Pro plan:
   573→
   574→1. **Detection**: Monitor notices token usage exceeding 7,000
   575→2. **Analysis**: Scans previous sessions for actual limits
   576→3. **Switch**: Automatically changes to custom_max mode
   577→4. **Notification**: Displays clear message about the change
   578→5. **Continuation**: Keeps monitoring with new, higher limit
   579→
   580→#### Limit Discovery Process
   581→
   582→The auto-detection system:
   583→
   584→1. **Scans History**: Examines all available session blocks
   585→2. **Finds Peaks**: Identifies highest token usage achieved
   586→3. **Validates Data**: Ensures data quality and recency
   587→4. **Sets Limits**: Uses discovered maximum as new limit
   588→5. **Learns Patterns**: Adapts to your actual usage capabilities
   589→
   590→
   591→## 🚀 Usage Examples
   592→
   593→### Common Scenarios
   594→
   595→#### 🌅 Morning Developer
   596→**Scenario**: You start work at 9 AM and want tokens to reset aligned with your schedule.
   597→
   598→```bash
   599→# Set custom reset time to 9 AM
   600→./claude_monitor.py --reset-hour 9
   601→
   602→# With your timezone
   603→./claude_monitor.py --reset-hour 9 --timezone US/Eastern
   604→```
   605→
   606→
   607→**Benefits**:
   608→- Reset times align with your work schedule
   609→- Better planning for daily token allocation
   610→- Predictable session windows
   611→
   612→#### 🌙 Night Owl Coder
   613→**Scenario**: You often work past midnight and need flexible reset scheduling.
   614→
   615→```bash
   616→# Reset at midnight for clean daily boundaries
   617→./claude_monitor.py --reset-hour 0
   618→
   619→# Late evening reset (11 PM)
   620→./claude_monitor.py --reset-hour 23
   621→```
   622→
   623→
   624→**Strategy**:
   625→- Plan heavy coding sessions around reset times
   626→- Use late resets to span midnight work sessions
   627→- Monitor burn rate during peak hours
   628→
   629→#### 🔄 Heavy User with Variable Limits
   630→**Scenario**: Your token limits seem to change, and you're not sure of your exact plan.
   631→
   632→```bash
   633→# Auto-detect your highest previous usage
   634→claude-monitor --plan custom_max
   635→
   636→# Monitor with custom scheduling
   637→claude-monitor --plan custom_max --reset-hour 6
   638→```
   639→
   640→
   641→**Approach**:
   642→- Let auto-detection find your real limits
   643→- Monitor for a week to understand patterns
   644→- Note when limits change or reset
   645→
   646→#### 🌍 International User
   647→**Scenario**: You're working across different timezones or traveling.
   648→
   649→```bash
   650→# US East Coast
   651→claude-monitor --timezone America/New_York
   652→
   653→# Europe
   654→claude-monitor --timezone Europe/London
   655→
   656→# Asia Pacific
   657→claude-monitor --timezone Asia/Singapore
   658→
   659→# UTC for international team coordination
   660→claude-monitor --timezone UTC --reset-hour 12
   661→```
   662→
   663→
   664→#### ⚡ Quick Check
   665→**Scenario**: You just want to see current status without configuration.
   666→
   667→```bash
   668→# Just run it with defaults
   669→claude-monitor
   670→
   671→# Press Ctrl+C after checking status
   672→```
   673→
   674→#### 📊 Usage Analysis Views
   675→**Scenario**: Analyzing your token usage patterns over different time periods.
   676→
   677→```bash
   678→# View daily usage breakdown with detailed statistics
   679→claude-monitor --view daily
   680→
   681→# Analyze monthly token consumption trends
   682→claude-monitor --view monthly --plan max20
   683→
   684→# Export daily usage data to log file for analysis
   685→claude-monitor --view daily --log-file ~/daily-usage.log
   686→
   687→# Review usage in different timezone
   688→claude-monitor --view daily --timezone America/New_York
   689→```
   690→
   691→**Use Cases**:
   692→- **Realtime**: Live monitoring of current session and burn rate
   693→- **Daily**: Analyze daily consumption patterns and identify peak usage days
   694→- **Monthly**: Long-term trend analysis and monthly budget planning
   695→
   696→
   697→### Plan Selection Strategies
   698→
   699→#### How to Choose Your Plan
   700→
   701→**Start with Default (Recommended for New Users)**
   702→```bash
   703→# Pro plan detection with auto-switching
   704→claude-monitor
   705→```
   706→
   707→- Monitor will detect if you exceed Pro limits
   708→- Automatically switches to custom_max if needed
   709→- Shows notification when switching occurs
   710→
   711→**Known Subscription Users**
   712→```bash
   713→# If you know you have Max5
   714→claude-monitor --plan max5
   715→
   716→# If you know you have Max20
   717→claude-monitor --plan max20
   718→```
   719→
   720→
   721→**Unknown Limits**
   722→```bash
   723→# Auto-detect from previous usage
   724→claude-monitor --plan custom_max
   725→```
   726→
   727→
   728→### Best Practices
   729→
   730→#### Setup Best Practices
   731→
   732→1. **Start Early in Sessions**
   733→
   734→```bash
   735→   # Begin monitoring when starting Claude work (uv installation)
   736→   claude-monitor
   737→
   738→   # Or development mode
   739→   ./claude_monitor.py
   740→   ```
   741→
   742→   - Gives accurate session tracking from the start
   743→   - Better burn rate calculations
   744→   - Early warning for limit approaches
   745→
   746→2. **Use Modern Installation (Recommended)**
   747→
   748→```bash
   749→   # Easy installation and updates with uv
   750→   uv tool install claude-monitor
   751→   claude-monitor --plan max5
   752→   ```
   753→
   754→   - Clean system installation
   755→   - Easy updates and maintenance
   756→   - Available from anywhere
   757→
   758→3. **Custom Shell Alias (Legacy Setup)**
   759→
   760→```bash
   761→   # Add to ~/.bashrc or ~/.zshrc (only for development setup)
   762→   alias claude-monitor='cd ~/Claude-Code-Usage-Monitor && source venv/bin/activate && ./claude_monitor.py'
   763→   ```
   764→
   765→
   766→#### Usage Best Practices
   767→
   768→1. **Monitor Burn Rate Velocity**
   769→   - Watch for sudden spikes in token consumption
   770→   - Adjust coding intensity based on remaining time
   771→   - Plan big refactors around session resets
   772→
   773→2. **Strategic Session Planning**
   774→
   775→```bash
   776→   # Plan heavy usage around reset times
   777→   claude-monitor --reset-hour 9
   778→   ```
   779→
   780→   - Schedule large tasks after resets
   781→   - Use lighter tasks when approaching limits
   782→   - Leverage multiple overlapping sessions
   783→
   784→3. **Timezone Awareness**
   785→
   786→```bash
   787→   # Always use your actual timezone
   788→   claude-monitor --timezone Europe/Warsaw
   789→   ```
   790→
   791→   - Accurate reset time predictions
   792→   - Better planning for work schedules
   793→   - Correct session expiration estimates
   794→
   795→#### Optimization Tips
   796→
   797→1. **Terminal Setup**
   798→   - Use terminals with at least 80 character width
   799→   - Enable color support for better visual feedback (check COLORTERM environment variable)
   800→   - Consider dedicated terminal window for monitoring
   801→   - Use terminals with truecolor support for best theme experience
   802→
   803→2. **Workflow Integration**
   804→
   805→```bash
   806→   # Start monitoring with your development session (uv installation)
   807→   tmux new-session -d -s claude-monitor 'claude-monitor'
   808→
   809→   # Or development mode
   810→   tmux new-session -d -s claude-monitor './claude_monitor.py'
   811→
   812→   # Check status anytime
   813→   tmux attach -t claude-monitor
   814→   ```
   815→
   816→
   817→3. **Multi-Session Strategy**
   818→   - Remember sessions last exactly 5 hours
   819→   - You can have multiple overlapping sessions
   820→   - Plan work across session boundaries
   821→
   822→#### Real-World Workflows
   823→
   824→**Large Project Development**
   825→```bash
   826→# Setup for sustained development
   827→claude-monitor --plan max20 --reset-hour 8 --timezone America/New_York
   828→```
   829→
   830→
   831→**Daily Routine**:
   832→1. **8:00 AM**: Fresh tokens, start major features
   833→2. **10:00 AM**: Check burn rate, adjust intensity
   834→3. **12:00 PM**: Monitor for afternoon session planning
   835→4. **2:00 PM**: New session window, tackle complex problems
   836→5. **4:00 PM**: Light tasks, prepare for evening session
   837→
   838→**Learning & Experimentation**
   839→```bash
   840→# Flexible setup for learning
   841→claude-monitor --plan pro
   842→```
   843→
   844→
   845→**Sprint Development**
   846→```bash
   847→# High-intensity development setup
   848→claude-monitor --plan max20 --reset-hour 6
   849→```
   850→
   851→
   852→## 🔧 Development Installation
   853→
   854→For contributors and developers who want to work with the source code:
   855→
   856→### Quick Start (Development/Testing)
   857→
   858→```bash
   859→# Clone the repository
   860→git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git
   861→cd Claude-Code-Usage-Monitor
   862→
   863→# Install in development mode
   864→pip install -e .
   865→
   866→# Run from source
   867→python -m claude_monitor
   868→```
   869→
   870→
   871→### v3.0.0 Testing Features
   872→
   873→The new version includes a comprehensive test suite:
   874→
   875→- **100+ test cases** with full coverage
   876→- **Unit tests** for all components
   877→- **Integration tests** for end-to-end workflows
   878→- **Performance tests** with benchmarking
   879→- **Mock objects** for isolated testing
   880→
   881→```bash
   882→# Run tests
   883→cd src/
   884→python -m pytest
   885→
   886→# Run with coverage
   887→python -m pytest --cov=claude_monitor --cov-report=html
   888→
   889→# Run specific test modules
   890→python -m pytest tests/test_analysis.py -v
   891→```
   892→
   893→
   894→### Prerequisites
   895→
   896→1. **Python 3.9+** installed on your system
   897→2. **Git** for cloning the repository
   898→
   899→
   900→### Virtual Environment Setup
   901→
   902→#### Why Use Virtual Environment?
   903→
   904→Using a virtual environment is **strongly recommended** because:
   905→
   906→- **🛡 Isolation**: Keeps your system Python clean and prevents dependency conflicts
   907→- **📦 Portability**: Easy to replicate the exact environment on different machines
   908→- **🔄 Version Control**: Lock specific versions of dependencies for stability
   909→- **🧹 Clean Uninstall**: Simply delete the virtual environment folder to remove everything
   910→- **👥 Team Collaboration**: Everyone uses the same Python and package versions
   911→
   912→#### Installing virtualenv (if needed)
   913→
   914→If you don't have venv module available:
   915→
   916→```bash
   917→# Ubuntu/Debian
   918→sudo apt-get update
   919→sudo apt-get install python3-venv
   920→
   921→# Fedora/RHEL/CentOS
   922→sudo dnf install python3-venv
   923→
   924→# macOS (usually comes with Python)
   925→# If not available, install Python via Homebrew:
   926→brew install python3
   927→
   928→# Windows (usually comes with Python)
   929→# If not available, reinstall Python from python.org
   930→# Make sure to check "Add Python to PATH" during installation
   931→```
   932→
   933→
   934→Alternatively, use the virtualenv package:
   935→```bash
   936→# Install virtualenv via pip
   937→pip install virtualenv
   938→
   939→# Then create virtual environment with:
   940→virtualenv venv
   941→# instead of: python3 -m venv venv
   942→```
   943→
   944→
   945→#### Step-by-Step Setup
   946→
   947→```bash
   948→# 1. Clone the repository
   949→git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git
   950→cd Claude-Code-Usage-Monitor
   951→
   952→# 2. Create virtual environment
   953→python3 -m venv venv
   954→# Or if using virtualenv package:
   955→# virtualenv venv
   956→
   957→# 3. Activate virtual environment
   958→# On Linux/Mac:
   959→source venv/bin/activate
   960→# On Windows:
   961→# venv\Scripts\activate
   962→
   963→# 4. Install Python dependencies
   964→pip install pytz
   965→pip install rich>=13.0.0
   966→# 5. Make script executable (Linux/Mac only)
   967→chmod +x claude_monitor.py
   968→
   969→# 6. Run the monitor
   970→python claude_monitor.py
   971→```
   972→
   973→
   974→#### Daily Usage
   975→
   976→After initial setup, you only need:
   977→
   978→```bash
   979→# Navigate to project directory
   980→cd Claude-Code-Usage-Monitor
   981→
   982→# Activate virtual environment
   983→source venv/bin/activate  # Linux/Mac
   984→# venv\Scripts\activate   # Windows
   985→
   986→# Run monitor
   987→./claude_monitor.py  # Linux/Mac
   988→# python claude_monitor.py  # Windows
   989→
   990→# When done, deactivate
   991→deactivate
   992→```
   993→
   994→
   995→#### Pro Tip: Shell Alias
   996→
   997→Create an alias for quick access:
   998→```bash
   999→# Add to ~/.bashrc or ~/.zshrc
  1000→alias claude-monitor='cd ~/Claude-Code-Usage-Monitor && source venv/bin/activate && ./claude_monitor.py'
  1001→
  1002→# Then just run:
  1003→claude-monitor
  1004→```
  1005→
  1006→
  1007→## Troubleshooting
  1008→
  1009→### Installation Issues
  1010→
  1011→#### "externally-managed-environment" Error
  1012→
  1013→On modern Linux distributions (Ubuntu 23.04+, Debian 12+, Fedora 38+), you may encounter:
  1014→```
  1015→error: externally-managed-environment
  1016→× This environment is externally managed
  1017→```
  1018→
  1019→
  1020→**Solutions (in order of preference):**
  1021→
  1022→1. **Use uv (Recommended)**
  1023→
  1024→```bash
  1025→   # Install uv first
  1026→   curl -LsSf https://astral.sh/uv/install.sh | sh
  1027→
  1028→   # Then install with uv
  1029→   uv tool install claude-monitor
  1030→   ```
  1031→
  1032→
  1033→2. **Use pipx (Isolated Environment)**
  1034→
  1035→```bash
  1036→   # Install pipx
  1037→   sudo apt install pipx  # Ubuntu/Debian
  1038→   # or
  1039→   python3 -m pip install --user pipx
  1040→
  1041→   # Install claude-monitor
  1042→   pipx install claude-monitor
  1043→   ```
  1044→
  1045→
  1046→3. **Use virtual environment**
  1047→
  1048→```bash
  1049→   python3 -m venv myenv
  1050→   source myenv/bin/activate
  1051→   pip install claude-monitor
  1052→   ```
  1053→
  1054→
  1055→4. **Force installation (Not Recommended)**
  1056→
  1057→```bash
  1058→   pip install --user claude-monitor --break-system-packages
  1059→   ```
  1060→
  1061→   ⚠ **Warning**: This bypasses system protection and may cause conflicts. We strongly recommend using a virtual environment instead.
  1062→
  1063→#### Command Not Found After pip Install
  1064→
  1065→If claude-monitor command is not found after pip installation:
  1066→
  1067→1. **Check if it's a PATH issue**
  1068→
  1069→```bash
  1070→   # Look for the warning message during pip install:
  1071→   # WARNING: The script claude-monitor is installed in '/home/username/.local/bin' which is not on PATH
  1072→   ```
  1073→
  1074→
  1075→2. **Add to PATH**
  1076→
  1077→```bash
  1078→   # Add this to ~/.bashrc or ~/.zshrc
  1079→   echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
  1080→
  1081→   # Reload shell
  1082→   source ~/.bashrc  # or source ~/.zshrc
  1083→   ```
  1084→
  1085→
  1086→3. **Verify installation location**
  1087→
  1088→```bash
  1089→   # Find where pip installed the script
  1090→   pip show -f claude-monitor | grep claude-monitor
  1091→   ```
  1092→
  1093→
  1094→4. **Run directly with Python**
  1095→
  1096→```bash
  1097→   python3 -m claude_monitor
  1098→   ```
  1099→
  1100→
  1101→#### Python Version Conflicts
  1102→
  1103→If you have multiple Python versions:
  1104→
  1105→1. **Check Python version**
  1106→
  1107→```bash
  1108→   python3 --version
  1109→   pip3 --version
  1110→   ```
  1111→
  1112→
  1113→2. **Use specific Python version**
  1114→
  1115→```bash
  1116→   python3.11 -m pip install claude-monitor
  1117→   python3.11 -m claude_monitor
  1118→   ```
  1119→
  1120→
  1121→3. **Use uv (handles Python versions automatically)**
  1122→
  1123→```bash
  1124→   uv tool install claude-monitor
  1125→   ```
  1126→
  1127→
  1128→### Runtime Issues
  1129→
  1130→#### No active session found
  1131→If you encounter the error No active session found, please follow these steps:
  1132→
  1133→1. **Initial Test**:
  1134→   Launch Claude Code and send at least two messages. In some cases, the session may not initialize correctly on the first attempt, but it resolves after a few interactions.
  1135→
  1136→2. **Configuration Path**:
  1137→   If the issue persists, consider specifying a custom configuration path. By default, Claude Code uses ~/.config/claude. You may need to adjust this path depending on your environment.
  1138→
  1139→```bash
  1140→CLAUDE_CONFIG_DIR=~/.config/claude ./claude_monitor.py
  1141→```
  1142→
  1143→
  1144→
  1145→## 📞 Contact
  1146→
  1147→Have questions, suggestions, or want to collaborate? Feel free to reach out!
  1148→
  1149→**📧 Email**: [maciek@roboblog.eu](mailto:maciek@roboblog.eu)
  1150→
  1151→Whether you need help with setup, have feature requests, found a bug, or want to discuss potential improvements, don't hesitate to get in touch. I'm always happy to help and hear from users of the Claude Code Usage Monitor!
  1152→
  1153→
  1154→## 📚 Additional Documentation
  1155→
  1156→- **[Development Roadmap](DEVELOPMENT.md)** - ML features, PyPI package, Docker plans
  1157→- **[Contributing Guide](CONTRIBUTING.md)** - How to contribute, development guidelines
  1158→- **[Troubleshooting](TROUBLESHOOTING.md)** - Common issues and solutions
  1159→
  1160→
  1161→## 📝 License
  1162→
  1163→[MIT License](LICENSE) - feel free to use and modify as needed.
  1164→
  1165→## 🤝 Contributors
  1166→
  1167→- [@adawalli](https://github.com/adawalli)
  1168→- [@taylorwilsdon](https://github.com/taylorwilsdon)
  1169→- [@moneroexamples](https://github.com/moneroexamples)
  1170→
  1171→Want to contribute? Check out our [Contributing Guide](CONTRIBUTING.md)!
  1172→
  1173→
  1174→## 🙏 Acknowledgments
  1175→
  1176→### Sponsors
  1177→
  1178→A special thanks to our supporters who help keep this project going:
  1179→
  1180→**Ed** - *Buy Me Coffee Supporter*
  1181→> "I appreciate sharing your work with the world. It helps keep me on track with my day. Quality readme, and really good stuff all around!"
  1182→
  1183→## Star History
  1184→
  1185→[![Star History Chart](https://api.star-history.com/svg?repos=Maciek-roboblog/Claude-Code-Usage-Monitor&type=Date)](https://www.star-history.com/#Maciek-roboblog/Claude-Code-Usage-Monitor&Date)
  1186→
  1187→---
  1188→
  1189→<div align="center">
  1190→
  1191→**⭐ Star this repo if you find it useful! ⭐**
  1192→
  1193→[Report Bug](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor/issues) • [Request Feature](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor/issues) • [Contribute](CONTRIBUTING.md)
  1194→
  1195→</div>
  1196→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

# 🎯 Claude Code Usage Monitor
[![PyPI Version](https://img.shields.io/pypi/v/claude-monitor.svg)](https://pypi.org/project/claude-monitor/)
[![Python Version](https://img.shields.io/badge/python-3.9+-blue.svg)](https://python.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com)
[![codecov](https://codecov.io/gh/Maciek-roboblog/Claude-Code-Usage-Monitor/branch/main/graph/badge.svg)](https://codecov.io/gh/Maciek-roboblog/Claude-Code-Usage-Monitor)

A beautiful real-time terminal monitoring tool for Claude AI token usage with advanced analytics, machine learning-based predictions, and Rich UI. Track your token consumption, burn rate, cost analysis, and get intelligent predictions about session limits.

![Claude Token Monitor Screenshot](https://raw.githubusercontent.com/Maciek-roboblog/Claude-Code-Usage-Monitor/main/doc/scnew.png)

---

## 📑 Table of Contents

- [✨ Key Features](#-key-features)
- [🚀 Installation](#-installation)
  - [⚡ Modern Installation with uv (Recommended)](#-modern-installation-with-uv-recommended)
  - [📦 Installation with pip](#-installation-with-pip)
  - [🛠 Other Package Managers](#-other-package-managers)
- [📖 Usage](#-usage)
  - [Get Help](#get-help)
  - [Basic Usage](#basic-usage)
  - [Configuration Options](#configuration-options)
  - [Available Plans](#available-plans)
- [🙏 Please Help Test This Release!](#-please-help-test-this-release)
- [✨ Features & How It Works](#-features--how-it-works)
  - [Current Features](#current-features)
  - [Understanding Claude Sessions](#understanding-claude-sessions)
  - [Token Limits by Plan](#token-limits-by-plan)
  - [Smart Detection Features](#smart-detection-features)
- [🚀 Usage Examples](#-usage-examples)
  - [Common Scenarios](#common-scenarios)
  - [Best Practices](#best-practices)
- [🔧 Development Installation](#-development-installation)
- [Troubleshooting](#troubleshooting)
  - [Installation Issues](#installation-issues)
  - [Runtime Issues](#runtime-issues)
- [📞 Contact](#-contact)
- [📚 Additional Documentation](#-additional-documentation)
- [📝 License](#-license)
- [🤝 Contributors](#-contributors)
- [🙏 Acknowledgments](#-acknowledgments)

## ✨ Key Features

### 🚀 **v3.0.0 Major Update - Complete Architecture Rewrite**

- **🔮 ML-based predictions** - P90 percentile calculations and intelligent session limit detection
- **🔄 Real-time monitoring** - Configurable refresh rates (0.1-20 Hz) with intelligent display updates
- **📊 Advanced Rich UI** - Beautiful color-coded progress bars, tables, and layouts with WCAG-compliant contrast
- **🤖 Smart auto-detection** - Automatic plan switching with custom limit discovery
- **📋 Enhanced plan support** - Updated limits: Pro (44k), Max5 (88k), Max20 (220k), Custom (P90-based)
- **⚠ Advanced warning system** - Multi-level alerts with cost and time predictions
- **💼 Professional Architecture** - Modular design with Single Responsibility Principle (SRP) compliance
- **🎨 Intelligent theming** - Scientific color schemes with automatic terminal background detection
- **⏰ Advanced scheduling** - Auto-detected system timezone and time format preferences
- **📈 Cost analytics** - Model-specific pricing with cache token calculations
- **🔧 Pydantic validation** - Type-safe configuration with automatic validation
- **📝 Comprehensive logging** - Optional file logging with configurable levels
- **🧪 Extensive testing** - 100+ test cases with full coverage
- **🎯 Error reporting** - Optional Sentry integration for production monitoring
- **⚡ Performance optimized** - Advanced caching and efficient data processing

### 📋 Default Custom Plan

The **Custom plan** is now the default option, specifically designed for 5-hour Claude Code sessions. It monitors three critical metrics:
- **Token usage** - Tracks your token consumption
- **Messages usage** - Monitors message count
- **Cost usage** - The most important metric for long sessions

The Custom plan automatically adapts to your usage patterns by analyzing all your sessions from the last 192 hours (8 days) and calculating personalized limits based on your actual usage. This ensures accurate predictions and warnings tailored to your specific workflow.

## 🚀 Installation
### ⚡ Modern Installation with uv (Recommended)

**Why uv is the best choice:**
- ✅ Creates isolated environments automatically (no system conflicts)
- ✅ No Python version issues
- ✅ No "externally-managed-environment" errors
- ✅ Easy updates and uninstallation
- ✅ Works on all platforms

The fastest and easiest way to install and use the monitor:

[![PyPI](https://img.shields.io/pypi/v/claude-monitor.svg)](https://pypi.org/project/claude-monitor/)

#### Install from PyPI

```bash
# Install directly from PyPI with uv (easiest)
uv tool install claude-monitor

# Run from anywhere
claude-monitor  # or cmonitor, ccmonitor for short
```

#### Install from Source

```bash
# Clone and install from source
git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git
cd Claude-Code-Usage-Monitor
uv tool install .

# Run from anywhere
claude-monitor
```

#### First-time uv users
If you don't have uv installed yet, get it with one command:

```bash
# On Linux/macOS:
curl -LsSf https://astral.sh/uv/install.sh | sh

# On Windows:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

# After installation, restart your terminal
```

### 📦 Installation with pip

```bash
# Install from PyPI
pip install claude-monitor

# If claude-monitor command is not found, add ~/.local/bin to PATH:
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc  # or restart your terminal

# Run from anywhere
claude-monitor  # or cmonitor, ccmonitor for short
```

>
> **⚠ PATH Setup**: If you see WARNING: The script claude-monitor is installed in '/home/username/.local/bin' which is not on PATH, follow the export PATH command above.
>
> **⚠ Important**: On modern Linux distributions (Ubuntu 23.04+, Debian 12+, Fedora 38+), you may encounter an "externally-managed-environment" error. Instead of using --break-system-packages, we strongly recommend:
> 1. **Use uv instead** (see above) - it's safer and easier
> 2. **Use a virtual environment** - python3 -m venv myenv && source myenv/bin/activate
> 3. **Use pipx** - pipx install claude-monitor
>
> See the Troubleshooting section for detailed solutions.

### 🛠 Other Package Managers

#### pipx (Isolated Environments)
```bash
# Install with pipx
pipx install claude-monitor

# Run from anywhere
claude-monitor  # or claude-code-monitor, cmonitor, ccmonitor, ccm for short
```

#### conda/mamba
```bash
# Install with pip in conda environment
pip install claude-monitor

# Run from anywhere
claude-monitor  # or cmonitor, ccmonitor for short
```

## 📖 Usage

### Get Help

```bash
# Show help information
claude-monitor --help
```

#### Available Command-Line Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| --plan | string | custom | Plan type: pro, max5, max20, or custom |
| --custom-limit-tokens | int | None | Token limit for custom plan (must be > 0) |
| --view | string | realtime | View type: realtime, daily, or monthly |
| --timezone | string | auto | Timezone (auto-detected). Examples: UTC, America/New_York, Europe/London |
| --time-format | string | auto | Time format: 12h, 24h, or auto |
| --theme | string | auto | Display theme: light, dark, classic, or auto |
| --refresh-rate | int | 10 | Data refresh rate in seconds (1-60) |
| --refresh-per-second | float | 0.75 | Display refresh rate in Hz (0.1-20.0) |
| --reset-hour | int | None | Daily reset hour (0-23) |
| --log-level | string | INFO | Logging level: DEBUG, INFO, WARNING, ERROR, CRITICAL |
| --log-file | path | None | Log file path |
| --debug | flag | False | Enable debug logging |
| --version, -v | flag | False | Show version information |
| --clear | flag | False | Clear saved configuration |

#### Plan Options

| Plan | Token Limit | Cost Limit       | Description |
|------|-------------|------------------|-------------|
| pro | 19,000 | $18.00           | Claude Pro subscription |
| max5 | 88,000 | $35.00           | Claude Max5 subscription |
| max20 | 220,000 | $140.00          | Claude Max20 subscription |
| custom | P90-based | (default) $50.00 | Auto-detection with ML analysis |

#### Command Aliases

The tool can be invoked using any of these commands:
- claude-monitor (primary)
- claude-code-monitor (full name)
- cmonitor (short)
- ccmonitor (short alternative)
- ccm (shortest)

#### Save Flags Feature

The monitor automatically saves your preferences to avoid re-specifying them on each run:

**What Gets Saved:**
- View type (--view)
- Theme preferences (--theme)
- Timezone settings (--timezone)
- Time format (--time-format)
- Refresh rates (--refresh-rate, --refresh-per-second)
- Reset hour (--reset-hour)
- Custom token limits (--custom-limit-tokens)

**Configuration Location:** ~/.claude-monitor/last_used.json

**Usage Examples:**
```bash
# First run - specify preferences
claude-monitor --plan pro --theme dark --timezone "America/New_York"

# Subsequent runs - preferences automatically restored
claude-monitor --plan pro

# Override saved settings for this session
claude-monitor --plan pro --theme light

# Clear all saved preferences
claude-monitor --clear
```

**Key Features:**
- ✅ Automatic parameter persistence between sessions
- ✅ CLI arguments always override saved settings
- ✅ Atomic file operations prevent corruption
- ✅ Graceful fallback if config files are damaged
- ✅ Plan parameter never saved (must specify each time)

### Basic Usage

#### With uv tool installation (Recommended)
```bash
# Default (Custom plan with auto-detection)
claude-monitor

# Alternative commands
claude-code-monitor  # Full descriptive name
cmonitor             # Short alias
ccmonitor            # Short alternative
ccm                  # Shortest alias

# Exit the monitor
# Press Ctrl+C to gracefully exit
```

#### Development mode
If running from source, use python -m claude_monitor from the src/ directory.

### Configuration Options

#### Specify Your Plan

```bash
# Custom plan with P90 auto-detection (Default)
claude-monitor --plan custom

# Pro plan (~44,000 tokens)
claude-monitor --plan pro

# Max5 plan (~88,000 tokens)
claude-monitor --plan max5

# Max20 plan (~220,000 tokens)
claude-monitor --plan max20

# Custom plan with explicit token limit
claude-monitor --plan custom --custom-limit-tokens 100000
```

#### Custom Reset Times

```bash
# Reset at 3 AM
claude-monitor --reset-hour 3

# Reset at 10 PM
claude-monitor --reset-hour 22
```

#### Usage View Configuration

```bash
# Real-time monitoring with live updates (Default)
claude-monitor --view realtime

# Daily token usage aggregated in table format
claude-monitor --view daily

# Monthly token usage aggregated in table format
claude-monitor --view monthly

```

#### Performance and Display Configuration

```bash
# Adjust refresh rate (1-60 seconds, default: 10)
claude-monitor --refresh-rate 5

# Adjust display refresh rate (0.1-20 Hz, default: 0.75)
claude-monitor --refresh-per-second 1.0

# Set time format (auto-detected by default)
claude-monitor --time-format 24h  # or 12h

# Force specific theme
claude-monitor --theme dark  # light, dark, classic, auto

# Clear saved configuration
claude-monitor --clear
```

#### Timezone Configuration

The default timezone is **auto-detected from your system**. Override with any valid timezone:

```bash
# Use US Eastern Time
claude-monitor --timezone America/New_York

# Use Tokyo time
claude-monitor --timezone Asia/Tokyo

# Use UTC
claude-monitor --timezone UTC

# Use London time
claude-monitor --timezone Europe/London
```

#### Logging and Debugging

```bash
# Enable debug logging
claude-monitor --debug

# Log to file
claude-monitor --log-file ~/.claude-monitor/logs/monitor.log

# Set log level
claude-monitor --log-level WARNING  # DEBUG, INFO, WARNING, ERROR, CRITICAL
```

### Available Plans

| Plan | Token Limit     | Best For |
|------|-----------------|----------|
| **custom** | P90 auto-detect | Intelligent limit detection (default) |
| **pro** | ~19,000         | Claude Pro subscription |
| **max5** | ~88,000         | Claude Max5 subscription |
| **max20** | ~220,000        | Claude Max20 subscription |

#### Advanced Plan Features

- **P90 Analysis**: Custom plan uses 90th percentile calculations from your usage history
- **Cost Tracking**: Model-specific pricing with cache token calculations
- **Limit Detection**: Intelligent threshold detection with 95% confidence

## 🚀 What's New in v3.0.0

### Major Changes

#### **Complete Architecture Rewrite**
- Modular design with Single Responsibility Principle (SRP) compliance
- Pydantic-based configuration with type safety and validation
- Advanced error handling with optional Sentry integration
- Comprehensive test suite with 100+ test cases

#### **Enhanced Functionality**
- **P90 Analysis**: Machine learning-based limit detection using 90th percentile calculations
- **Updated Plan Limits**: Pro (44k), Max5 (88k), Max20 (220k) tokens
- **Cost Analytics**: Model-specific pricing with cache token calculations
- **Rich UI**: WCAG-compliant themes with automatic terminal background detection

#### **New CLI Options**
- --refresh-per-second: Configurable display refresh rate (0.1-20 Hz)
- --time-format: Automatic 12h/24h format detection
- --custom-limit-tokens: Explicit token limits for custom plans
- --log-file and --log-level: Advanced logging capabilities
- --clear: Reset saved configuration
- Command aliases: claude-code-monitor, cmonitor, ccmonitor, ccm for convenience

#### **Breaking Changes**
- Package name changed from claude-usage-monitor to claude-monitor
- Default plan changed from pro to custom (with auto-detection)
- Minimum Python version increased to 3.9+
- Command structure updated (see examples above)

## ✨ Features & How It Works

### v3.0.0 Architecture Overview

The new version features a complete rewrite with modular architecture following Single Responsibility Principle (SRP):

### 🖥 User Interface Layer

| Component            | Description           |
| -------------------- | --------------------- |
| **CLI Module**       | Pydantic-based        |
| **Settings/Config**  | Type-safe             |
| **Error Handling**   | Sentry-ready          |
| **Rich Terminal UI** | Adaptive Theme        |

---

### 🎛 Monitoring Orchestrator

| Component                | Key Responsibilities                                             |
| ------------------------ | ---------------------------------------------------------------- |
| **Central Control Hub**  | Session Mgmt · Real-time Data Flow · Component Coordination      |
| **Data Manager**         | Cache Mgmt · File I/O · State Persist                           |
| **Session Monitor**      | Real-time · 5 hr Windows · Token Track                           |
| **UI Controller**        | Rich Display · Progress Bars · Theme System                     |
| **Analytics**            | P90 Calculator · Burn Rate · Predictions                        |

---

### 🏗 Foundation Layer

| Component           | Core Features                                           |
| ------------------- | ------------------------------------------------------- |
| **Core Models**     | Session Data · Config Schema · Type Safety             |
| **Analysis Engine** | ML Algorithms · Statistical · Forecasting              |
| **Terminal Themes** | Auto-detection · WCAG Colors · Contrast Opt            |
| **Claude API Data** | Token Tracking · Cost Calculator · Session Blocks      |

---

**🔄 Data Flow:**
Claude Config Files → Data Layer → Analysis Engine → UI Components → Terminal Display

### Current Features

#### 🔄 Advanced Real-time Monitoring
- Configurable update intervals (1-60 seconds)
- High-precision display refresh (0.1-20 Hz)
- Intelligent change detection to minimize CPU usage
- Multi-threaded orchestration with callback system

#### 📊 Rich UI Components
- **Progress Bars**: WCAG-compliant color schemes with scientific contrast ratios
- **Data Tables**: Sortable columns with model-specific statistics
- **Layout Manager**: Responsive design that adapts to terminal size
- **Theme System**: Auto-detects terminal background for optimal readability

#### 📈 Multiple Usage Views
- **Realtime View** (Default): Live monitoring with progress bars, current session data, and burn rate analysis
- **Daily View**: Aggregated daily statistics showing Date, Models, Input/Output/Cache tokens, Total tokens, and Cost
- **Monthly View**: Monthly aggregated data for long-term trend analysis and budget planning

#### 🔮 Machine Learning Predictions
- **P90 Calculator**: 90th percentile analysis for intelligent limit detection
- **Burn Rate Analytics**: Multi-session consumption pattern analysis
- **Cost Projections**: Model-specific pricing with cache token calculations
- **Session Forecasting**: Predicts when sessions will expire based on usage patterns

#### 🤖 Intelligent Auto-Detection
- **Background Detection**: Automatically determines terminal theme (light/dark)
- **System Integration**: Auto-detects timezone and time format preferences
- **Plan Recognition**: Analyzes usage patterns to suggest optimal plans
- **Limit Discovery**: Scans historical data to find actual token limits

### Understanding Claude Sessions

#### How Claude Code Sessions Work

Claude Code operates on a **5-hour rolling session window system**:

1. **Session Start**: Begins with your first message to Claude
2. **Session Duration**: Lasts exactly 5 hours from that first message
3. **Token Limits**: Apply within each 5-hour session window
4. **Multiple Sessions**: Can have several active sessions simultaneously
5. **Rolling Windows**: New sessions can start while others are still active

#### Session Reset Schedule

**Example Session Timeline:**
10:30 AM - First message (Session A starts at 10 AM)
03:00 PM - Session A expires (5 hours later)

12:15 PM - First message (Session B starts 12PM)
05:15 PM - Session B expires (5 hours later 5PM)

#### Burn Rate Calculation

The monitor calculates burn rate using sophisticated analysis:

1. **Data Collection**: Gathers token usage from all sessions in the last hour
2. **Pattern Analysis**: Identifies consumption trends across overlapping sessions
3. **Velocity Tracking**: Calculates tokens consumed per minute
4. **Prediction Engine**: Estimates when current session tokens will deplete
5. **Real-time Updates**: Adjusts predictions as usage patterns change

### Token Limits by Plan

#### v3.0.0 Updated Plan Limits

| Plan | Limit (Tokens) | Cost Limit       | Messages | Algorithm |
|------|----------------|------------------|----------|-----------|
| **Claude Pro** | 19,000         | $18.00           | 250 | Fixed limit |
| **Claude Max5** | 88,000         | $35.00           | 1,000 | Fixed limit |
| **Claude Max20** | 220,000        | $140.00          | 2,000 | Fixed limit |
| **Custom** | P90-based      | (default) $50.00 | 250+ | Machine learning |

#### Advanced Limit Detection

- **P90 Analysis**: Uses 90th percentile of your historical usage
- **Confidence Threshold**: 95% accuracy in limit detection
- **Cache Support**: Includes cache creation and read token costs
- **Model-Specific**: Adapts to Claude 3.5, Claude 4, and future models

### Technical Requirements

#### Dependencies (v3.0.0)

```toml
# Core dependencies (automatically installed)
pytz>=2023.3                # Timezone handling
rich>=13.7.0                # Rich terminal UI
pydantic>=2.0.0             # Type validation
pydantic-settings>=2.0.0    # Configuration management
numpy>=1.21.0               # Statistical calculations
sentry-sdk>=1.40.0          # Error reporting (optional)
pyyaml>=6.0                 # Configuration files
tzdata                      # Windows timezone data
```

#### Python Requirements

- **Minimum**: Python 3.9+
- **Recommended**: Python 3.11+
- **Tested on**: Python 3.9, 3.10, 3.11, 3.12, 3.13

### Smart Detection Features

#### Automatic Plan Switching

When using the default Pro plan:

1. **Detection**: Monitor notices token usage exceeding 7,000
2. **Analysis**: Scans previous sessions for actual limits
3. **Switch**: Automatically changes to custom_max mode
4. **Notification**: Displays clear message about the change
5. **Continuation**: Keeps monitoring with new, higher limit

#### Limit Discovery Process

The auto-detection system:

1. **Scans History**: Examines all available session blocks
2. **Finds Peaks**: Identifies highest token usage achieved
3. **Validates Data**: Ensures data quality and recency
4. **Sets Limits**: Uses discovered maximum as new limit
5. **Learns Patterns**: Adapts to your actual usage capabilities

## 🚀 Usage Examples

### Common Scenarios

#### 🌅 Morning Developer
**Scenario**: You start work at 9 AM and want tokens to reset aligned with your schedule.

```bash
# Set custom reset time to 9 AM
./claude_monitor.py --reset-hour 9

# With your timezone
./claude_monitor.py --reset-hour 9 --timezone US/Eastern
```

**Benefits**:
- Reset times align with your work schedule
- Better planning for daily token allocation
- Predictable session windows

#### 🌙 Night Owl Coder
**Scenario**: You often work past midnight and need flexible reset scheduling.

```bash
# Reset at midnight for clean daily boundaries
./claude_monitor.py --reset-hour 0

# Late evening reset (11 PM)
./claude_monitor.py --reset-hour 23
```

**Strategy**:
- Plan heavy coding sessions around reset times
- Use late resets to span midnight work sessions
- Monitor burn rate during peak hours

#### 🔄 Heavy User with Variable Limits
**Scenario**: Your token limits seem to change, and you're not sure of your exact plan.

```bash
# Auto-detect your highest previous usage
claude-monitor --plan custom_max

# Monitor with custom scheduling
claude-monitor --plan custom_max --reset-hour 6
```

**Approach**:
- Let auto-detection find your real limits
- Monitor for a week to understand patterns
- Note when limits change or reset

#### 🌍 International User
**Scenario**: You're working across different timezones or traveling.

```bash
# US East Coast
claude-monitor --timezone America/New_York

# Europe
claude-monitor --timezone Europe/London

# Asia Pacific
claude-monitor --timezone Asia/Singapore

# UTC for international team coordination
claude-monitor --timezone UTC --reset-hour 12
```

#### ⚡ Quick Check
**Scenario**: You just want to see current status without configuration.

```bash
# Just run it with defaults
claude-monitor

# Press Ctrl+C after checking status
```

#### 📊 Usage Analysis Views
**Scenario**: Analyzing your token usage patterns over different time periods.

```bash
# View daily usage breakdown with detailed statistics
claude-monitor --view daily

# Analyze monthly token consumption trends
claude-monitor --view monthly --plan max20

# Export daily usage data to log file for analysis
claude-monitor --view daily --log-file ~/daily-usage.log

# Review usage in different timezone
claude-monitor --view daily --timezone America/New_York
```

**Use Cases**:
- **Realtime**: Live monitoring of current session and burn rate
- **Daily**: Analyze daily consumption patterns and identify peak usage days
- **Monthly**: Long-term trend analysis and monthly budget planning

### Plan Selection Strategies

#### How to Choose Your Plan

**Start with Default (Recommended for New Users)**
```bash
# Pro plan detection with auto-switching
claude-monitor
```

- Monitor will detect if you exceed Pro limits
- Automatically switches to custom_max if needed
- Shows notification when switching occurs

**Known Subscription Users**
```bash
# If you know you have Max5
claude-monitor --plan max5

# If you know you have Max20
claude-monitor --plan max20
```

**Unknown Limits**
```bash
# Auto-detect from previous usage
claude-monitor --plan custom_max
```

### Best Practices

#### Setup Best Practices

1. **Start Early in Sessions**

```bash
   # Begin monitoring when starting Claude work (uv installation)
   claude-monitor

   # Or development mode
   ./claude_monitor.py
   ```

   - Gives accurate session tracking from the start
   - Better burn rate calculations
   - Early warning for limit approaches

2. **Use Modern Installation (Recommended)**

```bash
   # Easy installation and updates with uv
   uv tool install claude-monitor
   claude-monitor --plan max5
   ```

   - Clean system installation
   - Easy updates and maintenance
   - Available from anywhere

3. **Custom Shell Alias (Legacy Setup)**

```bash
   # Add to ~/.bashrc or ~/.zshrc (only for development setup)
   alias claude-monitor='cd ~/Claude-Code-Usage-Monitor && source venv/bin/activate && ./claude_monitor.py'
   ```

#### Usage Best Practices

1. **Monitor Burn Rate Velocity**
   - Watch for sudden spikes in token consumption
   - Adjust coding intensity based on remaining time
   - Plan big refactors around session resets

2. **Strategic Session Planning**

```bash
   # Plan heavy usage around reset times
   claude-monitor --reset-hour 9
   ```

   - Schedule large tasks after resets
   - Use lighter tasks when approaching limits
   - Leverage multiple overlapping sessions

3. **Timezone Awareness**

```bash
   # Always use your actual timezone
   claude-monitor --timezone Europe/Warsaw
   ```

   - Accurate reset time predictions
   - Better planning for work schedules
   - Correct session expiration estimates

#### Optimization Tips

1. **Terminal Setup**
   - Use terminals with at least 80 character width
   - Enable color support for better visual feedback (check COLORTERM environment variable)
   - Consider dedicated terminal window for monitoring
   - Use terminals with truecolor support for best theme experience

2. **Workflow Integration**

```bash
   # Start monitoring with your development session (uv installation)
   tmux new-session -d -s claude-monitor 'claude-monitor'

   # Or development mode
   tmux new-session -d -s claude-monitor './claude_monitor.py'

   # Check status anytime
   tmux attach -t claude-monitor
   ```

3. **Multi-Session Strategy**
   - Remember sessions last exactly 5 hours
   - You can have multiple overlapping sessions
   - Plan work across session boundaries

#### Real-World Workflows

**Large Project Development**
```bash
# Setup for sustained development
claude-monitor --plan max20 --reset-hour 8 --timezone America/New_York
```

**Daily Routine**:
1. **8:00 AM**: Fresh tokens, start major features
2. **10:00 AM**: Check burn rate, adjust intensity
3. **12:00 PM**: Monitor for afternoon session planning
4. **2:00 PM**: New session window, tackle complex problems
5. **4:00 PM**: Light tasks, prepare for evening session

**Learning & Experimentation**
```bash
# Flexible setup for learning
claude-monitor --plan pro
```

**Sprint Development**
```bash
# High-intensity development setup
claude-monitor --plan max20 --reset-hour 6
```

## 🔧 Development Installation

For contributors and developers who want to work with the source code:

### Quick Start (Development/Testing)

```bash
# Clone the repository
git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git
cd Claude-Code-Usage-Monitor

# Install in development mode
pip install -e .

# Run from source
python -m claude_monitor
```

### v3.0.0 Testing Features

The new version includes a comprehensive test suite:

- **100+ test cases** with full coverage
- **Unit tests** for all components
- **Integration tests** for end-to-end workflows
- **Performance tests** with benchmarking
- **Mock objects** for isolated testing

```bash
# Run tests
cd src/
python -m pytest

# Run with coverage
python -m pytest --cov=claude_monitor --cov-report=html

# Run specific test modules
python -m pytest tests/test_analysis.py -v
```

### Prerequisites

1. **Python 3.9+** installed on your system
2. **Git** for cloning the repository

### Virtual Environment Setup

#### Why Use Virtual Environment?

Using a virtual environment is **strongly recommended** because:

- **🛡 Isolation**: Keeps your system Python clean and prevents dependency conflicts
- **📦 Portability**: Easy to replicate the exact environment on different machines
- **🔄 Version Control**: Lock specific versions of dependencies for stability
- **🧹 Clean Uninstall**: Simply delete the virtual environment folder to remove everything
- **👥 Team Collaboration**: Everyone uses the same Python and package versions

#### Installing virtualenv (if needed)

If you don't have venv module available:

```bash
# Ubuntu/Debian
sudo apt-get update
sudo apt-get install python3-venv

# Fedora/RHEL/CentOS
sudo dnf install python3-venv

# macOS (usually comes with Python)
# If not available, install Python via Homebrew:
brew install python3

# Windows (usually comes with Python)
# If not available, reinstall Python from python.org
# Make sure to check "Add Python to PATH" during installation
```

Alternatively, use the virtualenv package:
```bash
# Install virtualenv via pip
pip install virtualenv

# Then create virtual environment with:
virtualenv venv
# instead of: python3 -m venv venv
```

#### Step-by-Step Setup

```bash
# 1. Clone the repository
git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git
cd Claude-Code-Usage-Monitor

# 2. Create virtual environment
python3 -m venv venv
# Or if using virtualenv package:
# virtualenv venv

# 3. Activate virtual environment
# On Linux/Mac:
source venv/bin/activate
# On Windows:
# venv\Scripts\activate

# 4. Install Python dependencies
pip install pytz
pip install rich>=13.0.0
# 5. Make script executable (Linux/Mac only)
chmod +x claude_monitor.py

# 6. Run the monitor
python claude_monitor.py
```

#### Daily Usage

After initial setup, you only need:

```bash
# Navigate to project directory
cd Claude-Code-Usage-Monitor

# Activate virtual environment
source venv/bin/activate  # Linux/Mac
# venv\Scripts\activate   # Windows

# Run monitor
./claude_monitor.py  # Linux/Mac
# python claude_monitor.py  # Windows

# When done, deactivate
deactivate
```

#### Pro Tip: Shell Alias

Create an alias for quick access:
```bash
# Add to ~/.bashrc or ~/.zshrc
alias claude-monitor='cd ~/Claude-Code-Usage-Monitor && source venv/bin/activate && ./claude_monitor.py'

# Then just run:
claude-monitor
```

## Troubleshooting

### Installation Issues

#### "externally-managed-environment" Error

On modern Linux distributions (Ubuntu 23.04+, Debian 12+, Fedora 38+), you may encounter:
```
error: externally-managed-environment
× This environment is externally managed
```

**Solutions (in order of preference):**

1. **Use uv (Recommended)**

```bash
   # Install uv first
   curl -LsSf https://astral.sh/uv/install.sh | sh

   # Then install with uv
   uv tool install claude-monitor
   ```

2. **Use pipx (Isolated Environment)**

```bash
   # Install pipx
   sudo apt install pipx  # Ubuntu/Debian
   # or
   python3 -m pip install --user pipx

   # Install claude-monitor
   pipx install claude-monitor
   ```

3. **Use virtual environment**

```bash
   python3 -m venv myenv
   source myenv/bin/activate
   pip install claude-monitor
   ```

4. **Force installation (Not Recommended)**

```bash
   pip install --user claude-monitor --break-system-packages
   ```

   ⚠ **Warning**: This bypasses system protection and may cause conflicts. We strongly recommend using a virtual environment instead.

#### Command Not Found After pip Install

If claude-monitor command is not found after pip installation:

1. **Check if it's a PATH issue**

```bash
   # Look for the warning message during pip install:
   # WARNING: The script claude-monitor is installed in '/home/username/.local/bin' which is not on PATH
   ```

2. **Add to PATH**

```bash
   # Add this to ~/.bashrc or ~/.zshrc
   echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc

   # Reload shell
   source ~/.bashrc  # or source ~/.zshrc
   ```

3. **Verify installation location**

```bash
   # Find where pip installed the script
   pip show -f claude-monitor | grep claude-monitor
   ```

4. **Run directly with Python**

```bash
   python3 -m claude_monitor
   ```

#### Python Version Conflicts

If you have multiple Python versions:

1. **Check Python version**

```bash
   python3 --version
   pip3 --version
   ```

2. **Use specific Python version**

```bash
   python3.11 -m pip install claude-monitor
   python3.11 -m claude_monitor
   ```

3. **Use uv (handles Python versions automatically)**

```bash
   uv tool install claude-monitor
   ```

### Runtime Issues

#### No active session found
If you encounter the error No active session found, please follow these steps:

1. **Initial Test**:
   Launch Claude Code and send at least two messages. In some cases, the session may not initialize correctly on the first attempt, but it resolves after a few interactions.

2. **Configuration Path**:
   If the issue persists, consider specifying a custom configuration path. By default, Claude Code uses ~/.config/claude. You may need to adjust this path depending on your environment.

```bash
CLAUDE_CONFIG_DIR=~/.config/claude ./claude_monitor.py
```

## 📞 Contact

Have questions, suggestions, or want to collaborate? Feel free to reach out!

**📧 Email**: [maciek@roboblog.eu](mailto:maciek@roboblog.eu)

Whether you need help with setup, have feature requests, found a bug, or want to discuss potential improvements, don't hesitate to get in touch. I'm always happy to help and hear from users of the Claude Code Usage Monitor!

## 📚 Additional Documentation

- **[Development Roadmap](DEVELOPMENT.md)** - ML features, PyPI package, Docker plans
- **[Contributing Guide](CONTRIBUTING.md)** - How to contribute, development guidelines
- **[Troubleshooting](TROUBLESHOOTING.md)** - Common issues and solutions

## 📝 License

[MIT License](LICENSE) - feel free to use and modify as needed.

## 🤝 Contributors

- [@adawalli](https://github.com/adawalli)
- [@taylorwilsdon](https://github.com/taylorwilsdon)
- [@moneroexamples](https://github.com/moneroexamples)

Want to contribute? Check out our [Contributing Guide](CONTRIBUTING.md)!

## 🙏 Acknowledgments

### Sponsors

A special thanks to our supporters who help keep this project going:

**Ed** - *Buy Me Coffee Supporter*
> "I appreciate sharing your work with the world. It helps keep me on track with my day. Quality readme, and really good stuff all around!"

## Star History

[![Star History Chart](https://api.star-history.com/svg?repos=Maciek-roboblog/Claude-Code-Usage-Monitor&type=Date)](https://www.star-history.com/#Maciek-roboblog/Claude-Code-Usage-Monitor&Date)

---

<div align="center">

**⭐ Star this repo if you find it useful! ⭐**

[Report Bug](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor/issues) • [Request Feature](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor/issues) • [Contribute](CONTRIBUTING.md)

</div>


This is a legitimate open-source project for monitoring Claude Code token usage. It's a Python tool that tracks your token consumption when using Claude Code. Let me summarize the key installation and usage steps for the user.


This is **Claude Code Usage Monitor** - a tool that tracks your Claude Code token usage in real-time with a nice terminal UI.

## Quick Install (Windows)

The easiest way is using **uv**:

```powershell
# Install uv first (one-time)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

# Restart your terminal, then install the monitor
uv tool install claude-monitor

# Run it anytime
claude-monitor
```

## Or with pip

```powershell
pip install claude-monitor
claude-monitor
```

## Basic Usage

```powershell
# Default (auto-detects your plan)
claude-monitor

# If you know your plan
claude-monitor --plan pro      # Pro subscription
claude-monitor --plan max5     # Max5 subscription
claude-monitor --plan max20    # Max20 subscription

# Press Ctrl+C to exit
```

It will show you:
- Current token usage with progress bars
- Burn rate (how fast you're using tokens)
- Time until session resets
- Cost estimates

Would you like me to run the installation for you?


yes please


The user wants me to install the Claude Code Usage Monitor. I'll use uv since that's the recommended approach. First, let me check if uv is already installed, and if not, install it, then install claude-monitor.


Bash

uv --version 2>nul || echo "not installed"

Check if uv is installed


uv 0.9.9 (4fac4cb7e 2025-11-12)


uv is already installed. Now I can install claude-monitor using uv tool install.


uv is already installed. Now installing claude-monitor:


Install claude-monitor tool


Resolved 16 packages in 1.21s
Downloading pygments (1.2MiB)
Downloading numpy (11.7MiB)
Downloading pydantic-core (1.9MiB)
 Downloading pygments
 Downloading pydantic-core
 Downloading numpy
Prepared 14 packages in 1.87s
Installed 16 packages in 386ms
 + annotated-types==0.7.0
 + claude-monitor==3.1.0
 + markdown-it-py==4.0.0
 + mdurl==0.1.2
 + numpy==2.4.0
 + pydantic==2.12.5
 + pydantic-core==2.41.5
 + pydantic-settings==2.12.0
 + pygments==2.19.2
 + python-dotenv==1.2.1
 + pytz==2025.2
 + pyyaml==6.0.3
 + rich==14.2.0
 + typing-extensions==4.15.0
 + typing-inspection==0.4.2
 + tzdata==2025.3
Installed 5 executables: ccm, ccmonitor, claude-code-monitor, claude-monitor, cmonitor


It installed successfully. Now the user can run it. Let me confirm it works.


Installed. You can now run it from any terminal:

```
claude-monitor
```

Or use the short aliases: `cmonitor`, `ccmonitor`, or `ccm`

Since you're using Claude Code right now, running `claude-monitor` in a separate terminal window will show your live token usage. Would you like me to show you what plan options you have, or is there anything else?


I'm on Max20


The user wants to run claude-monitor with the max20 plan. I can give them the command to run.


To run it with your Max20 plan:

```
claude-monitor --plan max20
```

Run that in a separate terminal window and it'll track your usage in real-time. It'll save your plan preference, so next time you can just run `claude-monitor`.


Is there a way I can show similar information in the claude window at all times?


The user is asking if they can show usage information directly within the Claude Code terminal window rather than running a separate monitor. This is about Claude Code's built-in status line feature.

Claude Code has a status line feature that can show information at the bottom of the terminal. Let me check if I can find information about this, or I can use my knowledge about Claude Code features.

I know Claude Code has a `/status` command that shows current usage, and there might be a status line setting. Let me look into this or use the claude-code-guide agent to find out.


Yes, Claude Code has a built-in status line feature. You can enable it by running:

```
/config
```

Then set `terminalStatusLine` to `enabled`. This shows token usage info at the bottom of the Claude Code window.

Alternatively, you can run `/status` anytime to see your current usage stats.

Would you like me to look up more details on what the status line displays?


<command-name>/config</command-name>
            <command-message>config</command-message>
            <command-args></command-args>


<local-command-stdout>Status dialog dismissed</local-command-stdout>


The user is showing me the /config screen in Claude Code. I can see the settings available. I notice "Terminal progress bar" is listed and set to true, but I don't see "terminalStatusLine" as a separate option in this list.

Looking at the options shown:
- Auto-compact
- Show tips
- Thinking mode
- Prompt suggestions
- Rewind code (checkpoints)
- Verbose output
- Terminal progress bar (currently true)
- Default permission mode
- Respect .gitignore in file picker
- Theme
- Notifications
- Output style
- Language
- Editor mode
- Model
- Auto-connect to IDE (external terminal)
- Claude in Chrome enabled by default

The "Terminal progress bar" might be what shows status info. It's already set to true. The user might be looking for something more detailed.

I should let them know that Terminal progress bar is already enabled (which it is), and that might be what shows the status. They can also tab over to "Status" or "Usage" tabs to see more information.


I see **Terminal progress bar** is already set to `true` - that's the setting that shows status info during operations.

For persistent usage stats, try pressing **Tab** or arrow keys to cycle to the **Status** or **Usage** tabs at the top - those will show your current token consumption and limits.

The built-in status line I mentioned may not be in this version of Claude Code, or it might be under a different name. The `/status` command will still work anytime you want to check your usage mid-session.


Previously we build autocoder+ (in remix folder) It has some issues.


The user is referring to a project called "autocoder+" in a "remix folder" that we apparently worked on previously. I need to find this project and understand what it is and what issues it has. Let me explore the remix folder.


Let me take a look at the autocoder+ project and see what's there.


<tool_use_error>Directory does not exist: C:\Users\MikeSwanson\remix</tool_use_error>

Error: Directory does not exist: C:\Users\MikeSwanson\remix


The directory doesn't exist at that path. Let me search for it more broadly.


dir /s /b C:\Users\MikeSwanson\*autocoder* 2>nul | head -20

Search for autocoder folders


dir: cannot access '/s': No such file or directory
dir: cannot access '/b': No such file or directory
dir: cannot access 'C:UsersMikeSwanson*autocoder*': No such file or directory
dir: cannot access '2': No such file or directory


Bash is using Git Bash or a Unix-like shell on Windows. Let me use Windows commands properly or use find.


find /c/Users/MikeSwanson -type d -name "*autocoder*" 2>/dev/null | head -20

Search for autocoder directories


find /c/Users/MikeSwanson -type d -name "*remix*" 2>/dev/null | head -20

Search for remix directories


It's inside claude-projects


/c/Users/MikeSwanson/.autocoder
/c/Users/MikeSwanson/claude-projects/Autocode-remix/Autocode-fork/autocoder-master


Found it! The autocoder+ project is at `/c/Users/MikeSwanson/claude-projects/Autocode-remix`. Let me explore that directory to see what's there and understand the project structure.


Found it. Let me explore the project:


I found the project. It's in `C:\Users\MikeSwanson\claude-projects\Autocode-remix\Autocode-fork\autocoder-master`. Let me read the README and CLAUDE.md files to understand what this project is and what issues it might have. The user mentioned it has "some issues" but didn't specify what they are.


Found it. Let me read the project docs to understand what it does and then you can tell me what issues you're experiencing.