finance

Token Economics Cheat-Sheet: Claude Code Cost Controls Reference

Token Economics Series: Part 1: Your AI Bill Is Lying to You | Part 2: The Practitioner’s Toolkit | Part 3: Scaling the Discipline | Cheat-Sheet

This is the quick-reference companion to the Token Economics series. No narrative, no opinions — just every command, setting, and mechanism you need for tracking and controlling Claude Code token spend, organised by task and by feature. The examples are Claude Code specific, but the underlying principles — model selection, effort control, context discipline, visibility — transfer to any AI coding tool. Keep this open while you work.


Quick Reference: “How Do I…”

GoalAnswer
Switch model mid-conversation?/model sonnet
Switch model per subagent?model: haiku in subagent frontmatter
Cap spending on a single run?--max-budget-usd 5.00 (print mode only)
See cost right now?/cost (API) or /context (all) or status line
See cost always?Status line with ccusage or custom script
Reduce thinking cost?/effort low or MAX_THINKING_TOKENS=0
Stop background token usage?DISABLE_NON_ESSENTIAL_MODEL_CALLS=1
Get team-wide usage data?Admin API: Usage Report + Cost Report endpoints
Keep logs forever?"logRetentionDays": 100000 in settings.json
Analyse my own logs?npx ccusage daily or DuckDB on JSONL
Limit MCP overhead?/mcp to disable unused servers, MAX_MCP_OUTPUT_TOKENS
Use cheapest model?--model haiku or model: haiku in subagent
Prevent reading huge files?PreToolUse hook on Read tool
Get fastest responses?/fast (Opus only, $30/$150 MTok)

Model Selection & Switching

MethodScopePersists?Details
/modelMid-sessionUntil session endsInteractive picker with effort slider
/model sonnetMid-sessionSame sessionShorthand, skips picker
--model <name>Session startThat sessionCLI flag
ANTHROPIC_MODEL env varAll sessionsUntil unsetEnvironment variable override
model in settings.jsonDefaultYesVia /config or direct edit
model: frontmatterPer-skill/subagentN/AEach can run different model
opusplan aliasConfigurableConfigurableOpus for planning, Sonnet for execution
--fallback-modelPrint modeThat invocationAuto-fallback when overloaded

Available aliases: opus, sonnet, haiku, opusplan. Append [1m] for 1M context: opus[1m], sonnet[1m].

Enterprise restriction: availableModels in managed/policy settings restricts which models users can select.

Auto-fallback: Claude Code may automatically fall back from Opus to Sonnet if you hit a usage threshold.


Effort & Thinking Controls

Effort Levels

LevelBehaviour
lowFast, cheap, minimal thinking. Good for straightforward edits.
mediumDefault for Opus 4.6 and Sonnet 4.6. Recommended for most coding.
highDeeper reasoning, more thinking tokens. For hard debugging, architecture.
maxOpus 4.6 only. No constraint on thinking token spend. Does not persist across sessions.

Setting Effort

MethodScopeDetails
/effortMid-sessionSlash command. Shows what auto currently resolves to.
/effort autoMid-sessionReset to default adaptive behaviour
Effort slider in /modelMid-sessionLeft/right arrows adjust
--effort <level>Session startCLI flag. Does not persist.
CLAUDE_CODE_EFFORT_LEVELAll sessionsHighest precedence. Overrides all other methods.
effortLevel in settings.jsonDefaultPersists across sessions.
effort: frontmatterPer-skill/subagentOverrides session level. Does not override env var.

Thinking Token Controls

SettingEffect
MAX_THINKING_TOKENS=NOverride fixed thinking budget. For Opus/Sonnet 4.6, only applies when set to 0 or with CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1.
MAX_THINKING_TOKENS=0Disable thinking entirely
Option+T / Alt+TQuick toggle thinking on/off
Ctrl+O (verbose mode)Makes thinking visible — see what it’s spending on
CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1Revert to fixed thinking budget controlled by MAX_THINKING_TOKENS

Context & Session Management

Commands

CommandWhat it does
/contextLive breakdown by category (files, tools, MCP, history, system) with optimisation suggestions
/compact [focus]Compress history. Optional focus: /compact Focus on API usage
/clearFull context reset. Wipes conversation history.
/rename <name>Name session before clearing so you can find it later
/resumeResume previous session by ID or name
--continue / -cContinue most recent conversation in current directory
--fork-sessionBranch from a resumed session without affecting the original
/rewindRestore conversation and code to a previous checkpoint
Esc+EscOpen rewind/checkpoint UI
Esc+Esc then “Summarize from here”Compact only from a selected point forward
Shift+Tab x2Enter plan mode — Claude plans before executing, preventing costly rework
EscapeStop current generation immediately

Auto-Compaction

Auto-compaction triggers when approaching context limits. It summarises the conversation while preserving code patterns, file states, and key decisions. Custom compaction instructions can be set in CLAUDE.md under # Compact instructions. Circuit breaker: stops after 3 consecutive failures.

Warning: Compaction itself consumes tokens. One developer found it consuming ~80% of session token usage silently. Monitor with /cost.

1M Context Window

Available for Opus 4.6 and Sonnet 4.6. Automatic on Max, Team, and Enterprise plans. Enable via /model opus[1m] or /model sonnet[1m]. Standard pricing — no premium for tokens beyond 200K. Disable with CLAUDE_CODE_DISABLE_1M_CONTEXT=1.


Cost & Usage Visibility

Built-in Commands

CommandWho it’s forWhat it shows
/costAPI users (not relevant for Pro/Max billing)Session cost ($), API duration, wall duration, lines added/removed
/statsSubscribers (Pro/Max)Usage patterns over time
/contextAll usersToken breakdown by category, context window fill %, optimisation suggestions
/usageVS Code extensionPlan usage view

Status Line

A customisable bar at the bottom of Claude Code that runs any shell script you configure, receiving JSON session data on stdin.

Configuration in settings.json:

{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/statusline.sh",
    "padding": 0
  }
}

Use /statusline and Claude Code will generate a status line script for you interactively.

Available data fields (JSON on stdin):

FieldDescription
model.display_nameCurrent model name
context_window.used_percentageContext fill percentage
context_window.total_tokensTotal context window size
current_usage.input_tokensCumulative input tokens this session
current_usage.output_tokensCumulative output tokens this session
current_usage.cache_creation_input_tokensCache creation tokens
current_usage.cache_read_input_tokensCache read tokens
current_usage.total_cost_usdSession cost in USD
rate_limits.5h.used_percentage5-hour window usage (subscribers)
rate_limits.7d.used_percentage7-day window usage (subscribers)

Note: current_usage is null before the first API call. rate_limits was added in v2.1.80.

JSONL Logs

AspectDetail
Location~/.claude/projects/<encoded-directory>/*.jsonl
FormatOne JSON object per line per event
ContentUser messages, assistant messages (with usage object), tool calls, results, metadata
RetentionDefault: 30 days, then deleted. Override: "logRetentionDays": 100000 in settings.json
Per-message fieldsinput_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens
Session metadatasessionId, parentUuid, uuid, timestamp, cwd, gitBranch, version
QueryingDuckDB: SELECT * FROM read_json_auto('session.jsonl')

Third-Party Analysis Tools

ToolInstallWhat it does
ccusagenpx ccusage dailyDaily/monthly/session/5-hr block reports, model breakdown, statusline integration, MCP server mode
Claude-Code-Usage-Monitorpip install claude-code-usage-monitorReal-time terminal dashboard, burn rate predictions, plan limit detection, P90 analysis
claudetopGitHubStatus line with live cost, cache efficiency, plugin system (8 extensions)
claude-code-loguv run claude-code-logJSONL to HTML/Markdown conversion for readable audit trails
clogGitHubWeb-based viewer with real-time file watching, conversation threading, token display

Caching

Prompt caching is automatic — no configuration needed. But understanding it is critical for cost control.

How It Works

Repeated content (system prompts, CLAUDE.md, conversation history) is cached server-side. Subsequent messages only pay the cache read price. Cache is invalidated by changing CLAUDE.md, system prompts, or anything in the prefix — keep them stable.

TTL

  • Default: 5 minutes. Pause longer than 5 minutes and you pay full uncached input price on resume.
  • Extended: 1 hour available. Cache write tokens cost 2x base input price. Cache reads cost 0.1x base price.

Pricing (Sonnet 4.6)

Token typePrice
Standard input$3/MTok
Cache read$0.30/MTok (90% savings)
Cache creation$3.75/MTok (25% premium)

200K Token Price Break

ConditionSonnet 4.6 InputSonnet 4.6 Output
Input up to 200K tokens$3/MTok$15/MTok
Input over 200K tokens$6/MTok$22.50/MTok

This applies per-request. Keep individual requests under 200K input tokens where possible.


CLI Flags & Environment Variables

Cost-Relevant CLI Flags

FlagEffect
--max-budget-usd <N>Hard spending cap (print mode only)
--max-turns <N>Limit agentic turns (print mode only)
--bareMinimal mode: skip hooks, skills, plugins, MCP, CLAUDE.md
--model <name>Set model for session
--effort <level>Set effort for session
--fallback-modelAuto-fallback when primary model overloaded (print mode)
--no-session-persistenceDon’t save session to disk (print mode)
--disallowedToolsRemove specific tools from context entirely

Cost-Relevant Environment Variables

VariableEffect
ANTHROPIC_MODELOverride model for all sessions
CLAUDE_CODE_EFFORT_LEVELOverride effort (highest precedence)
MAX_THINKING_TOKENSCap or disable thinking tokens
CLAUDE_CODE_DISABLE_ADAPTIVE_THINKINGRevert to fixed thinking budget
CLAUDE_CODE_DISABLE_1M_CONTEXTRemove 1M context option
MAX_MCP_OUTPUT_TOKENSCap MCP response size
DISABLE_NON_ESSENTIAL_MODEL_CALLSSuppress background model calls
DISABLE_COST_WARNINGSSuppress cost warning messages

Hooks for Cost Control

Hooks give you 12 lifecycle events and 4 handler types (command, prompt, agent, HTTP) to intercept Claude Code’s behaviour. These are the cost-relevant patterns.

Hook EventCost LeverExample
PreToolUse (Bash)Filter data before Claude reads itgrep for ERROR instead of cat-ing 10K lines
PreToolUse (Read)Block reading large filesDeny reads >1000 lines, suggest subagent
PreToolUse (WebFetch/WebSearch)Warn before expensive opsRemind user that web tools consume extra tokens
PostToolUse (Write/Edit)Auto-format to prevent reworknpx prettier --write on every file write
PostToolUse (Write)Cheap security reviewHaiku prompt hook auditing writes
StopForce continued workBlock premature stopping
PreCompactCustomise compactionControl what gets preserved during auto-compaction
SessionStartLoad context efficientlyInject relevant context once

Skills & Subagent Cost Patterns

Skills

FeatureCost Impact
On-demand loadingSkills load only when invoked. Full content stays out of context until needed.
disable-model-invocation: trueKeeps even the skill description out of context until manually invoked
Move instructions to skillsCLAUDE.md loads at session start. Skills load on demand. Target: CLAUDE.md under 200 lines.
model: frontmatterRun a skill on a cheaper model
effort: frontmatterOverride effort level per-skill

Subagents

FeatureCost Impact
Separate context windowSubagent’s verbose reads/output don’t bloat your main conversation. Only a summary returns.
model: haikuRun subagent on cheapest model
effort: frontmatterControl reasoning depth per-subagent
Built-in subagentsExplore (read-only, code search), Plan (architecture reasoning)
IsolationEach subagent gets fresh context. Their file reads don’t count against your main session.

Agent Teams

Multiple simultaneous Claude instances. Token usage roughly proportional to team size — expect ~7x usage compared to standard sessions when teammates run in plan mode. Use Sonnet for teammates, not Opus. Clean up when done: active teammates consume tokens even if idle. Enable with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1.


Team & Org Controls

Admin APIs

APIEndpointKey Capabilities
Usage ReportGET /v1/organizations/usage_report/messagesBucket by 1m/1h/1d. Group by model, workspace, API key, service tier. Filter by model, workspace, date range.
Cost ReportGET /v1/organizations/cost_reportUSD costs. Group by workspace or description. Parsed model and geo fields.
Claude Code AnalyticsSeparate endpointWorkspace telemetry for Claude Code specifically

Console Dashboard

Visual cost and usage reporting. Workspace spend limits configurable by admins. Available to Developer, Billing, and Admin roles.

Observability Integrations

PlatformMechanism
DatadogNative integration tile. Pre-built dashboards. FOCUS-compliant cost attribution.
HoneycombCustom OpenTelemetry collector. Minute-level granularity.
LiteLLMOpen-source Python proxy. Virtual keys for per-developer tracking. PostgreSQL-backed budgets.
BifrostCompiled LLM gateway. Prometheus metrics. Hierarchical budget controls.

For detailed coverage of observability platforms, see Part 3: Scaling the Discipline.


Version & Background Usage Notes

Version Pinning

Recent versions have had cache-breaking bugs that inflated costs 10-20x. Pin your version when stable. Check with claude --version, update with claude update.

Background Token Usage

Even when idle, Claude Code uses tokens for conversation summarisation (under $0.04/session) and command processing. Suppress non-essential background calls with DISABLE_NON_ESSENTIAL_MODEL_CALLS=1.

MCP Tool Overhead

MCP tool schemas are deferred by default — only tool names enter context until Claude actually uses a tool. Use /context to see what MCP tools are consuming, /mcp to disable unused servers, and MAX_MCP_OUTPUT_TOKENS to cap response size (default: 25,000 tokens, warning at 10K). Prefer CLI tools (gh, aws, gcloud) where possible — zero per-tool listing cost.


This reference is maintained by Viewyonder. For the strategic context behind these controls, read the Token Economics series. For help building token discipline into your team’s workflow, get in touch.

← All writing