How I keep AI coding agents cheap

Most of the code in the SaaS product I’m building is written by AI coding agents. I run Claude Code with an orchestrator that hands batches of work to developer agents, a reviewer, and two small helpers for git and build checks.

This post is how I keep that setup cheap and predictable. It has the practices I rely on, real numbers from my own sessions, and the prompt I use to audit them, which you can download at the end.

The short version

  • Measure agent sessions with a script. Your sense of where the tokens go is wrong.
  • 96% of my tokens are the model re-reading its own context. What gets into the context matters more than anything else.
  • Prompt cache expiry was my largest avoidable cost: 363 cache rewrites, about $222.
  • Use the big model for design and review. Fully specified work goes to a smaller one.
  • Give an agent file paths and a condition for done. Don’t give it summaries.
  • The reviewer reads the diff and nothing else.
  • Keep build and test output out of the context: one PASS or FAIL line, with the log in a file.
  • Build tools for your agents. A tool saves them from working out the same job every time, and hands back only the context they need.
  • Put every limit in one settings file, and make loops stop and ask you.
  • Keep a short lessons file, and empty it by turning lessons into rules and scripts.

Measure AI agent cost with a script, not a guess

The tempting way to audit a session is to ask the agent to read its own logs and tell you what was expensive. You get a confident answer with numbers in it, and the numbers are estimates. A model that reads ten thousand log lines and “counts” is doing something closer to vibes than arithmetic.

My rule is a script for facts and the model for judgement. Claude Code keeps session logs as JSONL files under ~/.claude/projects/, and every call in there has its input, output, cache read and cache write token counts. A small Node script adds them up, multiplies by a price file I can edit, and prints a table. The agent only gets to explain the table.

The metrics I watch most:

  • Cache hit rate, and every cache rewrite with its cause.
  • Subagent spawns by role and model.
  • The same call with the same input, repeated in one session.
  • A failed command followed by a different command for the same goal. That’s a workaround, and workarounds repeat.
  • My own messages that correct an earlier message.

That last one is uncomfortable to look at. If I’ve typed “no, only run the build” five times in a month, the problem isn’t the agent.

Where the tokens go

These are my totals for the last seven days, across everything I ran:

Cache read553.1M Cache write18.4M Output3.8M Input9.7k
575.2 million tokens in seven days.

That is 575 million tokens, and 96% of them are cache reads. Uncached input is under ten thousand tokens. Output, the part where an agent writes code, is 0.7%.

That chart explains most of what follows. An agent session is mostly the model reading its own context again, once per call. Whatever gets into the context is paid for on every call after it, until the session ends. A cache read is cheap per token, but there are 553 million of them. So nearly every change below comes from asking what is in the context that doesn’t need to be there.

Protect the prompt cache

The prompt cache is the best example of why I measure. With prompt caching, the part of the context that hasn’t changed is read from a cache at a fraction of the normal input price. The cache has a time to live. If nothing touches it before it expires, the next call writes the whole context again, at more than the full price.

Subagents get a five minute cache by default. That sounds fine until you look at what agents in a pipeline do, which is wait. The orchestrator waits for a developer agent. The developer agent waits for a build. A backend build with a container or two takes longer than five minutes without trying. Every one of those waits ends with a full context rewrite.

5 minute cache
Full rewrite
1 hour cache
Cache read
Yellow is the time the cache stays alive. When the wait runs past it, the next call pays for the whole context again.

On one stretch of my own logs the script counted 363 of those rewrites, around $222. The fix is one line in a settings file that gives subagents a one hour cache.

363cache rewrites
~$222paid for them

With the one hour cache, my latest 11 sessions used 99 subagents between them and show four rewrites, about $3.78. All four are the main session sitting idle for more than an hour, which is me leaving the desk. The cache hit rate is 98.5% for the main session and 95.7% for subagents.

Two related rules:

  • Changing the model, the reasoning effort, or the connected tool servers in the middle of a session rewrites the cache too. I pick them when the session starts and leave them alone.
  • The cache matches from the top of the prompt. So the stable part of an agent brief goes first, and the part that changes per task (the task id, the file list) goes at the end.

Use the big model for thinking, a small one for typing

The safe-looking default is the largest model everywhere. Most agent work needs no deep thought at all: a task with the files named, the change described and a build that says whether it worked.

My developer agents run on Sonnet by default. Opus is for the orchestrator, for reviews, and for tasks where the design is still open. Git operations and running the checks go to Haiku, because “run these four commands and tell me the result” is not a reasoning problem.

Those same 11 sessions cost $166 in total. The 56 developer agents account for $93.52 of it. The 14 git agents cost $1.17 and the 6 agents that run the checks cost $0.45.

Quality holds on specified work. Where it does go wrong, the cause is nearly always a vague brief, and a bigger model only hides a vague brief for a while.

Write smaller briefs for subagents

The common mistake is a long brief. The main session summarises everything it knows and pastes it into the subagent’s prompt. It feels thorough. In practice you pay for the same information twice, and the summary is a lossy copy of files the agent could read itself.

A brief has four things:

Goal:    one sentence
Read:    paths to the plan and the files that matter
Write:   the output file
Done:    the check that has to pass

No history and no copied content. The reply is limited as well. An agent answers once, in a few lines, and the first word is DONE, NEEDS_INPUT or BLOCKED. The details go in a file in the task folder, where I can read them if I care and the orchestrator doesn’t have to carry them in its context.

One more rule: before creating a new agent, check whether one with the right context already exists and send it a follow-up. The stats script flags briefs that repeat, and it still finds a few.

The reviewer reads only the diff

A reviewer agent that is free to explore the repository will explore the repository. It reads half the codebase, forms opinions about code nobody touched, and costs as much as the developer did.

Mine gets a patch file and writes a review file with a verdict line. That’s the whole job. I don’t review after every batch either. A developer agent takes about ten tasks, and one review covers the branch at the end. Per-batch reviews mostly flag things the next batch is about to change anyway.

If the review asks for fixes, a fresh reviewer looks at the new changes only. And after two rounds of fix and review, the pipeline stops and asks me. Two agents politely disagreeing with each other will happily go on all night.

  1. Fix 1
  2. Review 1
  3. Fix 2
  4. Review 2
  5. Stop and ask me
Two rounds, then a human decides.

Keep build and test output out of the context

Left alone, an agent runs the full test suite after every change and reads everything it prints. Both halves of that are expensive.

The first half is about when. During development, a task is done when the build passes. Tests and lint run once, at the very end, over the whole branch. If something fails there, it goes back as a fix. It sounds reckless. It isn’t, because a compile error catches most of what an agent gets wrong mid-task, and the final gate catches the rest.

The second half is the one people miss. A passing build contains one fact: it passed. The log that says so is hundreds of lines long. When an agent runs the build directly, every one of those lines lands in its context and is read again on each call for the rest of the session. That’s the 96% from earlier.

So my agents never run builds directly. They go through a small tool that runs the command, writes the full output to a log file in the task folder, and prints one line:

$ node task.mjs gate 0042 build -- npm run build
PASS build (41.3s) log: .tasks/0042-example/gates/build.log

On a failure it prints FAIL and the last 30 lines of the output, which is usually where the error is. The whole log is still on disk, and the agent can search it when 30 lines aren’t enough.

The final test run works the same way, with one more step. A separate agent on the smallest model runs the gates and reports pass or fail. It never reads code and never tries to fix anything. The test output stays out of the context of the agents that do the thinking. Those are the six agents that cost $0.45.

Build tools for your AI agents

The gate is one tool. The concept behind it is the most important thing in this post: arm your agents with tools.

Without a tool, an agent has to work out how to do a job every time it does it. Ask one to commit a batch of work and it thinks about what to run, runs git status, reads the output, runs git add, runs git diff to check itself, commits, runs git log to confirm, and then writes a long answer about what it did. Every one of those outputs stays in the context. The next agent works it all out again, a little differently.

A tool settles the how once. The agent makes one call and gets back only the context that matters for its next step. That means fewer tool calls, less thinking and shorter answers, and all three are tokens.

Each of my projects has a small toolbox that lives in the repo, next to the agent profiles. For the main one it’s a single Node file, 271 lines, with no dependencies. It has a handful of commands:

  • gate runs a build or a test command, logs it, and prints PASS or FAIL.
  • commit stages exactly the files it is given, commits them, and records which tasks of the plan the commit covers.
  • check answers “did this task land?” with yes and a commit hash, or with a failing exit code.
  • diff writes the patch file that the reviewer reads, so the reviewer never runs git.
  • status prints one screen that says where the task stands.

They all work the same way: one call, an answer in one line, and the details in a file for the rare case an agent needs them. In my latest 11 sessions the agents called that file 147 times.

I try not to write tools on a hunch. The stats script lists the shell habits that agents fall back on, and new tools come from that list. Today it shows 163 commands that swallow their own errors, 54 sleep-and-poll loops and 45 files written through a heredoc. My bar for a new tool is the same command shape at least 15 times across at least three sessions. Nothing clears it in the latest run, so those three are what I’m watching.

The tools have tests. An agent will edit a tool sooner or later, and I’d rather a test catch it than a broken pipeline.

Keep limits in one settings file

Limits written into prompts rot. “Use at most three agents.” “Keep replies short.” Change your mind once and you have to find every prompt that says it.

So there’s one file. It has the model and effort for each role, how many agents can run at once, how many a single task may use, the number of fix rounds, the reply length, and the steps where I have to approve. Scripts, skills and agent profiles read from it. Good starting values are three agents at a time, five per task, two fix rounds and five-line replies. Yours will differ, and the audit tells you which ones are wrong.

The approval steps matter more than they look. For me “done” means I approved it, not that the agent said so. The plan, the final result and anything hard to undo all wait for me.

A lessons file that empties itself

Every agent setup grows a memory file, and every memory file turns into a junk drawer. Left alone it fills with duplicates, entries about files that no longer exist, and rules that contradict each other.

What works better is a short list of workflow decisions, one line each:

- 2026-10-27 | review | reviewer reads only the diff | it explored the whole repo | task 0042

The list has a hard limit of ten lines. At ten, the session stops and I go through them. Each lesson becomes a rule in the instructions file, a step in a skill, a script, a hook or a settings value, and then the line is deleted. A lesson that stays in the file forever is a rule I haven’t bothered to enforce.

Related: watch what loads into every session. The instructions file that the agent always reads should hold short rules that apply to all work. Everything else belongs in a skill with clear trigger words, so it loads only when a request matches. Checks that must run every time belong in a hook or a script, which costs no context until it has something to report.

What I’d do first

If you run AI coding agents and have never looked at the logs, do the boring thing first. Write the script. Get the cache hit rate and the cost per session. I’d bet there is one finding in there that pays for the afternoon, the way the cache TTL does.

Then change one thing, run a small real task, and run the script again. Without a before and an after, you can’t tell whether a change saved anything.

This setup keeps changing. There are shell habits in the stats that should become tools, and limits that are still set by feel. But the sessions are cheap, they stop when they should, and I know where the money goes.

Download the audit prompt

I wrote the whole process down as one prompt, so you can run the same audit on your own sessions. It isn’t tied to Claude Code or to code. It reads your memory and instruction files, asks you for your limits, writes the measuring script, reports the top costs, and sets up the delegate skill and the lessons file described above.

Paste it into a session in the project you want to audit. Replace <days> with how far back to look and <sample task> with a small real task for the final check. It changes nothing without your approval.

FAQ

Why are my Claude Code sessions so expensive?

The usual causes are cache rewrites after idle gaps, the largest model doing routine work, raw build and test output in the context, and long briefs that copy content the agent could read from a file. The order differs per setup, so measure before changing anything.

How do I stop builds and tests from filling an agent’s context?

Wrap them in a script that writes the full output to a file and prints one PASS or FAIL line, plus the last lines of the log on a failure. Run the slow test suite once at the end, from a small agent that only reports the result.

How many subagents should run at the same time?

I cap it at three, and only for work that is independent. Two agents never change the same files, and an agent that needs another’s result waits for it.

Does this only apply to Claude Code?

No. The numbers here come from Claude Code, but Codex, OpenCode and others also keep session logs, bill for context, and let you choose a model per agent. The cache details will be different. Small briefs, diff-only review and limits in one file should carry over.

← All writing