Metadata-Version: 2.4
Name: fastpluggy-claude-monitor
Version: 0.1.11
Summary: Claude Code session monitoring plugin for FastPluggy
Author: FastPluggy Team
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: fastpluggy>=0.4.21
Requires-Dist: fastpluggy-websocket-tool>=0.1.0
Requires-Dist: fastpluggy-tasks-worker>=0.3.253
Requires-Dist: httpx
Requires-Dist: psutil
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Provides-Extra: tests
Requires-Dist: pytest>=7.0; extra == "tests"
Requires-Dist: pytest-cov>=4.0; extra == "tests"
Provides-Extra: e2e
Requires-Dist: fastpluggy-cli; extra == "e2e"

# Claude Monitor Plugin

![Claude Monitor](https://img.shields.io/badge/FastPluggy-Claude%20Monitor-blue)
[![Release](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/claude_monitor/-/badges/release.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/claude_monitor/-/releases)
[![Pipeline Status](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/claude_monitor/badges/main/pipeline.svg?key_text=CI)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/claude_monitor/-/pipelines?ignore_skipped=true)
[![Coverage](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/claude_monitor/badges/main/coverage.svg)](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/claude_monitor/-/pipelines)

A FastPluggy plugin that provides a web dashboard for monitoring running and recent Claude Code sessions.

## Features

- Session discovery from `~/.claude/projects/`
- Token usage tracking (input, output, cache)
- Active session detection (via file mtime + process detection)
- Cost estimation per model
- Per-command cost breakdown — see which slash commands cost the most (`/implement`, `/plan`, etc.)
- Cache efficiency metrics — hit ratio and estimated savings from prompt caching
- Push notifications when Claude needs tool approval (via notification_center VAPID)
- **Usage Analytics** — per-session diagnostics with token growth charts, expensive action detection, and burn rate projection
- **Recommendations engine** — configurable rules that flag inefficient usage patterns (context snowball, low cache efficiency, large file reads)

## Install

```bash
pip install -e ".[dev]"
```

## Usage

Once installed, the plugin registers at `/plugin/claude_monitor/` and appears in the FastPluggy sidebar menu.

## Usage Pages

Three usage tabs accessible from the sidebar:

- **Cost Breakdown** (`/usage/costs`) — estimated costs based on token counts and model rates. Supports daily/weekly/monthly/all-time periods with budget tracking.
- **Live Usage** (`/usage/live`) — real subscription utilization from the Claude OAuth API. Shows 5-hour and 7-day windows that determine throttling. Includes burn rate projection (linear/WMA).
- **Usage Trends** (`/usage/history`) — historical utilization trends over time with charts.
- **Session Analytics** (`/session/{id}/analytics`) — per-session token growth charts, cache efficiency, expensive actions table, and actionable recommendations.

### Prometheus metrics (`metrics` plugin)

Claude Monitor implements the `MetricsProvider` capability, so when the
[`fastpluggy-metrics`](https://gitlab.ggcorp.fr/open/fastpluggy/plugins/metrics)
plugin is installed in the same app, the real OAuth plan-usage is exposed at its
`/plugin-pkg/metrics/api/prometheus` endpoint (prefixed `fp_claude_monitor_`):

| Metric | Labels | Meaning |
|---|---|---|
| `fp_claude_monitor_plan_utilization_percent` | `window` (5h/7d), `model` (all/opus/sonnet) | Subscription utilization 0–100 |
| `fp_claude_monitor_plan_window_resets_at_seconds` | `window`, `model` | Unix ts of window reset |
| `fp_claude_monitor_plan_extra_credits_used` | — | Extra-usage credits this month |
| `fp_claude_monitor_plan_extra_monthly_limit_dollars` | — | Extra-usage monthly limit |
| `fp_claude_monitor_plan_last_fetch_seconds` | — | Unix ts of last good fetch |
| `fp_claude_monitor_plan_data_stale` | — | 1 if snapshot missing/>30 min old |
| `fp_claude_monitor_plan_info` | `subscription_type`, `rate_limit_tier` | Metadata (value 1) |

No extra endpoint or config in this plugin — the `metrics` plugin scrapes the
provider. Same data as `/usage/live/summary`, so Prometheus matches the dashboard.

### OAuth token self-refresh (headless / container use)

By default the plugin refreshes the OAuth access token itself (via the stored `refresh_token`) when it nears expiry, writing the rotated token back to the credentials file. This lets `claude_monitor` run on a host that does **not** run the Claude CLI (e.g. a headless container) without the token going stale.

> ⚠️ Only enable this when the instance is the **sole** user of those credentials (a dedicated login). If both this plugin and a running Claude CLI refresh the same credentials, the rotating refresh token will invalidate one of them.

Settings (env prefix `CLAUDE_MONITOR_`):

| Setting | Default | Purpose |
|---|---|---|
| `oauth_self_refresh` | `true` | Enable/disable self-refresh |
| `oauth_refresh_skew_seconds` | `300` | Refresh when within N seconds of expiry |
| `oauth_token_url` | `https://console.anthropic.com/v1/oauth/token` | Token endpoint |
| `oauth_client_id` | Claude Code public client id | Client id for the refresh grant |

#### Bootstrapping credentials onto a headless host

Self-refresh keeps a token alive, but the headless instance still needs a *first*
valid `~/.claude/.credentials.json` — and a host with no browser can't run
`claude /login` itself. Use [`scripts/bootstrap-headless-creds.sh`](scripts/bootstrap-headless-creds.sh)
from a workstation that has a browser: it does an **isolated** login (a separate
config dir, so your personal `~/.claude` is untouched and the headless instance
gets its own independent token chain — see the warning above), validates the
result, and ships it to the remote host over `scp` + `sudo install`.

```bash
REMOTE_HOST=myhost \
REMOTE_PATH=/data/claude-monitor/.credentials.json \
VERIFY_URL=http://myhost:18090/plugin-pkg/claude_monitor/api/usage/live \
  ./scripts/bootstrap-headless-creds.sh
```

The only manual step is completing the browser auth; with `VERIFY_URL` set it
then probes the live endpoint so you can confirm real numbers come back.

## Remote Control

Claude Monitor hooks into Claude Code's hook system to remotely control sessions from the browser.

- **Approval dashboard** (`/pending-approvals`) — approve, reject, or edit tool calls before they execute
- **Auto-approve rules** (`/auto-approve`) — configure glob/regex patterns to skip the dashboard for trusted tools (e.g. `Read`, `Glob`)
- **Session control** — stop sessions, inject system messages, or suppress output via the API
- **Command bar** — quick actions from the session detail page: `/approve`, `/reject`, `/stop`, `/inject`
- **Event stream** (`/events`) — live feed of all hook events with type and session filtering
- **SDK mode** — start headless Claude tasks from the dashboard via `claude-monitor-hook run`
- **WebSocket real-time updates** — instant approval UX via `websocket_tool` integration (no polling needed in the browser)

### Hook CLI

The `claude-monitor-hook` CLI is installed as a console_scripts entry point:

```bash
claude-monitor-hook pre-tool-use --api-base http://localhost:8000/plugin/claude_monitor
claude-monitor-hook permission-request --api-base http://localhost:8000/plugin/claude_monitor
claude-monitor-hook forward --api-base http://localhost:8000/plugin/claude_monitor
claude-monitor-hook run -p "describe this codebase" --api-base http://localhost:8000/plugin/claude_monitor
```

Visit `/api/hook-config` for a ready-to-paste `settings.json` snippet.
