Claude Code Cost: Track, Cap and Alert With a 30-Line Mod
By: Evgeny Padezhnov
Claude Code Cost: Track, Cap and Alert With a 30-Line Mod
A free working example. The code is quoted as it stands; what I did not verify is marked.
Updated 5 October 2026 · Claude Code 2.1.289
We run a fleet of autonomous Claude Code agents on one Linux box: they fix bugs, deploy static sites, write content and touch a production Postgres. Most sessions run with nobody watching, so Claude Code cost is visible only if someone asks for it.
This article fixes that with a small mod: session spend in the status line, one warning at 80% of a cap, and a stop on new prompts at the cap. Prices and plan limits are out of scope; see Is Claude Code free? Pricing, limits and what you actually pay.
Three ways to watch Claude Code usage
1. The built-in /cost command. It totals what the session has cost so far. It is passive: an unattended agent never types it.
2. Reading usage after the fact. The community tool ccusage reads the local session logs. Good for a weekly review, but by then the money is spent.
3. A mod that acts in the moment. Since v2.1.287 (1 October 2026), Claude Code supports mods: TypeScript function hooks that run inside the agent. A mod can refuse a prompt, intercept tool calls, and draw status-line entries and toasts: enough to turn a number you ask for into a limit the session enforces.
What the API exposes about spend
Everything below is from the types file of build 2.1.289. The API is early access and, in the file's own words, "may change between releases without notice".
$.session.usage()returns{ startedAt, context: { tokens, window, percent }, rateLimits: [...], cost?: { usd } }.cost.usdis "what the session has cost so far, as /cost totals it". The CLI always has it; the type marks it optional.rateLimitscarries thefive_hourandseven_daywindows.context.percenttells you how full the context window is.- For Claude Code token usage per request, the
turn.stepevent streams each model request, and its result carriesusagewithinput_tokens,output_tokens,cache_read_input_tokensandcache_creation_input_tokens.
The mod: three files
A mod is a folder with three files. The manifest declares a user setting, capUsd, default 5:
{
"name": "spend-guard",
"version": "0.1.0",
"description": "Shows session spend in the status line, warns at 80% and stops new prompts at a dollar cap",
"userConfig": {
"capUsd": {
"type": "number",
"title": "Session cap, USD",
"description": "New prompts are refused once the session has cost this much",
"default": 5
}
},
"author": {
"name": "Evgeny Padezhnov",
"url": "https://padezhnov.com"
}
}
hooks/hooks.json points at the module:
{ "modules": ["./register.ts"] }
And hooks/register.ts, verbatim:
import type { Register, EngineInterface } from 'claude-code'
const usd = (n: number) => `$${n.toFixed(2)}`
// A helper that takes $ must be declared at the top level: the engine checks every $ it can follow.
async function spent($: EngineInterface): Promise<number> {
return (await $.session.usage()).cost?.usd ?? 0
}
export const register: Register = (on, options) => {
const cap = Number(options.capUsd ?? 5)
let warned = false // module variable: a reload starts it over, which is fine for a nudge
// Refuse a new prompt once the session is over the cap.
on('prompt.submit', async ($, e, next) => {
const now = await spent($)
if (now >= cap) return { drop: `spend-guard: this session has cost ${usd(now)}, cap is ${usd(cap)}. Raise capUsd in /config or start a fresh session.` }
return next(e)
})
// After every turn: spend in the status line, one toast when crossing 80%.
on('turn.complete', async ($, e, next) => {
const done = await next(e)
const now = await spent($)
$.ui.status(`spend ${usd(now)} / ${usd(cap)}`)
if (!warned && now >= cap * 0.8) {
warned = true
$.ui.toast(`spend-guard: ${usd(now)} of ${usd(cap)} used`)
}
return done
})
}
Walkthrough
The cap. options carries the userConfig values. If nothing is set, the cap falls back to 5.
prompt.submit. Every hook gets ($, e, next). next(e) lets the prompt through to the engine. Returning { drop: '...' } means the prompt does not enter and the text is shown to the user: what was spent and how to raise the limit.
turn.complete. Fires when a turn ends. The hook lets the engine finish (await next(e)), reads spend and writes it to the status line with $.ui.status. The first time spend crosses 80% of the cap, $.ui.toast shows one toast.
Why spent($) is a top-level function. My first version had const spent = async ($) => ... inside register. The validator refused it. It follows every $ through the module, and it will not accept a module where $ is passed to a closure it cannot follow. Moving the helper to the top level as async function spent($) passed.
Why warned is a module variable. Module variables do not survive a hot reload; $.state (session values) does. With a plain let, editing the mod mid-session resets the flag and the 80% toast may show again. For a nudge that is fine; a warning that must fire once per session would belong in $.state.
Setting the cap
Load the folder locally with claude --plugin-dir <folder>. userConfig values live under pluginConfigs in settings, and each non-secret field shows in the config menu, so capUsd is changed from /config.
Validating it
claude plugin validate <dir> reads the manifest and module the way the engine will and lists what the module hooks and calls:
hooks: prompt.submit, turn.complete
calls: $.session.usage (via spent), $.ui.status, $.ui.toast
Validation passed
The module is also type-checked with tsc 5.9 against the types file. That is the extent of what I verified. claude plugin test refused to run on our box ("hooks modules are turned off in this process: the rollout switch was saved off by an earlier session"); mods are on by default since 2.1.287, but the CLI keeps a remote switch for them, and on our box it had been saved off.
Limits
- The cap is checked between prompts, not during a turn. One long turn can overshoot; the guard stops the next prompt, not the current one.
- A single-prompt run is checked once. In a one-shot
claude -psession the only check happens before any spend, so a per-session cap does nothing there. This is my reading of the code, not a measured result. - No UI outside the CLI and desktop app. In VS Code,
claude -pand the SDK only the hooks run. The status line and toast will not show; the drop still applies. costis optional in the type. If it is missing,spent()returns 0 and the guard never trips.- No sandbox. A mod runs with your own permissions. Read any mod before loading it.
Variations (ideas, not shipped code)
- Per-day cap.
$.storesurvives across sessions, so a daily total could live there; that fits a fleet better than a per-session cap. - Token-based cap. Sum
input_tokensandoutput_tokensfromturn.stepresults and drop prompts past a token budget.
Neither has been written or validated.
Our settings-based security gate taught us that deterministic rules carry the weight, not human approval; spend-guard follows that pattern. CLI basics are in the complete 2026 guide.
FAQ
How do I check Claude Code cost during a session?
Type /cost. A mod can read the same total from $.session.usage() as cost.usd.
Can Claude Code stop itself at a spending limit?
With a mod, yes: a prompt.submit hook that returns { drop: '...' } keeps new prompts out once spend reaches your cap.
Does the cap stop a turn that is already running? No. The check runs when a prompt is submitted, so one long turn can overshoot.
Does spend-guard work in VS Code or with claude -p?
The hooks run there, so the drop applies, but there is no UI: no status line, no toast.
How do I track Claude Code token usage per request?
Hook turn.step. Its result carries usage with input, output, cache-read and cache-creation token counts.
Information is accurate as of the publication date. Terms, prices, and regulations may change — verify with relevant professionals.