> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ccs.kaitran.ca/llms.txt
> Use this file to discover all available pages before exploring further.

# Usage Analytics API

> REST API endpoints for Claude Code usage tracking and analytics

# Usage Analytics API

Track token usage, costs, and usage patterns across all Claude Code sessions. The usage analytics system aggregates data from JSONL files and provides multiple views of consumption data.

## Overview

The usage API provides endpoints for:

* Daily, hourly, and monthly usage summaries
* Per-model cost breakdowns
* Session history and project tracking
* Anomaly detection for cost spikes
* Real-time cache status

## Authentication

All endpoints are available on localhost only ([http://localhost:3000](http://localhost:3000)). No authentication required.

## Endpoints

### GET /api/usage/summary

Get overall usage summary with total tokens, cost, and daily averages.

**Query Parameters:**

* `since` (optional): Start date in YYYYMMDD format
* `until` (optional): End date in YYYYMMDD format

<CodeGroup>
  ```bash Request theme={null}
  curl "http://localhost:3000/api/usage/summary?since=20260101&until=20260131"
  ```

  ```json Response theme={null}
  {
    "totalTokens": 15000000,
    "totalCost": 45.50,
    "inputTokens": 10000000,
    "outputTokens": 5000000,
    "cacheReadTokens": 2000000,
    "cacheWriteTokens": 500000,
    "dailyAverage": {
      "tokens": 500000,
      "cost": 1.52
    },
    "dateRange": {
      "from": "2026-01-01",
      "to": "2026-01-31"
    },
    "modelsUsed": ["claude-sonnet-4", "gemini-3-flash"]
  }
  ```
</CodeGroup>

***

### GET /api/usage/daily

Get daily usage trends with per-day breakdowns.

<CodeGroup>
  ```bash Request theme={null}
  curl http://localhost:3000/api/usage/daily
  ```

  ```json Response theme={null}
  {
    "daily": [
      {
        "date": "2026-01-05",
        "inputTokens": 450000,
        "outputTokens": 200000,
        "cacheReadTokens": 100000,
        "cacheWriteTokens": 25000,
        "cost": 1.85,
        "modelsUsed": ["claude-sonnet-4", "gemini-3-flash"],
        "modelBreakdown": {
          "claude-sonnet-4": {
            "inputTokens": 300000,
            "outputTokens": 150000,
            "cost": 1.35
          },
          "gemini-3-flash": {
            "inputTokens": 150000,
            "outputTokens": 50000,
            "cost": 0.50
          }
        }
      }
    ]
  }
  ```
</CodeGroup>

***

### GET /api/usage/hourly

Get hourly usage trends for detailed time-series analysis. Includes gap filling for continuous charts.

<CodeGroup>
  ```bash Request theme={null}
  curl http://localhost:3000/api/usage/hourly
  ```

  ```json Response theme={null}
  {
    "hourly": [
      {
        "hour": "2026-01-05 14:00",
        "inputTokens": 50000,
        "outputTokens": 20000,
        "cacheReadTokens": 10000,
        "cacheWriteTokens": 2500,
        "cost": 0.21,
        "modelsUsed": ["claude-sonnet-4"]
      },
      {
        "hour": "2026-01-05 15:00",
        "inputTokens": 0,
        "outputTokens": 0,
        "cost": 0,
        "modelsUsed": []
      }
    ]
  }
  ```
</CodeGroup>

***

### GET /api/usage/models

Get per-model usage statistics with cost breakdowns and I/O ratios.

<CodeGroup>
  ```bash Request theme={null}
  curl http://localhost:3000/api/usage/models
  ```

  ```json Response theme={null}
  {
    "models": [
      {
        "model": "claude-sonnet-4",
        "inputTokens": 8000000,
        "outputTokens": 3500000,
        "cacheReadTokens": 1500000,
        "cacheWriteTokens": 400000,
        "cost": 32.50,
        "percentage": 71.4,
        "ioRatio": 2.29
      },
      {
        "model": "gemini-3-flash",
        "inputTokens": 2000000,
        "outputTokens": 1500000,
        "cost": 13.00,
        "percentage": 28.6,
        "ioRatio": 1.33
      }
    ],
    "totalCost": 45.50
  }
  ```
</CodeGroup>

***

### GET /api/usage/insights

Get usage anomalies and insights for cost optimization.

<CodeGroup>
  ```bash Request theme={null}
  curl http://localhost:3000/api/usage/insights
  ```

  ```json Response theme={null}
  {
    "anomalies": [
      {
        "type": "cost_spike",
        "date": "2026-01-04",
        "value": 5.20,
        "threshold": 2.50,
        "message": "Daily cost 208% above average"
      },
      {
        "type": "high_input",
        "date": "2026-01-03",
        "value": 12000000,
        "threshold": 10000000,
        "message": "Input tokens exceeded 10M threshold"
      }
    ],
    "thresholds": {
      "highInput": 10000000,
      "highIoRatio": 100,
      "costSpikeMultiplier": 2,
      "highCacheRead": 1000000000
    }
  }
  ```
</CodeGroup>

**Anomaly Types:**

* `cost_spike`: Daily cost significantly above average
* `high_input`: Input tokens exceed 10M threshold
* `high_io_ratio`: Input-to-output ratio exceeds 100:1
* `high_cache_read`: Cache read tokens exceed 1B

***

### GET /api/usage/sessions

Get session history with pagination support.

**Query Parameters:**

* `limit` (optional): Number of sessions to return (default: 50)
* `offset` (optional): Pagination offset (default: 0)

<CodeGroup>
  ```bash Request theme={null}
  curl "http://localhost:3000/api/usage/sessions?limit=10&offset=0"
  ```

  ```json Response theme={null}
  {
    "sessions": [
      {
        "sessionId": "abc123",
        "projectPath": "~/projects/my-app",
        "lastActivity": "2026-01-05T14:30:00Z",
        "inputTokens": 100000,
        "outputTokens": 50000,
        "cost": 0.45,
        "modelsUsed": ["claude-sonnet-4"],
        "version": "1.2.3"
      }
    ],
    "total": 150,
    "limit": 10,
    "offset": 0
  }
  ```
</CodeGroup>

***

### GET /api/usage/monthly

Get monthly aggregated usage data.

<CodeGroup>
  ```bash Request theme={null}
  curl http://localhost:3000/api/usage/monthly
  ```

  ```json Response theme={null}
  {
    "monthly": [
      {
        "month": "2026-01",
        "inputTokens": 10000000,
        "outputTokens": 5000000,
        "cacheReadTokens": 2000000,
        "cacheWriteTokens": 500000,
        "cost": 45.50
      },
      {
        "month": "2025-12",
        "inputTokens": 8000000,
        "outputTokens": 4000000,
        "cost": 36.00
      }
    ]
  }
  ```
</CodeGroup>

***

### POST /api/usage/refresh

Force cache refresh to fetch latest usage data.

<CodeGroup>
  ```bash Request theme={null}
  curl -X POST http://localhost:3000/api/usage/refresh
  ```

  ```json Response theme={null}
  {
    "success": true,
    "message": "Cache cleared, refreshing data",
    "timestamp": 1704467400000
  }
  ```
</CodeGroup>

***

### GET /api/usage/status

Get cache status and last fetch timestamp.

<CodeGroup>
  ```bash Request theme={null}
  curl http://localhost:3000/api/usage/status
  ```

  ```json Response theme={null}
  {
    "cached": true,
    "lastFetch": 1704467400000,
    "lastFetchHuman": "2026-01-05T14:30:00Z",
    "cacheAge": 120000,
    "cacheAgeHuman": "2 minutes ago"
  }
  ```
</CodeGroup>

## Caching Strategy

The usage API uses a three-tier caching system:

1. **In-Memory Cache**: TTL varies by endpoint (1-5 minutes)
2. **Disk Cache**: Persisted to `~/.ccs/.cache/usage-cache.json` (7-day stale TTL)
3. **Stale-While-Revalidate**: Returns stale cache immediately, refreshes in background

### Cache Behavior

* **Fresh Cache** (\<1 min): Instant response from memory
* **Stale Cache** (1-7 days): Instant response, background refresh
* **No Cache**: Blocking fetch from JSONL files

## Data Sources

Usage data is aggregated from:

* `~/.claude/projects/*/usage.jsonl` - Default Claude directory
* `~/.ccs/instances/*/usage.jsonl` - CCS account instances

## Model Pricing

Costs are calculated using built-in pricing for:

* Claude (Haiku, Sonnet, Opus variants)
* OpenAI (GPT-4o, o1, o3, Codex)
* Google Gemini (Flash, Pro)
* GLM, Kimi, MiniMax, DeepSeek, Mistral

Pricing includes input/output tokens, cache creation, and cache reads.

## Error Responses

<CodeGroup>
  ```json 500 Server Error theme={null}
  {
    "error": "Failed to fetch usage data",
    "message": "Detailed error message"
  }
  ```

  ```json 503 Service Unavailable theme={null}
  {
    "error": "Cache unavailable",
    "message": "No cached data available and fetch failed"
  }
  ```
</CodeGroup>
