Option

cost-tracking

affaan-m/ECC affaan-m/ECC

Analysiert die Nutzung, die Ausgaben und die Budgets von Claude Code-Token anhand des lokalen ECC-Kosten-Tracker-Metrikenprotokolls. Bietet Zusammenfassungen, Aufschlüsselungen nach Modell, Sitzung oder Datum sowie einen CSV-Export.

...Alle erweitern
32
Zeit aktualisiert 2. Oktober 2026

Kostenverfolgung

Verwenden Sie diese Funktion, um die Kosten- und Nutzungshistorie von Claude Code anhand des Metriken-Protokolls zu analysieren, das der „stop:cost-tracker“- Hook von ECC schreibt.

Speicherort der Daten

Der Tracker fügt pro Session-Stop ein JSON-Objekt an die Datei ~/.claude/metrics/costs.jsonl an. Jede Zeile ist eine kumulative Momentaufnahme für diese Session. Um die Gesamtausgaben zu ermitteln, nehmen Sie daher die neueste Zeile pro session_id und summieren über alle Sessions hinweg – dabei werden die Zeilen mehrfach gezählt.

Zeilenschema:

Feld Bedeutung
timestamp ISO-Zeitstempel des Momentaufnahmes
session_id Claude-Code-Sitzungskennung
transcript_path Pfad zum Sitzungsprotokoll
Modell Verwendetes Modell
input_tokens / output_tokens Token-Anzahl
cache_write_tokens / cache_read_tokens Tokenanzahl im Prompt-Cache
geschätzte_Kosten_in_USD Vorab berechnete kumulierte Kosten in USD für die Sitzung

Verwenden Sie „estimated_cost_usd“ anstelle von manuell berechneten Preisen – Modell- und Cache-Preise ändern sich, und der Tracker ist die maßgebliche Quelle.

Anwendungsfälle

  • Der Nutzer fragt: „Wie viel habe ich ausgegeben?“, „Was hat diese Sitzung gekostet?“ oder „Wie hoch ist mein Token-Verbrauch?“
  • Der Benutzer erwähnt Budgets, Ausgabenobergrenzen, Überschreitungen oder Kostenkontrollen.
  • Der Nutzer wünscht eine Kostenaufschlüsselung nach Modell, Sitzung oder Datum oder einen CSV-Export.

So funktioniert es

Überprüfen Sie zunächst, ob das Protokoll vorhanden ist (verwenden Sie „node“, nicht „sqlite3“ – der Tracker schreibt JSONL, und „node“ ist plattformübergreifend):

node -e 'const fs=require("fs"),os=require("os"),p=require("path");const f=p.join(os.homedir(),".claude","metrics","costs.jsonl");console.log(fs.existsSync(f)?"Kostenprotokoll gefunden":"Kostenprotokoll nicht gefunden: "+f)'

Falls das Protokoll fehlt, dürfen keine Nutzungsdaten erfunden werden. Teilen Sie dem Nutzer mit, dass die Kostenverfolgung erst nach Beendigung der ersten Sitzung mit aktiviertem „stop:cost-tracker“-Hook mit Daten gefüllt wird.

Beispiel – Zusammenfassung nach Modell für die letzten 7 Tage

node -e '
const fs=require("fs"),os=require("os"),path=require("path");
const f=path.join(os.homedir(),".claude","metrics","costs.jsonl");
if(!fs.existsSync(f)){console.log("Kostenprotokoll nicht gefunden: "+f);process.exit(0);}
const rows = fs.readFileSync(f, „utf8“).split(/\r?\n/).filter(Boolean).map(l => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean);
const bySession = new Map();
for (const r of rows) { const k = r.session_id || r.transcript_path || r.timestamp; const p = bySession.get(k); if (!p || String(r.timestamp)>String(p.timestamp)), bySession.set(k, r);}
const latest = [...bySession.values()];
const cost = r => Number(r.estimated_cost_usd) || 0, day = r => String(r.timestamp || "").slice(0, 10), sum = a => a.reduce((s, r) => s + cost(r), 0), f4 = n => "$" + n.toFixed(4);
const today = new Date().toISOString().slice(0, 10), yest = new Date(Date.now() - 864e5).toISOString().slice(0, 10);
console.log("heute: "+f4(sum(latest.filter(r=>day(r)===today)))+" | gestern: " + f4(sum(latest.filter(r => day(r) === yest))) + " | insgesamt: " + f4(sum(latest)) + " (" + latest.length + " Sitzungen)");
const m = new Map(); for (const r of latest) { const k = r.model || „(unknown)“; m.set(k, (m.get(k) || 0) + cost(r)); }
console.log(„nach Modell:“); [...m.entries()].sort((a, b) => b[1] - a[1]).forEach(([k, v]) => console.log("  " + f4(v) + "  " + k));
'

Für einen Sitzungs-Drilldown oder einen CSV-Export durchlaufen Sie denselben aktuellen Datensatz (oder die Rohdatenzeilen für CSV) und geben Sie die benötigten Felder aus.

Hinweise zur Berichterstellung

Bei der Darstellung von Kostendaten sollten Sie die heutigen Ausgaben im Vergleich zu gestern, die Gesamtsumme über alle Sitzungen, eine Aufschlüsselung nach Modellen und die Anzahl der Sitzungen angeben. Formatieren Sie Beträge unter einem Dollar mit vier Dezimalstellen, größere Beträge mit zwei.

Anti-Muster

  • Summieren Sie nicht jede Zeile – die Werte sind pro Sitzung kumulativ; reduzieren Sie die Daten zunächst auf die aktuellste Zeile pro session_id.
  • Schätzen Sie die Kosten nicht anhand der rohen Token-Anzahlen, wenn „estimated_cost_usd“ vorhanden ist.
  • Gehen Sie nicht davon aus, dass das Protokoll vorhanden ist, ohne dies zu überprüfen.
  • Harten Sie die aktuellen Modellpreise nicht in benutzersichtbaren Antworten fest ein.
  • Empfehlen Sie nicht die Installation von nicht geprüften Hooks oder Plugins, die beliebigen Code ausführen.

Verwandte Themen

  • /cost-report – Bericht im Befehlsformat über dasselbe Metriken-Protokoll.
  • cost-aware-llm-pipeline – Muster für Modell-Routing und Budgetgestaltung.
  • token-budget-advisor – Kontext- und Token-Budget-Planung.
  • strategic-compact – Kontextkomprimierung zur Reduzierung wiederholter Token-Ausgaben.
Auf GitHub ansehen
---
name: cost-tracking
description: Analyze Claude Code token usage, spending, and budgets from the local ECC cost-tracker metrics log. Provides summaries, breakdowns by model, session, or date, and CSV export.
---

# Cost Tracking

Use this skill to analyze Claude Code cost and usage history from the metrics log
that ECC's `stop:cost-tracker` hook writes.

## Where the data lives

The tracker appends one JSON object per session-stop to
`~/.claude/metrics/costs.jsonl`. Each row is a **cumulative snapshot for that
session**, so to total spend you take the **latest row per `session_id`** and
sum across sessions — summing every row multiply-counts.

Row schema:

| Field | Meaning |
| --- | --- |
| `timestamp` | ISO timestamp of the snapshot |
| `session_id` | Claude Code session identifier |
| `transcript_path` | Path to the session transcript |
| `model` | Model used |
| `input_tokens` / `output_tokens` | Token counts |
| `cache_write_tokens` / `cache_read_tokens` | Prompt-cache token counts |
| `estimated_cost_usd` | Precomputed cumulative cost in USD for the session |

Prefer `estimated_cost_usd` over hand-calculating pricing — model and cache
prices change, and the tracker is the source of truth.

## When to Use

- The user asks "how much have I spent?", "what did this session cost?", or
  "what is my token usage?"
- The user mentions budgets, spending limits, overruns, or cost controls.
- The user wants a cost breakdown by model, session, or date, or a CSV export.

## How It Works

First verify the log exists (use `node`, not `sqlite3` — the tracker writes
JSONL, and `node` is cross-platform):

```bash
node -e 'const fs=require("fs"),os=require("os"),p=require("path");const f=p.join(os.homedir(),".claude","metrics","costs.jsonl");console.log(fs.existsSync(f)?"cost log found":"cost log not found: "+f)'
```

If the log is missing, do not fabricate usage data. Tell the user that cost
tracking populates after the first session ends with the `stop:cost-tracker`
hook enabled.

## Example — summary, by model, last 7 days

```bash
node -e '
const fs=require("fs"),os=require("os"),path=require("path");
const f=path.join(os.homedir(),".claude","metrics","costs.jsonl");
if(!fs.existsSync(f)){console.log("cost log not found: "+f);process.exit(0);}
const rows=fs.readFileSync(f,"utf8").split(/\r?\n/).filter(Boolean).map(l=>{try{return JSON.parse(l)}catch{return null}}).filter(Boolean);
const bySession=new Map();
for(const r of rows){const k=r.session_id||r.transcript_path||r.timestamp;const p=bySession.get(k);if(!p||String(r.timestamp)>String(p.timestamp))bySession.set(k,r);}
const latest=[...bySession.values()];
const cost=r=>Number(r.estimated_cost_usd)||0, day=r=>String(r.timestamp||"").slice(0,10), sum=a=>a.reduce((s,r)=>s+cost(r),0), f4=n=>"$"+n.toFixed(4);
const today=new Date().toISOString().slice(0,10), yest=new Date(Date.now()-864e5).toISOString().slice(0,10);
console.log("today: "+f4(sum(latest.filter(r=>day(r)===today)))+" | yesterday: "+f4(sum(latest.filter(r=>day(r)===yest)))+" | total: "+f4(sum(latest))+" ("+latest.length+" sessions)");
const m=new Map();for(const r of latest){const k=r.model||"(unknown)";m.set(k,(m.get(k)||0)+cost(r));}
console.log("by model:");[...m.entries()].sort((a,b)=>b[1]-a[1]).forEach(([k,v])=>console.log("  "+f4(v)+"  "+k));
'
```

For a session drilldown or CSV export, iterate the same `latest` set (or the raw
rows for CSV) and print the fields you need.

## Reporting Guidance

When presenting cost data, include today's spend vs yesterday, total across all
sessions, a by-model breakdown, and session count. Format sub-dollar amounts
with four decimals, larger amounts with two.

## Anti-Patterns

- Do not sum every row — they are cumulative per session; reduce to the latest
  row per `session_id` first.
- Do not estimate costs from raw token counts when `estimated_cost_usd` is present.
- Do not assume the log exists without checking.
- Do not hard-code current model pricing in user-facing answers.
- Do not recommend installing unreviewed hooks or plugins that execute arbitrary code.

## Related

- `/cost-report` - Command-form report over the same metrics log.
- `cost-aware-llm-pipeline` - Model-routing and budget-design patterns.
- `token-budget-advisor` - Context and token-budget planning.
- `strategic-compact` - Context compaction to reduce repeated token spend.

Alle Dateien

1 Dateien

cost-tracking installieren

Laden Sie die Skill-Dateien herunter und entpacken Sie sie in Ihr Verzeichnis „.claude/skills/“.

ZIP herunterladen

Klonen Sie das Repository und kopieren Sie die Skill-Dateien in Ihr Projekt.

git clone https://github.com/affaan-m/ECC/tree/main/skills/cost-tracking # Copy SKILL.md to your .claude/skills/ directory

Kopieren Kopieren
Schnelle Einrichtung: Kopiere den Skill-Ordner nach .claude/skills/ Claude erkennt den Skill automatisch und nutzt ihn.
Repository affaan-m/ECC

Ähnliche Skills

airtable-automation
Zeit aktualisiert 29. Juni 2026
notion-automation
Zeit aktualisiert 29. Juni 2026
seo-programmatic
Zeit aktualisiert 29. Juni 2026
revops
Zeit aktualisiert 29. Juni 2026
OR