Communitygithub.com

成本追蹤

追蹤並報告 Claude Code 的 Token 用量、花費與預算,資料源自本機 ECC 成本追蹤器指標記錄檔。當使用者詢問關於成本、花費、用量、Token、預算,或想按模型、工作階段、日期查看明細時使用。

成本追蹤 是什麼?

此技能讓開發者能直接透過 Claude Code 分析與報告成本與用量歷史記錄,資料來源為 ECC 的 `stop:cost-tracker` Hook 所寫入的 JSONL 指標記錄檔。它會先確認記錄檔是否存在,接著讀取所有行,並針對每個 `session_id` 僅取時間戳記最新的一筆(因為每筆記錄是該工作階段的累積快照),避免重複計算。技能提供現成的 Node.js 腳本,可輸出今日、昨日花費、總花費、工作階段總數及按模型分類的明細,並支援 CSV 匯出與深入工作階段查詢。支援 Claude Code,且遵循不要自行推算成本、不要對未經驗證的 Hook 做安裝建議等反模式,確保報告準確且安全。

相容平台✓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 Hook 所寫入的指標記錄檔。

資料存放位置

追蹤器會在每次工作階段結束時附加一筆 JSON 物件至 ~/.claude/metrics/costs.jsonl。每行代表該工作階段的累積快照,因此若要計算總花費,需取每個 session_id 的最新一行並加總各工作階段的值——若直接加總所有行會造成重複計算。

行結構:

欄位說明
timestamp快照的 ISO 時間戳記
session_idClaude Code 工作階段識別碼
transcript_path工作階段記錄檔的路徑
model所使用的模型
input_tokens / output_tokensToken 計數
cache_write_tokens / cache_read_tokensPrompt 快取 Token 計數
estimated_cost_usd該工作階段預先計算的累積成本(美元)

建議優先使用 estimated_cost_usd 而非自行手動計算定價——模型與快取價格會變動,追蹤器才是唯一來源。

使用時機

  • 使用者詢問「我花了多少錢?」「這個工作階段花費多少?」或「我的 Token 用量如何?」
  • 使用者提到預算、花費上限、超支或成本控制。
  • 使用者想要按模型、工作階段或日期查看成本明細,或匯出 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 Hook 後,成本追蹤功能會在首個工作階段結束時開始記錄資料。

範例——摘要、按模型分類、最近 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)===yest)))+" | 總計: "+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,可迭代上述的 latest 集合(若是 CSV 則使用原始行),輸出所需欄位即可。

報告指引

呈現成本資料時,應包含今日花費與昨日花費的比較、所有工作階段的總計、按模型分類的明細,以及工作階段數量。低於 1 美元的金額顯示四位小數,較大金額則顯示兩位小數。

反模式

  • 不要對每一行加總——每行是工作階段內的累積值;應先針對每個 session_id 取最新一筆。
  • 當 estimated_cost_usd 存在時,不要從原始 Token 計數自行估算成本。
  • 不要假設記錄檔一定存在而不先檢查。
  • 不要在回覆中使用者消息中硬編碼當前模型定價。
  • 不要推薦安裝未經審查的 Hook 或外掛,以免執行任意程式碼。

相關

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

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.

相關技能