Communitygithub.com

비용 추적

로컬 ECC 비용 추적기 메트릭 로그에서 Claude Code의 토큰 사용량, 지출 및 예산을 추적하고 보고합니다. 사용자가 비용, 지출, 사용량, 토큰, 예산 또는 모델, 세션, 날짜별 비용 분석에 대해 물을 때 사용합니다.

비용 추적란 무엇인가요?

이 스킬은 ECC의 `stop:cost-tracker` 훅이 작성하는 JSONL 메트릭 로그를 분석하여 Claude Code 비용 및 사용 내역을 추적하고 보고합니다. 비용 데이터는 `~/.claude/metrics/costs.jsonl` 파일에 저장되며, 각 JSON 객체는 세션 종료 시점의 누적 스냅샷입니다. 따라서 총 지출을 계산하려면 `session_id`별 최신 행만 합산해야 합니다. 선호하는 필드는 모델 및 캐시 가격 변동을 고려하여 사전 계산된 `estimated_cost_usd`입니다. 이 스킬은 사용자가 지출, 토큰 사용량, 예산 또는 비용 분석을 질문할 때 자동으로 활성화되며, `node`를 사용하여 로그 존재 여부를 확인하고 정확한 비용 보고서를 제공합니다. 주의할 점은 모든 행을 합산하지 않고 최신 행만 사용하며, `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 비용 및 사용 내역을 분석하는 데 사용합니다.

데이터 위치

트래커는 세션 종료 시 하나의 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를 수동 계산보다 우선 사용하세요. 모델 및 캐시 가격은 변동되며, 트래커가 진실 공급원(source of truth)입니다.

사용 시기

  • 사용자가 "얼마나 썼지?", "이 세션 비용은?", "내 토큰 사용량은?"이라고 물을 때
  • 사용자가 예산, 지출 한도, 초과 비용 또는 비용 제어를 언급할 때
  • 사용자가 모델, 세션 또는 날짜별 비용 분석이나 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)?"비용 로그 발견됨":"비용 로그를 찾을 수 없음: "+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("비용 로그를 찾을 수 없음: "+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가 있을 때 원시 토큰 수로 비용을 추정하지 마세요.
  • 확인 없이 로그가 존재한다고 가정하지 마세요.
  • 사용자에게 제공하는 답변에 현재 모델 가격을 하드코딩하지 마세요.
  • 검증되지 않은 훅이나 임의 코드를 실행하는 플러그인을 설치하도록 권장하지 마세요.

관련 항목

  • /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.

관련 스킬