Welcome to the complete documentation for OpenCode Monitor, a powerful CLI tool for monitoring and analyzing your OpenCode AI coding sessions.
📸 Screenshots: Throughout this documentation, you'll find clickable screenshot references that show actual command outputs. These screenshots are located in the
screenshots/directory. To add your own screenshots, replace the placeholder PNG files with actual screenshots of your terminal output.
🆕 Recent Updates: This documentation reflects the latest improvements including professional UI redesign, project analytics, session time tracking, and enhanced live dashboard features.
- Installation
- Basic Usage
- Command Reference
- Configuration
- Adding New Models
- Remote Pricing Fallback
- Currency Conversion
- Prometheus Metrics
- Setting Usage Quotas
- Exporting Reports
- Configuration Commands
- Troubleshooting
- Advanced Tips
Before installing OpenCode Monitor, ensure you have:
- Python 3.8+ installed on your system
- pip package manager (or pipx for isolated installs)
- OpenCode AI installed and configured
pipx is the recommended way to install OpenCode Monitor. It creates isolated Python environments and is the safest option across all platforms.
Advantages:
- ✅ No dependency conflicts with system packages
- ✅ Works on Arch Linux, Ubuntu, macOS, Windows
- ✅ No sudo required
- ✅ Easy to upgrade, uninstall, or manage multiple versions
- ✅ Automatically adds
ocmonitorto your PATH
# Clone the repository
git clone https://github.com/Shlomob/ocmonitor-share.git
cd ocmonitor-share
# Install with pipx (recommended)
pipx install .
# Or with optional extras:
pipx install ".[charts]" # Includes plotly for visualization
pipx install ".[export]" # Includes pandas for data export
pipx install ".[charts,export]" # All extrasInstalling pipx:
- Arch Linux:
sudo pacman -S python-pipx - Ubuntu/Debian:
sudo apt install pipx - macOS:
brew install pipx - Other:
python3 -m pip install --user pipx
For Linux and macOS users who prefer a traditional virtual environment setup:
# Clone the repository
git clone https://github.com/Shlomob/ocmonitor-share.git
cd ocmonitor-share
# Run the automated installer
./install.shThe installer will:
- ✅ Check Python version compatibility (3.8+)
- ✅ Create a virtual environment
- ✅ Install all required dependencies from
pyproject.toml - ✅ Configure PATH settings automatically
- ✅ Verify the installation
For development or custom setups:
# Clone the repository
git clone https://github.com/Shlomob/ocmonitor-share.git
cd ocmonitor-share
# Install Python dependencies
python3 -m pip install -r requirements.txt
# Install the package in development mode
python3 -m pip install -e ".[dev,charts,export]"Note: The project uses pyproject.toml for modern Python packaging. All dependencies are properly declared and will be installed automatically.
After installation, verify everything works:
# Check if ocmonitor is accessible
ocmonitor --version
ocmonitor --help
# Test with sample data
ocmonitor sessions test_sessions/
# Verify configuration
ocmonitor config showTroubleshooting pipx installs:
If ocmonitor command is not found after pipx install:
# Ensure pipx PATH is set up
pipx ensurepath
# Or manually add to your shell profile (~/.bashrc, ~/.zshrc)
export PATH="$HOME/.local/bin:$PATH"After installation, set up your personal configuration:
# Create configuration directory
mkdir -p ~/.config/ocmonitor
# Copy default configuration (if available in project)
cp config.toml ~/.config/ocmonitor/config.toml
# Or create a new configuration file
touch ~/.config/ocmonitor/config.toml
# Edit your configuration
nano ~/.config/ocmonitor/config.tomlYour configuration file should contain:
[paths]
messages_dir = "~/.local/share/opencode/storage/message"
export_dir = "./exports"
[ui]
table_style = "rich"
progress_bars = true
colors = trueIf you get "command not found" errors:
# Find your Python user base
python3 -m site --user-base
# Add to your shell profile (~/.bashrc or ~/.zshrc)
export PATH="$(python3 -m site --user-base)/bin:$PATH"
# Reload your shell
source ~/.bashrc # or ~/.zshrc# Show current configuration
ocmonitor config show
# Analyze all your sessions (auto-detects SQLite or files)
ocmonitor sessions
# Get a weekly breakdown
ocmonitor weekly
# Start live monitoring
ocmonitor live
# Force specific data source
ocmonitor live --source sqlite
ocmonitor sessions --source filesOpenCode v1.2.0+ uses SQLite database:
~/.local/share/opencode/opencode.db
Legacy versions (< v1.2.0) use flat JSON files:
~/.local/share/opencode/storage/message/
The tool automatically detects and uses the appropriate source. Use --source flag to force a specific backend.
These options can be used with any command:
| Option | Description | Example |
|---|---|---|
--config, -c |
Path to configuration file | --config /path/to/config.toml |
--theme, -t |
Set UI theme (dark or light) |
--theme light |
--verbose, -v |
Enable verbose output | --verbose |
--no-remote |
Disable remote pricing fallback | --no-remote |
--version |
Show version information | --version |
Use --no-remote to disable remote pricing fallback for a single command:
# Force local-only pricing for this session
ocmonitor --no-remote sessions
# Works with any command
ocmonitor --no-remote models
ocmonitor --no-remote daily --breakdownThis is useful when:
- You want to ensure only local pricing is used
- You're working offline and want to avoid fetch attempts
- Debugging pricing discrepancies
Analyze a single coding session in detail.
# Analyze a specific session directory
ocmonitor session ~/.local/share/opencode/storage/message/ses_20250118_143022
# With JSON output
ocmonitor session ~/.local/share/opencode/storage/message/ses_20250118_143022 --format jsonExample Output:
Click image to view full-size screenshot of session analysis output
#### `ocmonitor sessions [path]`
Analyze all sessions with summary statistics. Auto-detects SQLite database or legacy files.
```bash
# Analyze all sessions (auto-detect source)
ocmonitor sessions
# Specify path (legacy files only)
ocmonitor sessions ~/.local/share/opencode/storage/message
# Limit to recent sessions
ocmonitor sessions --limit 10
# Force specific source
ocmonitor sessions --source sqlite
ocmonitor sessions --source files
# JSON format for programmatic use
ocmonitor sessions --format json
Example Output:
Click image to view full-size screenshot of sessions summary output
### 2. Time-Based Analysis Commands
#### `ocmonitor daily <path>`
Daily usage breakdown with cost and token analysis.
```bash
# Daily breakdown
ocmonitor daily ~/.local/share/opencode/storage/message
# With per-model breakdown
ocmonitor daily ~/.local/share/opencode/storage/message --breakdown
# JSON output
ocmonitor daily ~/.local/share/opencode/storage/message --format json
Example Output:
Click image to view full-size screenshot of daily usage breakdown
#### `ocmonitor weekly <path> [--start-day <day>]`
Weekly usage patterns and trends with customizable week start days.
```bash
# Default (Monday start)
ocmonitor weekly ~/.local/share/opencode/storage/message
# Custom week start days
ocmonitor weekly ~/.local/share/opencode/storage/message --start-day sunday
ocmonitor weekly ~/.local/share/opencode/storage/message --start-day friday
# With per-model breakdown
ocmonitor weekly ~/.local/share/opencode/storage/message --start-day sunday --breakdown
# Specific year with custom week start
ocmonitor weekly ~/.local/share/opencode/storage/message --year 2025 --start-day wednesday
Supported Days: monday, tuesday, wednesday, thursday, friday, saturday, sunday
Features:
- 📅 Customize week boundaries to match your calendar preference
- 🗓️ US standard (Sunday), European (Monday), business week (Friday), etc.
- 📊 Date range display shows actual week boundaries
- 🎯 Table title indicates selected week start day
Monthly usage analysis and cost tracking.
# Monthly breakdown
ocmonitor monthly ~/.local/share/opencode/storage/message
# With per-model breakdown
ocmonitor monthly ~/.local/share/opencode/storage/message --breakdownDetailed breakdown of usage per AI model.
# Model usage statistics
ocmonitor models ~/.local/share/opencode/storage/message
# JSON format
ocmonitor models ~/.local/share/opencode/storage/message --format jsonExample Output:
Click image to view full-size screenshot of model usage analytics
Deep-dive detail for a single model. The name is fuzzy-matched against all known model names in the database.
# Exact or partial name — fuzzy matched
ocmonitor model claude-sonnet-4-5
ocmonitor model sonnet # lists all matching variants
ocmonitor model opus -f json # JSON output
ocmonitor model nonexistent # shows "No model found" + available listFuzzy Matching Behavior:
| Situation | Result |
|---|---|
| 0 matches | Shows "No model found" and lists all available model names |
| 1 match (or exact name) | Displays full detail panel + tool table |
| >1 matches | Lists candidates with "Did you mean one of these?" |
Output Layout:
╭─ Model Detail: claude-sonnet-4-5 ─────────────────────────────╮
│ First Used 2025-09-15 │
│ Last Used 2026-02-28 │
│ Sessions 42 │
│ Days Used 28 │
│ Interactions 1,247 │
│ │
│ Input Tokens 2,451,320 │
│ Output Tokens 489,210 │
│ Cache Read 1,102,400 │
│ Cache Write 312,500 │
│ │
│ Total Cost $47.23 │
│ Avg/Day $1.69 │
│ Avg/Session $1.12 │
│ │
│ Output Speed 62.4 tok/s (p50) │
╰─────────────────────────────────────────────────────────────────╯
Tool Usage for claude-sonnet-4-5
┏━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━┓
┃ Tool ┃ Calls ┃ Success ┃ Failed ┃ Success Rate ┃
┡━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━┩
│ read │ 620 │ 598 │ 22 │ 96% │
│ edit │ 412 │ 389 │ 23 │ 94% │
│ bash │ 298 │ 285 │ 13 │ 96% │
│ grep │ 156 │ 154 │ 2 │ 99% │
│ glob │ 134 │ 134 │ 0 │ 100% │
└────────┴───────┴─────────┴────────┴──────────────┘
Total tool calls: 1,620 1,560 succeeded 60 failed Overall: 96%
Options:
| Option | Description | Example |
|---|---|---|
--format, -f |
Output format (table, json, csv) |
-f json |
Notes:
- Requires SQLite database (OpenCode v1.2.0+). File-based storage is not supported for this command.
- Success rate colors: green ≥90%, yellow ≥70%, red <70%
- Output speed (p50) excludes tool-call-only interactions and interactions under 100 output tokens
Analyze AI usage costs and token consumption by coding project.
# Project usage breakdown
ocmonitor projects ~/.local/share/opencode/storage/message
# Filter by date range
ocmonitor projects ~/.local/share/opencode/storage/message --start-date 2024-01-01 --end-date 2024-01-31
# JSON format for detailed analysis
ocmonitor projects ~/.local/share/opencode/storage/message --format json
# CSV format for spreadsheet analysis
ocmonitor projects ~/.local/share/opencode/storage/message --format csvFeatures:
- 📊 Project Breakdown - Shows sessions, interactions, tokens, and costs per project
- 📈 Summary Statistics - Total projects, sessions, interactions, tokens, and cost
- 📅 Activity Tracking - First and last activity dates for each project
- 🤖 Model Usage - Lists AI models used for each project
- 📤 Export Support - Full export capabilities with detailed metadata
Example Output:
Project Usage Breakdown
┏━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
┃ Project ┃ Sessions ┃ Interactions ┃ Total Tokens ┃ Cost ┃ Models Used ┃
┡━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
│ ocmonitor │ 5 │ 12 │ 25,340 │ $0.0512 │ claude-sonnet-… │
│ myapp │ 3 │ 8 │ 18,200 │ $0.0364 │ claude-opus-4 │
│ website │ 2 │ 4 │ 8,150 │ $0.0163 │ grok-code │
└───────────┴──────────┴──────────────┴──────────────┴─────────┴─────────────────┘
╭────────────────────────────────── Summary ───────────────────────────────────╮
│ Total: 3 projects, 10 sessions, 24 interactions, 51,690 tokens, $0.10 │
╰──────────────────────────────────────────────────────────────────────────────╯
Real-time monitoring dashboard that updates automatically.
# Start live monitoring (updates every 5 seconds)
ocmonitor live ~/.local/share/opencode/storage/message
# Custom refresh interval (in seconds)
ocmonitor live ~/.local/share/opencode/storage/message --refresh 10Features:
- 🔄 Auto-refreshing display with professional UI redesign
- 📊 Real-time cost tracking with progress indicators
- ⏱️ Live session duration with 5-hour progress bar and color-coded time alerts
- 📈 Token usage updates and context window monitoring
- 🚦 Color-coded status indicators (green/orange/yellow/red based on time elapsed)
- 📂 Project name display for better context awareness
- 📝 Human-readable session titles replacing cryptic session IDs
- 🎨 Clean, professional styling with optimal space utilization
- 🔧 Tool Usage Stats - Real-time success rates for tools (bash, read, edit, etc.)
Click image to view full-size screenshot of the live monitoring dashboard
Start a Prometheus metrics server for Grafana/Prometheus integration.
# Start metrics server (default port 9090)
ocmonitor metrics
# Custom port
ocmonitor metrics --port 8080
# Custom host
ocmonitor metrics --host 127.0.0.1
# Scrape metrics
curl http://localhost:9090/metricsFeatures:
- 📊 Prometheus Format - Exposes metrics in Prometheus exposition format
- 🔄 Real-time Data - Fresh session data loaded on each scrape
- 🏷️ Labeled Metrics - Per-model and per-project labels for granular queries
- ⚙️ Configurable - Custom host and port via CLI flags or config
Metrics Exposed:
ocmonitor_tokens_input_total{model}- Input tokens per modelocmonitor_tokens_output_total{model}- Output tokens per modelocmonitor_cost_dollars_total{model}- Total cost per modelocmonitor_sessions_total{model}- Session count per modelocmonitor_session_duration_hours_total- Total session durationocmonitor_sessions_by_project{project}- Sessions by project
Note: Requires prometheus_client>=0.17.0. Install with pip install prometheus_client>=0.17.0
OpenCode Monitor uses a configuration file located at: ~/.config/ocmonitor/config.toml
# Create the configuration directory
mkdir -p ~/.config/ocmonitor
# Create your configuration file
touch ~/.config/ocmonitor/config.tomlOpenCode Monitor searches for configuration files in this order:
~/.config/ocmonitor/config.toml(recommended user location)config.toml(current working directory)ocmonitor.toml(current working directory)- Project directory fallback
OpenCode Monitor supports both SQLite database (OpenCode v1.2.0+) and legacy JSON files (< v1.2.0).
Edit your ~/.config/ocmonitor/config.toml file:
[paths]
# OpenCode v1.2.0+ SQLite database (preferred)
database_file = "~/.local/share/opencode/opencode.db"
# Legacy file storage (fallback for pre-v1.2.0)
messages_dir = "~/.local/share/opencode/storage/message"
# Directory for exports
export_dir = "./my-exports"# SQLite database path
export OCMONITOR_DATABASE_FILE="/custom/path/to/opencode.db"
# Legacy messages directory
export OCMONITOR_MESSAGES_DIR="/custom/path/to/messages"
# Use in commands
ocmonitor sessions# Force specific source
ocmonitor sessions --source sqlite
ocmonitor sessions --source files
# With legacy file path
ocmonitor sessions --source files /custom/path/to/messagesHere's a complete ~/.config/ocmonitor/config.toml with all available options:
# OpenCode Monitor Configuration
[paths]
# OpenCode v1.2.0+ SQLite database (preferred)
database_file = "~/.local/share/opencode/opencode.db"
# Legacy path to OpenCode messages directory (< v1.2.0)
messages_dir = "~/.local/share/opencode/storage/message"
# Directory for exports
export_dir = "./exports"
[ui]
# Table style: "rich", "simple", "minimal"
table_style = "rich"
# Enable progress bars
progress_bars = true
# Enable colors in output
colors = true
# Refresh interval for live dashboard (seconds)
live_refresh_interval = 5
[export]
# Default export format: "csv", "json"
default_format = "csv"
# Include metadata in exports
include_metadata = true
# Include raw data in exports
include_raw_data = false
[models]
# Path to models pricing configuration
config_file = "models.json"
# Remote pricing fallback from models.dev
# Automatically fetches pricing for models not in local files
remote_fallback = false
remote_url = "https://models.dev/api.json"
remote_timeout_seconds = 8
remote_cache_ttl_hours = 24
remote_cache_path = "~/.cache/ocmonitor/models_dev_api.json"
user_file = "~/.config/ocmonitor/models.json"
allow_stale_cache_on_error = true
[analytics]
# Default timeframe for reports: "daily", "weekly", "monthly"
default_timeframe = "daily"
# Number of recent sessions to analyze by default
recent_sessions_limit = 50
[quotas]
# Daily spending limits per model (in USD)
daily_limits = { claude-sonnet-4 = 10.0, claude-opus-4 = 20.0 }
# Monthly spending limits
monthly_limits = { claude-sonnet-4 = 200.0, claude-opus-4 = 400.0 }
# Enable quota warnings
enable_warnings = true
[metrics]
# Prometheus metrics server configuration
port = 9090
host = "0.0.0.0"
[currency]
# Display currency (ISO 4217 code): USD, GBP, EUR, CNY, JPY, INR, or custom
code = "USD"
symbol = "$"
# Conversion rate from USD (ignored when remote_rates = true)
rate = 1.0
# Display format: "symbol_prefix" ($1.23) or "code_suffix" (1.23 USD)
display_format = "symbol_prefix"
# Decimal places (auto if not set: JPY=0, most others=2)
# decimals = 2
# Live rate fetching from frankfurter.dev (free, no API key)
remote_rates = false
remote_rates_url = "https://api.frankfurter.dev/v1/latest?base=USD"
remote_rates_timeout_seconds = 8
remote_rates_cache_ttl_hours = 24
remote_rates_cache_path = "~/.cache/ocmonitor/exchange_rates.json"
allow_stale_rates_on_error = trueModels are defined in the models.json file. Each model includes pricing and technical specifications.
{
"claude-sonnet-4-20250514": {
"input": 3.0,
"output": 15.0,
"cacheWrite": 3.75,
"cacheRead": 0.30,
"contextWindow": 200000,
"sessionQuota": 6.00,
"description": "Claude Sonnet 4 (2025-05-14)"
},
"claude-opus-4": {
"input": 15.0,
"output": 75.0,
"cacheWrite": 18.75,
"cacheRead": 1.50,
"contextWindow": 200000,
"sessionQuota": 10.00,
"description": "Claude Opus 4"
},
"grok-code": {
"input": 0.0,
"output": 0.0,
"cacheWrite": 0.0,
"cacheRead": 0.0,
"contextWindow": 256000,
"sessionQuota": 0.0,
"description": "Grok Code (Free)"
}
}Add your new model to the models.json file:
{
"existing-models": "...",
"new-ai-model": {
"input": 5.0,
"output": 25.0,
"cacheWrite": 6.25,
"cacheRead": 0.50,
"contextWindow": 128000,
"sessionQuota": 15.0,
"description": "New AI Model"
},
"another-model": {
"input": 0.0,
"output": 0.0,
"cacheWrite": 0.0,
"cacheRead": 0.0,
"contextWindow": 100000,
"sessionQuota": 0.0,
"description": "Another Free Model"
}
}Test that your new model is recognized:
# Check if the model appears in configuration
ocmonitor config show
# Test with session data that uses the new model
ocmonitor sessions /path/to/sessionsFor models with provider prefixes (like provider/model-name), add both versions:
{
"provider/model-name": {
"input": 2.0,
"output": 10.0,
"cacheWrite": 2.5,
"cacheRead": 0.20,
"contextWindow": 150000,
"sessionQuota": 8.0,
"description": "Provider Model"
},
"model-name": {
"input": 2.0,
"output": 10.0,
"cacheWrite": 2.5,
"cacheRead": 0.20,
"contextWindow": 150000,
"sessionQuota": 8.0,
"description": "Provider Model (short name)"
}
}| Field | Description | Required | Example |
|---|---|---|---|
input |
Cost per 1M input tokens (USD) | ✅ | 3.0 |
output |
Cost per 1M output tokens (USD) | ✅ | 15.0 |
cacheWrite |
Cost per 1M cache write tokens (USD) | ✅ | 3.75 |
cacheRead |
Cost per 1M cache read tokens (USD) | ✅ | 0.30 |
contextWindow |
Maximum context window size | ✅ | 200000 |
sessionQuota |
Maximum session cost quota (USD) | ✅ | 6.00 |
description |
Human-readable model name | ❌ | "Claude Sonnet 4" |
input: Base cost for processing input tokens (prompt tokens)output: Cost for generating output tokens (response tokens)cacheWrite: Cost for writing tokens to cache (context caching feature)cacheRead: Cost for reading tokens from cache (much cheaper than input)contextWindow: Maximum number of tokens the model can process in one requestsessionQuota: Maximum cost limit per session (0 = no limit)description: Optional human-readable name for display purposes
For free models, set all costs to 0.0:
{
"free-model": {
"input": 0.0,
"output": 0.0,
"cacheWrite": 0.0,
"cacheRead": 0.0,
"contextWindow": 100000,
"sessionQuota": 0.0,
"description": "Free AI Model"
}
}OpenCode Monitor supports automatic pricing updates from models.dev, a community-maintained database of AI model pricing.
models.dev is an open-source project that maintains up-to-date pricing information for AI models from various providers. It provides a standardized API for accessing model costs, context windows, and rate limits.
When enabled, OpenCode Monitor will:
- Check local pricing first - Uses your local
models.jsonand user override file - Fetch from models.dev - Downloads current pricing for any missing models
- Cache the results - Stores data locally for 24 hours to minimize API calls
- Merge intelligently - Only fills gaps; never overwrites your local prices
Models are resolved in this order (highest to lowest priority):
- OpenCode's pre-computed cost - Used directly when present in session data
- User override file (
~/.config/ocmonitor/models.json) - Your personal overrides - Project/local
models.json- Project-specific pricing - models.dev remote fallback - Community pricing (fill-only, never overwrites)
Edit your ~/.config/ocmonitor/config.toml:
[models]
# Enable remote pricing fallback
remote_fallback = true
# Optional: customize settings
remote_url = "https://models.dev/api.json"
remote_timeout_seconds = 8
remote_cache_ttl_hours = 24
remote_cache_path = "~/.cache/ocmonitor/models_dev_api.json"
user_file = "~/.config/ocmonitor/models.json"
allow_stale_cache_on_error = true| Option | Description | Default |
|---|---|---|
remote_fallback |
Enable remote pricing fetch | false |
remote_url |
models.dev API endpoint | https://models.dev/api.json |
remote_timeout_seconds |
HTTP request timeout | 8 |
remote_cache_ttl_hours |
Cache validity period | 24 |
remote_cache_path |
Local cache file location | ~/.cache/ocmonitor/models_dev_api.json |
user_file |
User pricing overrides | ~/.config/ocmonitor/models.json |
allow_stale_cache_on_error |
Use expired cache if fetch fails | true |
For a single command:
ocmonitor --no-remote sessions
ocmonitor --no-remote modelsGlobally:
[models]
remote_fallback = falseThe remote pricing cache is stored at ~/.cache/ocmonitor/models_dev_api.json and is shared across all your OpenCode Monitor projects. This means:
- ✅ One download serves all projects
- ✅ Works offline after first fetch
- ✅ Automatically refreshes after TTL expires
- ✅ Uses file locking for safe concurrent access
If remote fetch fails (no internet, API down):
- ✅ Uses cached data if available (even if expired)
- ✅ Falls back to local-only pricing
- ✅ CLI continues working without errors
- ✅ No pricing gaps for known models
Create ~/.config/ocmonitor/models.json for personal pricing overrides:
{
"my-custom-model": {
"input": 5.0,
"output": 25.0,
"cacheWrite": 6.25,
"cacheRead": 0.50,
"contextWindow": 128000,
"sessionQuota": 15.0
},
"claude-sonnet-4": {
"input": 2.5,
"output": 12.0,
"sessionQuota": 5.0
}
}User overrides have highest priority and will overwrite any local or remote pricing.
{
"anthropic.claude-sonnet-4-20250514-v1:0": {
"input": 3.0,
"output": 15.0,
"cacheWrite": 3.75,
"cacheRead": 0.30,
"contextWindow": 1000000,
"sessionQuota": 10.0,
"description": "Claude Sonnet 4 (2025-05-14)"
}
}{
"gpt-4o": {
"input": 2.50,
"output": 10.0,
"cacheWrite": 0.0,
"cacheRead": 0.0,
"contextWindow": 128000,
"sessionQuota": 0.0,
"description": "GPT-4o"
}
}
}
---
## 💱 Currency Conversion
OpenCode Monitor supports displaying costs in your local currency instead of USD. All internal calculations remain in USD; conversion happens only at display and export time.
### Quick Setup
Edit your `~/.config/ocmonitor/config.toml`:
```toml
[currency]
code = "GBP"
symbol = "£"
rate = 0.79| Currency | Code | Symbol | Example Rate |
|---|---|---|---|
| US Dollar | USD | $ | 1.00 |
| British Pound | GBP | £ | 0.79 |
| Euro | EUR | € | 0.92 |
| Chinese Yuan | CNY | ¥ | 7.24 |
| Japanese Yen | JPY | ¥ | 149.50 |
| Indian Rupee | INR | ₹ | 83.12 |
| Option | Description | Default |
|---|---|---|
code |
ISO 4217 currency code | USD |
symbol |
Currency symbol | $ |
rate |
Conversion rate from USD | 1.0 |
display_format |
symbol_prefix ($1.23) or code_suffix (1.23 USD) |
symbol_prefix |
decimals |
Decimal places (auto if not set) | null |
remote_rates |
Enable live rate fetching | false |
remote_rates_url |
Exchange rate API endpoint | frankfurter.dev |
remote_rates_timeout_seconds |
API request timeout | 8 |
remote_rates_cache_ttl_hours |
Cache validity period | 24 |
Symbol Prefix (default):
display_format = "symbol_prefix"
# Output: $1.23, £0.99, €5.50Code Suffix:
display_format = "code_suffix"
# Output: 1.23 USD, 0.99 GBP, 5.50 EURCurrencies like JPY, KRW, and VND automatically use 0 decimal places unless explicitly configured:
[currency]
code = "JPY"
symbol = "¥"
rate = 149.50
# Output: ¥150 (0 decimals auto-applied)Enable automatic rate fetching from frankfurter.dev (free, no API key required):
[currency]
code = "EUR"
symbol = "€"
remote_rates = true
remote_rates_timeout_seconds = 8
remote_rates_cache_ttl_hours = 24How it works:
- Checks cache freshness before fetching
- Downloads latest rates from frankfurter.dev
- Caches results locally (24-hour TTL by default)
- Falls back to stale cache if fetch fails
- Falls back to configured
rateif no cache available
Cache location: ~/.cache/ocmonitor/exchange_rates.json
Exported reports include currency metadata:
JSON export:
{
"metadata": {
"currency": {
"code": "GBP",
"rate": 0.79
}
}
}CSV export:
# Currency: GBP (rate: 0.79 from USD)
session_id,cost,model
ses_123,$1.23,claude-sonnet-4OpenCode Monitor now includes a Prometheus metrics endpoint, allowing you to scrape session analytics into Prometheus and visualize them in Grafana.
Prometheus is an open-source monitoring system that collects metrics from configured targets. The ocmonitor metrics command starts a lightweight HTTP server that exposes session analytics in Prometheus exposition format, enabling real-time monitoring and alerting.
# Start metrics server with default settings (port 9090)
ocmonitor metrics
# Custom port
ocmonitor metrics --port 8080
# Custom host and port
ocmonitor metrics --host 127.0.0.1 --port 9090Startup Banner:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 OpenCode Monitor Metrics Server
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🌐 Endpoint: http://0.0.0.0:9090/metrics
Press Ctrl+C to stop
All metrics are exposed at http://localhost:9090/metrics (or your configured host/port):
| Metric Name | Type | Labels | Description |
|---|---|---|---|
ocmonitor_tokens_input_total |
Gauge | model |
Total input tokens |
ocmonitor_tokens_output_total |
Gauge | model |
Total output tokens |
ocmonitor_tokens_cache_read_total |
Gauge | model |
Total cache read tokens |
ocmonitor_tokens_cache_write_total |
Gauge | model |
Total cache write tokens |
ocmonitor_cost_dollars_total |
Gauge | model |
Total cost in USD |
ocmonitor_sessions_total |
Gauge | model |
Total number of sessions |
ocmonitor_interactions_total |
Gauge | model |
Total number of interactions |
ocmonitor_output_rate_tokens_per_second |
Gauge | model |
P50 output rate (tok/s) |
ocmonitor_session_duration_hours_total |
Gauge | (none) | Total session duration across all models |
ocmonitor_sessions_by_project |
Gauge | project |
Sessions grouped by project |
Using curl:
curl http://localhost:9090/metricsSample output:
# HELP ocmonitor_tokens_input_total Total input tokens
# TYPE ocmonitor_tokens_input_total gauge
ocmonitor_tokens_input_total{model="claude-sonnet-4-20250514"} 2451320.0
ocmonitor_tokens_input_total{model="claude-opus-4"} 892340.0
# HELP ocmonitor_cost_dollars_total Total cost in USD
# TYPE ocmonitor_cost_dollars_total gauge
ocmonitor_cost_dollars_total{model="claude-sonnet-4-20250514"} 47.23
ocmonitor_cost_dollars_total{model="claude-opus-4"} 89.45
# HELP ocmonitor_session_duration_hours_total Total session duration in hours
# TYPE ocmonitor_session_duration_hours_total gauge
ocmonitor_session_duration_hours_total 142.5
Add ocmonitor to your prometheus.yml:
scrape_configs:
- job_name: 'ocmonitor'
static_configs:
- targets: ['localhost:9090']
scrape_interval: 30sCreate a simple Grafana dashboard with PromQL queries:
Total Cost by Model:
ocmonitor_cost_dollars_total
Total Tokens Over Time:
sum(ocmonitor_tokens_input_total) + sum(ocmonitor_tokens_output_total)
Sessions by Project:
ocmonitor_sessions_by_project
Add to ~/.config/ocmonitor/config.toml:
[metrics]
port = 9090
host = "0.0.0.0"Environment Variables:
export OCMONITOR_METRICS_PORT=9090
export OCMONITOR_METRICS_HOST=0.0.0.0The metrics server uses Prometheus's Custom Collector pattern:
- On each scrape, the
collect()method is called - Fresh data is loaded from the SQLite database
- Metrics are computed using the existing SessionAnalyzer
- GaugeMetricFamily objects are yielded with current values
This design ensures:
- ✅ No background threads or polling
- ✅ Prometheus controls data freshness via scrape interval
- ✅ Always reflects the latest session data
- ✅ Graceful degradation on errors (returns zero-valued metrics)
The metrics feature requires prometheus_client:
# Install with metrics support
pip install "ocmonitor[metrics]"
# Or manually
pip install prometheus_client>=0.17.0Port already in use:
ocmonitor metrics --port 8080 # Use a different portMissing dependency:
pip install prometheus_client>=0.17.0Graceful shutdown:
Press Ctrl+C to stop the server cleanly.
Quotas help you monitor and control your AI usage costs by setting spending limits.
Edit ~/.config/ocmonitor/config.toml to set quota limits:
[quotas]
# Daily spending limits per model (in USD)
daily_limits = {
claude-sonnet-4 = 10.0,
claude-opus-4 = 20.0,
claude-opus-4.1 = 25.0
}
# Weekly spending limits
weekly_limits = {
claude-sonnet-4 = 50.0,
claude-opus-4 = 100.0
}
# Monthly spending limits
monthly_limits = {
claude-sonnet-4 = 200.0,
claude-opus-4 = 400.0,
"*" = 500.0 # Total limit across all models
}
# Enable quota warnings
enable_warnings = true
# Warning threshold (percentage of quota)
warning_threshold = 80.0
# Action when quota exceeded: "warn", "block"
quota_action = "warn"Set quotas using environment variables:
# Daily limits
export OCMONITOR_DAILY_CLAUDE_SONNET_4=10.0
export OCMONITOR_DAILY_CLAUDE_OPUS_4=20.0
# Monthly limits
export OCMONITOR_MONTHLY_TOTAL=500.0[quotas]
daily_limits = {
claude-sonnet-4 = 15.0, # $15/day for Sonnet
claude-opus-4 = 30.0 # $30/day for Opus
}
enable_warnings = true[quotas]
# Daily limits per model
daily_limits = {
claude-sonnet-4 = 10.0,
claude-opus-4 = 20.0,
"*" = 35.0 # Total daily limit
}
# Weekly limits
weekly_limits = {
claude-sonnet-4 = 60.0,
claude-opus-4 = 120.0,
"*" = 200.0
}
# Monthly limits
monthly_limits = {
claude-sonnet-4 = 250.0,
claude-opus-4 = 500.0,
"*" = 800.0
}
# Warning settings
enable_warnings = true
warning_threshold = 75.0 # Warn at 75% of quota
email_notifications = "admin@example.com"Check your current quota usage:
# Show quota status in daily report
ocmonitor daily ~/.local/share/opencode/storage/message --show-quotas
# Show quota status in model breakdown
ocmonitor models ~/.local/share/opencode/storage/message --show-quotasOpenCode Monitor provides powerful export capabilities for creating reports and integrating with other tools.
ocmonitor export <report_type> [path] [options]Export detailed session data:
# Export all sessions to CSV
ocmonitor export sessions --format csv --output sessions_report.csv
# Export to JSON
ocmonitor export sessions --format json --output sessions_data.json
# Export recent sessions only
ocmonitor export sessions --limit 50 --format csv
# Force SQLite source
ocmonitor export sessions --source sqlite --format csv# Export daily breakdown
ocmonitor export daily ~/.local/share/opencode/storage/message --format csv --output daily_usage.csv
# Last 30 days
ocmonitor export daily ~/.local/share/opencode/storage/message --days 30 --format json# Export weekly data
ocmonitor export weekly ~/.local/share/opencode/storage/message --format csv --output weekly_report.csv
# Last 12 weeks
ocmonitor export weekly ~/.local/share/opencode/storage/message --weeks 12 --format json# Export monthly analysis
ocmonitor export monthly ~/.local/share/opencode/storage/message --format csv --output monthly_analysis.csv
# Last 6 months
ocmonitor export monthly ~/.local/share/opencode/storage/message --months 6 --format json# Export model breakdown
ocmonitor export models ~/.local/share/opencode/storage/message --format csv --output model_usage.csv
# JSON format with metadata
ocmonitor export models ~/.local/share/opencode/storage/message --format json --include-metadata# Export project breakdown
ocmonitor export projects ~/.local/share/opencode/storage/message --format csv --output project_usage.csv
# JSON format with detailed metadata
ocmonitor export projects ~/.local/share/opencode/storage/message --format json --include-metadata
# Filter by date range
ocmonitor export projects ~/.local/share/opencode/storage/message --start-date 2024-01-01 --end-date 2024-01-31 --format csv| Option | Description | Example |
|---|---|---|
--format |
Output format (csv, json) |
--format csv |
--output |
Output filename | --output report.csv |
--limit |
Limit number of records | --limit 100 |
--days |
Number of days to include | --days 30 |
--weeks |
Number of weeks to include | --weeks 12 |
--months |
Number of months to include | --months 6 |
--include-metadata |
Include additional metadata | --include-metadata |
--include-raw-data |
Include raw session data | --include-raw-data |
--start-date |
Start date for filtering (YYYY-MM-DD) | --start-date 2024-01-01 |
--end-date |
End date for filtering (YYYY-MM-DD) | --end-date 2024-01-31 |
--timeframe |
Predefined timeframe filter | --timeframe weekly |
ocmonitor export sessions ~/.local/share/opencode/storage/message --format csv --output sessions.csvGenerated CSV Structure:
session_id,date,start_time,end_time,duration_minutes,model,total_cost,input_tokens,output_tokens,cache_tokens
ses_20250118_143022,2025-01-18,14:30:22,14:53:37,23.25,claude-sonnet-4,2.45,15420,8340,2100
ses_20250118_120830,2025-01-18,12:08:30,12:53:38,45.13,claude-opus-4,4.32,18650,9240,1850ocmonitor export sessions ~/.local/share/opencode/storage/message --format json --output sessions.json --include-metadataGenerated JSON Structure:
{
"metadata": {
"export_date": "2025-01-18T15:30:00Z",
"tool_version": "1.0.0",
"total_sessions": 25,
"date_range": {
"start": "2025-01-01",
"end": "2025-01-18"
}
},
"sessions": [
{
"session_id": "ses_20250118_143022",
"date": "2025-01-18",
"start_time": "14:30:22",
"end_time": "14:53:37",
"duration_minutes": 23.25,
"model": "claude-sonnet-4",
"total_cost": 2.45,
"tokens": {
"input": 15420,
"output": 8340,
"cache": 2100,
"total": 25860
},
"cost_breakdown": {
"input_cost": 0.46,
"output_cost": 1.25,
"cache_cost": 0.63,
"total_cost": 2.45
}
}
]
}Create a script for daily exports:
#!/bin/bash
# daily_export.sh
DATE=$(date +%Y%m%d)
EXPORT_DIR="./reports"
mkdir -p $EXPORT_DIR
# Export daily report
ocmonitor export daily \
--format csv \
--output "$EXPORT_DIR/daily_${DATE}.csv"
# Export sessions
ocmonitor export sessions \
--format json \
--output "$EXPORT_DIR/sessions_${DATE}.json" \
--include-metadata
echo "Reports exported to $EXPORT_DIR/"#!/bin/bash
# weekly_report.sh
WEEK=$(date +%Y_W%U)
ocmonitor export weekly \
--format csv \
--output "weekly_report_${WEEK}.csv" \
--weeks 1
ocmonitor export models \
--format csv \
--output "model_usage_${WEEK}.csv"The configuration command helps you manage and view your OpenCode Monitor settings.
# Display complete configuration
ocmonitor config showText Output Example:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ⚙️ Configuration ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
📁 Paths:
Messages Directory: ~/.local/share/opencode/storage/message
Export Directory: ./exports
🎨 UI Settings:
Table Style: rich
Progress Bars: enabled
Colors: enabled
Live Refresh: 5 seconds
📤 Export Settings:
Default Format: csv
Include Metadata: enabled
Include Raw Data: disabled
🤖 Models:
Configuration File: models.json
Supported Models: 6
📊 Analytics:
Default Timeframe: daily
Recent Sessions Limit: 50
# Show the full active configuration
ocmonitor config showocmonitor config show currently displays the full configuration. Section filtering options such as --section are not available in v1.0.3.
There is currently no separate ocmonitor config validate command. Configuration is validated automatically whenever ocmonitor starts and loads config.toml.
# Load and display the active configuration
ocmonitor config showIf the config file has invalid TOML syntax or unsupported values, ocmonitor will exit with an error before running the command.
# Show the full configuration
ocmonitor config showocmonitor config set exists in the CLI help, but it is currently a placeholder and does not write changes yet.
For now, edit the configuration file directly:
# Edit the user config file directly
$EDITOR ~/.config/ocmonitor/config.toml
# Then verify the updated config loads correctly
ocmonitor config showThere is currently no ocmonitor config reset command.
To reset to defaults, remove or rename your custom config file and rerun ocmonitor:
# Back up your user config
mv ~/.config/ocmonitor/config.toml ~/.config/ocmonitor/config.toml.bak
# Confirm the app now loads with default settings
ocmonitor config showIf you use a project-local config.toml or ocmonitor.toml, remove or rename that file instead.
There is currently no ocmonitor config paths command.
ocmonitor searches for configuration files in this order:
~/.config/ocmonitor/config.toml
./config.toml
./ocmonitor.toml
packaged default config bundled with ocmonitor
Example Output:
📁 Configuration File Locations:
Primary Configuration:
File: ~/.config/ocmonitor/config.toml
Status: ✅ Found (recommended location)
Project Configuration:
File: ./config.toml
Status: ❌ Not found (optional)
Models Configuration:
File: ./models.json
Status: ✅ Found
Environment Overrides:
OCMONITOR_MESSAGES_DIR: not set
OCMONITOR_EXPORT_DIR: not set
You can override any configuration setting using environment variables:
# Override messages directory
export OCMONITOR_MESSAGES_DIR="/custom/path"
# Override export format
export OCMONITOR_EXPORT_FORMAT="json"
# Override UI settings
export OCMONITOR_UI_COLORS="false"
export OCMONITOR_UI_TABLE_STYLE="simple"
# Use the overrides
ocmonitor config showProblem: Terminal shows command not found: ocmonitor
Solutions:
# Check if Python scripts directory is in PATH
echo $PATH | grep -o '[^:]*python[^:]*bin'
# Find Python user base
python3 -m site --user-base
# Add to PATH (add to ~/.bashrc or ~/.zshrc)
export PATH="$(python3 -m site --user-base)/bin:$PATH"
# Reload shell
source ~/.bashrc # or ~/.zshrc
# Alternative: Use full path
python3 /path/to/ocmonitor/run_ocmonitor.py --help
# Alternative: Reinstall in development mode
cd /path/to/ocmonitor
python3 -m pip install -e .Problem: Python import errors when running commands
Solutions:
Option 1: Use pipx (Recommended for dependency issues)
# Uninstall current version
pipx uninstall ocmonitor
# Reinstall with pipx (creates clean isolated environment)
cd /path/to/ocmonitor
pipx install .Option 2: Fix pip installation
# Check Python version
python3 --version # Should be 3.8+
# Reinstall dependencies
python3 -m pip install -r requirements.txt --force-reinstall
# Check for missing dependencies
python3 -c "import click, rich, pydantic, toml; print('All dependencies OK')"
# Install specific missing package
python3 -m pip install click rich pydantic toml
# Clear Python cache
find . -name "__pycache__" -type d -exec rm -rf {} +
find . -name "*.pyc" -deleteProblem: Architecture mismatch errors (arm64 vs x86_64)
Solutions:
# Check system architecture
uname -m
# For Apple Silicon Macs, use native Python
which python3
/opt/homebrew/bin/python3 --version
# Reinstall with correct architecture
python3 -m pip uninstall pydantic pydantic-core
python3 -m pip install pydantic pydantic-core --no-cache-dir
# Force reinstall all dependencies
python3 -m pip install -r requirements.txt --force-reinstall --no-cache-dirProblem: Messages directory not found error
Solutions:
# Check if OpenCode is installed
which opencode
# Check default location
ls -la ~/.local/share/opencode/storage/message
# Find OpenCode data directory
find ~ -name "opencode" -type d 2>/dev/null
# Check OpenCode configuration
opencode config list 2>/dev/null | grep storage
# Set the messages directory by editing config.toml directly
$EDITOR ~/.config/ocmonitor/config.toml
# Verify the configuration loads correctly
ocmonitor config showProblem: Errors when reading session files
Solutions:
# Check for corrupted session files
find ~/.local/share/opencode/storage/message -name "*.json" -exec python3 -m json.tool {} \; > /dev/null
# Find specific problematic files
find ~/.local/share/opencode/storage/message -name "*.json" -print0 | while IFS= read -r -d '' file; do
python3 -m json.tool "$file" > /dev/null 2>&1 || echo "Invalid JSON: $file"
done
# Test with specific session
ocmonitor session ~/.local/share/opencode/storage/message/problematic_session
# Use verbose mode for debugging
ocmonitor sessions ~/.local/share/opencode/storage/message --verboseProblem: Permission denied errors when accessing files
Solutions:
# Check file permissions
ls -la ~/.local/share/opencode/storage/message
# Fix permissions if needed
chmod -R 755 ~/.local/share/opencode/storage/message
# Check if export directory is writable
mkdir -p ./exports
touch ./exports/test.txt && rm ./exports/test.txt
# Use an alternative export directory by editing config.toml directly
$EDITOR ~/.config/ocmonitor/config.tomlProblem: "Unknown model" in reports
Solutions:
# Check which models are configured
ocmonitor config show
# View current models.json
cat models.json
# Find unrecognized model names in your data
grep -r "model.*:" ~/.local/share/opencode/storage/message | grep -v claude | grep -v grok | head -5
# Add missing model to models.json
# Edit models.json and add the new model configuration
# Verify the models configuration loads correctly
ocmonitor config showProblem: Export commands fail or produce empty files
Solutions:
# Test export with verbose output
ocmonitor export sessions --format csv --output test.csv --verbose
# Check export directory permissions
ls -la ./exports
# Try different export format
ocmonitor export sessions --format json --output test.json
# Test with limited data
ocmonitor export sessions --limit 5 --format csv
# Check disk space
df -h .Problem: Sessions not found after upgrading OpenCode to v1.2.0+
Solutions:
# Check if SQLite database exists
ls -la ~/.local/share/opencode/opencode.db
# Verify data source detection
ocmonitor sessions --verbose
# Force SQLite mode
ocmonitor sessions --source sqlite
# Check for legacy files (pre-v1.2.0)
ls -la ~/.local/share/opencode/storage/message/
# Update the database location by editing config.toml directly
$EDITOR ~/.config/ocmonitor/config.tomlNote: OpenCode v1.2.0+ stores sessions in SQLite at ~/.local/share/opencode/opencode.db. The tool automatically detects and prefers SQLite when available, falling back to legacy files only when SQLite is not found.
# Run any command with verbose output
ocmonitor sessions ~/.local/share/opencode/storage/message --verbose
# Set debug environment variable
export OCMONITOR_DEBUG=1
ocmonitor sessions ~/.local/share/opencode/storage/messageThere is currently no ocmonitor config system-info command. When reporting issues, include the following command output instead:
ocmonitor --version
python3 --version
uname -a
ocmonitor config showWhen reporting issues, include:
-
System Information:
ocmonitor --version python3 --version uname -a
-
Error Messages: Full error output with
--verboseflag -
Configuration:
ocmonitor config show
-
Steps to Reproduce: Exact commands that cause the issue
- 🐛 GitHub Issues: For bug reports and feature requests
- 💬 Discussions: For questions and community help
- 📚 Documentation: Check this guide and README files
The --breakdown flag adds per-model token consumption and cost details to daily, weekly, and monthly reports.
# Show model breakdown in daily report
ocmonitor daily --breakdown
# Show model breakdown in weekly report
ocmonitor weekly --breakdown
# Show model breakdown in monthly report
ocmonitor monthly --breakdownExample Output:
Daily Usage Breakdown
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━┓
┃ Date / Model ┃ Sessions ┃ Interactions┃ Total Tokens┃ Cost ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━┩
│ 2024-01-13 │ 1 │ 2 │ 1,150 │ $0.0128 │
│ ↳ claude-sonnet-4-20250514 │ 1 │ 2 │ 1,150 │ $0.0128 │
│ 2024-01-14 │ 1 │ 1 │ 5,200 │ $0.0000 │
│ ↳ grok-code │ 1 │ 1 │ 5,200 │ $0.0000 │
└────────────────────────────────┴──────────┴────────────┴───────────┴─────────┘
Features:
- Model rows indented and styled distinctly
- Shows sessions, interactions, tokens, and cost per model
- Models sorted by cost (descending)
- Total row shows aggregate values
# Process large datasets efficiently
ocmonitor sessions --limit 1000
# Use JSON format for faster processing
ocmonitor sessions --format json | jq '.sessions | length'
# Focus on recent data
ocmonitor daily --days 7# Export multiple reports with different filters
ocmonitor sessions --limit 100 --format csv --output recent_sessions.csv
ocmonitor weekly --weeks 4 --format json --output last_month.json
ocmonitor projects --format csv --output all_projects.csv#!/bin/bash
# Monthly cost check script
COST=$(ocmonitor monthly --format json | jq '.summary.total_cost')
LIMIT=100.0
if (( $(echo "$COST > $LIMIT" | bc -l) )); then
echo "⚠️ Monthly cost $COST exceeds limit $LIMIT"
# Send notification, email, etc.
fi# Export for data analysis
ocmonitor export sessions \
--format json \
--include-raw-data \
--output sessions.json
# Export project data for analysis
ocmonitor export projects \
--format json \
--include-metadata \
--output projects.json
# Process with jq
cat sessions.json | jq '.sessions[] | select(.total_cost > 5.0)'
cat projects.json | jq '.projects[] | select(.cost > 10.0)'
# Import into database (example)
python3 scripts/import_to_db.py sessions.json
python3 scripts/import_projects_to_db.py projects.jsonCreate custom export formats:
#!/usr/bin/env python3
# custom_export.py
import json
import sys
from datetime import datetime
def custom_export(sessions_file):
with open(sessions_file) as f:
data = json.load(f)
# Custom processing
for session in data['sessions']:
print(f"{session['date']},{session['model']},{session['total_cost']}")
if __name__ == "__main__":
custom_export(sys.argv[1])Usage:
ocmonitor export sessions --format json --output temp.json
python3 custom_export.py temp.json > custom_report.csvCreate configuration templates for different use cases:
# Development configuration
cp ~/.config/ocmonitor/config.toml ~/.config/ocmonitor/config.dev.toml
# Edit development settings
nano ~/.config/ocmonitor/config.dev.toml
# Production configuration
cp ~/.config/ocmonitor/config.toml ~/.config/ocmonitor/config.prod.toml
# Edit production settings
nano ~/.config/ocmonitor/config.prod.toml
# Use specific configuration
OCMONITOR_CONFIG=~/.config/ocmonitor/config.dev.toml ocmonitor sessionsOpenCode Monitor uses pytest for testing. Tests are organized in tests/:
tests/unit/- Unit tests for individual modulestests/integration/- CLI integration teststests/conftest.py- Shared fixtures
# Run all tests
pytest
# Run only unit tests
pytest -m unit
# Run only integration tests
pytest -m integration
# Run with coverage
pytest --cov=ocmonitorThis completes the comprehensive documentation for OpenCode Monitor. For additional help, please refer to the GitHub repository or file an issue for support.




