Communitygithub.com

コストトラッキング

Claude Codeのトークン使用量、支出、予算を、ECCのローカルコストトラッカーメトリクスログから追跡およびレポートします。ユーザーがコスト、支出、使用量、トークン、予算、モデル別/セッション別/日付別のコスト内訳について質問したときに使用します。

コストトラッキング とは?

このスキルは、Claude Codeのコストと使用履歴を分析するための強力なツールです。ECCの`stop:cost-tracker`フックによって生成される`~/.claude/metrics/costs.jsonl`ファイルに保存されたJSONLデータを読み取り、累積セッションコストを正確に集計します。ユーザーは「今月の支出は?」「このセッションのトークン使用量は?」といった質問ができ、スキルはモデル別、セッション別、日付別の内訳を提示します。このスキルは、Claude Code環境で動作し、Node.jsを使用してクロスプラットフォームでJSONLファイルを処理します。セッションごとに最新の行のみを集計することで重複カウントを防ぎ、`estimated_cost_usd`フィールドを優先して使用することで、手動計算や変動する価格設定に依存しない正確なコスト報告を実現します。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

コストトラッキング は何をしますか?

このスキルを使用すると、ECCのstop:cost-trackerフックが書き込むメトリクスログから、Claude Codeのコストと使用履歴を分析できます。

データの保存場所

トラッカーは、セッション停止ごとに1つの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セッションの事前計算された累積コスト(USD)

手動で価格を計算するよりもestimated_cost_usdを優先してください。モデルとキャッシュの価格は変動するため、トラッカーが信頼できる情報源です。

使用するタイミング

  • ユーザーが「いくら使った?」「このセッションのコストは?」「トークン使用量は?」と尋ねた場合
  • ユーザーが予算、支出制限、超過、コスト管理について言及した場合
  • ユーザーがモデル別、セッション別、日付別のコスト内訳、またはCSVエクスポートを希望する場合

仕組み

まずログファイルが存在するか確認します(sqlite3ではなくnodeを使用 — トラッカーは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ドル未満の金額は小数点以下4桁、大きな金額は小数点以下2桁でフォーマットします。

アンチパターン

  • すべての行を合計しないでください — 行はセッションごとに累積されています。まず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.

関連スキル