Vibe coding with Claude Code course · Module 15: Advanced Claude Code

Costs, limits and choosing a model

9 min read
In this lesson9

Halfway through the final project. Since morning two longboats from lesson 14_9 have been working, overnight the watch from lesson 14_7, and a loop every ten minutes asked about commits. In the middle of a request Claude stops, and two lines appear at the bottom of the terminal:

Usage limit reached · limit resets 3:45pm
Continuing automatically at 3:45pm · Esc to cancel

The plan limit ran out at the worst moment. This lesson teaches two things: what to do when you are already stuck, and how to set up a voyage so that the powder does not run out on routine work.

What you already know

In lesson 5_10 you met /usage with its breakdown into skills, subagents, plugins and MCP servers, the effort levels, the word ultrathink and the rule that a subagent gives parallelism, not a smarter answer. In lesson 4_10 you looked into the hold with /context. From lesson 14_1 you know that claude -p without --model takes the model from your settings, and that a key from ANTHROPIC_API_KEY takes precedence over the subscription. In lesson 14_4 you heard that every enabled plugin adds its descriptions to every turn, in lesson 14_7 you set --max-turns, and in lesson 14_9 you counted that parallel sessions pay from one limit. Here you put these together into a voyage budget.

When the limit stops you halfway

Those two lines are an automatic resume. In an interactive session on a subscription, Claude Code waits in the open session and, after the limit renews, picks up the interrupted task by itself, without you sending your message again. So you leave the session open, and Esc cancels the wait. After a few resumes in a row Claude Code stops waiting by itself and sends you to /rate-limit-options: there you choose to wait, to buy extra funds (usage credits) with /usage-credits, or a higher plan. A resumed task still asks for permissions, so it can stop on a question when you are not there. Waiting saves one task, but it does not tell you why the limit went so fast.

Where the tokens went

Start with /usage and the w key, that is, the last seven days. Besides the breakdown from lesson 5_10 there is a Loops part: the heaviest /loop loops of recent days, with the number of runs and tokens per run. The loop from lesson 14_9 that sent the whole conversation every ten minutes will surface right there.

The second matter is the cargo that sails with every turn although nobody ordered it. Every turn gets CLAUDE.md with its imports, the descriptions of skills and subagents, and the tool names from MCP servers. The full definitions of MCP tools load only when used, and the full text of a skill only after it is invoked. The exception is a skill with disable-model-invocation: true, such as /pre-commit from lesson 14_4: its description is not in the context at all. The /skill-doctor command shows what each skill costs and which ones you have never used. The rest you investigate with a request:

Request for Claude Code:

Do not change any files. List what in this project goes into every turn: CLAUDE.md
with its imports, the descriptions of skills and subagents from .claude/, and the servers
from .mcp.json. For each item give the word count (wc -w) and say whether it can be
shortened, moved to a skill, or switched off.

Claude only reads and counts, and the decision to switch something off is yours. The documentation advises moving a long procedure from CLAUDE.md into a skill, because a skill pays for its text only when it is needed.

The third source is a script's report. A claude -p run with --output-format json has the total_cost_usd field and a breakdown by model in modelUsage:

jq '{subtype, num_turns, total_cost_usd, models: (.modelUsage | map_values(.costUSD))}' report.json

The amounts are Claude Code's estimate at list prices, not an invoice. On a subscription you pay nothing for them, but they are excellent for comparisons: the same run on two models, with a subagent and without. In our case a run with a one-sentence question on Haiku had two turns, and each of its requests carried about 50 thousand tokens: instructions, tools, skill descriptions and memory files. Most of it came from the cache, but every new session starts with the same cargo, and how big it is for you depends on your skills, plugins and servers.

Brakes for scripts

--max-turns from lesson 14_7 counts the agent's steps. --max-budget-usd counts money: it works only in -p mode, stops the run when the estimate of spending reaches the given amount, and counts subagents in it. The generate-tests.sh script from lesson 14_2 gets it in one place:

  claude -p "Write Vitest tests for @$FILE: every exported function and the edge cases.
Return only TypeScript code, without Markdown fences and without explanations." \
    --model sonnet --max-turns 5 --max-budget-usd 0.5 > "$TEST_FILE.tmp" || continue

The amount 0.5 is an example; you will work out your own in a moment. In our case a run stopped by the limit ended with exit code 1, and in the JSON it had subtype equal to error_max_budget_usd, an empty result and the error Reached maximum budget. In the script || continue then moves to the next file, and only the .tmp remains.

The limit is not a wall, though. Claude Code compares spending with the limit after the model's response, and a response that crosses it still counts. In our case a run with a deliberately too small limit stopped only after four turns, and total_cost_usd showed a multiple of the limit. The limit also applies to one run, so a loop over ten files can spend ten times as much. So you set the amount from a trial: one file with --output-format json, a read of total_cost_usd and num_turns, and a limit with a margin in the script.

Model and effort without supervision

Routine and a hard problem need different settings. Renaming getCurrentUserId to getViewerId in about ten Treasure Map files is routine that tsc will check, and the documentation gives such a change as an example for low. You open the session with flags that are not saved as defaults:

claude --model sonnet --effort low

In this session the request reads: "Rename getCurrentUserId to getViewerId in lib/session.ts and in all usages, including the test mocks. Done when npx tsc --noEmit and npm run test -- --run pass". For scripts that rework a dozen files by a pattern in the evening, Sonnet is enough, and for simple subagents Haiku, as in lesson 5_10.

You go higher for a bug in someone else's code, a schema change or hunting for a hole before publishing: the default model (as of November 2026 that is Opus) with high or xhigh, and max only for a really hard problem that Claude works on without you. The opusplan alias joins both worlds: Opus plans in plan mode and Sonnet executes. Fable you choose by hand with /model fable, and depending on the plan it may be billed from usage credits. In the API Fable costs four times as much per token as Sonnet (as of November 2026). In -p mode nobody will see a consent question, so Claude Code bills it to usage credits without asking. --model fable in a loop is a financial decision, not a technical one.

Subscription or API key

-p mode uses the key whenever the variable is set. An interactive session asks about it once and remembers the answer. After you approve it, you pay for every token from the API account, even though your plan is paid. You change the choice with the "Use custom API key" switch in /config, visible only when the variable is set, and /status shows which login is in effect. A key makes sense in CI with --bare or for team billing. /schedule tasks and cloud sessions always use the subscription.

What raises the cost without improving the answer

  • a subagent sent "for a smarter answer": it is the same model or a smaller one, on the same task;
  • max or Fable on routine that tsc will check anyway;
  • a forgotten /loop loop in a long conversation;
  • skills, plugins and MCP servers you do not use, which sail with every turn;
  • /compact in a huge session when you do not need the history: /clear costs nothing.

Captain's review

  1. Every claude -p in scripts has --model, --max-turns and --max-budget-usd.
  2. No flagships on routine. There is no --model fable or --effort max in the scripts.
  3. Login. claude auth status --text shows the subscription when you count on it, and env | grep ANTHROPIC_API_KEY prints nothing.
  4. Loops. The Loops part of /usage shows no loop you forgot about.

A typical agent mistake: you ask for a rename, and Claude suggests /model fable and /effort max "so that nothing slips through", or writes those flags into a script. You will recognise it by the model name and level in the command. A rename is checked by tsc, not by deeper thinking, so you pay more for the same answer.

Next step

Run a trial on one file and ask: "In scripts/generate-tests.sh add the --max-budget-usd flag with the amount from the trial run times two, and in a comment above the loop write down where that number comes from. Do not run the loop". Then a commit, for example "Cost brakes in scripts". In the editor next to the lesson you will type the numbers from your trial, and the calculator will show what the whole loop will cost and whether the limit is too tight.

Remember: you count the powder before the battle, and you do not send the flagship on a routine watch.

Code for this lesson: App.tsx
// A loop calculator with brakes: what a claude -p script will cost, counted from your trial run
import { useState } from 'react';

export type Level = 'ok' | 'warn' | 'error';
export type Model = 'haiku' | 'sonnet' | 'opus' | 'fable';
export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
export type Kind = 'routine' | 'hard';

export interface Finding {
  level: Level;
  text: string;
}

export interface Plan {
  files: number;
  testTurns: number;
  testCost: string;
  maxTurns: number;
  budget: string;
  model: Model;
  effort: Effort;
  kind: Kind;
  smarterSubagent: boolean;
}

export interface Estimate {
  expectedRuns: number;
  worstRuns: number;
  expectedUsd: number | null;
  worstUsd: number | null;
  suggestedBudget: number | null;
}

export function num(text: string): number | null {
  const t = text.trim().replace(',', '.');
  if (t === '') return null;
  const n = Number(t);
  return Number.isFinite(n) && n > 0 ? n : null;
}

// The unit is the cost of your trial run on one file. The cost of a turn is approximated by the trial average.
export function estimate(p: Plan): Estimate {
  const files = Math.max(0, Math.floor(p.files));
  const turns = Math.max(1, p.testTurns);
  const cost = num(p.testCost);
  const budget = num(p.budget);
  const perRunWorst = Math.max(1, p.maxTurns) / turns;
  let worstPerRun = perRunWorst;
  if (cost !== null && budget !== null) {
    const capRuns = budget / cost + 1 / turns;
    worstPerRun = Math.min(perRunWorst, capRuns);
  }
  return {
    expectedRuns: files,
    worstRuns: files * worstPerRun,
    expectedUsd: cost === null ? null : files * cost,
    worstUsd: cost === null ? null : files * worstPerRun * cost,
    suggestedBudget: cost === null ? null : Math.ceil(cost * 2 * 100) / 100,
  };
}

export function review(p: Plan): Finding[] {
  const out: Finding[] = [];
  const cost = num(p.testCost);
  const budget = num(p.budget);
  if (p.maxTurns < p.testTurns) {
    out.push({ level: 'error', text: '--max-turns ' + p.maxTurns + ' is less than the ' + p.testTurns + ' turns in the trial: the runs will end with error_max_turns.' });
  }
  if (budget === null) {
    out.push({ level: 'warn', text: 'Without --max-budget-usd the only brake is --max-turns.' });
  } else if (cost === null) {
    out.push({ level: 'warn', text: 'Enter total_cost_usd from the trial to judge the limit.' });
  } else if (budget < cost) {
    out.push({ level: 'error', text: 'A limit lower than the trial cost: most runs will be stopped by error_max_budget_usd and leave only .tmp.' });
  } else if (budget < cost * 1.5) {
    out.push({ level: 'warn', text: 'A small margin. A file harder than the trial one will reach the limit, and a response that crosses it still counts.' });
  } else {
    out.push({ level: 'ok', text: 'A limit with a margin: it will stop a run that goes round in circles and will not hinder ordinary ones.' });
  }
  if (p.model === 'fable') {
    out.push({ level: 'error', text: 'Fable in -p: depending on the plan it is billed from usage credits, and nobody will see a consent question.' });
  }
  if (p.kind === 'routine') {
    if (p.effort === 'max') out.push({ level: 'error', text: 'max on routine overthinks: you pay more for an answer no better than with high.' });
    else if (p.effort === 'xhigh' || p.effort === 'high') out.push({ level: 'warn', text: 'Routine will be checked by tsc or the tests anyway. The default medium is enough, and low for a rename.' });
    if (p.model === 'opus') out.push({ level: 'warn', text: 'Sonnet is enough for routine runs.' });
  } else {
    if (p.effort === 'low') out.push({ level: 'warn', text: 'A hard problem on low: Claude will give a starting point faster but check less. Consider high or xhigh.' });
    if (p.model === 'haiku') out.push({ level: 'warn', text: 'Haiku is a model for simple subagent tasks, not for a hard problem.' });
  }
  if (p.smarterSubagent) {
    out.push({ level: 'error', text: 'A subagent for a smarter answer is the same model or a smaller one on the same task: more tokens, the same quality.' });
  }
  return out;
}

export function command(p: Plan): string {
  const parts = ['claude -p "Write Vitest tests for @$FILE."', '--model ' + p.model];
  if (p.effort !== 'medium') parts.push('--effort ' + p.effort);
  parts.push('--max-turns ' + p.maxTurns);
  const budget = num(p.budget);
  if (budget !== null) parts.push('--max-budget-usd ' + budget);
  parts.push('> "$TEST_FILE.tmp" || continue');
  return parts.join(' ');
}

export function fmt(n: number): string {
  return n.toFixed(2);
}

const START: Plan = {
  files: 9,
  testTurns: 4,
  testCost: '',
  maxTurns: 5,
  budget: '',
  model: 'sonnet',
  effort: 'medium',
  kind: 'routine',
  smarterSubagent: false,
};

export const AGENT_MISTAKE: Plan = { ...START, model: 'fable', effort: 'max', maxTurns: 30 };

const LEVEL_CLASS: Record<Level, string> = {
  ok: 'text-emerald-400',
  warn: 'text-amber-400',
  error: 'text-rose-400',
};

function Field(props: { label: string; value: string | number; onChange: (v: string) => void; hint?: string }) {
  return (
    <label className="flex flex-col gap-1 text-sm">
      <span className="font-semibold">{props.label}</span>
      <input className="rounded bg-slate-900 p-1 font-mono" value={props.value} onChange={(e) => props.onChange(e.target.value)} />
      {props.hint ? <span className="text-xs text-slate-400">{props.hint}</span> : null}
    </label>
  );
}

export default function App() {
  const [p, setP] = useState<Plan>(START);
  const set = <K extends keyof Plan>(key: K, value: Plan[K]) => setP({ ...p, [key]: value });
  const e = estimate(p);
  const findings = review(p);

  return (
    <div className="min-h-screen space-y-4 bg-slate-950 p-4 text-slate-100">
      <h1 className="text-xl font-bold">What will the loop cost?</h1>
      <p className="text-sm text-slate-300">You enter the trial numbers yourself: one file, the same model, --output-format json, then jq.</p>
      <div className="flex flex-wrap gap-2 text-sm">
        <button type="button" className="rounded bg-slate-800 px-2 py-1 hover:bg-slate-700" onClick={() => setP(START)}>Routine from the lesson</button>
        <button type="button" className="rounded bg-slate-800 px-2 py-1 hover:bg-slate-700" onClick={() => setP(AGENT_MISTAKE)}>Agent mistake: a flagship on routine</button>
      </div>
      <div className="grid gap-3 md:grid-cols-3">
        <Field label="Files in the loop" value={p.files} onChange={(v) => set('files', Number(v) || 0)} />
        <Field label="num_turns from the trial" value={p.testTurns} onChange={(v) => set('testTurns', Number(v) || 1)} />
        <Field label="total_cost_usd from the trial" value={p.testCost} onChange={(v) => set('testCost', v)} hint="Your estimate from the report, empty = counted in trial units" />
        <Field label="--max-turns" value={p.maxTurns} onChange={(v) => set('maxTurns', Number(v) || 1)} />
        <Field label="--max-budget-usd" value={p.budget} onChange={(v) => set('budget', v)} hint="empty = no limit" />
        <label className="flex flex-col gap-1 text-sm">
          <span className="font-semibold">Task</span>
          <select className="rounded bg-slate-900 p-1" value={p.kind} onChange={(ev) => set('kind', ev.target.value as Kind)}>
            <option value="routine">routine (a rename, tests by a pattern)</option>
            <option value="hard">hard problem (someone else's bug, a hole)</option>
          </select>
        </label>
        <label className="flex flex-col gap-1 text-sm">
          <span className="font-semibold">--model</span>
          <select className="rounded bg-slate-900 p-1 font-mono" value={p.model} onChange={(ev) => set('model', ev.target.value as Model)}>
            {['haiku', 'sonnet', 'opus', 'fable'].map((m) => <option key={m} value={m}>{m}</option>)}
          </select>
        </label>
        <label className="flex flex-col gap-1 text-sm">
          <span className="font-semibold">--effort</span>
          <select className="rounded bg-slate-900 p-1 font-mono" value={p.effort} onChange={(ev) => set('effort', ev.target.value as Effort)}>
            {['low', 'medium', 'high', 'xhigh', 'max'].map((m) => <option key={m} value={m}>{m}</option>)}
          </select>
        </label>
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={p.smarterSubagent} onChange={(ev) => set('smarterSubagent', ev.target.checked)} />
          have a subagent check the answer to be sure
        </label>
      </div>
      <pre className="overflow-x-auto whitespace-pre-wrap rounded bg-slate-900 p-2 font-mono text-xs">{command(p)}</pre>
      <section className="grid gap-2 text-sm md:grid-cols-2">
        <p className="rounded border border-slate-700 p-2">
          Typical: {fmt(e.expectedRuns)} x trial{e.expectedUsd !== null ? ' = ' + fmt(e.expectedUsd) + ' USD estimate' : ''}
        </p>
        <p className="rounded border border-slate-700 p-2">
          Worst case (every run up to the limit): {fmt(e.worstRuns)} x trial{e.worstUsd !== null ? ' = ' + fmt(e.worstUsd) + ' USD estimate' : ''}
        </p>
      </section>
      {e.suggestedBudget !== null ? (
        <p className="text-sm">Suggested limit: the trial cost times two, that is --max-budget-usd {e.suggestedBudget}.</p>
      ) : null}
      <p className="text-xs text-slate-400">The amounts are Claude Code's estimate at list prices, not an invoice. A change of model or effort is a new trial.</p>
      <ul className="space-y-1 text-sm">
        {findings.map((f) => (
          <li key={f.text} className={LEVEL_CLASS[f.level]}>{f.level}: {f.text}</li>
        ))}
      </ul>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. The plan limit vanishes in the middle of the week, although you work as usual. Where do you start?

  2. 2. What raises the cost without improving the answer?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Put the steps in order before you run generate-tests.sh with --max-budget-usd on all the files:

  1. QuestionQuiz: When a task costs too much
  2. QuestionQuiz: Cost without a better answer
  3. Put in orderSorting: A budget limit for a loop
  4. QuestionQuiz: An approved API key

Useful articles