К основному содержанию
скилл CX Codex

cost · sethgammon — скилл для Claude Code: отчёты о расходах

Скилл cost показывает расход токенов и стоимость сессий, кампаний и периодов. Помогает понять, куда уходит бюджет и как меняется темп расходов.

MIT ★ 937 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local
Открыть на GitHub

Что делает cost

/cost собирает данные о текущей сессии, расходах за день или неделю, всей истории либо выбранной кампании. В отчёте есть стоимость, число токенов и сообщений, разбивка по моделям и темп расходов. Для чтения данных скрипт использует scripts/session-tokens.js, а также файлы телеметрии и scripts/pricing.json.

Если скрипт недоступен, скилл берёт данные из session-costs.jsonl и помечает оценку как приблизительную. При отсутствии pricing.json используется встроенная в скрипт стоимость. Скилл работает в режиме чтения: файлы проекта он не меняет.

Какие задачи решает

  • проверить стоимость текущей сессии и темп расходов
  • суммировать расходы за день или неделю
  • сравнить стоимость сессий по кампаниям
  • посмотреть разбивку токенов и расходов по моделям

Примеры запросов агенту

  • Покажи стоимость текущей сессии командой /cost.
  • Посчитай расходы за неделю через /cost week.
  • Покажи расходы кампании release командой /cost campaign release.

Как установить cost

1Через маркетплейс плагинов

/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local

Команда ставит плагин citadel целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add SethGammon/Citadel --skill cost -a claude-code

3Вручную: положить файлы

~/.claude/skills/cost/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/cost/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о cost

Как установить cost в Claude Code?

В Claude Code добавьте маркетплейс командой /plugin marketplace add SethGammon/Citadel, затем установите плагин командой /plugin install citadel@citadel-local.

Что делает cost?

Он читает данные сессий и телеметрии и формирует отчёты о токенах и расходах. Можно посмотреть текущую сессию, период или кампанию.

Откуда cost берёт данные о расходах?

Сначала скилл запускает scripts/session-tokens.js, а также читает телеметрию и scripts/pricing.json. Если скрипт недоступен, он использует session-costs.jsonl и помечает сумму как оценочную.

Исходный текст

SKILL.md · MIT
---
name: cost
license: MIT
description: >-
  Deep cost exploration and transparency. Shows real token usage, session costs,
  campaign spend, burn rates, and model breakdown. Reads Claude Code's native
  session data for exact numbers. Complements /dashboard with focused cost views.
user-invocable: true
auto-trigger: false
trigger_keywords:
  - cost
  - costs
  - cost breakdown
  - campaign cost
  - token usage
  - burn rate
  - model breakdown
last-updated: 2026-03-30
---

# /cost -- Session & Campaign Cost Explorer

## When to Use

- `/cost` -- current session cost and burn rate
- `/cost today` -- today's total spend
- `/cost week` -- this week's spend
- `/cost campaign {slug}` -- total spend for a specific campaign
- `/cost all` -- lifetime cost summary
- When /do routes "how much", "what's the cost", "spending", "tokens", "burn rate"

## Inputs

Optional arguments parsed from user message:
- `today` -- filter to today's sessions
- `week` -- filter to last 7 days
- `campaign {slug}` -- filter to a specific campaign
- `all` -- show all-time data
- No argument -- show current session

## Protocol

### Step 1: READ REAL DATA

Run the session-tokens.js script to get real token data:

```bash
node scripts/session-tokens.js              # current/latest session
node scripts/session-tokens.js --today      # today's sessions
node scripts/session-tokens.js --all        # all sessions (use for week/all/campaign)
```

Also read:
- `.planning/telemetry/cost-tracker-state.json` for live burn rate
- `.planning/telemetry/session-costs.jsonl` for campaign attribution
- `scripts/pricing.json` to show which pricing is being used

If `session-tokens.js` is not available or fails, fall back to session-costs.jsonl
data and clearly mark output as "(estimated)".

### Step 2: RENDER BASED ON SCOPE

**Current session (`/cost` with no args):**

```
=== Session Cost Report ===
Session: {sessionId (first 8 chars)}
Started: {relative time} ({absolute time})
Duration: {minutes} min

Tokens:
  Input:          {N} tokens
  Output:         {N} tokens
  Cache creation: {N} tokens
  Cache read:     {N} tokens
  Total:          {N} tokens

Cost: ${total}
Burn rate: ${rate}/min
Messages: {N} ({N} main + {N} across {N} subagents)

Model breakdown:
  claude-opus-4-6:         {N} messages (${cost}, {pct}% of spend)
  claude-haiku-4-5:        {N} messages (${cost}, {pct}% of spend)

Cache efficiency: {pct}% of input tokens served from cache
  (Higher = more cost-efficient. Cache reads cost 10x less than fresh input.)

Pricing source: scripts/pricing.json (version {version})
```

**Today / Week / All (`/cost today`, `/cost week`, `/cost all`):**

```
=== Cost Report: {Today / This Week / All Time} ===

Summary:
  Sessions: {N}
  Total cost: ${total}
  Subagents spawned: {N}
  Total messages: {N}

Top 5 sessions by cost:
  ${cost}  {duration}min  {agents} agents  {msgs} msgs  {date}
  ${cost}  {duration}min  {agents} agents  {msgs} msgs  {date}
  ...

By campaign (from session-costs.jsonl):
  {slug}: ${cost} across {N} sessions
  _unattached: ${cost} across {N} sessions

Average session: ${avg_cost} | ${avg_rate}/min | {avg_duration} min

For historical charts and billing-window views: npx ccusage
```

**Campaign (`/cost campaign {slug}`):**

```
=== Campaign Cost: {slug} ===

Total: ${cost} across {N} sessions ({N} agents, {N} min)
Average session: ${avg}

Sessions:
  {date}: ${cost} ({duration} min, {agents} agents, {msgs} msgs)
  {date}: ${cost} ({duration} min, {agents} agents, {msgs} msgs)
  ...
```

### Step 3: ADD CONTEXT

After the cost data, add one of these contextual lines based on the numbers:

- If burn rate > $2/min: "Burn rate is high. Consider whether subagent-heavy work
  could be restructured into smaller focused sessions."
- If cache hit rate < 50%: "Low cache hit rate. Long conversations with many tool
  results tend to have lower cache efficiency."
- If no real data available: "Cost data is estimated. Real token data becomes
  available when sessions complete and Claude Code writes session JSONL files."
- Otherwise: no extra context needed.

### Step 4: FRINGE CASES

**If scripts/session-tokens.js does not exist:**
Fall back to session-costs.jsonl data. Show estimated costs with "(est)" marker.

**If no session data exists:**
```
No session data found. Cost tracking requires Claude Code session files
at ~/.claude/projects/. These are created automatically by Claude Code.
```

**If pricing.json is missing or unreadable:**
Use hardcoded pricing in session-tokens.js. Note: "Using built-in pricing (pricing.json not found)."

**If user asks about Pro/Max subscription costs:**
```
Note: Pro/Max subscribers pay a flat monthly fee, not per-token.
The token counts shown here represent your usage volume, not billing.
For rate limit awareness, token throughput matters more than dollar cost.
```

## Fringe Cases

- **Telemetry directory missing**: `.planning/telemetry/` does not exist — output: "No telemetry data found. Run any skill first to generate session data, then re-run /cost."
- **Malformed telemetry JSON**: a `session-*.json` file fails to parse — output: "Telemetry file is corrupted. Delete `.planning/telemetry/session-*.json` and re-run the skill that generated it." Skip the bad file and continue with the rest.
- **MCP cost API returns no data**: Claude Code is not tracking this session — output: "Session cost unavailable from MCP. Check that Claude Code is running with cost tracking enabled. Showing telemetry file data only." Fall back to session-costs.jsonl.
- **All session files are from a different project**: project paths in the files do not match the current working directory — warn: "Session files found belong to a different project. You may be in the wrong directory." List the project paths found in the session files.

## Contextual Gates

**Disclosure:** "Reading telemetry and session data. No files modified."
**Reversibility:** green — read-only; no files modified
**Trust gates:**
- Any: full cost report, session data, campaign attribution.

## Quality Gates

- Always show real data when available, estimated when not
- Always label data source: (real) vs (est)
- Never claim specific dollar savings from Citadel -- show raw hook facts instead
- Suggest ccusage for features we don't replicate (charts, billing windows)
- Round costs to 2 decimal places, tokens to nearest K/M
- Total output must fit on one screen for current-session view

## Exit Protocol

/cost does not produce a HANDOFF block. It is a read-only cost exploration tool.
After displaying the report, wait for the next user command.

© SethGammon · MIT · SethGammon/Citadel

Похожие скиллы

Каталог скиллов SKILL.md →

Сначала — cost от других авторов.

cost getagentseal Скилл cost для Claude Code и Codex показывает расходы на AI-кодинг за сегодня. Он разбирает траты по моделям и проектам и отмечает необычные значения. CX Codex +1 ★ 11 881звёзд репо convex-cost convex Скилл convex-cost оценивает расходы на Convex и находит функции, сжигающие бюджет. Показывает график роста затрат и предлагает дешёвое исправление. CX Codex +1 43 800установок google-cloud-waf-cost-optimization официальный google Скилл google-cloud-waf-cost-optimization для Claude Code, Gemini CLI и Codex, который оценивает рабочие нагрузки Google Cloud по столпу Cost Optimization фреймворка Well-Architected. CX Codex +1 14 266установок cost-optimization Seth Hobson Скилл cost-optimization помогает разбирать расходы AWS, Azure, GCP и OCI, находить лишние ресурсы и настраивать правила контроля бюджета. CX Codex +1 11 506установок aws-billing-and-cost-management aws Скилл aws-billing-and-cost-management анализирует расходы в AWS, ищет резервы экономии и настраивает бюджеты. Помогает проверить аномалии цен, оценить Savings Plans и снизить затраты на инфраструктуру. CX Codex +1 10 300установок az-cost-optimize официальный github Скилл az-cost-optimize анализирует Azure-ресурсы и IaC, ищет варианты снижения затрат и создаёт GitHub issues после подтверждения. Нужен при ревизии расходов проекта в Azure. CX Codex +1 8 700установок cost-aware-llm-pipeline affaan-m Скилл cost-aware-llm-pipeline для Claude Code маршрутизирует простые задачи к дешёвым моделям, отслеживает расходы на API и кэширует промпты, сохраняя качество на сложных запросах. CX Codex +1 6 400установок

Из того же набора55

Весь набор →
test-gen Скилл test-gen генерирует и прогоняет тесты под существующий фреймворк проекта с проверкой типичных сценариев, краевых случаев и ошибок. CX Codex +1 ★ 937звёзд репо design Скилл design собирает дизайн-манифест из стилей проекта или ответов на вопросы. Хук после правок отмечает отклонения в CSS и компонентах. CX Codex +1 ★ 937звёзд репо live-preview Скилл live-preview делает скриншоты компонентов в процессе сборки, а не по готовности. Ловит регрессии вёрстки и невидимые блоки до того, как они уйдут дальше. CX Codex +1 ★ 937звёзд репо architect Скилл architect превращает PRD или описание задачи в архитектурный план с деревом файлов, моделью данных и фазами сборки. CX Codex +1 ★ 937звёзд репо merge-review Скилл merge-review проверяет очередь слияний от fleet-агентов, находит пересечения файлов между ветками и предлагает безопасный порядок merge перед тем, как принимать изменения в main. CX Codex +1 ★ 937звёзд репо deploy-steward Скилл deploy-steward для Claude Code по очереди вливает готовые PR в main, проверяет CI, запускает деплой и создаёт задачи на починку при сбоях. CX Codex +1 ★ 937звёзд репо prd Собирает PRD по описанию приложения: задаёт вопросы, определяет объём и технические решения. Документ можно передать Archon для разбиения на кампанию. CX Codex +1 ★ 937звёзд репо organize Скилл organize для аудита и исправления структуры проекта: проверяет, где лежат файлы, переносит их по конвенции и обновляет импорты. Код внутри файлов не трогает. CX Codex +1 ★ 937звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой