選項

cost-tracking

affaan-m/ECC affaan-m/ECC

根據本機 ECC 成本追蹤器指標日誌,分析 Claude Code 代幣的使用情況、支出及預算。提供摘要、依模型、會話或日期分類的明細,並支援 CSV 匯出功能。

...展開全部
32
更新時間 2026-10-02

成本追蹤

使用此技能,可根據 ECC 的stop:cost-tracker鉤子所寫入的指標日誌, 分析 Claude Code 的成本與使用紀錄。

資料儲存位置

追蹤器會針對每個 session-stop 將一個 JSON 物件追加至 ~/.claude/metrics/costs.jsonl。每行皆為該 會話的累計快照,因此要計算總支出時,需針對每個session_id取最新一行,並 跨會話求和 — 注意,每行求和會產生重複計數。

資料列結構:

欄位 含義
timestamp 快照的 ISO 時間戳記
session_id Claude Code 會話識別碼
對話記錄路徑 會話記錄的路徑
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- 透過上下文壓縮來減少重複的代幣消耗。
在 GitHub 上查看
---
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

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ Claude 會自動偵測並使用該技能
儲存庫 affaan-m/ECC

相關技能

airtable-automation
更新時間 2026-06-29
notion-automation
更新時間 2026-06-29
seo-programmatic
更新時間 2026-06-29
revops
更新時間 2026-06-29
OR