diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..598f462 --- /dev/null +++ b/.gitignore @@ -0,0 +1,201 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be added to the global gitignore or merged into this project gitignore. For a PyCharm +# project, it is not recommended to check the machine-specific absolute paths. +.idea/ + +# VS Code +.vscode/ + +# macOS +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Windows +Thumbs.db +ehthumbs.db +Desktop.ini + +# uv +.python-version +uv.lock + +# Project-specific +# Claude monitor database (for future ML features) +*.db +*.sqlite +.claude_monitor/ + +# Temporary files +*.tmp +*.temp +*.swp +*.swo +*~ + +# Log files +*.log +logs/ + +# Editor backups +*.bak +*.orig \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..dff535d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,196 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +Claude Code Usage Monitor is a Python-based terminal application that provides real-time monitoring of Claude AI token usage. The project tracks token consumption, calculates burn rates, and predicts when tokens will be depleted across different Claude subscription plans. + +## Core Architecture + +### Project Structure +This is a single-file Python application (418 lines) with modern packaging: +- **ccusage_monitor.py**: Main application containing all monitoring logic +- **pyproject.toml**: Modern Python packaging configuration with console script entry points +- **ccusage CLI integration**: External dependency on `ccusage` npm package for data fetching + +### Key Components +- **Data Collection**: Uses `ccusage blocks --json` to fetch Claude usage data +- **Session Management**: Tracks 5-hour rolling session windows with automatic detection +- **Plan Detection**: Supports Pro (~7K), Max5 (~35K), Max20 (~140K), and custom_max (auto-detected) plans +- **Real-time Display**: Terminal UI with progress bars and burn rate calculations +- **Console Scripts**: Two entry points (`ccusage-monitor`, `claude-monitor`) both calling `main()` + +### Key Functions +- `run_ccusage()`: Executes ccusage CLI and parses JSON output at ccusage_monitor.py:13 +- `calculate_hourly_burn_rate()`: Analyzes token consumption patterns from the last hour at ccusage_monitor.py:101 +- `main()`: Entry point function at ccusage_monitor.py:249 for console script integration +- Session tracking logic handles overlapping 5-hour windows and automatic plan switching + +## Development Commands + +### Setup and Installation + +#### Modern Installation with uv (Recommended) +```bash +# Install global dependency +npm install -g ccusage + +# Clone and install the tool with uv +git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git +cd Claude-Code-Usage-Monitor +uv tool install . + +# Run from anywhere +ccusage-monitor +# or +claude-monitor +``` + +#### Traditional Installation +```bash +# Install global dependency +npm install -g ccusage + +# Create virtual environment (recommended) +python3 -m venv venv +source venv/bin/activate # Linux/Mac +# venv\Scripts\activate # Windows + +# Install Python dependencies +pip install pytz + +# Make executable (Linux/Mac) +chmod +x ccusage_monitor.py +``` + +#### Development Setup with uv +```bash +# Install global dependency +npm install -g ccusage + +# Clone and set up for development +git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git +cd Claude-Code-Usage-Monitor + +# Install in development mode with uv +uv sync +uv run ccusage_monitor.py +``` + +### Running the Monitor + +#### With uv tool installation +```bash +# Default mode (Pro plan) +ccusage-monitor +# or +claude-monitor + +# Different plans +ccusage-monitor --plan max5 +ccusage-monitor --plan max20 +ccusage-monitor --plan custom_max + +# Custom configuration +ccusage-monitor --reset-hour 9 --timezone US/Eastern +``` + +#### Traditional/Development mode +```bash +# Default mode (Pro plan) +python ccusage_monitor.py +./ccusage_monitor.py # If made executable + +# Different plans +./ccusage_monitor.py --plan max5 +./ccusage_monitor.py --plan max20 +./ccusage_monitor.py --plan custom_max + +# Custom configuration +./ccusage_monitor.py --reset-hour 9 --timezone US/Eastern + +# With uv in development +uv run ccusage_monitor.py --plan max5 +``` + +### Building and Testing + +#### Package Building +```bash +# Build package with uv +uv build + +# Verify build artifacts +ls dist/ # Should show .whl and .tar.gz files +``` + +#### Testing Installation +```bash +# Test local installation +uv tool install --editable . + +# Verify commands work +ccusage-monitor --help +claude-monitor --help + +# Test uninstall +uv tool uninstall claude-usage-monitor +``` + +#### Manual Testing +Currently no automated test suite. Manual testing involves: +- Running on different platforms (Linux, macOS, Windows) +- Testing with different Python versions (3.6+) +- Verifying plan detection and session tracking +- Testing console script entry points (`ccusage-monitor`, `claude-monitor`) + +## Dependencies + +### External Dependencies +- **ccusage**: npm package for Claude token usage data (must be installed globally) +- **pytz**: Python timezone handling library + +### Standard Library Usage +- subprocess: For executing ccusage CLI commands +- json: For parsing ccusage output +- datetime/timedelta: For session time calculations +- argparse: For command-line interface + +## Development Notes + +### Session Logic +The monitor operates on Claude's 5-hour rolling session system: +- Sessions start with first message and last exactly 5 hours +- Multiple sessions can be active simultaneously +- Token limits apply per 5-hour session window +- Burn rate calculated from all sessions in the last hour + +### Plan Detection +- Starts with Pro plan (7K tokens) by default +- Automatically switches to custom_max when Pro limit exceeded +- custom_max scans previous sessions to find actual token limits +- Supports manual plan specification via command line + +## Package Structure + +### Console Script Entry Points +The `pyproject.toml` defines two console commands: +```toml +[project.scripts] +ccusage-monitor = "ccusage_monitor:main" +claude-monitor = "ccusage_monitor:main" +``` +Both commands call the same `main()` function for consistency. + +### Build Configuration +- **Build backend**: hatchling (modern Python build system) +- **Python requirement**: >=3.6 for broad compatibility +- **Package includes**: Main script, documentation files, license + +### Future Development +See DEVELOPMENT.md for roadmap including: +- ML-powered auto-detection with DuckDB storage +- PyPI package distribution +- Docker containerization with web dashboard +- Enhanced analytics and prediction features \ No newline at end of file diff --git a/README.md b/README.md index 3bb2b14..9f9b5c5 100644 --- a/README.md +++ b/README.md @@ -49,9 +49,46 @@ A beautiful real-time terminal monitoring tool for Claude AI token usage. Track ## 🚀 Installation -### ⚡ Quick Start +### ⚡ Modern Installation with uv (Recommended) -For immediate testing (not recommended for regular use): +The fastest and easiest way to install and use the monitor: + +#### First-time uv users +If you don't have uv installed yet, get it with one command: + +```bash +# Install uv (one-time setup) + +# 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 +``` + +#### Install and run the monitor +```bash +# Install dependencies +npm install -g ccusage + +# Clone and install the tool with uv +git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git +cd Claude-Code-Usage-Monitor +uv tool install . + +# Run from anywhere +ccusage-monitor +# or +claude-monitor +``` + +### 🔧 Legacy Installation Methods + +#### Quick Start (Development/Testing) + +For immediate testing or development: ```bash # Install dependencies @@ -64,14 +101,12 @@ cd Claude-Code-Usage-Monitor python ccusage_monitor.py ``` -### 🔒 Production Setup (Recommended) - #### Prerequisites 1. **Python 3.6+** installed on your system 2. **Node.js** for ccusage CLI tool -### Virtual Environment Setup +#### Virtual Environment Setup #### Why Use Virtual Environment? @@ -182,6 +217,18 @@ claude-monitor ### Basic Usage +#### With uv tool installation (Recommended) +```bash +# Default (Pro plan - 7,000 tokens) +ccusage-monitor +# or +claude-monitor + +# Exit the monitor +# Press Ctrl+C to gracefully exit +``` + +#### Traditional/Development mode ```bash # Default (Pro plan - 7,000 tokens) ./ccusage_monitor.py @@ -194,6 +241,22 @@ claude-monitor #### Specify Your Plan +**With uv tool installation:** +```bash +# Pro plan (~7,000 tokens) - Default +ccusage-monitor --plan pro + +# Max5 plan (~35,000 tokens) +ccusage-monitor --plan max5 + +# Max20 plan (~140,000 tokens) +ccusage-monitor --plan max20 + +# Auto-detect from highest previous session +ccusage-monitor --plan custom_max +``` + +**Traditional/Development mode:** ```bash # Pro plan (~7,000 tokens) - Default ./ccusage_monitor.py --plan pro @@ -210,6 +273,16 @@ claude-monitor #### Custom Reset Times +**With uv tool installation:** +```bash +# Reset at 3 AM +ccusage-monitor --reset-hour 3 + +# Reset at 10 PM +ccusage-monitor --reset-hour 22 +``` + +**Traditional/Development mode:** ```bash # Reset at 3 AM ./ccusage_monitor.py --reset-hour 3 @@ -222,6 +295,22 @@ claude-monitor The default timezone is **Europe/Warsaw**. Change it to any valid timezone: +**With uv tool installation:** +```bash +# Use US Eastern Time +ccusage-monitor --timezone US/Eastern + +# Use Tokyo time +ccusage-monitor --timezone Asia/Tokyo + +# Use UTC +ccusage-monitor --timezone UTC + +# Use London time +ccusage-monitor --timezone Europe/London +``` + +**Traditional/Development mode:** ```bash # Use US Eastern Time ./ccusage_monitor.py --timezone US/Eastern @@ -390,10 +479,10 @@ The auto-detection system: ```bash # Auto-detect your highest previous usage -./ccusage_monitor.py --plan custom_max +ccusage-monitor --plan custom_max # Monitor with custom scheduling -./ccusage_monitor.py --plan custom_max --reset-hour 6 +ccusage-monitor --plan custom_max --reset-hour 6 ``` **Approach**: @@ -406,16 +495,16 @@ The auto-detection system: ```bash # US East Coast -./ccusage_monitor.py --timezone America/New_York +ccusage-monitor --timezone America/New_York # Europe -./ccusage_monitor.py --timezone Europe/London +ccusage-monitor --timezone Europe/London # Asia Pacific -./ccusage_monitor.py --timezone Asia/Singapore +ccusage-monitor --timezone Asia/Singapore # UTC for international team coordination -./ccusage_monitor.py --timezone UTC --reset-hour 12 +ccusage-monitor --timezone UTC --reset-hour 12 ``` #### ⚡ Quick Check @@ -423,7 +512,7 @@ The auto-detection system: ```bash # Just run it with defaults -./ccusage_monitor.py +ccusage-monitor # Press Ctrl+C after checking status ``` @@ -435,7 +524,7 @@ The auto-detection system: **Start with Default (Recommended for New Users)** ```bash # Pro plan detection with auto-switching -./ccusage_monitor.py +ccusage-monitor ``` - Monitor will detect if you exceed Pro limits - Automatically switches to custom_max if needed @@ -444,16 +533,16 @@ The auto-detection system: **Known Subscription Users** ```bash # If you know you have Max5 -./ccusage_monitor.py --plan max5 +ccusage-monitor --plan max5 # If you know you have Max20 -./ccusage_monitor.py --plan max20 +ccusage-monitor --plan max20 ``` **Unknown Limits** ```bash # Auto-detect from previous usage -./ccusage_monitor.py --plan custom_max +ccusage-monitor --plan custom_max ``` ### Best Practices @@ -462,27 +551,29 @@ The auto-detection system: 1. **Start Early in Sessions** ```bash - # Begin monitoring when starting Claude work + # Begin monitoring when starting Claude work (uv installation) + ccusage-monitor + + # Or development mode ./ccusage_monitor.py ``` - Gives accurate session tracking from the start - Better burn rate calculations - Early warning for limit approaches -2. **Use Virtual Environment** +2. **Use Modern Installation (Recommended)** ```bash - # Production setup with isolation - python3 -m venv venv - source venv/bin/activate - pip install pytz + # Easy installation and updates with uv + uv tool install claude-usage-monitor + ccusage-monitor --plan max5 ``` - - Prevents dependency conflicts - - Clean uninstallation - - Reproducible environments + - Clean system installation + - Easy updates and maintenance + - Available from anywhere -3. **Custom Shell Alias** +3. **Custom Shell Alias (Legacy Setup)** ```bash - # Add to ~/.bashrc or ~/.zshrc + # Add to ~/.bashrc or ~/.zshrc (only for development setup) alias claude-monitor='cd ~/Claude-Code-Usage-Monitor && source venv/bin/activate && ./ccusage_monitor.py' ``` @@ -496,7 +587,7 @@ The auto-detection system: 2. **Strategic Session Planning** ```bash # Plan heavy usage around reset times - ./ccusage_monitor.py --reset-hour 9 + ccusage-monitor --reset-hour 9 ``` - Schedule large tasks after resets - Use lighter tasks when approaching limits @@ -505,7 +596,7 @@ The auto-detection system: 3. **Timezone Awareness** ```bash # Always use your actual timezone - ./ccusage_monitor.py --timezone Europe/Warsaw + ccusage-monitor --timezone Europe/Warsaw ``` - Accurate reset time predictions - Better planning for work schedules @@ -520,7 +611,10 @@ The auto-detection system: 2. **Workflow Integration** ```bash - # Start monitoring with your development session + # Start monitoring with your development session (uv installation) + tmux new-session -d -s claude-monitor 'ccusage-monitor' + + # Or development mode tmux new-session -d -s claude-monitor './ccusage_monitor.py' # Check status anytime @@ -537,7 +631,7 @@ The auto-detection system: **Large Project Development** ```bash # Setup for sustained development -./ccusage_monitor.py --plan max20 --reset-hour 8 --timezone America/New_York +ccusage-monitor --plan max20 --reset-hour 8 --timezone America/New_York ``` **Daily Routine**: @@ -550,13 +644,13 @@ The auto-detection system: **Learning & Experimentation** ```bash # Flexible setup for learning -./ccusage_monitor.py --plan pro +ccusage-monitor --plan pro ``` **Sprint Development** ```bash # High-intensity development setup -./ccusage_monitor.py --plan max20 --reset-hour 6 +ccusage-monitor --plan max20 --reset-hour 6 ``` --- diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..d99782f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,59 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "claude-usage-monitor" +version = "1.0.0" +description = "A real-time terminal monitoring tool for Claude AI token usage" +readme = "README.md" +license = "MIT" +requires-python = ">=3.6" +authors = [ + { name = "Maciek", email = "maciek@roboblog.eu" }, +] +keywords = ["claude", "ai", "token", "monitoring", "usage", "terminal"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Topic :: Software Development", + "Topic :: System :: Monitoring", +] +dependencies = [ + "pytz", +] + +[project.urls] +Homepage = "https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor" +Repository = "https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git" +Issues = "https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor/issues" + +[project.scripts] +ccusage-monitor = "ccusage_monitor:main" +claude-monitor = "ccusage_monitor:main" + +[tool.hatch.build.targets.wheel] +packages = ["."] +include = ["ccusage_monitor.py"] + +[tool.hatch.build.targets.sdist] +include = [ + "ccusage_monitor.py", + "README.md", + "LICENSE", + "CLAUDE.md", + "DEVELOPMENT.md", + "CONTRIBUTING.md", + "TROUBLESHOOTING.md", +] \ No newline at end of file