Communitygithub.com

成本追蹤

追蹤並報告 Claude Code 的代幣用量、花費與預算,資料來源為本機 ECC 成本追蹤器指標日誌。當使用者詢問成本、花費、用量、代幣、預算或依模型、工作階段、日期的成本明細時使用。

成本追蹤 是什麼?

這個技能讓 AI 代理能夠查詢並報告 Claude Code 的累積成本與代幣用量,資料來自 ECC 的 `stop:cost-tracker` 事件所寫入的本機 JSONL 日誌檔 (`~/.claude/metrics/costs.jsonl`)。日誌中每一行對應一個工作階段的累積快照,因此正確的總和計算方式是針對每個 `session_id` 只取最新的一行,再跨工作階段加總,而非直接加總所有行。技能提供範例指令來檢查日誌是否存在、計算當日/昨日/總花費、依模型分類、以及匯出 CSV 明細。也明確列出反模式(例如不要重複計算累積行、不要手動推算成本),並建議報告時包含當日 vs 昨日、模型細項、工作階段數量等指標。支援的平台為 Claude Code(搭配 ECC 掛鉤),使用 `node` 讀取 JSONL 檔案。

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/cost-tracking

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

成本追蹤 是做什麼的?

使用這項技能來分析來自 ECC 的 stop:cost-tracker 掛鉤所寫入的指標日誌,以取得 Claude Code 的成本與用量歷史。

資料存放位置

追蹤器在每次工作階段結束時,會附加一個 JSON 物件到 ~/.claude/metrics/costs.jsonl。每一列是該工作階段的累積快照,因此要計算總花費時,應取每個 session_id 最新的那一列,再跨工作階段加總——若對每一列都加總會造成重複計算。

各欄位說明:

欄位意義
timestamp快照的 ISO 時間戳記
session_idClaude Code 工作階段識別碼
transcript_path工作階段逐字稿的路徑
model使用的模型
input_tokens / output_tokens代幣數量
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)?"cost log found":"cost log not found: "+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("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));
'

若要取得單一工作階段的明細或 CSV 匯出,請對相同的 latest 集合(或原始列)進行迭代,並輸出所需的欄位。

報告指南

呈現成本資料時,應包含當日花費 vs 昨日、所有工作階段的總和、依模型分類的明細,以及工作階段數量。金額小於 1 美元時格式化成四位小數,較大金額則使用兩位小數。

反模式

  • 不要對每一列都加總——它們是每個工作階段的累積值;應先歸約至每個 session_id 的最新一列。
  • 如果 estimated_cost_usd 存在,不要使用原始代幣數量來估算成本。
  • 不要未經檢查就假設日誌檔案存在。
  • 不要在回覆中使用使用者目前看到的模型定價(請勿硬編碼)。
  • 不要建議安裝未經審查的掛鉤或會執行任意程式碼的插件。

相關

  • /cost-report - 基於相同指標日誌的命令列報告。
  • cost-aware-llm-pipeline - 模型路由與預算設計模式。
  • token-budget-advisor - 上下文與代幣預算規劃。
  • strategic-compact - 情境壓縮以減少重複的代幣花費。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相關技能