cost-tracking
affaan-m/ECC
根据本地 ECC 成本追踪器指标日志,分析 Claude Code 代币的使用情况、支出及预算。提供汇总数据、按模型、会话或日期分类的明细,并支持导出为 CSV 文件。
...展开全部成本追踪
使用此技能分析来自ECC的stop:cost-tracker钩子所写入的指标日志中的
Claude Code成本和使用历史。
数据存储位置
追踪器会为每个会话停止事件向
~/.claude/metrics/costs.jsonl 追加一个 JSON 对象。每行数据都是该
会话的累计快照,因此要计算总支出,需针对每个session_id提取最新一行数据,
并跨会话求和——注意,每行数据的求和会产生多次计数。
行结构:
| 字段 | 含义 |
|---|---|
timestamp |
快照的 ISO 时间戳 |
session_id |
Claude Code 会话标识符 |
transcript_path |
会话记录的路径 |
model |
使用的模型 |
输入令牌数/输出令牌数 |
令牌计数 |
cache_write_tokens/cache_read_tokens |
提示词缓存中的令牌数量 |
estimated_cost_usd |
该会话的预计算累计成本(美元) |
建议优先使用estimated_cost_usd而非手动计算定价——模型和缓存
价格会发生变化,而追踪器才是权威数据来源。
何时使用
- 用户询问“我花了多少钱?”、“本次会话花费多少?”或 “我的代币使用量是多少?”
- 用户提及预算、支出限额、超支或成本控制。
- 用户希望按模型、会话或日期获取成本明细,或导出 CSV 文件。
工作原理
首先验证日志是否存在(使用node,而非sqlite3— 追踪器写入
JSONL 格式,且node支持跨平台):
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)?"找到成本日志":"未找到成本日志: "+f)'
如果日志缺失,请勿伪造使用数据。告知用户,成本
跟踪数据将在首次会话结束且启用了stop:cost-tracker
钩子后生成。
示例 — 按模型分类的过去 7 天汇总
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("未找到成本日志:"+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("今天: " + f4(sum(latest.filter(r => day(r) === today))) + " | 昨天: " + f4(sum(latest.filter(r => day(r) === yesterday))) + " | 总计: " + f4(sum(latest)) + " (" + latest.length + " 次会话)");
const m=new Map();for(const r of latest){const k=r.model||"(未知)";m.set(k,(m.get(k)||0)+cost(r));}
console.log("按模型分类:");[...m.entries()].sort((a,b)=>b[1]-a[1]).forEach(([k,v])=>console.log(" "+f4(v)+" "+k));
'
若要进行会话细分或导出 CSV,请遍历同一组最新数据(或 CSV 的原始
行),并输出所需的字段。
报告指南
在呈现成本数据时,应包含今日与昨日的支出对比、所有 会话的总计、按模型细分的明细以及会话次数。小于一美元的金额 格式化为四位小数,较大金额则保留两位小数。
反模式
- 切勿对每行数据求和——这些数据是按会话累积的;应先按
session_id筛选出 每个会话的最新一行。 - 当存在
estimated_cost_usd字段时,请勿根据原始代币计数估算成本。 - 未经核查,请勿假设日志存在。
- 请勿在面向用户的回答中硬编码当前模型的定价。
- 不要建议安装未经审核且会执行任意代码的钩子或插件。
相关
/cost-report- 基于同一指标日志的命令行格式报告。cost-aware-llm-pipeline- 模型路由和预算设计模式。token-budget-advisor- 上下文和令牌预算规划。strategic-compact- 通过上下文压缩减少重复的令牌消耗。
---
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.
所有文件
1 个文件安装 cost-tracking
下载技能文件并将其解压到 .claude/skills/ 目录下。
下载ZIP克隆仓库并复制技能文件到您的项目中。
git clone https://github.com/affaan-m/ECC/tree/main/skills/cost-tracking # Copy SKILL.md to your .claude/skills/ directory
复制





首页
