Logo de Hatch3r Cost Tracking

Hatch3r Cost Tracking

Organização
hatch3r
hatch3r-cost-tracking

Tracks token usage and estimate costs for agent sessions. Use when monitoring spend, approaching budget limits, or generating cost reports.

Visão geral

Publicado porhatch3r
Repositóriohatch3r
Nome da habilidadehatch3r-cost-tracking
Estrelas
26
Forks
7
Arquivos incluídos
Somente instruções
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Sem arquivos extras

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por hatch3r no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Hatch3r Cost Tracking no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/hatch3r/hatch3r/tree/main/skills/hatch3r-cost-tracking
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/hatch3r/hatch3r.git /tmp/hatch3r
mkdir -p .claude/skills
cp -r /tmp/hatch3r/skills/hatch3r-cost-tracking .claude/skills/hatch3r-cost-tracking
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Hatch3r Cost Tracking em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Hatch3r Cost Tracking automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Hatch3r Cost Tracking não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Cost Tracking Workflow

Quick Start

Applies when: the project tracks cloud/LLM spend against a budget. On a project with no cost-accounting need, skip (per rules/hatch3r-right-sizing.md).

Task Progress:
- [ ] Step 0: Detect ambiguity (P8 B1)
- [ ] Step 1: Review cost tracking configuration
- [ ] Step 2: Estimate current session token usage
- [ ] Step 2a: Re-fetch pricing before reporting (currency gate)
- [ ] Step 3: Identify cost optimization opportunities
- [ ] Step 4: Generate cost report

Step 0 — Detect Ambiguity (P8 B1)

Before any work, scan the invocation for unresolved questions in scope, intent, acceptance criteria, target environment, or irreversibility. If any are found, ask the user via the platform-native question tool per agents/shared/user-question-protocol.md. Do not proceed under silent assumption. Default path, not an exception. Triggers for THIS skill: tracking scope (session vs issue vs epic), budget values when missing from hatch.json, hardStop authority (block vs warn), report format target, and whether to defer non-critical work over budget.

Fan-out Discipline (P8 B2)

Fan-out scales with task size; token cost never justifies serializing independent work (rules/hatch3r-fan-out-discipline.md P8 B2; agents/shared/efficiency-patterns.md). Emit sub_agents_spawned: { count, rationale, task_structure } in your output.

Step 1: Review Configuration

  1. Check hatch.json for a costTracking section.
  2. Note configured budgets: sessionBudget, issueBudget, epicBudget.
  3. Note warning thresholds and whether hardStop is enabled.
  4. If no configuration exists, operate in report-only mode.

Step 2: Estimate Token Usage

Estimate tokens for the current session using these rules:

Content TypeRuleAccuracy
Messages~4 characters per tokenHigh -- stable ratio for English text
Tool callsJSON length / 4 (input), response length / 4 (output)Medium -- JSON has more overhead characters
File readsCharacter count / 4High -- but large files may be truncated by the tool
Web searches~500 tokens per searchLow -- varies widely by result length
Subagent spawnsEstimate full context re-sent per spawn (~2000-5000 tokens base)Medium -- depends on included rules/context

Subagent cost multiplier. Each subagent spawn carries a base cost for the agent protocol, included rules, and context. A pipeline with 8 subagents (researcher + implementer + reviewer + fixer + 4 Phase 4 specialists) has significant overhead from context re-transmission. Factor this into budget estimates.

Calculate estimated cost using named-model rates tied to model IDs. Published-vendor rates drift between model releases — re-fetch before every report per Step 2a; the accessed: date marks when each row was last verified.

ModelModel IDInput (per 1M)Output (per 1M)accessed
Claude Haiku 4.5claude-haiku-4-5$1.00$5.002026-06-06
Claude Sonnet 4.6claude-sonnet-4-6$3.00$15.002026-06-06
Claude Sonnet 5claude-sonnet-5$3.00$15.002026-07-13
Claude Opus 4.8claude-opus-4-8$5.00$25.002026-06-06
Claude Fable 5claude-fable-5$10.00$50.002026-07-13

Cache-read multiplier. Cached input tokens (cache_read_input_tokens in the API usage block) bill at ~0.1× the model's base input rate; cache writes bill at 1.25× (5-minute TTL) or 2× (1-hour TTL). When a session reuses a large cached prefix, price cache_read_input_tokens separately at 0.1× base input — counting them at full input rate overstates spend by up to 10× on cache-heavy agent loops. Total prompt size = input_tokens (uncached) + cache_creation_input_tokens + cache_read_input_tokens.

Step 2a: Re-fetch Pricing Before Reporting (currency gate)

Published per-token rates change between model releases. Before emitting a cost figure, verify the rate table is current:

  1. If any row's accessed: date is older than 30 days, re-fetch the vendor's current pricing (Anthropic: https://www.anthropic.com/pricing, or the live claude-api skill's models/pricing reference) and update the row's rates + accessed: date in place.
  2. Confirm the model the session actually ran on maps to a named row. If the session used a model ID absent from the table (e.g. an older or non-Anthropic model), add a row with its published rates and accessed: date rather than defaulting to the nearest tier.
  3. State the accessed: date of the rate used directly in the report (see Step 4). A cost figure with no rate-provenance date is unverifiable — never report a dollar amount without it.

If pricing cannot be re-fetched (offline, vendor page unreachable), proceed with the on-file rates but flag the figure as (rates as of <accessed-date>, not re-verified) in the report.

Default Budgets

When hatch.json has no costTracking section, apply these defaults (report-only — no hard stop unless hardStop: true):

Budget TypeDefault
sessionBudget$10.00
issueBudget$5.00
epicBudget$25.00
warningThresholds[0.5, 0.75, 0.9]
hardStopfalse

Enforcement

ThresholdAction
50%Log warning, continue
75%Alert user, suggest optimization
90%Strong warning, recommend delegation or checkpoint
100%Stop (if hardStop: true) or alert and continue

Step 3: Identify Optimizations

Review usage patterns for savings:

  • Large file reads: Were files read multiple times without changes? Cache instead.
  • Model tier: Could routine tasks (linting, formatting) use a faster/cheaper model?
  • Context bloat: Is irrelevant context accumulating? Summarize and trim.
  • Batching: Were multiple small tool calls made that could be combined?
  • Scope creep: Did work expand beyond the original issue? Scope back.

Step 4: Generate Report

Produce a cost report in this format:

## Cost Report: {scope}

**Period:** {session/issue/sprint}

**Token Usage:**
- Input tokens (uncached): ~{n}
- Cache-read tokens: ~{n} (billed ~0.1x base input)
- Cache-write tokens: ~{n} (billed 1.25x / 2x by TTL)
- Output tokens: ~{n}
- Total tokens: ~{n}

**Estimated Cost:** ${amount} ({model-id}, rates accessed {YYYY-MM-DD})

**Budget Status:** {amount} / {budget} ({percentage}%)

**Breakdown:**

| Phase | Tokens | Cost | % of Total |
|-------|--------|------|-----------|
| Planning | ~{n} | ${x} | {%} |
| Implementation | ~{n} | ${x} | {%} |
| Testing | ~{n} | ${x} | {%} |
| Review | ~{n} | ${x} | {%} |
| Sub-agents | ~{n} | ${x} | {%} |

**Optimization Opportunities:**
- {suggestions based on usage patterns}

Include total estimated tokens (uncached input + cache-read + cache-write + output), estimated cost at the named-model rate with its accessed: date, budget status (if configured), and top optimization opportunities. Always present estimated values with the ~ prefix. Never report a dollar figure without the model ID and rate-access date. Never suppress threshold alerts.

Error Handling

  • Token usage data unavailable: If the platform does not expose token metrics, use input/output character counts divided by 4 as an estimate. Note the approximation method in the report.
  • Budget limit exceeded mid-session: Stop non-critical operations, produce a partial cost report, and recommend which remaining tasks to defer or delegate to a lower-cost model.
  • Cost configuration missing from hatch.json: Operate in report-only mode and note that budget enforcement is inactive. Recommend adding cost configuration to enable guardrails.

Definition of Done

  • Cost configuration reviewed (or report-only mode noted)
  • Token usage estimated for current session (uncached input / cache-read / cache-write / output split)
  • Pricing rates verified current per Step 2a; report cites model ID + rate accessed: date
  • Optimization opportunities identified
  • Cost report generated with budget status

Related Skills & Agents

  • Skill: hatch3r-context-health — context health monitoring complements cost tracking for session management

References

  • Anthropic API pricing — accessed 2026-06-06, official-docs (Anthropic). Source for the per-million-token input/output rates per named model (Haiku 4.5 $1/$5, Sonnet 4.6 $3/$15, Opus 4.8 $5/$25) and the cache-read 0.1x / cache-write 1.25x-2x multipliers in Step 2; these drift between model releases — re-verify per Step 2a when running a cost report.
  • Token counting — Anthropic API docs — accessed 2026-06-05, official-docs (Anthropic). Source for treating the ~4-characters-per-token figure as an approximation; the documented count-tokens endpoint is authoritative when exact counts are required.

Perguntas frequentes

O que a habilidade de IA Hatch3r Cost Tracking faz?

Tracks token usage and estimate costs for agent sessions. Use when monitoring spend, approaching budget limits, or generating cost reports.

Por que usar Hatch3r Cost Tracking no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Hatch3r Cost Tracking é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Hatch3r Cost Tracking no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/hatch3r/hatch3r/tree/main/skills/hatch3r-cost-tracking. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Hatch3r Cost Tracking?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Hatch3r Cost Tracking?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Hatch3r Cost Tracking com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Hatch3r Cost Tracking é gratuita?

Sim. A habilidade é publicada no GitHub por hatch3r sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇