token-budget-tracking

token-budget-tracking is a skill for Claude Code, Codex from cosmicstack-labs/mercury-agent-skills. It costs 43 tokens per session (3,688 once invoked), scanned A, original, MIT.

A set of methods for measuring and controlling the text usage of AI agents. AI providers often charge by tokens, which are small pieces of text processed by a language model.

In plain words
What is it for?
Use it to set limits, monitor usage in real time, assign costs, compare models, and find ways to reduce consumption in multi-agent applications.
Why use it?
It helps prevent runaway agents or loops from creating unexpected costs. It also shows which agents, tasks, users, or models consume the most text and money.

Skill for Claude CodeCodex

Written for no agent in particular: nothing here depends on one. Also seen: positional $N argument.

Good fit Use it to set limits, monitor usage in real time, assign costs, compare models, and find ways to reduce consumption in multi-agent applications.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/cosmicstack-labs/mercury-agent-skills/token-budget-tracking
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add cosmicstack-labs/mercury-agent-skills --skill token-budget-tracking
Clone the repo
git clone --depth 1 https://github.com/cosmicstack-labs/mercury-agent-skills

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for token-budget-tracking

README.md
[![agentmods](https://agentmods.dev/badge/skills/cosmicstack-labs/mercury-agent-skills/token-budget-tracking/github.svg)](https://agentmods.dev/skills/cosmicstack-labs/mercury-agent-skills/token-budget-tracking)
Your own site
<a href="https://agentmods.dev/skills/cosmicstack-labs/mercury-agent-skills/token-budget-tracking"><img src="https://agentmods.dev/badge/skills/cosmicstack-labs/mercury-agent-skills/token-budget-tracking/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for token-budget-tracking

Your own site · 80×15
<a href="https://agentmods.dev/skills/cosmicstack-labs/mercury-agent-skills/token-budget-tracking"><img src="https://agentmods.dev/badge/skills/cosmicstack-labs/mercury-agent-skills/token-budget-tracking.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 43 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 3,688 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe. Third-party audits
  • NVIDIA SkillSpector pass 7 Sept 2026
How audits are shown
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00043 $0.03688
Opus 5 $0.00022 $0.01844
Sonnet 5 $0.00009 $0.00738
Haiku 4.5 $0.00004 $0.00369

Measured 10d ago against content hash 0dbbe518bb36, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-10, from the pricing page.

Security

Grade A, and why

token-budget-tracking scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 10d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

categories/ai-ml/token-budget-tracking/SKILL.md · 444 lines

How it starts

The opening of the file, as written. The whole thing — 444 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Token Budget Tracking & Optimization

Overview

In production multi-agent systems, token costs are the new infrastructure bill — and they can spiral fast. An agent in a loop can burn through hundreds of dollars in minutes. This skill covers how to set budgets, track consumption in real time, attribute costs to specific agents and tasks, and optimize token usage without sacrificing quality.


Core Concepts

Token Cost Economics

Model Input ($/1M tokens) Output ($/1M tokens) Cost per 100K tasks (4K avg)
GPT-4o $2.50 $10.00 ~$1,250
Claude 3.5 Sonnet $3.00 $15.00 ~$1,800
GPT-4o-mini $0.15 $0.60 ~$75
Claude 3 Haiku $0.25 $1.25 ~$150

A single runaway agent consuming 50K tokens per loop for 100 iterations = $50-$150 in minutes.

Budget Dimensions

Dimension What It Tracks Why It Matters
Per Agent Tokens consumed by each agent Identify expensive agents
Per Task Cost per completed task Measure ROI per task type
Per User Cost attributed to a user/session Bill-back, abuse detection
Per Model Cost by LLM provider/model Model selection decisions
Daily/Weekly Aggregate burn rate Budget forecasting
Per Step Tokens per reasoning step Detect inefficient reasoning

Step-by-Step Implementation

Step 1: Build a Token Counter

from dataclasses import dataclass, field
from collections import defaultdict
import time
import threading

@dataclass
class TokenUsage:
    prompt_tokens: int = 0
    completion_tokens: int = 0
    total_tokens: int = 0
    
    def __add__(self, other: "TokenUsage"):
        return TokenUsage(
            prompt_tokens=self.prompt_tokens + other.prompt_tokens,
            completion_tokens=self.completion_tokens + other.completion_tokens,
            total_tokens=self.total_tokens + other.total_tokens
        )

class TokenCounter:
    """Tracks token usage across all agents with attribution."""
    
    def __init__(self):
        self.usage: dict[str, dict[str, TokenUsage]] = defaultdict(
            lambda: defaultdict(TokenUsage)
        )
        self._lock = threading.Lock()
    
    def record(self, agent_name: str, task_id: str, 
               prompt_tokens: int, completion_tokens: int):
        """Record token usage for an agent-task pair."""
        with self._lock:
            usage = TokenUsage(
                prompt_tokens=prompt_tokens,
                completion_tokens=completion_tokens,
                total_tokens=prompt_tokens + completion_tokens
            )
            self.usage[agent_name][task_id] = usage
    
    def agent_total(self, agent_name: str) -> TokenUsage:
        """Get total tokens for an agent."""
        with self._lock:
            total = TokenUsage()
            for task_usage in self.usage[agent_name].values():
                total += task_usage
            return total
    
    def task_cost(self, agent_name: str, task_id: str,
                  input_rate: float, output_rate: float) -> float:
        """Calculate monetary cost for a specific task."""
        usage = self.usage[agent_name].get(task_id)
        if not usage:
            return 0.0
        return (
            usage.prompt_tokens * input_rate / 1_000_000 +
            usage.completion_tokens * output_rate / 1_000_000
        )
    
    def top_agents(self, n: int = 10) -> list[tuple[str, TokenUsage]]:
        """Get the n highest-consuming agents."""
        with self._lock:
            totals = [
                (agent, self.agent_total(agent))
                for agent in self.usage
            ]
            totals.sort(key=lambda x: x[1].total_tokens, reverse=True)
            return totals[:n]

Read the full file on GitHub · 444 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 10d ago First seen · 444 lines · 43 tokens per session scan A 0dbbe518bb36

Subscribe to this mod's changes

token-budget-tracking is a skill published in the GitHub repository cosmicstack-labs/mercury-agent-skills (470 stars, last pushed 16d ago), licensed MIT. It adds 43 tokens to every session and 3,688 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

modern-saas-builder

Founder-minded senior product engineer and SaaS architect skill. Use when building, planning, architecting, validating, designing, testing, securing, deploying, or monetizing modern SaaS products, micro-SaaS, web apps, AI agents, Web3/Base applications, agent commerce, or Telegram bots/Mini Apps. Always active when…

lijnati/modern-saas-builder-skills · 98 tokens

claude-md-improver

Audit and improve CLAUDE.md files in repositories. Use when user asks to check, audit, update, improve, or fix CLAUDE.md files. Scans for all CLAUDE.md files, evaluates quality against templates, outputs quality report, then makes targeted updates. Also use when the user mentions "CLAUDE.md maintenance" or "project…

anthropics/claude-plugins-official · 82 tokens

gke-workload-security

Audits, configures, and hardens workload-level security controls for Google Kubernetes Engine (GKE) applications and namespaces. Covers running cluster security audits (auditcluster.sh), configuring Workload Identity Federation (impersonation, KSA/GSA binding, and pod setup), enforcing Network Policies (default-deny…

google/skills · 181 tokens

gke-reliability

Improves GKE workload reliability, using PDBs, health probes, and topology spread constraints. Use when configuring GKE workload reliability, setting up PDBs, or configuring GKE health probes (liveness, readiness, startup). Don't use for disaster recovery setup or full cluster backups (use gke-backup-dr instead).

google/skills · 73 tokens

agent-platform-model-registry

Agent Platform Model Registry Management. Use when you need to upload, list, describe, update, or delete machine learning models (and their versions) in the Agent Platform Model Registry. Don't use for model training, model deployment to endpoints, or managing non-Agent Platform models.

google/skills · 60 tokens

chenhao-limit-up

A framework for judging Chinese A-share stocks that have reached the daily price-rise limit, using market mood, sector leadership, and trading momentum.

questflowai/investorskills · 44 tokens