diff --git a/Releases/v2.5/.claude/skills/BudgetMonitor/SKILL.md b/Releases/v2.5/.claude/skills/BudgetMonitor/SKILL.md new file mode 100644 index 00000000..7d9ef9fe --- /dev/null +++ b/Releases/v2.5/.claude/skills/BudgetMonitor/SKILL.md @@ -0,0 +1,312 @@ +--- +name: BudgetMonitor +description: Resource consciousness system for AI cost tracking and budget management. USE WHEN user asks about budget, usage, costs, spending, or resource consumption. +--- + +# BudgetMonitor Skill + +Resource consciousness system for PAI. Tracks AI service usage and costs to enable financial awareness and intelligent resource management. + +**Domain**: Resource management, cost tracking, financial planning +**Triggers**: "budget", "usage", "costs", "spending", "how much", "resource" + +--- + +## Philosophy + +> "A cat that doesn't know how much it eats can never hunt for itself." + +BudgetMonitor implements resource consciousness - the foundation for intelligent AI usage. It's not just about tracking costs; it's about building awareness that enables better decisions. + +**The Journey:** +1. **Visibility** (Now): See what we consume +2. **Intelligence** (Next): Understand cost vs value +3. **Consciousness** (Future): Make resource-aware decisions +4. **Optimization** (Goal): Maximize value per dollar spent + +--- + +## Quick Reference + +### Check Current Status +``` +"What's my budget status?" +"How much have I spent this month?" +"Show usage" +``` + +### Generate Dashboard +``` +"Show budget dashboard" +"Generate usage dashboard" +``` + +### Track Session +``` +"Log this session usage" +"Record session costs" +``` + +--- + +## Data Architecture + +``` +~/.claude/BUDGET/ +├── config.yaml # Budget limits, alert thresholds +├── TRACKER.md # Human-readable current state +├── usage.jsonl # Session-by-session usage log +└── history/ # Monthly archives + └── 2026-01.jsonl +``` + +### Usage Record Schema + +```json +{ + "timestamp": "2026-01-30T14:30:00Z", + "session_id": "abc123", + "duration_minutes": 45, + "messages": 23, + "tokens_estimated": { + "input": 46000, + "output": 92000 + }, + "cost_estimated": 8.55, + "rating": 9, + "tasks_completed": 3, + "skills_used": ["Research", "BeCreative", "BudgetMonitor"] +} +``` + +### Config Schema (config.yaml) + +```yaml +budget: + monthly_limit: 100.00 # USD + currency: "USD" + +alerts: + caution: 70 # 70% of budget + warning: 85 # 85% of budget + critical: 95 # 95% of budget + +services: + claude: + sonnet-4: + input_per_million: 3.00 + output_per_million: 15.00 + opus-4: + input_per_million: 15.00 + output_per_million: 75.00 + haiku: + input_per_million: 0.80 + output_per_million: 4.00 + + # Add other AI services as needed + chatgpt: + gpt-4: + input_per_million: 30.00 + output_per_million: 60.00 +``` + +--- + +## Alert Levels + +| Level | Threshold | Indicator | Action | +|-------|-----------|-----------|--------| +| 🟢 Normal | < 70% | All good | Continue normally | +| 🟡 Caution | 70-85% | Budget awareness | Monitor usage | +| 🟠 Warning | 85-95% | Active concern | Consider optimization | +| 🔴 Critical | > 95% | Budget exhausted | Restrict non-essential | + +--- + +## Workflow Routing + +| Workflow | Triggers | Description | +|----------|----------|-------------| +| `Workflows/Status.md` | "budget status", "usage", "how much spent" | Current budget state | +| `Workflows/Dashboard.md` | "budget dashboard", "show dashboard" | Generate visual HTML dashboard | +| `Workflows/TrackSession.md` | "track session", "log usage" | Record session usage | +| `Workflows/DailyReport.md` | "daily budget", "usage report" | Daily summary | + +--- + +## Tools + +| Tool | Purpose | +|------|---------| +| `Tools/Dashboard.ts` | Generate HTML dashboard | +| `Tools/TrackSession.ts` | Record session usage | +| `Tools/CalculateBudget.ts` | Compute budget metrics | + +--- + +## Examples + +**Example 1: Quick status check** +``` +User: "What's my budget looking like?" +→ Status workflow +→ Returns: "🟢 $45.20 spent of $100 (45.2%), 15 days remaining, on track" +``` + +**Example 2: Deep dive** +``` +User: "Show me the budget dashboard" +→ Dashboard workflow +→ Generates HTML at ~/.claude/BUDGET/dashboard.html +→ Opens in browser with: + - Daily usage trends + - Service breakdown + - Alert level visualization + - Projection to month end +``` + +**Example 3: Session tracking** +``` +User: "Log this session usage" +→ TrackSession workflow +→ Calculates tokens from session history +→ Appends to usage.jsonl +→ Updates TRACKER.md +``` + +--- + +## Integration Patterns + +### Manual Tracking +After each significant session: +```bash +# Track current session +cd ~/.claude/skills/BudgetMonitor +bun run Tools/TrackSession.ts +``` + +### Automatic Tracking (Recommended) +Add to your session-end workflow/hook: +```bash +# In hooks or session-end processing +bun run ~/.claude/skills/BudgetMonitor/Tools/TrackSession.ts +``` + +### Morning Brief Integration +Include budget status in daily summaries: +```markdown +### Budget Status +Read ~/.claude/BUDGET/TRACKER.md for current state +Include alert level if > 70% +``` + +--- + +## Implementation Roadmap + +### Phase 1: Visibility (Current) +- [x] Budget configuration schema +- [x] Usage tracking schema +- [x] Human-readable tracker (TRACKER.md) +- [ ] Dashboard generation (HTML/charts) +- [ ] Workflow implementations +- [ ] Tool implementations + +### Phase 2: Intelligence (Future) +- [ ] Track user ratings per session +- [ ] Calculate cost-per-high-rating +- [ ] Identify high-ROI patterns +- [ ] Value-based reporting + +### Phase 3: Consciousness (Future) +- [ ] Resource state awareness in responses +- [ ] Resource-aware decision making +- [ ] Automatic usage optimization +- [ ] Smart model selection (Haiku vs Sonnet vs Opus) + +### Phase 4: Optimization (Future) +- [ ] Predictive budget management +- [ ] Cost-benefit analysis per task type +- [ ] Automatic throttling recommendations +- [ ] Multi-month trend analysis + +--- + +## File Organization + +| Path | Purpose | +|------|---------| +| `SKILL.md` | Skill documentation (this file) | +| `Workflows/Status.md` | Budget status workflow | +| `Workflows/Dashboard.md` | Dashboard generation workflow | +| `Workflows/TrackSession.md` | Session tracking workflow | +| `Workflows/DailyReport.md` | Daily summary workflow | +| `Tools/Dashboard.ts` | Dashboard generator | +| `Tools/TrackSession.ts` | Session logger | +| `Tools/CalculateBudget.ts` | Budget calculator | + +--- + +## Benefits + +**Visibility:** +- Know exactly how much you're spending +- Track trends over time +- Identify expensive patterns + +**Control:** +- Set budget limits +- Get alerts before overspending +- Make informed decisions about model selection + +**Intelligence:** +- Understand which tasks cost most +- Optimize for value vs cost +- Plan resource usage effectively + +**Foundation:** +- Builds awareness needed for autonomous AI +- Enables resource-conscious decision making +- Prepares for future value generation capabilities + +--- + +## Design Principles + +**Simplicity:** +- YAML configuration (easy to edit) +- JSONL logs (append-only, grep-friendly) +- Markdown tracker (human-readable) +- No database required + +**Privacy:** +- All data stored locally +- No external services +- User controls all data + +**Extensibility:** +- Easy to add new AI services +- Simple to customize alert thresholds +- Workflow-based architecture + +**Integration:** +- Works with any PAI configuration +- Hooks-compatible +- Skill-routing compatible + +--- + +## Changelog + +### 2026-01-30 - v1.0.0 +- Initial creation with core tracking architecture +- Budget configuration schema +- Usage logging schema +- Alert level system +- Workflow routing structure +- Tool specifications + +--- + +*Part of PAI v2.5 resource consciousness initiative* diff --git a/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/AlertCheck.md b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/AlertCheck.md new file mode 100644 index 00000000..4ef3d069 --- /dev/null +++ b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/AlertCheck.md @@ -0,0 +1,118 @@ +# AlertCheck Workflow + +**Purpose:** Check budget thresholds and trigger alerts when crossed. + +--- + +## Trigger + +Called by: +- TrackSession (after each session) +- Overnight processor (nightly check) +- Manual request + +--- + +## Steps + +### Step 1: Load Current State + +```typescript +const config = loadConfig('~/.claude/BUDGET/config.yaml'); +const usage = loadUsage('~/.claude/BUDGET/usage.jsonl'); +const currentPercent = calculatePercentUsed(usage, config); +const previousAlert = loadState('~/.claude/BUDGET/Data/alert-state.json'); +``` + +### Step 2: Determine Current Level + +```typescript +function getAlertLevel(percent, thresholds) { + if (percent >= thresholds.critical) return 'critical'; + if (percent >= thresholds.warning) return 'warning'; + if (percent >= thresholds.caution) return 'caution'; + return 'normal'; +} + +const currentLevel = getAlertLevel(currentPercent, config.alerts); +``` + +### Step 3: Check for Level Change + +```typescript +const levelOrder = ['normal', 'caution', 'warning', 'critical']; +const previousIndex = levelOrder.indexOf(previousAlert.level); +const currentIndex = levelOrder.indexOf(currentLevel); + +const escalated = currentIndex > previousIndex; +const deescalated = currentIndex < previousIndex; +``` + +### Step 4: Take Action on Escalation + +**Caution (70%):** +```bash +# Log the transition +echo "$(date): Entered CAUTION at ${currentPercent}%" >> ~/.claude/BUDGET/alerts.log +``` + +**Warning (85%):** +```bash +# Voice notification +curl -s -X POST http://localhost:8888/notify \ + -H "Content-Type: application/json" \ + -d '{"message": "Budget warning: 85 percent of monthly limit consumed"}' + +# Log +echo "$(date): Entered WARNING at ${currentPercent}%" >> ~/.claude/BUDGET/alerts.log +``` + +**Critical (95%):** +```bash +# Urgent voice notification +curl -s -X POST http://localhost:8888/notify \ + -H "Content-Type: application/json" \ + -d '{"message": "Budget critical: 95 percent consumed. Restricting to essential tasks only."}' + +# Log +echo "$(date): Entered CRITICAL at ${currentPercent}%" >> ~/.claude/BUDGET/alerts.log + +# Write restriction flag +echo "critical" > ~/.claude/BUDGET/Data/restriction-mode +``` + +### Step 5: Save State + +```typescript +saveState('~/.claude/BUDGET/Data/alert-state.json', { + level: currentLevel, + percent: currentPercent, + timestamp: new Date().toISOString(), + runway_days: calculateRunway() +}); +``` + +--- + +## Monthly Reset + +On the first of each month (or config.plan.reset_day): + +1. Archive current month's usage to `history/YYYY-MM.jsonl` +2. Clear `usage.jsonl` +3. Reset alert state to 'normal' +4. Log: "Monthly budget reset" + +--- + +## Integration with Resource Consciousness (Phase 3) + +When Phase 3 is enabled, the alert state is exposed in the PAI algorithm output: + +```markdown +🤖 PAI ALGORITHM ════════════════════════════════════════════ + Task: [task description] + 📊 Resources: 🟡 72% | $28 remaining | 8 days +``` + +This enables Aineko to make resource-aware decisions. diff --git a/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/DailyReport.md b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/DailyReport.md new file mode 100644 index 00000000..b5ef4ed9 --- /dev/null +++ b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/DailyReport.md @@ -0,0 +1,79 @@ +# DailyReport Workflow + +**Purpose:** Generate a daily budget summary for MorningBrief integration. + +--- + +## Trigger + +Called by: +- MorningBrief skill (automatic) +- User request ("daily budget report") +- Overnight processor + +--- + +## Output Format + +For MorningBrief integration, return a concise block: + +```markdown +### Budget Status + +{EMOJI} **{PERCENT}%** consumed | ${REMAINING} remaining | {RUNWAY} days runway + +{If yesterday had notable spending:} +Yesterday: ${YESTERDAY_SPEND} across {SESSION_COUNT} sessions + +{If alert level > normal:} +**{ALERT_LEVEL}:** {RECOMMENDATION} +``` + +--- + +## Steps + +### Step 1: Calculate Yesterday's Metrics + +```typescript +const yesterday = usage.filter(u => isYesterday(u.timestamp)); +const metrics = { + sessions: yesterday.length, + cost: sum(yesterday.map(u => u.cost_estimated)), + avgRating: avg(yesterday.filter(u => u.rating).map(u => u.rating)) +}; +``` + +### Step 2: Calculate MTD Metrics + +Same as Status workflow. + +### Step 3: Compare to Pace + +```typescript +const idealDailySpend = budget / daysInMonth; +const actualDailyAvg = spentMTD / daysElapsed; +const paceStatus = actualDailyAvg <= idealDailySpend ? 'on track' : 'over pace'; +``` + +### Step 4: Format for MorningBrief + +```markdown +### Budget Status + +🟢 **32%** consumed | $68.00 remaining | 22 days runway + +Yesterday: $4.20 across 3 sessions (avg rating: 8.5) +Pace: On track ($3.20/day vs $3.33/day target) +``` + +--- + +## Alert Escalation + +| Level | In MorningBrief | +|-------|----------------| +| 🟢 Normal | Brief mention only | +| 🟡 Caution | Mention + pace warning | +| 🟠 Warning | Prominent + recommendations | +| 🔴 Critical | FIRST item + action required | diff --git a/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/Dashboard.md b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/Dashboard.md new file mode 100644 index 00000000..15d6cdee --- /dev/null +++ b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/Dashboard.md @@ -0,0 +1,104 @@ +# Dashboard Workflow + +**Purpose:** Generate a visual HTML dashboard showing budget status, trends, and projections. + +--- + +## Voice Notification + +```bash +curl -s -X POST http://localhost:8888/notify \ + -H "Content-Type: application/json" \ + -d '{"message": "Generating budget dashboard"}' \ + > /dev/null 2>&1 & +``` + +--- + +## Steps + +### Step 1: Gather Data + +1. Read `~/.claude/BUDGET/config.yaml` +2. Read `~/.claude/BUDGET/usage.jsonl` (all records) +3. Calculate all metrics from Status workflow +4. Aggregate daily/weekly/monthly trends + +### Step 2: Generate Dashboard + +Run the dashboard tool: +```bash +bun run ~/.claude/skills/BudgetMonitor/Tools/Dashboard.ts +``` + +### Step 3: Open Dashboard + +```bash +# Open in default browser +xdg-open ~/.claude/BUDGET/dashboard.html 2>/dev/null || \ +open ~/.claude/BUDGET/dashboard.html 2>/dev/null || \ +echo "Dashboard generated at ~/.claude/BUDGET/dashboard.html" +``` + +--- + +## Dashboard Sections + +### 1. Header +- Current month/year +- Plan name +- Overall status indicator (🟢/🟡/🟠/🔴) + +### 2. Budget Gauge +- Visual progress bar/gauge +- Current spend vs limit +- Projected end-of-month + +### 3. Daily Spending Chart +- Bar chart of daily costs +- 7-day moving average line +- Budget pace line (ideal daily spend) + +### 4. Usage Breakdown +- By skill (which skills cost most) +- By time of day (when do we use most) +- By rating (cost vs quality correlation) + +### 5. Projections +- Current trajectory vs budget +- Days of runway remaining +- Recommendations + +### 6. Historical Comparison +- This month vs last month +- Trend direction + +### 7. Phase 2 Preview (if enabled) +- Cost per high rating +- Value metrics +- ROI estimates + +--- + +## Dashboard Design + +```html + +:root { + --pai-blue: #3B82F6; + --pai-dark: #1E3A5F; + --pai-light: #93C5FD; + --status-green: #22C55E; + --status-yellow: #EAB308; + --status-orange: #F97316; + --status-red: #EF4444; +} +``` + +--- + +## Output + +- **File:** `~/.claude/BUDGET/dashboard.html` +- **Auto-refresh:** Dashboard includes meta refresh every 5 minutes +- **Mobile-friendly:** Responsive design for phone viewing diff --git a/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/Status.md b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/Status.md new file mode 100644 index 00000000..a0beb655 --- /dev/null +++ b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/Status.md @@ -0,0 +1,98 @@ +# Status Workflow + +**Purpose:** Display current budget status in a concise, actionable format. + +--- + +## Voice Notification + +```bash +curl -s -X POST http://localhost:8888/notify \ + -H "Content-Type: application/json" \ + -d '{"message": "Checking budget status"}' \ + > /dev/null 2>&1 & +``` + +--- + +## Steps + +### Step 1: Load Data + +Read the following files: +- `~/.claude/BUDGET/config.yaml` - Budget limits and thresholds +- `~/.claude/BUDGET/TRACKER.md` - Current state +- `~/.claude/BUDGET/usage.jsonl` - Raw usage data (if exists) + +### Step 2: Calculate Metrics + +```typescript +// Metrics to calculate +const metrics = { + monthlyBudget: config.plan.monthly_cost, + spentMTD: sum(usage.filter(u => isThisMonth(u)).map(u => u.cost_estimated)), + remaining: monthlyBudget - spentMTD, + percentUsed: (spentMTD / monthlyBudget) * 100, + daysInMonth: getDaysInMonth(), + daysElapsed: getDayOfMonth(), + daysRemaining: daysInMonth - daysElapsed, + dailyAverage: spentMTD / daysElapsed, + projectedTotal: dailyAverage * daysInMonth, + runway: remaining / dailyAverage // Days until budget exhausted at current rate +}; +``` + +### Step 3: Determine Alert Level + +| Condition | Level | Emoji | +|-----------|-------|-------| +| percentUsed < 70 | Normal | 🟢 | +| percentUsed < 85 | Caution | 🟡 | +| percentUsed < 95 | Warning | 🟠 | +| percentUsed >= 95 | Critical | 🔴 | + +### Step 4: Format Output + +```markdown +## Budget Status + +{EMOJI} **{PERCENT}%** of monthly budget consumed + +| Metric | Value | +|--------|-------| +| Spent (MTD) | ${SPENT} | +| Remaining | ${REMAINING} | +| Days Left | {DAYS} | +| Daily Average | ${DAILY_AVG} | +| Projected Total | ${PROJECTED} | +| Runway | {RUNWAY} days | + +{ALERT_MESSAGE if level > normal} + +{RECOMMENDATIONS if level > caution} +``` + +### Step 5: Recommendations by Level + +**Caution (🟡):** +- "Consider pacing heavier tasks toward end of month" +- "Current trajectory: on track / slightly over" + +**Warning (🟠):** +- "Recommend deferring non-essential research" +- "Focus on high-value tasks only" +- "Consider overnight processing for batch work" + +**Critical (🔴):** +- "Budget nearly exhausted" +- "Restrict to essential tasks only" +- "Wait for budget reset on {DATE}" + +--- + +## Integration + +This workflow is invoked by: +- Direct user request ("budget status", "usage") +- MorningBrief skill (daily report integration) +- AlertCheck workflow (when thresholds crossed) diff --git a/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/SyncUsage.md b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/SyncUsage.md new file mode 100644 index 00000000..ba5e3d19 --- /dev/null +++ b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/SyncUsage.md @@ -0,0 +1,111 @@ +# SyncUsage Workflow + +**Purpose:** Sync real-time usage data from AI service APIs and dashboards. + +--- + +## Voice Notification + +```bash +curl -s -X POST http://localhost:8888/notify \ + -H "Content-Type: application/json" \ + -d '{"message": "Syncing usage data from AI service dashboards"}' \ + > /dev/null 2>&1 & +``` + +--- + +## Reality Check + +Most AI services **do not provide usage APIs** with standard API keys: + +| Service | API Access | Workaround | +|---------|------------|------------| +| OpenAI | Needs Admin Key | Dashboard or middleware | +| Anthropic | Needs Admin Key | Dashboard (Claude Max = subscription) | +| Perplexity | No API | Dashboard only | +| xAI/Grok | No API | Dashboard only | +| Google | Needs Service Account | AI Studio dashboard | + +--- + +## Sync Methods + +### Method 1: Open All Dashboards (Quick Check) + +```bash +bun run ~/.claude/skills/BudgetMonitor/Tools/ScrapeDashboards.ts all +``` + +This opens all dashboards in browser tabs for manual verification. + +### Method 2: API Fetch (Where Available) + +```bash +bun run ~/.claude/skills/BudgetMonitor/Tools/FetchUsage.ts +``` + +This queries APIs that work with configured keys. + +### Method 3: Manual Entry + +After checking dashboards, update `~/.claude/BUDGET/usage.jsonl`: + +```bash +echo '{"timestamp":"2026-01-30T14:00:00Z","service":"openai","cost_usd":45.23,"source":"dashboard"}' >> ~/.claude/BUDGET/usage.jsonl +``` + +Or edit `~/.claude/BUDGET/TRACKER.md` directly. + +--- + +## Dashboard URLs + +| Service | Dashboard URL | +|---------|---------------| +| OpenAI | https://platform.openai.com/usage | +| Anthropic | https://console.anthropic.com/settings/usage | +| Perplexity | https://www.perplexity.ai/settings/api | +| xAI/Grok | https://console.x.ai/usage | +| Google AI Studio | https://aistudio.google.com/app/plan | + +--- + +## Future: Middleware Tracking + +For per-request tracking without admin APIs, we need middleware in the PAI inference layer: + +```typescript +// In Tools/Inference.ts - wrap API calls +async function trackUsage(provider: string, response: any) { + if (response.usage) { + appendFileSync(USAGE_PATH, JSON.stringify({ + timestamp: new Date().toISOString(), + service: provider, + tokens_input: response.usage.prompt_tokens, + tokens_output: response.usage.completion_tokens, + model: response.model + }) + '\n'); + } +} +``` + +This would capture costs at the source rather than polling dashboards. + +--- + +## Recommended Routine + +### Daily (via MorningBrief) +- Quick budget check via dashboard +- Note any services approaching limits + +### Weekly +- Run `bun run ~/.claude/skills/BudgetMonitor/Tools/ScrapeDashboards.ts all` +- Update TRACKER.md with actual figures +- Regenerate dashboard: `bun run ~/.claude/skills/BudgetMonitor/Tools/Dashboard.ts` + +### Monthly +- Archive to `~/.claude/BUDGET/history/YYYY-MM.jsonl` +- Review trends +- Adjust budgets as needed diff --git a/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/TrackSession.md b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/TrackSession.md new file mode 100644 index 00000000..6f160d80 --- /dev/null +++ b/Releases/v2.5/.claude/skills/BudgetMonitor/Workflows/TrackSession.md @@ -0,0 +1,134 @@ +# TrackSession Workflow + +**Purpose:** Record usage data for a completed session. + +--- + +## Trigger + +This workflow is called: +1. By session-end hook (automatic) +2. Manually via "track this session" +3. By overnight processor for batch recording + +--- + +## Steps + +### Step 1: Gather Session Data + +Collect from environment/context: +```typescript +const sessionData = { + timestamp: new Date().toISOString(), + session_id: process.env.CLAUDE_SESSION_ID || generateId(), + duration_minutes: calculateDuration(), + messages: countMessages(), + tokens_estimated: { + input: estimateInputTokens(), + output: estimateOutputTokens() + } +}; +``` + +### Step 2: Estimate Cost + +```typescript +// Load config +const config = loadConfig('~/.claude/BUDGET/config.yaml'); + +// Calculate cost based on plan type +if (config.plan.type === 'subscription') { + // For subscription, estimate based on typical usage distribution + // This is approximate - subscription doesn't have per-token billing + sessionData.cost_estimated = estimateSubscriptionCost(sessionData); +} else if (config.plan.type === 'api') { + // For API, calculate exact cost + const inputCost = (sessionData.tokens_estimated.input / 1_000_000) * config.plan.api.input_cost_per_1m; + const outputCost = (sessionData.tokens_estimated.output / 1_000_000) * config.plan.api.output_cost_per_1m; + sessionData.cost_estimated = inputCost + outputCost; +} +``` + +### Step 3: Add Metadata + +```typescript +// If available, add quality/value data +sessionData.rating = getSessionRating(); // If user rated +sessionData.tasks_completed = countVerifiedISC(); // ISC criteria verified +sessionData.skills_used = getSkillsInvoked(); // Which skills were used +``` + +### Step 4: Append to Log + +```bash +# Append as JSONL +echo '${JSON.stringify(sessionData)}' >> ~/.claude/BUDGET/usage.jsonl +``` + +### Step 5: Update Tracker + +Update `~/.claude/BUDGET/TRACKER.md` with new totals: +- Increment session count +- Add to running cost total +- Update daily log table +- Recalculate averages + +### Step 6: Check Alerts + +Invoke AlertCheck workflow to see if thresholds crossed. + +--- + +## Token Estimation Heuristics + +Since exact token counts aren't always available: + +| Content Type | Avg Tokens/Message | +|--------------|-------------------| +| User message (short) | 50-200 | +| User message (with code) | 500-2000 | +| Assistant response (short) | 200-500 | +| Assistant response (with code) | 1000-5000 | +| Tool call | 100-300 | +| Tool result | 200-2000 | + +### Formula +```typescript +function estimateTokens(messages) { + let input = 0, output = 0; + + for (const msg of messages) { + const base = msg.content.length / 4; // Rough char-to-token + const adjustment = hasCode(msg) ? 1.5 : 1.0; + + if (msg.role === 'user') input += base * adjustment; + else output += base * adjustment; + } + + return { input, output }; +} +``` + +--- + +## Integration + +### Session End Hook + +Add to `~/.claude/hooks/session-end.sh`: +```bash +#!/bin/bash +# Track session usage +bun run ~/.claude/skills/BudgetMonitor/Tools/TrackSession.ts \ + --session-file="$1" \ + >> ~/.claude/BUDGET/tracking.log 2>&1 +``` + +### Manual Tracking + +``` +User: "Track this session" +→ Invokes TrackSession with current session data +→ Returns: "Session recorded: ~$X.XX estimated, Y messages, Z tasks" +```