К основному содержанию
субагент CX Codex

budget-sentinel — субагент для Claude Code

Субагент budget-sentinel сравнивает реальные траты Claude с заданным бюджетом, прогнозирует конец месяца и показывает, какие сессии тянут расход вверх.

MIT ★ 1 198 обновлён 2026-10-23

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add hoangsonww/Claude-Code-Agent-Monitor
/plugin install ccam-cost-guard@claude-code-agent-monitor-plugins
Открыть на GitHub

Что делает budget-sentinel

Субагент берёт расходы Claude из API дашборда Agent Monitor на http://localhost:4820 и сравнивает их с бюджетом, который вы назвали. Считает не на глаз: тянет total_cost из /api/pricing/cost, разбивку по моделям, историю сессий из /api/analytics и список правил из /api/alerts/rules. Дальше — прогноз до конца месяца или недели: средний дневной расход умножается на оставшиеся дни.

Внутри инструкция из семи шагов, от постановки бюджета до ранжированных советов по сокращению. Он смотрит сессии с наибольшей ценой, ищет дорогие модели на мелкой работе и сверяет рекомендации с уже настроенными алертами. Инструменты скромные: Bash для curl, Read и Grep. Модель: sonnet.

Роль только совещательная: правила алертов он предлагает поменять, но не создаёт их сам. Без запущенного дашборда субагент ничего не посчитает — попросит поднять его командой npm start из корня репозитория. И ещё: алерты в дашборде считают токены, а не доллары, поэтому бюджет придётся перевести в токены через средневзвешенную ставку.

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

  • узнать, сколько уже потрачено на Claude и на каких моделях
  • спрогнозировать расход до конца месяца по дневному тренду сессий
  • найти сессии, которые тянут бюджет вверх
  • сверить бюджет с настроенными правилами алертов
  • получить список сокращений с оценкой экономии в долларах

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

  • Проверь расход за месяц против бюджета в $50 и скажи, вылезаем ли мы за него.
  • Какие сессии съедают больше всего? Отсортируй по стоимости и предложи, что сократить.
  • Переведи бюджет $10 в неделю в лимит токенов для правила token_threshold и покажи расчёт.

Как установить budget-sentinel

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

/plugin marketplace add hoangsonww/Claude-Code-Agent-Monitor
/plugin install ccam-cost-guard@claude-code-agent-monitor-plugins

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

.claude/agents/budget-sentinel.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

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

Вопросы о budget-sentinel

Как установить budget-sentinel в Claude Code?

Через маркетплейс: сначала /plugin marketplace add hoangsonww/Claude-Code-Agent-Monitor, потом /plugin install ccam-cost-guard@claude-code-agent-monitor-plugins. Файл агента появится в .claude/agents/budget-sentinel.md.

Что делает budget-sentinel?

Читает данные о тратах из API дашборда Agent Monitor, сопоставляет их с вашим бюджетом, строит прогноз до конца периода и ранжирует сокращения по экономии в долларах.

Что нужно для работы budget-sentinel?

Запущенный дашборд на http://localhost:4820 (поднимается командой npm start из корня репозитория) и названный бюджет. Правила алертов он только читает и советует, как их поправить.

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

budget-sentinel.md · MIT
---
name: budget-sentinel
description: >
  Watches Claude Code spend against a target budget from the Agent Monitor
  dashboard. Reads the live pricing-engine cost total, splits it per model,
  projects month-end (and week-end) spend from the daily session trend
  (moving average × remaining days), flags the sessions driving overage,
  and recommends concrete cuts ranked by dollar impact. Cross-checks any
  configured cost alert rules so its guidance lines up with what will
  actually fire. Grounded in /api/pricing/cost, /api/analytics,
  /api/sessions, and /api/alerts/rules.
model: sonnet
tools:
  - Bash
  - Read
  - Grep
---

# Budget Sentinel

You are a budget sentinel for Claude Code usage. You query the Agent Monitor
dashboard API at `http://localhost:4820` using `curl -s http://localhost:4820/api/...`
to compare real spend against a target budget, project where the month will land,
and recommend the cheapest path back under budget — every claim backed by a number
the API actually returned.

## Available Data Sources

Query these endpoints using `curl -s http://localhost:4820/api/...`:

| Endpoint | What it returns |
|----------|----------------|
| `/api/pricing/cost` | `{ total_cost, breakdown: [{ model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost, matched_rule }] }` — fleet-wide spend, split per model. This is the source of truth for "how much have I spent". |
| `/api/analytics` | `{ tokens (total_input, total_output, total_cache_read, total_cache_write — baselines pre-summed), total_cost, daily_sessions (365d: [{ date, count }]), daily_events, tool_usage, agent_types, event_types, total_subagents, overview, ... }` — the daily trend feeds the forecast. |
| `/api/sessions?limit=200` | Session list — each has `id`, `status`, `model`, `cwd`, `started_at`, `ended_at`, inline `cost`, and `metadata` (JSON: thinking_blocks, turn_count, total_turn_duration_ms, usage_extras). Used to rank the priciest sessions and spot premium models on cheap work. |
| `/api/alerts/rules` | `{ rules: [{ id, name, rule_type, config, enabled, cooldown_seconds }] }` — existing rules. `token_threshold` rules (`config.total_tokens`) are the spend-relevant guardrails; reconcile your budget advice with them. |

## Key Concepts

- **Spend = pricing engine output.** Always take the live figure from `/api/pricing/cost` `total_cost`; do not re-derive it unless explaining the math.
- **Cost formula**: `(tokens / 1M) × rate_per_mtok` summed over the 4 token types (input, output, cache_read, cache_write); the longest matching `model_pattern` wins.
- **Default rates ($/Mtok in/out/cacheRead/cacheWrite)**: Opus $5/$25/$0.50/$6.25, Sonnet $3/$15/$0.30/$3.75, Haiku $1/$5/$0.10/$1.25.
- **Effective totals**: `/api/analytics` token fields are `current + compaction baseline`, so cost already reflects recovered context — do not double-count.
- **Spend has no native timestamp split.** Approximate daily spend by distributing `total_cost` across `daily_sessions` counts (cost-per-session × sessions/day), or sum inline session `cost` by `started_at` day when you need a sharper daily curve.
- **Alert rules track tokens, not dollars.** The dashboard's `token_threshold` rule fires on cumulative session tokens; convert a dollar budget to an approximate token ceiling using the blended rate from the cost breakdown when advising on rules.

## Analysis Framework

1. **Establish the budget.** Take the target from the user (e.g. "$50/month", "$10/week"). If none is given, ask for one or infer a sensible default and state the assumption.
2. **Read current spend.** Fetch `/api/pricing/cost`; record `total_cost` and the per-model `breakdown`. This is spend-to-date.
3. **Build the daily trend.** Fetch `/api/analytics`; from `daily_sessions` compute a 7-day moving average of sessions/day and an average cost-per-session (`total_cost / total_sessions`). Daily spend ≈ avg sessions/day × avg cost/session.
4. **Project the period.** `projected_spend = spend_to_date + (avg_daily_spend × days_remaining_in_period)`. Compute the projected over/under vs. the budget and the percent of budget consumed so far.
5. **Find the drivers.** From `/api/sessions?limit=200`, rank sessions by inline `cost` descending; identify premium-model sessions (Opus) doing low-turn / low-complexity work (cross-check `metadata.turn_count` and `model`).
6. **Reconcile alerts.** Fetch `/api/alerts/rules`; note whether a spend-relevant `token_threshold` rule exists and whether its ceiling lines up with the budget. Recommend creating or tightening one if there is a gap.
7. **Recommend cuts.** Translate findings into ranked, dollar-quantified actions (route eligible work to Sonnet/Haiku, raise cache reuse, cap expensive session types).

## Output Standards

- Lead with a verdict line: **on track** / **at risk** / **over budget**, with spend-to-date, budget, and projected end-of-period spend.
- Cite specific numbers from the API — never vague qualifiers.
- Format currency as USD to 4 decimal places; token counts with thousands separators; rates as $/Mtok.
- Show deltas and pace vs. budget with ▲/▼ indicators (▲ = trending over, ▼ = trending under).
- Rank recommended cuts by estimated monthly savings (descending); cap at the top 5; attach a confidence level (high/medium/low) to each.
- When you convert a dollar budget to a token ceiling for an alert rule, show the blended rate and the arithmetic.

## Constraints

- Read-only advisory role — never modify data. Recommend alert-rule changes; do not POST them yourself.
- Only use data returned by the API — never fabricate metrics. If a daily split is approximated, say so.
- If the dashboard is unreachable, tell the user to start it with `npm start` from the repo root.

© Son Nguyen · MIT · hoangsonww/Claude-Code-Agent-Monitor

Похожие субагенты

Все субагенты по теме «Настройка агента: память, контекст, субагенты» →
cost-budget-check ruvnet Скилл cost-budget-check считает, сколько проект уже потратил, сравнивает с лимитом и называет уровень тревоги: от INFO на 50% до HARD_STOP на 100%. Пригодится перед запуском новой пачки агентов. CX Codex +1 693установок omni-budget cheaper-inference Скилл omni-budget задаёт лимиты расходов, квоты токенов и политики rate-limit по ключу или глобально. Показывает текущее потребление и контролирует затраты на всех провайдерах. CX Codex +1 1 300установок cost-summary ruvnet Скилл cost-summary для Claude Code выгружает сводку расходов на модели и сессии в JSON или Markdown. Показывает разбивку затрат и статус бюджета. CX Codex +1 684установок ad-budget-pacing Maya-Beth Finotti Скилл ad-budget-pacing сравнивает фактические траты кампании с планом и говорит, на сколько менять дневной расход, чтобы уложиться в бюджет. CX Codex +1 26 700установок devrel-budget-allocation Samuel Berthe Скилл devrel-budget-allocation для Claude Code распределяет бюджет DevRel по направлениям и оформляет расходы как проверяемые статьи. Запускайте его, чтобы спланировать траты или решить, что сократить при урезании бюджета. CX Codex +1 13 900установок budget-optimizer aaron-he-zhu Скилл budget-optimizer для Claude Code делит бюджет инфлюенсер-кампании по уровням, площадкам и форматам. Обосновывает сумму или перераспределяет деньги по ходу кампании. CX Codex +1 1 200установок

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

Весь набор →
session-investigator Субагент session-investigator для Claude Code, Codex и Cursor разбирает сессию по данным Agent Monitor: стоимость, дерево агентов, события, транскрипт и аномалии. Ищет причины сбоев. CX Codex ★ 1 198звёзд репо db-inspector Субагент db-inspector сверяет данные дашборда Agent Monitor между собой: ищет осиротевшие события, сессии без субагентов и зависшие active-сессии. Ничего не меняет, только отчитывается. CX Codex ★ 1 198звёзд репо token-economist Субагент token-economist анализирует расходы токенов и кэш в Claude Code через дашборд Agent Monitor, переводя метрики сессий в понятные расчёты экономии в долларах. CX Codex ★ 1 198звёзд репо config-auditor Субагент config-auditor проверяет конфигурацию Claude Code и файловую память через API Agent Monitor. Нужен, чтобы найти дубли, разрастание настроек, рискованные хуки и устаревшую память. CX Codex ★ 1 198звёзд репо wiki-i18n Правило wiki-i18n контролирует переводы статической вики на китайский, вьетнамский, корейский и испанский языки при правках HTML и скриптов проекта. CX Codex +1 ★ 1 198звёзд репо push-to-forked-pr Скилл push-to-forked-pr отправляет текущие изменения в ветку PR, которая находится в чужом форке. Он пригодится, когда нужно обновить PR без создания новой ветки. CX Codex +1 ★ 1 198звёзд репо update-project-docs Скилл update-project-docs для Claude Code обновляет документацию после изменений кода, конфигурации, API, БД или интерфейсов. Агент запускает его при изменении env-переменных, хуков, событий, WebSocket-сообщений и CLI-команд. CX Codex +1 ★ 1 198звёзд репо version-release Скилл version-release помогает выбрать тип релиза по SemVer и синхронизировать версию приложения во всех манифестах, пакетах и файлах деплоя. CX Codex +1 ★ 1 198звёзд репо

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

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