Skip to main content
skill CX Codex

cost-accrual-tracker — Claude Code skill: real-time API cost tracking

cost-accrual-tracker — a skill for Claude Code and five other platforms that tracks API spending per response during LLM execution. Captures partial costs when a run is aborted mid-stream.

MIT 175 installs ★ 274 updated 2026-10-30

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add curiositech/some_claude_skills --skill cost-accrual-tracker -a claude-code
Open on GitHub

What cost-accrual-tracker does

Each API response triggers recordUsage(), which adds input and output tokens to a running total. getCurrentCost() returns the accrued amount at any point, so a UI widget can display live spend without polling faster than responses arrive.

Abort handling is explicit by design. The tracker calls finalize('aborted') before throwing AbortError, preserving token data for partial runs. Claude prompt caching is tracked separately: cache_read_input_tokens come at 90% lower cost, while cache_creation_input_tokens cost extra — lumping them with regular input tokens produces wrong totals.

The BudgetGuard pattern takes a maxCostUsd and a warn threshold; it returns 'warn' or 'exceed' and fires callbacks so execution can stop automatically. This skill covers live accrual only — not historical dashboards, pricing tiers, or billing infrastructure. It pairs with cost-optimizer and cost-verification-auditor from the same repository.

What it helps with

  • track API spend in real time across multiple LLM calls
  • capture partial token costs when a request is aborted
  • auto-stop execution once a dollar budget is hit
  • account for Claude prompt-cache savings in cost calculations
  • feed live cost data into an execution UI widget

Example prompts for the agent

  • Add real-time API cost tracking to this multi-step LLM pipeline
  • Set up auto-stop if total spend exceeds 0.50 USD
  • Show the partial token costs for the run that was just aborted

How to install cost-accrual-tracker

1Skills CLI (Vercel)

npx skills add curiositech/some_claude_skills --skill cost-accrual-tracker -a claude-code

2Manually: put the files in place

~/.claude/skills/cost-accrual-tracker/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/cost-accrual-tracker/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about cost-accrual-tracker

How do I install cost-accrual-tracker in Claude Code?

Run npx skills add curiositech/some_claude_skills --skill cost-accrual-tracker -a claude-code. The skill file will be placed at ~/.claude/skills/cost-accrual-tracker/SKILL.md.

What does cost-accrual-tracker do?

It accumulates API costs response by response during LLM execution, exposes the running total for live display, and captures partial costs if the run is aborted before completion.

Does cost-accrual-tracker work with Claude prompt caching?

Yes. It tracks cache_read_input_tokens and cache_creation_input_tokens as separate buckets, because mixing them with standard input tokens gives inaccurate cost figures.

Source text

SKILL.md · MIT
---
name: cost-accrual-tracker
description: Track real-time API cost accrual during LLM execution. Activate on 'cost tracking', 'token usage', 'API costs', 'budget monitoring', 'usage metrics'. NOT for cost estimation, pricing tiers,
  or billing systems.
allowed-tools: Read,Write,Edit
metadata:
  tags:
  - cost
  - accrual
  - tracker
  pairs-with:
  - skill: cost-optimizer
    reason: Real-time cost tracking data feeds the optimizer decision engine for model downgrades
  - skill: cost-verification-auditor
    reason: Tracked costs are validated against actual API bills by the verification auditor
  - skill: llm-router
    reason: Cost accrual data informs the router model selection to stay within budget
---

# Cost Accrual Tracker

Real-time tracking of API costs during LLM execution with support for partial costs on abort.

## When to Use

✅ **Use for**:
- Implementing real-time cost tracking during execution
- Capturing partial costs when executions are aborted
- Building cost display widgets for execution UIs
- Integrating token counting into execution pipelines
- Adding budget thresholds with auto-stop

❌ **NOT for**:
- Cost estimation before execution (use pricing calculators)
- Billing system design (use billing-system skill)
- Price tier management or discounts
- Historical cost analytics dashboards

## Core Patterns

### 1. Token-Based Cost Calculation

```typescript
interface TokenUsage {
  inputTokens: number;
  outputTokens: number;
  cacheReadTokens?: number;   // Prompt caching hits
  cacheWriteTokens?: number;  // Prompt caching misses
}

interface CostCalculation {
  inputCostUsd: number;
  outputCostUsd: number;
  cacheSavingsUsd?: number;
  totalCostUsd: number;
}

function calculateCost(usage: TokenUsage, model: string): CostCalculation {
  const pricing = MODEL_PRICING[model];

  const inputCostUsd = (usage.inputTokens / 1_000_000) * pricing.inputPerMTok;
  const outputCostUsd = (usage.outputTokens / 1_000_000) * pricing.outputPerMTok;

  return {
    inputCostUsd,
    outputCostUsd,
    totalCostUsd: inputCostUsd + outputCostUsd,
  };
}
```

### 2. Incremental Accrual Pattern

Track costs as they accrue, not just at completion:

```typescript
class CostAccrualTracker {
  private totalInputTokens = 0;
  private totalOutputTokens = 0;
  private accruedCostUsd = 0;
  private readonly model: string;

  constructor(model: string) {
    this.model = model;
  }

  /**
   * Called after each API response (streaming or complete)
   */
  recordUsage(usage: TokenUsage): void {
    this.totalInputTokens += usage.inputTokens;
    this.totalOutputTokens += usage.outputTokens;

    const cost = calculateCost(usage, this.model);
    this.accruedCostUsd += cost.totalCostUsd;
  }

  /**
   * Get current accrued cost (for real-time display)
   */
  getCurrentCost(): number {
    return this.accruedCostUsd;
  }

  /**
   * Finalize on completion or abort
   */
  finalize(reason: 'completed' | 'aborted' | 'failed'): CostReport {
    return {
      totalInputTokens: this.totalInputTokens,
      totalOutputTokens: this.totalOutputTokens,
      totalCostUsd: this.accruedCostUsd,
      completionReason: reason,
      finalizedAt: Date.now(),
    };
  }
}
```

### 3. Abort-Aware Cost Capture

**Critical**: Always capture partial costs on abort:

```typescript
// In execution handler
const tracker = new CostAccrualTracker(model);

try {
  for await (const chunk of executeStream(request)) {
    if (abortSignal.aborted) {
      // CRITICAL: Capture cost BEFORE throwing
      const partialCost = tracker.finalize('aborted');
      onCostUpdate(partialCost);
      throw new AbortError('Execution aborted');
    }

    tracker.recordUsage(chunk.usage);
    onCostUpdate(tracker.getCurrentCost());
  }

  return tracker.finalize('completed');
} catch (error) {
  if (error instanceof AbortError) {
    throw error; // Already handled
  }
  return tracker.finalize('failed');
}
```

### 4. Budget Threshold Pattern

Auto-stop execution when budget is exceeded:

```typescript
interface BudgetConfig {
  maxCostUsd: number;
  warnAtPercentage: number;  // e.g., 0.8 for 80%
  onWarn?: (current: number, max: number) => void;
  onExceed?: (current: number, max: number) => void;
}

function createBudgetGuard(config: BudgetConfig) {
  return {
    check(currentCostUsd: number): 'ok' | 'warn' | 'exceed' {
      const percentage = currentCostUsd / config.maxCostUsd;

      if (percentage >= 1.0) {
        config.onExceed?.(currentCostUsd, config.maxCostUsd);
        return 'exceed';
      }

      if (percentage >= config.warnAtPercentage) {
        config.onWarn?.(currentCostUsd, config.maxCostUsd);
        return 'warn';
      }

      return 'ok';
    }
  };
}
```

## Anti-Patterns

### Lost Costs on Abort

**Novice thinking**: "Just throw an error when aborted"

**Reality**: If you don't capture costs before aborting, you lose:
- Token usage data for partial execution
- Accurate cost reporting for billing
- Audit trail for debugging

**Timeline**: Always been an issue, but became critical with expensive models (GPT-4, Claude Opus)

**Correct approach**: Always call `finalize()` with partial data BEFORE throwing abort errors.

### Polling Without Debounce

**Novice thinking**: "Poll cost endpoint every 100ms for real-time updates"

**Reality**:
- Wastes bandwidth and CPU
- Cost updates only happen after API responses
- Polling faster than response rate is pointless

**Correct approach**: Poll at 1-2 second intervals, or use event-driven updates from the execution stream.

### Ignoring Prompt Caching

**Novice thinking**: "Just multiply tokens by price per token"

**Reality**: Claude's prompt caching changes the cost model:
- Cache reads are 90% cheaper
- Cache writes cost extra on first use
- Ignoring caching leads to inaccurate costs

**Timeline**:
- Pre-2024: No caching, simple calculation
- 2024+: Claude prompt caching requires separate tracking

**Correct approach**: Track `cache_read_input_tokens` and `cache_creation_input_tokens` separately.

### Per-Request Cost Objects

**Novice thinking**: "Create new tracker for each request"

**Reality**: For DAG execution with multiple nodes:
- Need aggregate cost across all nodes
- Need to attribute costs to specific nodes
- Need rollup for parent execution

**Correct approach**: Hierarchical tracking - per-node trackers that roll up to execution-level.

## State Flow

```
                    ┌─────────────────────────────────────────┐
                    │           CostAccrualTracker            │
                    └─────────────────────────────────────────┘
                                        │
              ┌─────────────────────────┼─────────────────────────┐
              │                         │                         │
              ▼                         ▼                         ▼
    ┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
    │  recordUsage()  │     │ getCurrentCost()│     │   finalize()    │
    │                 │     │                 │     │                 │
    │ After each API  │     │ For real-time   │     │ On completion,  │
    │ response        │     │ display         │     │ abort, or fail  │
    └─────────────────┘     └─────────────────┘     └─────────────────┘
              │                         │                         │
              │                         │                         │
              ▼                         ▼                         ▼
    ┌─────────────────────────────────────────────────────────────────┐
    │                        CostReport                               │
    │  { inputTokens, outputTokens, totalCostUsd, completionReason }  │
    └─────────────────────────────────────────────────────────────────┘
```

## UI Display Pattern

For real-time cost display in execution UIs:

```typescript
// Poll every 2 seconds while executing
useEffect(() => {
  if (status !== 'running') return;

  const interval = setInterval(async () => {
    const response = await fetch(`/api/execute/${executionId}`);
    const data = await response.json();
    setAccruedCost(data.cost.accruedUsd);
    setTokens({
      input: data.cost.inputTokens,
      output: data.cost.outputTokens,
    });
  }, 2000);

  return () => clearInterval(interval);
}, [executionId, status]);

// Display format
<div className="cost-display">
  <span className="cost-amount">${accruedCost.toFixed(4)}</span>
  <span className="token-count">
    {tokens.input.toLocaleString()} in / {tokens.output.toLocaleString()} out
  </span>
</div>
```

## Integration Points

| Component | Responsibility |
|-----------|----------------|
| `CostAccrualTracker` | Per-execution token counting and cost calculation |
| `ExecutionManager` | Aggregates costs across DAG executions |
| `BudgetGuard` | Threshold monitoring and auto-stop |
| `/api/execute/:id` | Exposes current cost via polling |
| Cost Display Widget | Real-time UI rendering |

## References

See `/references/claude-api-pricing.md` for current Claude API pricing.

© curiositech · MIT · curiositech/some_claude_skills

Similar skills

All skills for AI and ML →

From the same set180

The whole set →
nextjs-app-router-expert The nextjs-app-router-expert skill guides Next.js 14/15 App Router work, from route design to data loading. Use it when building or debugging server-rendered React features. CX Codex +1 176installs windows-95-web-designer windows-95-web-designer generates modern web apps styled with authentic Windows 95 design patterns, beveled chrome, and taskbars. Extrapolates retro OS layouts to AI dialogs and mobile viewports. CX Codex +1 176installs panic-room-finder The panic-room-finder skill helps map a house, spot possible concealed spaces, and plan a safe room. Use it to guide a non-destructive first look at a property. CX Codex +1 176installs pixel-art-infographic-creator pixel-art-infographic-creator is a Claude Code skill that draws diagrams and infographics in 16-bit SNES game style for educational materials. CX Codex +1 176installs openapi-spec-writer openapi-spec-writer writes OpenAPI 3.0 and 3.1 specifications for REST APIs. Useful for API-first design, contract definition, and setting up Swagger or Redoc documentation. CX Codex +1 175installs cost-verification-auditor cost-verification-auditor is a Claude Code skill that compares estimated token costs with actual API usage. It triggers when investigating a discrepancy between a forecast and an API bill. CX Codex +1 175installs values-behavioral-interview The values-behavioral-interview skill for Claude Code helps prepare structured stories for values and behavioral interviews, including failures and follow-up questions. CX Codex +1 174installs interview-loop-strategist interview-loop-strategist builds an end-to-end interview preparation roadmap for senior ML and AI engineering roles at Anthropic and peer teams. It structures timelines, mock sessions, and project narratives. CX Codex +1 173installs

Project sponsors

Companies that keep this analytics open