Communitygithub.com

成本追踪

追踪并报告 Claude Code 的令牌用量、花费和预算,数据来源于本地 ECC 成本追踪器指标日志。当用户询问成本、花费、用量、令牌、预算或按模型、会话、日期的成本明细时使用。

成本追踪 是什么?

该技能允许 AI 助手(尤其是 Claude Code)直接分析本地存储的指标日志,回答关于 Claude Code 使用成本和令牌消耗的问题。它利用 `stop:cost-tracker` 钩子在每个会话结束时写入的 `~/.claude/metrics/costs.jsonl` 文件,该文件包含每个会话的累积快照(JSON 行格式)。技能会教会助手正确处理数据:先按 `session_id` 保留最新行(以避免重复计算),然后按模型和日期汇总成本。如果日志文件缺失,它不会凭空捏造数据,而是提供清晰指引,告诉用户如何启用钩子。输出包括当日花费、昨日花费、总额、按模型分解及会话数量,金额展示精确到四或两位小数。该技能适用于所有支持运行 shell 命令获取本地 JSON 日志的平台,无需依赖第三方数据库或 API。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

成本追踪 是做什么的?

使用此技能来从指标日志中分析 Claude Code 成本和用量历史,该日志由 ECC 的 stop:cost-tracker 钩子写入。

数据存储位置

追踪器会在每次会话停止时向 ~/.claude/metrics/costs.jsonl 追加一个 JSON 对象。每一行是该会话的累积快照,因此要计算总花费,你需要取每个 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 集合(或原始行)进行迭代,并打印所需字段。

报告指南

在呈现成本数据时,应包括当日花费与昨日对比、所有会话的总计、按模型的分解以及会话数量。少于 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.

相关技能