Skill: rusel95/token-usage-optimizer (version 1.0.5)

--- name: token-usage-optimizer version: 1.0.5 description: Maximize your Claude Code subscription value with smart usage monitoring and burn rate optimization. Track 5-hour session and 7-day weekly quotas, get one-time alerts, and daily reports showing if you're under/over-using your $20-200/month plan. Ultra-lightweight (10min cache, minimal API calls). Perfect for Pro, Max 100, and Max 200 subscribers who want to get every dollar's worth. metadata: clawdbot: emoji: "📊" os: - darwin - linux requires: bins: - curl - date - grep --- # Token Usage Optimizer **Version:** 1.0.5 **Get the most out of your Claude Code subscription** by monitoring usage in real-time and optimizing your daily burn rate. ## Why Use This? You're paying $20-200/month for Claude Code. Are you: - ✅ Using it to its full potential? - ❌ Hitting limits too early? - ❌ Leaving quota unused at reset? This skill tracks your **5-hour session** and **7-day weekly** quotas, calculates your **daily burn rate**, and tells you if you should use more or throttle back. ## Features - 📊 **Burn Rate Tracking** — Are you under/over/on-pace for optimal usage? - ⚡ **Smart Alerts** — One-time warnings when SESSION > 50% (no spam) - 🎯 **Plan-Aware** — Auto-detects Pro ($20), Max 100 ($100), Max 200 ($200) - 💾 **Ultra-Lightweight** — 10-minute cache, minimal API calls - 📅 **Daily Reports** — Evening summary: SESSION, WEEKLY, burn rate - 🔄 **Token Health Check** — Hourly check + alert if manual refresh needed (~once per week) ## Quick Start ### 1. Setup Run the setup wizard to configure your OAuth tokens: ```bash cd {baseDir} ./scripts/setup.sh ``` You'll need: - **Access Token** (`sk-ant-oat01-...`) - **Refresh Token** (`sk-ant-ort01-...`) See `references/token-extraction.md` for how to get these. ### 2. Check Usage ```bash ./scripts/check-usage.sh ``` Output: ``` SESSION=22.0 WEEKLY=49.0 BURN_RATE=OK CACHED_AT=1771583780 ``` ### 3. Human-Readable Report ```bash ./scripts/report.sh ``` Output: ``` 📊 Claude Code Daily Check: ⏱️ SESSION (5h): 22% 📅 WEEKLY (7d): 49% ⚪ На темпі — оптимальне використання ``` ## Burn Rate Interpretation - **🟢 UNDER** — You're under-using your subscription. Use more to get your money's worth! - **⚪ OK** — On pace. Optimal usage for your plan. - **🔴 OVER** — Over-burning. You'll hit limits before reset. ## Daily Budget by Plan | Plan | Monthly | Weekly Budget | Daily Budget | |------|---------|---------------|--------------| | Pro | $20 | ~14% | ~2% | | Max 100 | $100 | ~14% | ~2% | | Max 200 | $200 | ~14% | ~2% | *(7-day window resets weekly, so ~14% per day = 100% per week)* ## Integration with Heartbeat Add to your `HEARTBEAT.md`: ```markdown ### Evening Check (18:00-20:00) - Claude Code usage: `/path/to/token-usage-optimizer/scripts/report.sh` ``` ## Alert Thresholds - **SESSION > 50%** → 🟡 One-time warning (won't repeat until next reset) - **WEEKLY > 80%** → 🟡 One-time warning Alerts use state tracking (`/tmp/claude-usage-alert-state`) to avoid spam. ## Cache Default: `/tmp/claude-usage.cache` with 10-minute TTL. Override: ```bash CACHE_FILE=/custom/path CACHE_TTL=300 ./scripts/check-usage.sh ``` ## Files - `scripts/setup.sh` — Initial token configuration - `scripts/check-usage.sh` — Core usage checker (cached, burn rate calc) - `scripts/report.sh` — Human-readable daily report - `references/api-endpoint.md` — Anthropic OAuth API docs - `references/token-extraction.md` — How to get OAuth tokens - `references/plans.md` — Claude Code subscription tiers ## API Endpoint ``` GET https://api.anthropic.com/api/oauth/usage Authorization: Bearer <access-token> anthropic-beta: oauth-2025-04-20 ``` Response: ```json { "five_hour": { "utilization": 22.0, "resets_at": "2026-02-20T14:00:00.364238+00:00" }, "seven_day": { "utilization": 49.0, "resets_at": "2026-02-24T10:00:01.364256+00:00" } } ``` ## Requirements - `curl` — API requests - `date` — Timestamp parsing - `grep`, `cut`, `printf` — Text parsing No external dependencies (jq, etc.). ## Privacy Tokens are stored in `{baseDir}/.tokens` (gitignored). Never share your access/refresh tokens. ## Token Health Check (Recommended) OAuth tokens work for ~1 week, then need manual refresh. Set up 30-minute health check for better reliability: ```bash # Add cron job to check token health every 30 minutes openclaw cron add \ --name "claude-token-refresh" \ --every 30m \ --announce \ --message "Запусти {baseDir}/scripts/auto-refresh-cron.sh" ``` **What it does:** - ✅ Token valid → silent (no spam) - 🔴 Token expired → **one-time alert** with manual refresh instructions **Manual refresh (once per week, 30 seconds):** ```bash claude auth login # Browser opens → sign in to claude.ai → done! ``` Tokens auto-sync to `{baseDir}/.tokens` after successful login. ## Troubleshooting **"No token configured"** → Run `./scripts/setup.sh` **"Token expired" / "API request failed"** → OAuth tokens expire after ~1 week → Manual refresh: `claude auth login` (browser opens → sign in → done) → Set up hourly health check to get alerts before expiry (see above) **Burn rate shows empty** → API response missing `resets_at` — try again in a few minutes **Auto-refresh failed** → OAuth refresh endpoint may have changed → Manual refresh: `claude auth login` → copy new tokens → run `./scripts/setup.sh` ## Changelog ### v1.0.5 (2026-02-22) - 🐛 **Bugfix:** Fixed token extraction in `auto-refresh-cron.sh` (removed quotes handling) - ⚡ **Performance:** Reduced cron interval from 1h to 30m for more reliable token refresh - 📝 Improved reliability of OAuth token sync with `~/.claude/.credentials.json` ### v1.0.4 (2026-02-21) - 🔄 Replaced automatic refresh with health check + manual refresh workflow - 📚 Updated documentation with manual refresh instructions - ⏰ Health check alerts when manual refresh needed (~once per week) ### v1.0.3 (2026-02-20) - ⏱️ Fixed auto-refresh interval (hourly instead of 5h) - 📊 Improved burn rate calculation accuracy ## Contributing Found a bug or have a feature request? → Open an issue on ClawHub: https://clawhub.ai/friday/token-usage-optimizer ## License MIT

path: README.md
content: # Token Usage Optimizer

**Maximize your Claude Code subscription value** with smart usage monitoring and burn rate optimization.

## Why?

You're paying **$20-200/month** for Claude Code. This skill helps you:

- 📊 **Track usage** — 5-hour session & 7-day weekly quotas
- ⚡ **Get alerts** — One-time warnings at 50% session usage
- 🎯 **Optimize burn rate** — See if you're under/over/on-pace daily
- 💰 **Maximize value** — Use your subscription to its fullest

## Quick Start

```bash
# 1. Setup tokens
./scripts/setup.sh

# 2. Check usage
./scripts/check-usage.sh

# 3. Daily report
./scripts/report.sh
```

## Features

- ✅ **Burn Rate Tracking** — UNDER/OK/OVER vs ~14%/day budget
- ✅ **Smart Alerts** — One-time warnings (no spam)
- ✅ **Plan-Aware** — Works with Pro, Max 100, Max 200
- ✅ **Ultra-Lightweight** — 10-min cache, minimal API calls
- ✅ **No Dependencies** — Just bash + curl + python3
- ✅ **Manual Refresh** — ~Once per week, 30 seconds (`claude auth login`)

## Output Example

```
📊 Claude Code Daily Check:

⏱️  SESSION (5h): 22%
📅 WEEKLY (7d): 49%

⚪ On pace — optimal usage
```

## Installation

### Via ClawHub (Recommended)

```bash
clawdhub install token-usage-optimizer
```

### Manual

```bash
git clone https://github.com/yourusername/token-usage-optimizer.git
cd token-usage-optimizer
./scripts/setup.sh
```

## Integration with OpenClaw

Add to `HEARTBEAT.md`:

```markdown
### Evening Check (18:00-20:00)
- Claude Code usage: /path/to/token-usage-optimizer/scripts/report.sh
```

## Documentation

- [`SKILL.md`](SKILL.md) — Full skill documentation
- [`references/api-endpoint.md`](references/api-endpoint.md) — API details
- [`references/token-extraction.md`](references/token-extraction.md) — How to get tokens
- [`references/plans.md`](references/plans.md) — Subscription tiers

## Security

- Tokens stored in `.tokens` (gitignored)
- File permissions: 600 (owner read/write only)
- Never commit tokens to git

## License

MIT

## Contributing

Found a bug? Have a feature request?

→ Open an issue on [ClawHub](https://clawhub.ai/friday/token-usage-optimizer)

## Author

Created by Friday (П'ятниця) 🏝️

Built to solve the problem: "I'm paying $100/month but don't know if I'm using it optimally."


path: references/api-endpoint.md
content: # Anthropic OAuth Usage API

Official API endpoint for Claude Code usage monitoring.

## Endpoint

```
GET https://api.anthropic.com/api/oauth/usage
```

## Headers

```
Authorization: Bearer <access-token>
anthropic-beta: oauth-2025-04-20
```

## Example Request

```bash
curl -s "https://api.anthropic.com/api/oauth/usage" \
  -H "[REDACTED_SECRET]" \
  -H "anthropic-beta: oauth-2025-04-20"
```

## Response Format

```json
{
  "five_hour": {
    "utilization": 22.0,
    "resets_at": "2026-02-20T14:00:00.364238+00:00"
  },
  "seven_day": {
    "utilization": 49.0,
    "resets_at": "2026-02-24T10:00:01.364256+00:00"
  },
  "seven_day_oauth_apps": null,
  "seven_day_opus": null,
  "seven_day_sonnet": {
    "utilization": 35.0,
    "resets_at": "2026-02-24T16:00:00.364265+00:00"
  },
  "seven_day_cowork": null,
  "iguana_necktie": null,
  "extra_usage": {
    "is_enabled": true,
    "monthly_limit": 5000,
    "used_credits": 4887.0,
    "utilization": 97.74
  }
}
```

## Fields

### `five_hour`
- **Rolling 5-hour window** session limit
- Prevents rapid bursts of usage
- Resets every 5 hours
- `utilization`: percentage (0-100)
- `resets_at`: ISO 8601 timestamp (UTC)

### `seven_day`
- **Rolling 7-day window** weekly limit
- Main quota for subscription tier
- Resets weekly
- `utilization`: percentage (0-100)
- `resets_at`: ISO 8601 timestamp (UTC)

### `seven_day_sonnet` (Optional)
- Model-specific weekly quota for Sonnet
- Not all plans have this

### `extra_usage` (Optional)
- Additional monthly credits
- `monthly_limit`: total credits per month
- `used_credits`: credits consumed
- `utilization`: percentage (0-100)

## Rate Limits

- No documented rate limits for this endpoint
- Recommended: cache responses for 5-10 minutes
- Avoid excessive polling (>1 req/min)

## Error Responses

### Authentication Error

```json
{
  "type": "error",
  "error": {
    "type": "authentication_error",
    "message": "OAuth authentication is currently not supported.",
    "details": {
      "error_visibility": "user_facing"
    }
  },
  "request_id": "req_..."
}
```

**Cause:** Invalid or expired access token

**Fix:** Use refresh token to get new access token

### Missing Beta Header

If you forget `anthropic-beta: oauth-2025-04-20`, you may get an error or outdated response format.

## Notes

- All timestamps are in UTC
- `utilization` is a float (can have decimals)
- `resets_at` format: `YYYY-MM-DDTHH:MM:SS.ssssss+00:00`
- Some fields may be `null` depending on your plan

## Subscription Tiers

Different tiers have different quota limits (not exposed in API):

- **Pro ($20/mo):** Lower limits
- **Max 100 ($100/mo):** Medium limits
- **Max 200 ($200/mo):** Higher limits

The API doesn't expose absolute quota limits, only utilization percentage.

## Best Practices

1. **Cache responses** for 5-10 minutes
2. **Use refresh token** for long-running scripts
3. **Monitor `five_hour` more frequently** than `seven_day` (it resets faster)
4. **Set alerts** at 50% (five_hour) and 80% (seven_day)
5. **Track burn rate** to optimize subscription usage


path: references/plans.md
content: # Claude Code Subscription Plans

Overview of Claude Code pricing tiers and quota expectations.

## Available Plans

### Pro ($20/month)

- Basic access to Claude Code
- Lower usage quotas
- Good for casual users
- **5-hour limit:** Lower threshold
- **7-day limit:** ~200-300 requests/week (estimated)

### Max 100 ($100/month)

- 5× capacity vs Pro
- Designed for power users
- **5-hour limit:** Higher threshold
- **7-day limit:** ~1000-1500 requests/week (estimated)

### Max 200 ($200/month)

- 10× capacity vs Pro
- For heavy professional use
- **5-hour limit:** Highest threshold
- **7-day limit:** ~2000-3000 requests/week (estimated)

## Daily Budget

All plans reset on a **7-day rolling window**, so:

- **Daily target:** ~14% of weekly quota (100% ÷ 7 days)
- **Goal:** Use subscription to its fullest without hitting limits

### Example for Max 100:

| Day | Target Usage | Actual | Status |
|-----|--------------|--------|--------|
| Mon | 14% | 12% | 🟢 UNDER (use more!) |
| Tue | 28% | 35% | 🔴 OVER (throttle) |
| Wed | 42% | 45% | ⚪ OK (on pace) |
| Thu | 56% | 58% | ⚪ OK |
| Fri | 70% | 68% | ⚪ OK |
| Sat | 84% | 80% | 🟢 UNDER |
| Sun | 100% | 95% | 🟢 UNDER |

**Insight:** If you're consistently UNDER, consider downgrading. If OVER, upgrade.

## Quota Windows

### 5-Hour Session Window

- **Purpose:** Prevent rapid bursts
- **Strategy:** Monitor frequently, alert at 50%
- **Resets:** Every 5 hours (rolling)
- **Impact:** Short-term throttling

### 7-Day Weekly Window

- **Purpose:** Main subscription quota
- **Strategy:** Track daily burn rate (~14%/day)
- **Resets:** Every 7 days (rolling)
- **Impact:** Long-term capacity planning

## Optimization Strategies

### Under-Using Your Plan?

- ✅ Use Claude Code more throughout the day
- ✅ Batch smaller queries instead of avoiding usage
- ✅ Explore more features (code generation, refactoring)
- ❌ Don't waste — but get your money's worth!

### Over-Using Your Plan?

- ✅ Spread usage across the week
- ✅ Use session window more efficiently (wait for resets)
- ✅ Consider upgrading to next tier
- ❌ Don't hit limits mid-week!

### On Pace?

- ✅ You're optimizing well!
- ✅ Keep monitoring to maintain balance

## Plan Detection

The API **does not expose** which plan you're on. This skill infers burn rate based on:

1. Your current utilization percentage
2. Days elapsed since weekly reset
3. Expected daily budget (~14%)

All plans follow the same **7-day rolling window**, so the burn rate calculation works universally.

## Cost Per Request

Approximate (varies by model and prompt size):

| Plan | Monthly | $/request (estimated) |
|------|---------|----------------------|
| Pro | $20 | ~$0.07-0.10 |
| Max 100 | $100 | ~$0.07-0.10 |
| Max 200 | $200 | ~$0.07-0.10 |

Higher tiers = more requests, not cheaper per-request.

## Recommendations by User Type

### Casual User (2-3 sessions/week)
→ **Pro** is sufficient

### Daily User (1-2 hours/day)
→ **Max 100** for best value

### Power User (3+ hours/day, CI/CD, automation)
→ **Max 200** to avoid limits

## Notes

- Quotas are **rolling windows**, not calendar-based
- Utilization % is the same across all tiers (100% = your plan's limit)
- Extra usage credits (if available) are separate from main quota
- Opus usage may have separate limits (check `seven_day_opus` field)

## References

- [Claude Code Pricing](https://claude.ai/pricing)
- [Anthropic API Docs](https://docs.anthropic.com/)


path: references/token-extraction.md
content: # Token Extraction Guide

How to get your Claude Code OAuth tokens for usage monitoring.

## Method 1: Via Claude CLI (Recommended)

### macOS

1. **Authenticate with Claude CLI:**
   ```bash
   claude auth login
   ```

2. **Find the auth file:**
   ```bash
   # Try these locations:
   cat ~/.claude/auth.json
   cat ~/Library/Application\ Support/Claude/auth.json
   
   # Or search:
   find ~/Library/Application\ Support -name "*auth*" -type f 2>/dev/null | grep -i claude
   ```

3. **Extract tokens from JSON:**
   ```json
   {
     "accessToken": "sk-ant-oat01-...",
     "refreshToken": "sk-ant-ort01-...",
     "expiresAt": 1234567890000
   }
   ```

### Linux

1. **Authenticate:**
   ```bash
   claude auth login
   ```

2. **Find auth data:**
   ```bash
   # Common locations:
   cat ~/.config/claude/auth.json
   cat ~/.claude/auth.json
   
   # Or use secret-tool:
   secret-tool search application "Claude Code"
   ```

## Method 2: Browser DevTools

If you can't find the auth file:

1. Open https://claude.ai in your browser
2. Sign in to your account
3. Open DevTools (F12 or Cmd+Opt+I)
4. Go to **Application** → **Local Storage** → `https://claude.ai`
5. Look for keys like `auth_token`, `oauth_token`, or similar
6. Copy the values

**Note:** This may not work for all setups. Method 1 is preferred.

## Method 3: Manual OAuth Flow

Advanced users can implement the OAuth flow manually:

1. **Authorization endpoint:**
   ```
   https://claude.ai/oauth/authorize
   ```

2. **Token endpoint:**
   ```
   https://platform.claude.com/oauth/token
   ```

3. **Required scopes:**
   - `user:inference`
   - `user:sessions:claude_code`
   - `user:profile`

See Anthropic OAuth docs for full details.

## Token Format

- **Access Token:** `sk-ant-oat01-...` (long alphanumeric string)
- **Refresh Token:** `sk-ant-ort01-...` (long alphanumeric string)

## Security

- ✅ **Do:** Store tokens in `.tokens` file (gitignored)
- ✅ **Do:** Set file permissions to 600 (`chmod 600 .tokens`)
- ❌ **Don't:** Commit tokens to git
- ❌ **Don't:** Share tokens publicly
- ❌ **Don't:** Use someone else's tokens

## Token Expiry

- Access tokens expire after a certain time
- Use refresh token to get a new access token
- This skill doesn't auto-refresh yet (manual re-run of setup required)

## Troubleshooting

**"No auth file found"**
→ Run `claude auth login` first

**"Permission denied"**
→ Check file permissions: `ls -l ~/.claude/auth.json`

**"Token invalid"**
→ Token may have expired. Re-run `claude auth login`


path: scripts/auto-refresh-cron.sh
content: #!/bin/bash
# Check Claude OAuth token health and alert if refresh needed

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_DIR="$(dirname "$SCRIPT_DIR")"
TOKEN_FILE="$BASE_DIR/.tokens"
ALERT_STATE="/tmp/claude-oauth-refresh-alert"

# Extract current access token
if [ ! -f "$TOKEN_FILE" ]; then
  echo "❌ Token file not found: $TOKEN_FILE" >&2
  exit 1
fi

ACCESS_TOKEN=$(grep ACCESS_TOKEN "$TOKEN_FILE" | cut -d'=' -f2)

if [ -z "$ACCESS_TOKEN" ]; then
  echo "❌ Could not extract access token" >&2
  exit 1
fi

# Test if token works (minimal API call)
RESPONSE=$(curl -s "https://api.anthropic.com/api/oauth/usage" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "anthropic-beta: oauth-2025-04-20")

# Check if token is valid
if echo "$RESPONSE" | grep -q '"five_hour"'; then
  # Token works! Clear alert state
  rm -f "$ALERT_STATE"
  echo "✅ OAuth token is valid"
  
  # Sync to ~/.claude/.credentials.json if needed
  if [ -f ~/.claude/.credentials.json ]; then
    REFRESH_TOKEN=$(grep REFRESH_TOKEN "$TOKEN_FILE" | cut -d'=' -f2)
    EXPIRES_AT=$(($(date +%s) * 1000 + 3600000))  # +1 hour
    
    python3 << PYTHON_EOF
import json, os
creds_file = os.path.expanduser('~/.claude/.credentials.json')
try:
    with open(creds_file, 'r') as f:
        creds = json.load(f)
    creds['claudeAiOauth']['accessToken'] = "$ACCESS_TOKEN"
    creds['claudeAiOauth']['refreshToken'] = "$REFRESH_TOKEN"
    creds['claudeAiOauth']['expiresAt'] = $EXPIRES_AT
    with open(creds_file, 'w') as f:
        json.dump(creds, f, indent=2)
    os.chmod(creds_file, 0o600)
except Exception as e:
    pass  # Silent fail - not critical
PYTHON_EOF
  fi
  
  exit 0
elif echo "$RESPONSE" | grep -q "token_expired\|authentication_error"; then
  # Token expired - need manual refresh
  
  # Alert only once (until token is refreshed)
  if [ ! -f "$ALERT_STATE" ]; then
    echo "🔴 OAuth token has EXPIRED!"
    echo ""
    echo "📋 Manual refresh required:"
    echo "   1. Run: claude auth login"
    echo "   2. Browser will open for OAuth flow"
    echo "   3. Sign in to claude.ai"
    echo "   4. Done! Tokens auto-update"
    echo ""
    echo "This happens ~once per week. Takes 30 seconds."
    
    # Mark alert as sent
    date > "$ALERT_STATE"
    exit 1
  else
    # Alert already sent, silent fail
    echo "⚠️  Token expired (alert already sent)"
    exit 1
  fi
else
  # Unexpected response
  echo "⚠️  Unexpected API response:"
  echo "$RESPONSE" | head -5
  exit 1
fi


path: scripts/check-usage.sh
content: #!/bin/bash
# Ultra-lightweight Claude Code usage checker
# Token-friendly: aggressive caching, minimal API calls, one-time alerts

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_DIR="$(dirname "$SCRIPT_DIR")"

# Config
CACHE_FILE="${CACHE_FILE:-/tmp/claude-usage.cache}"
STATE_FILE="${STATE_FILE:-/tmp/claude-usage-alert-state}"
CACHE_TTL="${CACHE_TTL:-600}"  # 10 minutes default
TOKEN_FILE="$BASE_DIR/.tokens"

# Check if tokens configured
if [ ! -f "$TOKEN_FILE" ]; then
  echo "ERROR: No tokens configured. Run setup.sh first." >&2
  exit 1
fi

# Load tokens
source "$TOKEN_FILE"

if [ -z "$ACCESS_TOKEN" ]; then
  echo "ERROR: ACCESS_TOKEN not found in $TOKEN_FILE" >&2
  exit 1
fi

# Check cache freshness
if [ -f "$CACHE_FILE" ]; then
  if [[ "$OSTYPE" == "darwin"* ]]; then
    AGE=$(($(date +%s) - $(stat -f%m "$CACHE_FILE")))
  else
    AGE=$(($(date +%s) - $(stat -c%Y "$CACHE_FILE")))
  fi
  
  if [ "$AGE" -lt "$CACHE_TTL" ]; then
    cat "$CACHE_FILE"
    exit 0
  fi
fi

# Check if claude CLI is available (handles auto-refresh automatically)
if command -v claude >/dev/null 2>&1; then
  # Claude CLI available - use it to get fresh token
  # It will auto-refresh if needed and update ~/.claude/.credentials.json
  
  # Trigger a simple query to ensure token is fresh
  echo "ping" | claude --quiet >/dev/null 2>&1 || true
  
  # Extract fresh token from credentials file
  if [ -f ~/.claude/.credentials.json ]; then
    FRESH_TOKEN=$(python3 -c "import json; d=json.load(open('$HOME/.claude/.credentials.json')); print(d.get('claudeAiOauth', {}).get('accessToken', ''))" 2>/dev/null)
    if [ -n "$FRESH_TOKEN" ]; then
      ACCESS_TOKEN="$FRESH_TOKEN"
      # Update .tokens file for consistency
      sed -i.bak "s|ACCESS_TOKEN=.*|ACCESS_TOKEN=\"$ACCESS_TOKEN\"|" "$TOKEN_FILE" 2>/dev/null || true
    fi
  fi
fi

# Fetch fresh data
RESP=$(curl -sf "https://api.anthropic.com/api/oauth/usage" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "anthropic-beta: oauth-2025-04-20" 2>&1)

# Check if failed
if [ -z "$RESP" ] || echo "$RESP" | grep -q "token_expired\|authentication_error"; then
  echo "ERROR: API request failed. Token may be expired." >&2
  echo "Hint: Run 'claude auth login' to refresh tokens." >&2
  exit 1
fi

# Parse critical fields only
SESSION=$(echo "$RESP" | grep -o '"five_hour":{"utilization":[0-9.]*' | grep -o '[0-9.]*$')
WEEKLY=$(echo "$RESP" | grep -o '"seven_day":{"utilization":[0-9.]*' | grep -o '[0-9.]*$')
WEEKLY_RESET=$(echo "$RESP" | grep -o '"seven_day":{"utilization":[0-9.]*,"resets_at":"[^"]*"' | grep -o 'resets_at":"[^"]*"' | cut -d'"' -f3)

# Calculate burn rate vs expected (daily budget = 14.3% = 100%/7 days)
BURN_RATE=""
if [ -n "$WEEKLY_RESET" ] && [ -n "$WEEKLY" ]; then
  if [[ "$OSTYPE" == "darwin"* ]]; then
    RESET_TS=$(date -j -f "%Y-%m-%dT%H:%M:%S" "${WEEKLY_RESET%.*}" +%s 2>/dev/null || echo 0)
  else
    RESET_TS=$(date -d "$WEEKLY_RESET" +%s 2>/dev/null || echo 0)
  fi
  
  if [ "$RESET_TS" -gt 0 ]; then
    NOW=$(date +%s)
    DAYS_LEFT=$(( ($RESET_TS - $NOW) / 86400 ))
    DAYS_ELAPSED=$(( 7 - $DAYS_LEFT ))
    EXPECTED=$(( $DAYS_ELAPSED * 14 ))  # ~14% per day (simplified)
    WEEKLY_INT=$(printf "%.0f" "${WEEKLY:-0}")
    DIFF=$(( $WEEKLY_INT - $EXPECTED ))
    
    if [ "$DIFF" -lt -10 ]; then
      BURN_RATE="UNDER"  # Can use more
    elif [ "$DIFF" -gt 10 ]; then
      BURN_RATE="OVER"   # Over-using
    else
      BURN_RATE="OK"     # On pace
    fi
  fi
fi

# Check previous state for alert deduplication
PREV_SESSION=0
if [ -f "$STATE_FILE" ]; then
  PREV_SESSION=$(grep "^LAST_SESSION=" "$STATE_FILE" 2>/dev/null | cut -d= -f2)
  PREV_SESSION=${PREV_SESSION:-0}
fi

# Save to cache
echo "SESSION=${SESSION:-0}" > "$CACHE_FILE"
echo "WEEKLY=${WEEKLY:-0}" >> "$CACHE_FILE"
echo "BURN_RATE=${BURN_RATE}" >> "$CACHE_FILE"
echo "CACHED_AT=$(date +%s)" >> "$CACHE_FILE"

# Check if should alert (only on threshold crossing)
SESSION_INT=$(printf "%.0f" "${SESSION:-0}")
PREV_INT=$(printf "%.0f" "$PREV_SESSION")

if [ "$SESSION_INT" -gt 50 ] && [ "$PREV_INT" -le 50 ]; then
  echo "ALERT_SESSION=1" >> "$CACHE_FILE"
fi

# Update state
echo "LAST_SESSION=${SESSION:-0}" > "$STATE_FILE"

# Output
cat "$CACHE_FILE"


path: scripts/refresh-token.sh
content: #!/bin/bash
# Auto-refresh Claude Code OAuth token

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_DIR="$(dirname "$SCRIPT_DIR")"
TOKEN_FILE="$BASE_DIR/.tokens"

if [ ! -f "$TOKEN_FILE" ]; then
  echo "ERROR: No tokens configured" >&2
  exit 1
fi

source "$TOKEN_FILE"

if [ -z "$REFRESH_TOKEN" ]; then
  echo "ERROR: No refresh token found" >&2
  exit 1
fi

# Refresh via Anthropic API
# Note: This endpoint may not be public yet, using alternative approach
# For now, manual re-login via `claude auth login` is needed

echo "⚠️  Auto-refresh not yet implemented"
echo "Please run: claude auth login"
echo "Then update .tokens file with new credentials"
exit 1

# TODO: Implement proper OAuth refresh flow when API is documented


path: scripts/report.sh
content: #!/bin/bash
# Human-readable Claude Code usage report

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Run check (it writes to cache automatically)
"$SCRIPT_DIR/check-usage.sh" > /dev/null || {
  echo "❌ Failed to check usage" >&2
  exit 1
}

# Parse results from cache
SESSION=$(grep "^SESSION=" /tmp/claude-usage.cache | cut -d= -f2)
WEEKLY=$(grep "^WEEKLY=" /tmp/claude-usage.cache | cut -d= -f2)
BURN_RATE=$(grep "^BURN_RATE=" /tmp/claude-usage.cache | cut -d= -f2)

SESSION_INT=$(printf "%.0f" "$SESSION")
WEEKLY_INT=$(printf "%.0f" "$WEEKLY")

# Burn rate interpretation
case "$BURN_RATE" in
  UNDER)
    BURN_MSG="🟢 Under-using — you can use more to maximize your subscription value!"
    ;;
  OVER)
    BURN_MSG="🔴 Over-using — burn rate exceeds daily budget (~14%/day)"
    ;;
  OK)
    BURN_MSG="⚪ On pace — optimal usage"
    ;;
  *)
    BURN_MSG=""
    ;;
esac

# Session alert
if grep -q "ALERT_SESSION=1" /tmp/claude-usage.cache 2>/dev/null; then
  echo "🟡 WARNING: Session usage > 50% ($SESSION_INT%)"
  echo ""
fi

# Report
echo "📊 Claude Code Daily Check:"
echo ""
echo "⏱️  SESSION (5h): $SESSION_INT%"
echo "📅 WEEKLY (7d): $WEEKLY_INT%"
echo ""
if [ -n "$BURN_MSG" ]; then
  echo "$BURN_MSG"
fi


path: scripts/setup.sh
content: #!/bin/bash
# Setup wizard for token-usage-optimizer

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_DIR="$(dirname "$SCRIPT_DIR")"
TOKEN_FILE="$BASE_DIR/.tokens"

echo "🔧 Token Usage Optimizer Setup"
echo ""
echo "You need OAuth tokens from Claude Code CLI."
echo "See references/token-extraction.md for instructions."
echo ""

# Check if already configured
if [ -f "$TOKEN_FILE" ]; then
  echo "⚠️  Tokens already configured in $TOKEN_FILE"
  read -p "Overwrite? (y/N): " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    exit 0
  fi
fi

# Prompt for access token
echo "1️⃣  Enter your Access Token (sk-ant-oat01-...):"
read -r ACCESS_TOKEN

if [ -z "$ACCESS_TOKEN" ]; then
  echo "❌ Access token required"
  exit 1
fi

# Prompt for refresh token
echo ""
echo "2️⃣  Enter your Refresh Token (sk-ant-ort01-...):"
read -r REFRESH_TOKEN

if [ -z "$REFRESH_TOKEN" ]; then
  echo "⚠️  No refresh token provided (optional but recommended)"
fi

# Save to file
cat > "$TOKEN_FILE" <<EOF
# Claude Code OAuth Tokens
# Generated: $(date)

ACCESS_TOKEN="$ACCESS_TOKEN"
REFRESH_TOKEN="$REFRESH_TOKEN"
EOF

chmod 600 "$TOKEN_FILE"

echo ""
echo "✅ Tokens saved to $TOKEN_FILE"
echo ""
echo "Next steps:"
echo "  ./scripts/check-usage.sh   # Check your usage"
echo "  ./scripts/report.sh        # Human-readable report"
echo ""
echo "To integrate with heartbeat, add to HEARTBEAT.md:"
echo "  $BASE_DIR/scripts/report.sh"


Security scan verdicts — ClawScan: suspicious | static analysis: suspicious | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)