Cost Tracking

affaan-m/ECC/skills/cost-tracking

作者 affaan-mef648e01899ba3e8dc6371642deaaf64b4477775无许可证275K 个星标收录于 2026年10月9日更新于 2026年10月9日仓库4天前更新

Track and report Claude Code token usage, spending, and budgets from the local ECC cost-tracker metrics log. Use when the user asks about costs, spending, usage, tokens, budgets, or cost breakdowns by model, session, or date.

AI 生成的概览

从本地 JSONL 指标日志分析 Claude Code 的 token 用量与费用历史,并报告支出和预算。

功能
读取位于 ~/.claude/metrics/costs.jsonl 的本地成本跟踪指标日志,其中每行是该会话的累计快照,并先按会话归约到最新一行再汇总。生成支出摘要,例如今日与昨日对比、所有会话总计、会话数量,以及按模型、会话或日期的明细,并可选导出 CSV。同时说明行字段结构和快照缓存布局。
适用场景
适用于用户询问已花费多少、某次会话花费多少或 token 用量是多少的场景。也适合回答有关预算、支出上限、超支或按模型、会话、日期查看费用明细的问题。
运行要求
需要 Node.js 运行时来执行内联的检查与报告命令,并需要读取本地指标日志 ~/.claude/metrics/costs.jsonl 的权限,该日志由 ECC 的 stop:cost-tracker 钩子写入。该技能不附带脚本,仅为说明文档。

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.

ECC also maintains internal per-session files under ~/.claude/metrics/cost-snapshots/ so runtime hooks can read the current session total without rescanning all history. Treat those files as a rebuildable cache; each snapshot stores a byte cursor so only newly appended rows are scanned. Stable reads are O(1), while updates are O(new bytes). Stale entries are pruned after 30 days or when the directory exceeds 512 sessions. Cold catch-up work is limited to 16 MiB per hook invocation, and malformed unterminated rows larger than 1 MiB are discarded with a resumable cursor. Reports and exports should continue to use costs.jsonl.

Row schema:

FieldMeaning
timestampISO timestamp of the snapshot
session_idClaude Code session identifier
transcript_pathPath to the session transcript
modelModel used
input_tokens / output_tokensToken counts
cache_write_tokens / cache_read_tokensPrompt-cache token counts
estimated_cost_usdPrecomputed 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.

来源与署名

来源:affaan-m/ECC位于skills/cost-tracking提交ef648e0

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架