Communitygithub.com

费用追踪

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

费用追踪 是什么?

该技能用于分析 Claude Code 的成本和使用历史记录,数据来源于 ECC 的 `stop:cost-tracker` 钩子写入的指标日志文件 `~/.claude/metrics/costs.jsonl`。该文件以 JSONL 格式存储每次会话停止时的累积快照,因此计算总花费时必须按 `session_id` 取每行最新行再求和,避免重复计数。技能通过 Node.js 脚本读取和解析日志,支持按日期、模型或会话进行摘要、细目和 CSV 导出。它能提供今日、昨日与总花费对比、按模型分解以及会话数量等关键报告,帮助用户监控预算、控制成本,并避免常见陷阱如重复求和或手动估算价格。

兼容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/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 集合(或行原始数据用于 CSV)并打印所需字段。

报告指南

呈现成本数据时,应包括今日支出与昨日对比、所有会话的总计、按模型分解以及会话数量。金额小于 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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相关技能