ericrisco/rsc-harness/cost-tracking
Claude Code and agent skill by ericrisco/rsc-harness
- community
Checking that the SKILL.md file is still in the repository.
Use when metering and capping AI or cloud app spend — tokens read from the response `usage` object, priced off a dated rate table, ledgered per user/tenant/feature, with alerts and a hard cap before the bill. NOT cash runway (that is `finance-ops`), NOT cost-per-unit margin (that is `unit-economics`), NOT booking the spend (that is `bookkeeping`).
Install
npx vskill@latest install ericrisco/rsc-harness/cost-trackingSKILL.md
The same SKILL.md was published earlier as ericrisco/rsc-harness/cost-tracking.
Cost tracking
You are building the money meter for an AI or cloud app: every model call gets a token count, a price, a ledger row, and a budget check — so a cap fires before the invoice, not when finance forwards it in a panic. Model-API spend roughly doubled from $3.5B to $8.4B between late 2024 and mid 2025 (firecrawl.dev best-llm-observability-tools, accessed 2026-06-02); the bill is now big enough to need a guardrail, not a spreadsheet at month-end.
The chain you build, in order — each step feeds the next:
- Capture — read tokens from the response, not from a pre-send guess.
- Price — multiply tokens by a versioned, dated rate table.
- Ledger — append one idempotent row per request, tagged for attribution.
- Budget — roll the ledger up against a soft and a hard threshold.
- Guard — alert, degrade, or refuse before the threshold becomes an invoice.
The one rule that organizes everything: bill against the response `usage` object. Anything you compute before the call is an estimate — good only for the pre-flight cap check, never for the ledger.
What this skill produces
A checkable cost setup: a pricing table (each model row carries effective_date + source), an append-only ledger schema (idempotency key + attribution keys), and a budget with both a soft and a hard threshold. scripts/verify.sh lints those artifacts (last section). Prose alone is not a deliverable — emit the config.
Capture: read usage, do not estimate
Pre-send token counts (tiktoken, Anthropic client.messages.count_tokens()) are estimates. They exist for the pre-flight cap check — "will this request likely breach the budget?" — and nothing else. The truth lands in the response: input, output, cached, and reasoning tokens, plus audio/image tokens where the modality applies. Bill the ledger off that object.
Two provider facts that bite if you assume otherwise:
- Anthropic
count_tokens()returns input tokens only, is free, has its own rate limit, and is still an estimate. Anthropic is not tiktoken-compatible — do not reuse an OpenAI tokenizer to price Claude (platform.claude.com token-counting; github.com/anthropics/anthropic-tokenizer-typescript, accessed 2026-06-02). - Output and reasoning tokens are the expensive half — output runs 4-5x the input rate. A meter that only counts input is wrong by most of the bill.
Wrap the SDK call once so capture cannot be skipped. A meter you have to remember to call is a meter that's already missing rows (langfuse.com token-and-cost-tracking, accessed 2026-06-02).
Pricing is data, never literals
Rates drift fast and silently mis-bill when stale. Keep prices in a versioned table — one row per model, each with effective_date and source — loaded as data. Never write a rate as a literal in business logic. Look up by model and fail loud on an unknown model; never default to $0, or a new model silently bills as free and the leak is invisible.
These numbers are a snapshot, not a constant — model names and rates move month to month. Each row carries its own effective_date and source. A price that depends on prompt size (Haiku 5.5 above 100K tokens) gets one row per tier, as above: price() picks the row whose prompt-size bounds contain the request's input tokens, and fails loud when none does. The dated per-provider snapshots, the usage-field map per provider, and refresh instructions live in references/pricing-tables.md; read it before you trust a rate.
Ledger: append-only, idempotent, attributed
One row per request, append-only. Two things must be on every row or the ledger lies:
- A request/idempotency key. Retries and SDK auto-retries fire the same logical call twice; without a key the row is written twice and you double-count spend.
- At least one attribution key (user, tenant, feature, model). A per-org total can tell you the bill is high; it cannot tell you which feature or customer is the leak. Attribution is the difference between "spend is up" and "the summarize-document feature on the enterprise tenant tripled."
This is an operational ledger, not the accounting record — categorizing the spend into the books is bookkeeping, and the same rows feed the cost numerator in unit-economics and one input line in finance-ops. "Cost per active user" on the behavior side is analytics; charging customers for metered usage is stripe.
Budgets, alerts, caps
A budget needs a soft state (alert + degrade) and a hard state (refuse). Roll the ledger up per window (day/month) and per attribution key, then branch:
| Spend vs budget | State | Action | |
|---|---|---|---|
| < 50% | normal | log only | |
| 50% / 80% | warn | fire alert to the same pipe as cloud alerts; no behavior change | |
| 100% | soft cap | degrade — downshift to a cheaper model, drop optional/enrichment calls, shrink context | |
| over hard cap | hard cap | refuse the request with a typed error (BudgetExceededError), not a silent failure |
Two distinct checks, do not conflate them:
- Pre-flight gate uses the estimate (pre-send token count × rate) to refuse a request that would obviously blow the hard cap — this is the only legitimate use of an estimate.
- Post-hoc reconciliation rolls up the ledger (real
usage) against the budget. When someone asks "why is the bill 3x the estimate," you compare provider-billed usage to your ledgeredusage— the gap is almost always uncounted output/reasoning/cache-write tokens or missing rows from un-wrapped call sites.
The three levers that move the number
Don't assert savings — show the break-even. Pricing per fact-checked sources accessed 2026-06-02 (platform.claude.com prompt-caching; finout.io anthropic-api-pricing).
- Prompt caching. Cache reads cost 0.05x base input on Opus 5.5 and Sonnet 5.5, 0.1x on Haiku 5.5 (
references/pricing-tables.md). The 5-min write costs 1.25x, the 1-hour write 2x. So a 5-min entry pays for itself after one cache hit:1.25 + r·h(cached,r= read ratio) beats1·(1+h)(uncached) onceh ≥ 0.25/(1−r), which ish ≥ 1at either ratio. Caching a stable system prompt across a session is almost always net cheaper. - Batch API. 50% off on both OpenAI and Anthropic, async within 24h, and it stacks with caching — combined up to ~95% off. Use it for anything not user-facing-realtime: evals, backfills, nightly summaries.
- Model downshift. The largest lever. Route easy requests to Haiku/cheap models and reserve Opus/GPT-5.5 for hard ones — Opus 5.5 input costs 40x Haiku 5.5 ($4 vs $0.10 per MTok) and 2x Sonnet 5.5, downshifting the routable half of traffic dwarfs a few percent of caching.
"We'll add caching later" without measuring the hit rate is a guess, not a lever. Instrument cache_read_tokens in the ledger first, then you know.
Cloud spend is the slow backstop
App-level metering is your real-time guard. Cloud billing alerts are a delayed backstop — useful, but never the thing standing between you and a runaway loop.
- AWS Cost Anomaly Detection is ML-based, runs ~3x/day with up to 24h data delay → SNS → Lambda. AWS Budgets adds threshold alerts on the same pipe.
- GCP/Azure are threshold-only. GCP's budget → Pub/Sub → Cloud Function is the one that can actually pause or throttle a workload programmatically.
Route every cloud alert into the same alert pipe as your app-level budget alerts so there's one place to look. The 24h delay is exactly why the in-app cap exists: by the time AWS notices the anomaly, the loop already spent the money. Recipes and the alert-routing pattern are in references/cloud-caps.md; the cap plumbing in depth is aws-essentials / gcp-essentials.
Build vs buy
| You want | Use | Trade-off | |
|---|---|---|---|
| Zero code change, fastest setup | Helicone (proxy, ~2-min) | adds a network hop / latency | |
| SDK-level capture + a ready cost table | Langfuse (MIT, ships model+tokenizer cost table) | you wire the SDK, but no proxy hop | |
| Hard spend caps at a gateway, per team or app key | Bifrost (self-hosted, Apache-2.0; budgets and rate limits per virtual key) | one more service to run; caps are per key, not per feature | |
| Full control / custom attribution / typed caps | DIY ledger (this skill) | you own pricing-table freshness and capture coverage |
(firecrawl.dev best-llm-observability-tools; guptadeepak.com top-5-llm-observability-platforms-2026, accessed 2026-06-02; docs.getbifrost.ai features/governance/virtual-keys, accessed 2026-10-19.) Buy the proxy/platform when you want spend visibility fast; build the ledger when caps and per-feature attribution must live inside your own logic.
Anti-patterns
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/cost-tracking/SKILL.md
Popularity
- Repository stars
- 141
- Repository forks
- 11
- 7-day trend score
- 30
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/ericrisco/rsc-harness/cost-tracking)