### Full Project Setup and Installation Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Follow these steps to clone the repository, set up a virtual environment, install dependencies, and make the script executable. ```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 ``` -------------------------------- ### Install and Run with uv Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Recommended installation method using uv for easy setup and updates. This command installs the tool and starts monitoring with a specific plan. ```bash # Easy installation and updates with uv uv tool install claude-monitor claude-monitor --plan max5 ``` -------------------------------- ### Flexible Setup for Learning Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md A flexible monitoring setup suitable for learning and experimentation, using the 'pro' plan. ```bash # Flexible setup for learning claude-monitor --plan pro ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/DEVELOPMENT.md Clone the project repository and install development dependencies using UV. This setup is essential for contributing to the project. ```bash # Clone the repository git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git cd Claude-Code-Usage-Monitor # Install development dependencies with UV uv sync --extra dev # Install pre-commit hooks uv run pre-commit install # Run tests uv run pytest # Run linting uv run ruff check . uv run ruff format . ``` -------------------------------- ### Install Claude Monitor with uv Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Install uv first, then use it to install `claude-monitor`. This is the recommended method for resolving 'externally-managed-environment' errors. ```bash # Install uv curl -LsSf https://astral.sh/uv/install.sh | sh source ~/.bashrc # Install claude-monitor uv tool install claude-monitor claude-monitor ``` -------------------------------- ### Start Monitoring Early Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Begin monitoring when starting Claude work for accurate session tracking and better burn rate calculations. Use this command for initial setup. ```bash # Begin monitoring when starting Claude work (uv installation) claude-monitor # Or development mode ./claude_monitor.py ``` -------------------------------- ### Install Claude Monitor (v3.0.0) Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Use `pip install claude-monitor` for standard installations or `uv tool install claude-monitor` for environments managed by uv. ```bash # OLD (deprecated) pip install claude-usage-monitor # NEW (v3.0.0) pip install claude-monitor uv tool install claude-monitor ``` -------------------------------- ### Install Claude Monitor from Source Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Clone the repository and install the tool using uv. This method is recommended for development or if you need the latest version. ```bash git clone https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor.git cd Claude-Code-Usage-Monitor uv tool install . ``` -------------------------------- ### Verify Release Installation Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/RELEASE.md After publishing, verify the release by installing the package in a new environment and checking the version. ```bash # In a new environment uv tool install claude-monitor claude-monitor --version # Test all command aliases cmonitor --version ccm --version ``` -------------------------------- ### Manually install core dependencies Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md If dependency installation fails, manually install the core libraries required by `claude-monitor`, such as `pytz`, `rich`, and `pydantic`. ```bash # Manual installation of core dependencies pip install pytz>=2023.3 rich>=13.7.0 pydantic>=2.0.0 pip install pydantic-settings>=2.0.0 numpy>=1.21.0 ``` -------------------------------- ### Clone Repository and Install in Development Mode Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Steps for contributors and developers to clone the repository and install the monitor in development mode using pip. ```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 ``` -------------------------------- ### Set Up Development Environment Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/CONTRIBUTING.md Create and activate a Python virtual environment, then install the project with development dependencies. Make the main script executable on Linux/Mac. ```bash # Create virtual environment python3 -m venv venv source venv/bin/activate # Linux/Mac # venv\Scripts\activate # Windows # Install project and development dependencies pip install -e .[dev] # Make script executable (Linux/Mac) chmod +x claude_monitor.py ``` -------------------------------- ### Bootstrap Initialization Utilities Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Provides one-time setup functions for logging, environment variables, and directory creation. These are typically called by the CLI before the main monitoring process begins. ```python from pathlib import Path from claude_monitor.cli.bootstrap import ( setup_logging, setup_environment, init_timezone, ensure_directories, ) # Configure logging — console suppressed in monitor mode, file optional setup_logging( level="DEBUG", log_file=Path.home() / ".claude-monitor" / "logs" / "debug.log", disable_console=True, ) # Set UTF-8 stdout and default environment variables setup_environment() # Sets CLAUDE_MONITOR_CONFIG and CLAUDE_MONITOR_CACHE_DIR if not already set # Create required directories under ~/.claude-monitor/ ensure_directories() ``` -------------------------------- ### Install Claude Monitor with a virtual environment Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Create and activate a Python virtual environment, then install `claude-monitor` within it. This isolates dependencies. ```bash python3 -m venv venv source venv/bin/activate pip install claude-monitor claude-monitor ``` -------------------------------- ### Install and Use Claude Monitor CLI Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Install the tool using uv or pip and invoke it with various command-line arguments to customize its behavior, such as setting the plan, theme, timezone, or view mode. Saved preferences can be cleared using the --clear option. ```bash # Install uv tool install claude-monitor # or pip install claude-monitor # Basic usage (custom plan with P90 auto-detection) claude-monitor # Pro plan, dark theme, Eastern time, 5-second refresh claude-monitor --plan pro --theme dark --timezone America/New_York --refresh-rate 5 # Daily usage table view claude-monitor --view daily # Monthly view with Max20 plan claude-monitor --view monthly --plan max20 # Custom token limit override claude-monitor --plan custom --custom-limit-tokens 150000 # Log to file at WARNING level claude-monitor --log-level WARNING --log-file "~/.claude-monitor/logs/monitor.log" # Show version claude-monitor --version # Clear all saved preferences claude-monitor --clear # Available command aliases cmonitor ccmonitor ccm claude-code-monitor ``` -------------------------------- ### Install Claude Monitor with pipx Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Install `claude-monitor` using pipx, a tool for installing Python applications in isolated environments. Ensure pipx is installed first. ```bash # Install pipx sudo apt install pipx # Ubuntu/Debian pipx install claude-monitor claude-monitor ``` -------------------------------- ### Check Claude Monitor installation Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Verify the installation of `claude-monitor` and its executable location using `pip show` and `which`. ```bash pip show claude-monitor which claude-monitor ``` -------------------------------- ### Install and Use uv for Dependency Management Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Recommended method to install the claude-monitor tool using uv, which handles Python versions and dependencies efficiently. ```bash # Install uv first curl -LsSf https://astral.sh/uv/install.sh | sh # Then install with uv uv tool install claude-monitor ``` -------------------------------- ### High-Intensity Sprint Development Setup Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md A setup optimized for high-intensity development sprints, utilizing a specific token plan and reset hour. ```bash # High-intensity development setup claude-monitor --plan max20 --reset-hour 6 ``` -------------------------------- ### Install Claude Monitor with pip Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Installs the claude-monitor package from PyPI. Ensure ~/.local/bin is in your PATH to run the command directly. ```bash 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 ``` -------------------------------- ### Setup for Sustained Large Project Development Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Configure the monitor for sustained development on large projects with specific token plans, reset hours, and timezones. ```bash # Setup for sustained development claude-monitor --plan max20 --reset-hour 8 --timezone America/New_York ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Installs the uv package manager, a fast Python package installer and resolver. Restart your terminal after installation. ```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" ``` -------------------------------- ### Force Installation with --break-system-packages (Not Recommended) Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md This command forces the installation of claude-monitor, bypassing system package management. Use with caution as it may cause conflicts. ```bash pip install --user claude-monitor --break-system-packages ``` -------------------------------- ### Build and Use UsageEntry Model Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Demonstrates how to construct a UsageEntry object with timestamp, token counts, cost, and model details. Includes an example of TokenCounts and SessionBlock. ```python from datetime import datetime, timezone, timedelta from claude_monitor.core.models import ( UsageEntry, TokenCounts, BurnRate, UsageProjection, SessionBlock, CostMode, normalize_model_name, ) # Build a UsageEntry entry = UsageEntry( timestamp=datetime.now(timezone.utc), input_tokens=1_200, output_tokens=350, cache_creation_tokens=0, cache_read_tokens=400, cost_usd=0.00531, model="claude-3-5-sonnet-20241022", message_id="msg_01ABC", request_id="req_XYZ", ) ``` ```python # TokenCounts with computed total tc = TokenCounts(input_tokens=5_000, output_tokens=1_000, cache_creation_tokens=200, cache_read_tokens=800) print(tc.total_tokens) # 7000 ``` ```python # SessionBlock duration now = datetime.now(timezone.utc) block = SessionBlock( id="b-001", start_time=now - timedelta(hours=2), end_time=now + timedelta(hours=3), is_active=True, token_counts=tc, cost_usd=0.15, ) print(block.duration_minutes) # ~120.0 (uses actual_end_time if set) print(block.total_tokens) # 7000 print(block.total_cost) # 0.15 ``` -------------------------------- ### Install Core Dependencies Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md List of core dependencies for the Claude Code Usage Monitor v3.0.0. Ensure these are installed for proper functionality. ```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 ``` -------------------------------- ### Install Python venv on Fedora/RHEL/CentOS Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Instructions for installing the Python virtual environment module on Fedora, RHEL, or CentOS systems. ```bash # Fedora/RHEL/CentOS sudo dnf install python3-venv ``` -------------------------------- ### Install Python venv on Ubuntu/Debian Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Instructions for installing the Python virtual environment module on Ubuntu or Debian-based systems if it's not already available. ```bash # Ubuntu/Debian sudo apt-get update sudo apt-get install python3-venv ``` -------------------------------- ### Start with Default Pro Plan Monitoring Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Begin monitoring with the default Pro plan. The tool automatically detects exceeding limits and switches to 'custom_max' if necessary, providing notifications. ```bash # Pro plan detection with auto-switching claude-monitor ``` -------------------------------- ### Custom Shell Alias for Legacy Setup Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md A legacy setup method for development environments. Add this alias to your shell configuration file (e.g., ~/.bashrc or ~/.zshrc) to easily run the monitor from source. ```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' ``` -------------------------------- ### Use Specific Python Version for Installation and Execution Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md When multiple Python versions are present, specify the desired version (e.g., python3.11) for installing and running the monitor. ```bash python3.11 -m pip install claude-monitor python3.11 -m claude_monitor ``` -------------------------------- ### Daily Usage of Claude Monitor Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md After initial setup, navigate to the project directory, activate the virtual environment, and run the monitor script. Deactivate when finished. ```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 ``` -------------------------------- ### Validate Configuration with Python Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Use a Python script to load settings and validate the configuration without starting the monitor. This checks for errors in plan, theme, and timezone settings. ```python from claude_monitor.core.settings import Settings try: settings = Settings.load_with_last_used(['--plan', 'custom']) print('Configuration valid') print(f'Plan: {settings.plan}') print(f'Theme: {settings.theme}') print(f'Timezone: {settings.timezone}') except Exception as e: print(f'Configuration error: {e}') ``` -------------------------------- ### Install Claude Monitor with uv Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Installs the claude-monitor package using the uv tool, which is recommended for its ability to create isolated environments and avoid Python version conflicts. ```bash uv tool install claude-monitor ``` -------------------------------- ### Install Claude Monitor with conda/mamba Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Installs the claude-monitor package within a conda or mamba environment using pip. ```bash # Install with pip in conda environment pip install claude-monitor ``` -------------------------------- ### Run Claude Monitor with Saved Preferences Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Starts the claude-monitor using previously saved preferences. Only the plan type needs to be specified if it differs from the saved settings. ```bash claude-monitor --plan pro ``` -------------------------------- ### Commit Message Format Examples Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/CONTRIBUTING.md Use a standardized prefix (Add, Fix, Update, Docs, Test, Refactor, Style) followed by a concise description of the change. ```bash # Good commit messages git commit -m "Add: ML-powered token prediction algorithm" git commit -m "Fix: Handle edge case when no sessions are active" git commit -m "Update: Improve error handling in ccusage integration" git commit -m "Docs: Add examples for timezone configuration" # Prefixes to use: # Add: New features # Fix: Bug fixes # Update: Improvements to existing features # Docs: Documentation changes # Test: Test additions or changes # Refactor: Code refactoring # Style: Code style changes ``` -------------------------------- ### Get Help for Claude Monitor Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Displays the help information for the claude-monitor command, listing all available options and their descriptions. ```bash claude-monitor --help ``` -------------------------------- ### Install and Use pipx for Isolated Environments Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Install claude-monitor using pipx to create an isolated environment, which is a good alternative for managing Python applications. ```bash # Install pipx sudo apt install pipx # Ubuntu/Debian # or python3 -m pip install --user pipx # Install claude-monitor pipx install claude-monitor ``` -------------------------------- ### Python Testing Guidelines Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/CONTRIBUTING.md Name test files starting with 'test_'. Write clear docstrings for tests and cover normal cases as well as edge cases. ```python # Test file naming: test_*.py # tests/test_core.py import pytest from claude_monitor.core import TokenMonitor def test_token_calculation(): """Test token usage calculation.""" monitor = TokenMonitor() result = monitor.calculate_usage(1000, 500) assert result == 50.0 # 50% usage def test_burn_rate_calculation(): """Test burn rate calculation with edge cases.""" monitor = TokenMonitor() # Normal case assert monitor.calculate_burn_rate(100, 10) == 10.0 # Edge case: zero time assert monitor.calculate_burn_rate(100, 0) == 0 ``` -------------------------------- ### Retrieve Package Version using importlib.metadata Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/VERSION_MANAGEMENT.md When the package is installed, its version can be retrieved using `importlib.metadata.version`. This is the primary method for version detection. ```python importlib.metadata.version("claude-monitor") ``` -------------------------------- ### Initialize and Run Monitoring Orchestrator Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Sets up the MonitoringOrchestrator to poll usage data, register callbacks for data updates and session events, and start the monitoring process. Ensure callbacks are defined before registration. ```python import time from typing import Any, Dict, Optional from claude_monitor.monitoring.orchestrator import MonitoringOrchestrator orchestrator = MonitoringOrchestrator( update_interval=10, # poll every 10 seconds data_path="~/.claude/projects", ) # Register data-update callback def on_data(monitoring_data: Dict[str, Any]) -> None: data = monitoring_data["data"] token_limit = monitoring_data["token_limit"] blocks = data.get("blocks", []) active = [b for b in blocks if b.get("isActive")] if active: pct = active[0]["totalTokens"] / token_limit * 100 print(f"Usage: {active[0]['totalTokens']:,}/{token_limit:,} ({pct:.1f}%)") orchestrator.register_update_callback(on_data) # Register session-lifecycle callback def on_session(event: str, session_id: str, data: Optional[Dict]) -> None: print(f"Session event: {event} — {session_id}") orchestrator.register_session_callback(on_session) # Provide CLI args for plan-aware token limit calculation import argparse args = argparse.Namespace(plan="max5", custom_limit_tokens=None) orchestrator.set_args(args) orchestrator.start() # Wait up to 10s for the first data fetch if orchestrator.wait_for_initial_data(timeout=10.0): print("Initial data received") time.sleep(30) # monitor for 30 seconds # Force an immediate refresh fresh = orchestrator.force_refresh() orchestrator.stop() ``` -------------------------------- ### Check Python version and install Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Ensure you are using Python 3.9+ for Claude Monitor v3.0.0. If your version is too old, use a specific Python version like 3.11 for installation and execution. ```bash # Check Python version python3 --version # If too old, upgrade Python or use specific version python3.11 -m pip install claude-monitor python3.11 -m claude_monitor ``` -------------------------------- ### Add Local Bin Directory to PATH Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md If the 'claude-monitor' command is not found after installation, add the local bin directory to your system's PATH environment variable. ```bash # Add this to ~/.bashrc or ~/.zshrc echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # Reload shell source ~/.bashrc # or source ~/.zshrc ``` -------------------------------- ### System Information Commands Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md These commands are used to gather system and environment information for bug reports. They include details about the operating system, Python version, installation path, and command-line help output. ```bash uname -a # Linux/Mac ``` ```bash systeminfo # Windows ``` ```bash python --version ``` ```bash pip show claude-monitor ``` ```bash which claude-monitor ``` ```bash echo $PATH ``` ```bash claude-monitor --help ``` ```bash claude-monitor --debug | head -20 ``` -------------------------------- ### Complete Uninstall and Reinstallation Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md This script outlines the steps for a complete uninstallation and fresh reinstallation of the Claude Monitor. It includes removing the package, clearing configuration and cache files, and then performing a new installation using uv, pipx, or pip. ```bash # 1. Uninstall completely pip uninstall claude-monitor uv tool uninstall claude-monitor # if using uv pipx uninstall claude-monitor # if using pipx ``` ```bash # 2. Clear all configuration rm -rf ~/.claude-monitor/ ``` ```bash # 3. Clear Python cache find . -name "*.pyc" -delete 2>/dev/null find . -name "__pycache__" -delete 2>/dev/null ``` ```bash # 4. Fresh installation (choose one) uv tool install claude-monitor # Recommended # OR pipx install claude-monitor # Alternative # OR python -m venv venv && source venv/bin/activate && pip install claude-monitor ``` ```bash # 5. Test installation claude-monitor --help claude-monitor --version ``` -------------------------------- ### Aggregate Usage Data from Session Blocks Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Loads usage entries and aggregates them into daily blocks using SessionAnalyzer and UsageAggregator. Requires prior setup of data loading and analysis components. ```python from claude_monitor.data.analysis import analyze_usage from claude_monitor.data.analyzer import SessionAnalyzer from claude_monitor.data.reader import load_usage_entries from claude_monitor.core.models import CostMode entries, _ = load_usage_entries(hours_back=720) analyzer = SessionAnalyzer(session_duration_hours=5) blocks = analyzer.transform_to_blocks(entries) weekly_agg = UsageAggregator("", aggregation_mode="daily") result = weekly_agg.aggregate_from_blocks(blocks, view_type="daily") ``` -------------------------------- ### Get Themed Console and Styled Output Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Utilizes the theme system to auto-detect terminal background and provide a Rich Console instance with appropriate styling. Supports forcing specific themes and provides helper functions for styled printing. ```python from claude_monitor.terminal.themes import ( BackgroundDetector, BackgroundType, ThemeManager, get_themed_console, get_cost_style, get_velocity_indicator, print_themed, ) # Auto-detect terminal background bg = BackgroundDetector.detect_background() print(bg) # BackgroundType.DARK or BackgroundType.LIGHT # Get a Rich Console with the auto-detected theme console = get_themed_console() console.print("[success]All systems go[/success]") # Force a specific theme dark_console = get_themed_console(force_theme="dark") light_console = get_themed_console(force_theme="light") classic_console = get_themed_console(force_theme="classic") # ThemeManager — lower-level control manager = ThemeManager() theme_cfg = manager.get_theme("dark") print(theme_cfg.name) # "dark" print(theme_cfg.symbols["check"]) # "✓" print(theme_cfg.symbols["spinner"]) # ["⠋","⠙","⠹",...] # Print styled text (convenience wrapper) print_themed("Loading data...", style="info") print_themed("Approaching limit!", style="warning") print_themed("Limit hit.", style="error") # Cost-based style selection for cost in [0.50, 3.00, 15.00]: style = get_cost_style(cost) print(f"${cost:.2f} → style: {style}") # $0.50 → style: cost.low # $3.00 → style: cost.medium # $15.00 → style: cost.high # Burn rate velocity indicator for rate in [30, 100, 200, 500]: vi = get_velocity_indicator(rate) print(f"{rate} tok/min → {vi['emoji']} {vi['label']}") # 30 tok/min → 🐌 Slow # 100 tok/min → ➡️ Normal # 200 tok/min → 🚀 Fast # 500 tok/min → ⚡ Very fast ``` -------------------------------- ### Run with Default Settings Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Execute the monitor with default configurations for a quick status check. Press Ctrl+C to exit after viewing. ```bash # Just run it with defaults claude-monitor ``` ```bash # Press Ctrl+C after checking status ``` -------------------------------- ### Prepare for Manual Release Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/RELEASE.md Ensure your local repository is up-to-date and run tests and linting before proceeding with a manual release. ```bash git checkout main git pull origin main uv sync --extra dev uv run ruff check . uv run ruff format --check . ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/CONTRIBUTING.md Fork the project repository on GitHub and then clone your fork locally. Navigate into the project directory. ```bash # Fork the repository on GitHub # Then clone your fork git clone https://github.com/YOUR-USERNAME/Claude-Code-Usage-Monitor.git cd Claude-Code-Usage-Monitor ``` -------------------------------- ### Find pip Installation Location Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Use 'pip show -f' to locate where pip has installed the 'claude-monitor' script and its associated files. ```bash pip show -f claude-monitor | grep claude-monitor ``` -------------------------------- ### Build Package with uv Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/RELEASE.md Clean any previous build artifacts and then use `uv build` to create the distribution packages. ```bash # Clean previous builds rm -rf dist/ # Build with uv uv build # Verify build artifacts ls -la dist/ # Should show: # - claude_monitor-1.0.9-py3-none-any.whl # - claude_monitor-1.0.9.tar.gz ``` -------------------------------- ### Configure Usage View Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Choose how token usage is displayed. Options include real-time updates or aggregated daily/monthly tables. ```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 ``` -------------------------------- ### After Migration: Single Source of Truth for Version Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/VERSION_MANAGEMENT.md Shows the solution where `__init__.py` imports the version, and `pyproject.toml` is the sole source of truth, ensuring versions are always in sync. ```python # src/claude_monitor/__init__.py from claude_monitor._version import __version__ # Always in sync! # pyproject.toml version = "3.0.0" # Single source of truth ``` -------------------------------- ### Configure Performance and Display Settings Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Adjust performance parameters such as the refresh rate for monitoring data and the display refresh rate for the UI. Time format and theme can also be set. ```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 ``` -------------------------------- ### Select Known Subscription Plans Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Manually select a plan if you know your subscription level. Supports 'max5' and 'max20'. ```bash # If you know you have Max5 claude-monitor --plan max5 ``` ```bash # If you know you have Max20 claude-monitor --plan max20 ``` -------------------------------- ### Check Claude Data Files Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Verify the existence and location of Claude data files in the ~/.claude/projects directory to diagnose startup timeouts. ```bash ls -la ~/.claude/projects/*.jsonl ``` -------------------------------- ### Before Migration: Multiple Version Definitions Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/VERSION_MANAGEMENT.md Illustrates the problem of multiple, unsynchronized version definitions in `__init__.py` and `pyproject.toml`, leading to sync issues. ```python # Multiple version definitions - sync issues! # src/claude_monitor/__init__.py __version__ = "2.5.0" # pyproject.toml version = "3.0.0" # Different version! ``` -------------------------------- ### Integrate Monitoring with Tmux Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Integrate the Claude monitor into your development workflow using tmux for persistent monitoring sessions. These commands start a detached monitoring session and attach to it. ```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 ``` -------------------------------- ### Analyze Token Usage with Views Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Generate usage reports using different views like 'daily' or 'monthly'. Options include logging to a file and specifying timezones. ```bash # View daily usage breakdown with detailed statistics claude-monitor --view daily ``` ```bash # Analyze monthly token consumption trends claude-monitor --view monthly --plan max20 ``` ```bash # Export daily usage data to log file for analysis claude-monitor --view daily --log-file ~/daily-usage.log ``` ```bash # Review usage in different timezone claude-monitor --view daily --timezone America/New_York ``` -------------------------------- ### Add ~/.local/bin to PATH for Shell Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Appends the ~/.local/bin directory to the PATH environment variable in the bash configuration file. This allows executable scripts installed by pip to be run from anywhere in the terminal. ```bash echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### Configure Logging and Debugging Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Enable debug logging, specify a log file path, or set the log level for detailed troubleshooting. Supports standard logging levels. ```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 ``` -------------------------------- ### Get Cost Limit and Validate Plan Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Retrieve cost limits for specified plans and validate if a given plan name is recognized. Requires access to the 'Plans' module and 'PlanType' enum. ```python print(get_cost_limit("pro")) # 18.0 print(get_cost_limit("max20")) # 140.0 ``` ```python print(Plans.is_valid_plan("max5")) # True print(Plans.is_valid_plan("ultra")) # False ``` ```python pt = PlanType.from_string("max20") cfg = Plans.get_plan(pt) print(cfg.name, cfg.token_limit) # max20 220000 ``` -------------------------------- ### Create and Push Git Tag Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/RELEASE.md Create an annotated git tag for the new release version and push it to the remote repository. ```bash # Create annotated tag git tag -a v1.0.9 -m "Release v1.0.9" # Push tag to GitHub git push origin v1.0.9 ``` -------------------------------- ### Aggregate Usage Data Daily or Monthly Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Aggregates raw usage entries into daily or monthly statistics with per-model breakdowns. Configurable with data path, aggregation mode, and timezone. Use `calculate_totals` to get grand totals. ```python from claude_monitor.data.aggregator import UsageAggregator # Daily aggregation (reads data automatically via aggregate()) aggregator = UsageAggregator( data_path="~/.claude/projects", aggregation_mode="daily", timezone="America/New_York", ) daily_data = aggregator.aggregate() for day in daily_data: print( f"{day['date']} | in={day['input_tokens']:,} out={day['output_tokens']:,} " f"| ${day['total_cost']:.4f} | models: {day['models_used']}" ) # Monthly aggregation monthly_aggregator = UsageAggregator( data_path="~/.claude/projects", aggregation_mode="monthly", timezone="UTC", ) monthly_data = monthly_aggregator.aggregate() for month in monthly_data: print(f"{month['month']} | total cost: ${month['total_cost']:.2f}") # Calculate grand totals across all periods totals = aggregator.calculate_totals(daily_data) print(f"Total tokens: {totals['total_tokens']:,}") print(f"Total cost: ${totals['total_cost']:.4f}") print(f"Total entries: {totals['entries_count']}") ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/CONTRIBUTING.md Stage all your changes, commit them with a descriptive message following the specified format, and push the branch to your fork. ```bash # Add and commit your changes git add . git commit -m "Add: Brief description of your change" # Push to your fork git push origin feature/your-feature-name # Open a Pull Request on GitHub ``` -------------------------------- ### Run Claude Monitor with Default Settings Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Executes the claude-monitor with default settings, which includes auto-detection for the custom plan. ```bash claude-monitor ``` -------------------------------- ### Manage Variable Token Limits Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Use 'custom_max' plan to auto-detect your highest previous token usage. Combine with --reset-hour for custom scheduling. ```bash # Auto-detect your highest previous usage claude-monitor --plan custom_max ``` ```bash # Monitor with custom scheduling claude-monitor --plan custom_max --reset-hour 6 ``` -------------------------------- ### Follow Log File Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Monitor the debug log file in real-time using 'tail -f' to observe ongoing activity and errors. ```bash tail -f ~/.claude-monitor/logs/debug.log ``` -------------------------------- ### Run Monitor Directly with Python Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md If the script is not directly executable, you can run the monitor module using the 'python3 -m' command. ```bash python3 -m claude_monitor ``` -------------------------------- ### Run Docker Container for Claude Monitor Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/DEVELOPMENT.md Use these commands to deploy the Claude Code Usage Monitor as a Docker container. Options include lightweight monitoring, enabling the web dashboard, and persisting data. ```bash # Lightweight monitoring docker run -e PLAN=max5 maciek/claude-monitor # With web dashboard docker run -p 8080:8080 maciek/claude-monitor --web-mode # Persistent data docker run -v ~/.claude_monitor:/data maciek/claude-monitor ``` -------------------------------- ### Specify Custom Configuration Path for Runtime Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md If the 'No active session found' error occurs, try specifying the CLAUDE_CONFIG_DIR environment variable to point to the correct configuration directory. ```bash CLAUDE_CONFIG_DIR=~/.config/claude ./claude_monitor.py ``` -------------------------------- ### Publish Package to PyPI Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/RELEASE.md Upload the built distribution artifacts to PyPI using `twine`. This can be done interactively or using an API token. ```bash # Install twine if needed uv tool install twine # Upload to PyPI (will prompt for credentials) uv tool run twine upload dist/ # Or with API token uv tool run twine upload dist/* --username __token__ --password ``` -------------------------------- ### Enable Debug Mode with File Logging Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Activate full debug output and redirect logs to a specified file for detailed analysis. ```bash claude-monitor --debug ``` ```bash claude-monitor --debug --log-file ~/.claude-monitor/logs/debug.log ``` -------------------------------- ### Configure Custom Token Limit Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Set a custom token limit for the 'custom' plan. The limit must be a positive integer. ```bash claude-monitor --plan custom --custom-limit-tokens 50000 ``` ```bash claude-monitor --plan custom --custom-limit-tokens 0 ``` -------------------------------- ### Specify Claude Plan Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Configure the monitoring plan by selecting a predefined tier or a custom limit. The 'custom' plan uses P90 auto-detection by default. ```bash 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 ``` -------------------------------- ### Analyze Claude Usage Over Time Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Loads usage entries, groups them into sessions, detects limits, and computes burn rates and projections. Use `quick_start=True` for faster analysis of the last 24 hours. Disable the cache with `use_cache=False` for fresh data. ```python from claude_monitor.data.analysis import analyze_usage # Full analysis — last 192 hours result = analyze_usage(hours_back=192) print(result["metadata"]) # { # "generated_at": "2025-07-23T12:00:00+00:00", # "hours_analyzed": 192, # "entries_processed": 1420, # "blocks_created": 14, # "limits_detected": 2, # "load_time_seconds": 0.42, # "transform_time_seconds": 0.08, # } for block in result["blocks"]: active = "ACTIVE" if block["isActive"] else "past" print( f"[{active}] {block['startTime']} → {block['endTime']} | " f"tokens={block['totalTokens']:,} | ${block['costUSD']:.4f}" ) if block.get("burnRate"): print(f" Burn rate: {block['burnRate']['tokensPerMinute']:.1f} tok/min, " f"${block['burnRate']['costPerHour']:.4f}/hr") if block.get("projection"): print(f" Projection: {block['projection']['remainingMinutes']} min remaining, " f"projected {block['projection']['totalTokens']:,} total tokens") # Quick-start mode (last 24h only, faster load) quick_result = analyze_usage(hours_back=24, quick_start=True) # Disable cache for fresh data fresh_result = analyze_usage(hours_back=96, use_cache=False) ``` -------------------------------- ### Auto-Detect Unknown Limits Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Use the 'custom_max' plan to automatically detect your highest previous token usage when subscription limits are unknown. ```bash # Auto-detect from previous usage claude-monitor --plan custom_max ``` -------------------------------- ### Access Plan Limits and Calculate Dynamic Limits Source: https://context7.com/maciek-roboblog/claude-code-usage-monitor/llms.txt Retrieve fixed token, cost, and message limits for predefined subscription plans or calculate a dynamic P90 token limit from historical session blocks for the 'custom' plan. The default token limit is used if no historical data is available. ```python from claude_monitor.core.plans import Plans, PlanType, get_token_limit, get_cost_limit # Enumerate all plans for plan_type, config in Plans.all_plans().items(): print(f"{config.display_name}: {config.formatted_token_limit} tokens, " f"${config.cost_limit:.2f} cost limit, {config.message_limit} msgs") # Pro: 19k tokens, $18.00 cost limit, 250 msgs # Max5: 88k tokens, $35.00 cost limit, 1000 msgs # Max20: 220k tokens, $140.00 cost limit, 2000 msgs # Custom: 44k tokens, $50.00 cost limit, 250 msgs # Fixed plan limit (no blocks needed) print(get_token_limit("pro")) # 19000 print(get_token_limit("max5")) # 88000 print(get_token_limit("max20")) # 220000 # Custom P90 limit from historical session blocks blocks = [ {"isGap": False, "isActive": False, "totalTokens": 40000}, {"isGap": False, "isActive": False, "totalTokens": 85000}, {"isGap": False, "isActive": True, "totalTokens": 22000}, # active — excluded ] dynamic_limit = get_token_limit("custom", blocks) print(dynamic_limit) # P90 of completed blocks, at least DEFAULT_TOKEN_LIMIT ``` -------------------------------- ### Check Claude data directory Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Verify the existence of the default Claude data directory (`~/.claude/projects`) and ensure you have active Claude Code sessions with recent messages. ```bash # Check if directory exists ls ~/.claude/projects # Start Claude Code session first # Go to claude.ai/code and send messages ``` -------------------------------- ### Enable debug logging Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md To debug session detection or other issues, enable debug logging for `claude-monitor` and direct the output to a file for review. ```bash # Enable debug logging claude-monitor --debug --log-file /tmp/claude-debug.log # Check logs tail -f /tmp/claude-debug.log ``` -------------------------------- ### Create Virtual Environment with virtualenv Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/README.md Use the virtualenv package to create a Python virtual environment if you prefer it over the built-in venv module. ```bash pip install virtualenv virtualenv venv ``` -------------------------------- ### Set Claude Monitor plan Source: https://github.com/maciek-roboblog/claude-code-usage-monitor/blob/main/TROUBLESHOOTING.md Specify the desired token limit plan for Claude Monitor using the `--plan` flag. Valid options include `pro`, `max5`, `max20`, and `custom`. ```bash # Correct plan names (case-insensitive) claude-monitor --plan pro # 44k tokens claude-monitor --plan max5 # 88k tokens claude-monitor --plan max20 # 220k tokens claude-monitor --plan custom # P90 auto-detection ```