Cursor’s headless CLI now reports reasoning tokens next to ordinary input and output counts. The change landed in November 2026, and a DEV Community write-up on Cursor pricing calls out the practical effect: a script can read reasoningTokens in both per-turn and total usage, so CI cost accounting finally has the number it was missing. If you run the agent from cron jobs, pre-push hooks or pipelines, that field decides whether your monthly bill is a surprise or a line item.
Cursor pricing has also shifted under everyone’s feet. Old request-based plans now carry a legacy label, the new tiers run on shared usage pools, and third-party models bill at API list price. Nobody can read a single dashboard number and tell you what last night’s scripted run cost. A small Python ledger fixes that. It wraps every headless call, prices it from an editable table, stores it in SQLite and fails a CI job when a budget line is crossed. The same pattern slots straight into running the CLI in GitHub Actions, and you can finish the build in about 70 minutes.
The finished project is a small standard-library Python tool with its own passing unit tests. It needs no paid dependency, and a fake agent script lets you test everything without spending a single token.
Don't miss new tech stories on Google
Add Shattered once in the Google app and our stories show up in your news suggestions.
Why a Cursor CLI Cost Ledger Beats Checking the Dashboard #
A dashboard answers one question: how much of my plan is gone? A scripted workflow raises a different one. Which job, on which model, burned how many tokens, and what would that have cost at list price? Without per-run records you cannot compare a nightly docs sync against a pull request reviewer, and you cannot tell whether switching a task from one model to another saved money or only felt cheaper.
Agents are spreading fast enough that the question matters. The 2025 Stack Overflow Developer Survey, summarized in its leaders report on AI agents, found that “87% of survey respondents are concerned about the accuracy of AI agents, while 81% are concerned about security and privacy when using them.” Spend is a separate worry, but anyone who has watched an unattended agent loop knows it belongs next to those two. A ledger gives you the evidence to answer a finance team before they ask.
Three properties make per-run records worth the effort. First, they are comparable. Every row carries the same columns, so a Sonnet run and a Carbon run line up in one query. Second, they are dated. Prices change on schedule (Gemini 4 Carbon doubles on December 1, 2026), and a dated price table keeps last week’s rows honest after the new rate starts. Third, they are enforceable. A budget gate turns a spreadsheet habit into an exit code that stops a runaway job.
The ledger also exposes a trap that dashboards hide. Included plan usage is a pool, not dollars. When a run draws from that pool, the number you can compute is a list-price equivalent, which is still the right yardstick for comparing models and tasks. The ledger labels it that way and keeps the real invoice separate.
Cursor Pricing for Headless Runs: What You Actually Pay #
Start with the plan structure, because it sets the ceiling. According to the pricing guide at Strict Themes, the documented included usage steps from Limited on Free to Base on Plus, then 4x Plus on Premium, 15x Plus on Super and 50x Plus on Ultra. Cursor’s own pricing page lists annual billing at $80 for Plus, $300 for Premium, $1,000 for Super and $2,000 for Ultra, excluding tax. Teams seats run $30, $100 or $200 per seat each month, matching the usage tier.
| Plan | Included usage | Annual billing (excl. tax) |
|---|---|---|
| Free | Limited | None |
| Plus | Base | $80 a year |
| Premium | 4x Plus | $300 a year |
| Super | 15x Plus | $1,000 a year |
| Ultra | 50x Plus | $2,000 a year |
| Teams | Matches the seat tier | $30, $100 or $200 per seat a month |
Several details matter for scripts. Cursor’s documentation reportedly shares one weekly usage pool across the editor agent, the CLI and Cloud Agents, so a heavy overnight job eats into what your editor session can use the next morning. Free and Plus reportedly exclude third-party models and Cloud Agents, which means a CLI script on those plans may not be able to select the model you planned around. Check the plan page before you design the workflow.
Third-party models bill separately. On individual plans that reportedly means API list price drawn from prepaid credit. Teams and Enterprise add a Cursor Token Rate of $0.25 per million tokens on eligible third-party requests, on top of model API pricing, and the rate also applies to bring-your-own-key usage. Individual plans do not pay it. The rate skips any third-party model whose cache-read price sits strictly below $0.10 per million tokens across every pricing tier. Legacy request-based plans still exist, with on-demand usage at the model’s API rate plus 20%, and Max Mode lives only there.
Regional data residency adds another multiplier. Cursor’s pricing page says opting in carries a 10% uplift on model pricing for eligible models. The ledger in this tutorial models the token rate and leaves the residency uplift as a config tweak you can add in the advanced section.
Per-model rates come from Cursor’s model pricing page. The table below holds the rates the ledger ships with. Two sources confirmed each figure, and the Gemini 4 Carbon schedule comes from the model page plus a pricing explainer at HuiaHub. For a wider view of how these prices stack up against rival assistants, see the Claude Code, Cursor and Copilot pricing and limits comparison.
| Model in Cursor | Input per 1M | Cache read per 1M | Cache write per 1M | Output per 1M |
|---|---|---|---|---|
| Claude Opus 5.5 | $4 | Not listed here | Not listed here | $20 |
| Claude Sonnet 5.5 | $2 | Not listed here | Not listed here | $10 |
| Claude Fable 5.2 | $8 | $0.20 | $10 | $40 |
| Gemini 4 Carbon (through Nov. 30) | $2 | $0.10 | Not listed here | $10 |
| Gemini 4 Carbon (from Dec. 1) | $4 | $0.20 | Not listed here | $20 |
Claude Fable 5.2 replaced Fable 5.1 in Cursor’s documentation, so any script that still names the older model needs a new ID. Gemini 4 Neon also appears in the catalog as a third-party model, but only one source gave its rates, so the ledger leaves it out until you confirm the numbers yourself.
Prerequisites and Versions #
Set up a clean folder and confirm each tool before writing code. Most failures later in the tutorial trace back to an old runtime or a CLI that never reached the PATH. The versions below match what the author used for testing. If your local Cursor CLI setup already works, you can skip the install steps and jump to the capture in Step 2.
| Requirement | Version | Why you need it |
|---|---|---|
| Node.js | 22.13 or newer | Cursor’s Agent SDK documentation sets this floor for its CLI |
| Python | 3.12 (tested on 3.12.3) | Runs the wrapper, parser, tests and reports |
| Cursor CLI (agent) | Latest release | Provides the headless print mode the ledger wraps |
| SQLite | Bundled with Python | Stores one row per run, no server needed |
| Git | Any current release | Lets the agent read a repo and lets you tag runs by branch |
| A Cursor plan with CLI access | Premium or higher recommended | Third-party models and Cloud Agents need a paid tier |
You also need a repository to point the agent at, a terminal that can keep environment variables between commands, and about $1 of spare credit if you plan to run the real CLI in Step 2. The fake agent in Step 9 covers everything else for free.
The headless entry point is print mode. As the Repowise guide to Cursor CLI headless mode describes it, you pass -p or --print with a prompt and the agent runs non-interactively, which suits scripts, CI pipelines and GitHub Actions. Cursor’s documented example looks like agent -p "..." --model "gpt-5". The older cursor-agent name reportedly remains as an alias, so either command can work on your machine.
Phase 1: Check the Tools and Capture a Raw Run (Steps 1 to 3) #
Step 1: Verify Node, Python and the CLI
Run four commands and read the output before moving on. Each one confirms a requirement from the table, and the last lists the model identifiers your account can actually select. The CLI changelog reportedly added agent models and a --list-models flag in January 2026. If your build words it differently, agent --help shows the right spelling.
node --version
python3 --version
agent --version
agent models
Write down the exact model strings. They become the keys of your price table in Step 4, and a mismatch between the string you pass to --model and the key in the table is the most common reason a run fails to price. Expect output that resembles v22.13.0 for Node and Python 3.12.3 for Python. Your CLI version string will differ from anything printed here.
Step 2: Capture One Raw Headless Result
Every parser guess in this tutorial depends on the real shape of the output, so capture one before writing a line of parser code. Use a cheap prompt on a cheap model, redirect stdout to a file and search it for token fields. The command below uses --output-format json, the machine-readable option the headless documentation points to for CI. If your build names the flag differently, substitute the right one.
agent -p "Describe this repository in one sentence" --model claude-sonnet-5-5 --output-format json > raw.json
python3 -m json.tool raw.json | grep -i tokens
Look for three things in the result. Find the key that holds total usage, find the keys that hold input and output counts, and find reasoningTokens. Cursor’s release notes say headless results began including that field in both per-turn and total usage when the model uses reasoning, so a non-reasoning run may omit it entirely. Run the capture twice, once with a reasoning-heavy prompt, to see both shapes. Save both files, because they become test fixtures in Step 10.
The parser in Step 6 matches field names after stripping underscores and lowercasing, so input_tokens and inputTokens both work. If your capture shows a name the parser does not know, add it to the alias table and move on. Do not rewrite the parser around a single capture.
Step 3: Create the Project Skeleton
Make one folder with a package for the code and a folder for tests. Keep the database and the price table at the project root so CI can cache the first and review changes to the second.
mkdir -p cursor-ledger/ledger cursor-ledger/tests
cd cursor-ledger
touch ledger/__init__.py
git init
Add ledger.db to .gitignore right away. The database can store raw agent output (more on that in the pitfalls), and a committed database leaks prompts and code into history. Commit prices.json instead, because price changes deserve a pull request and a reviewer.
Phase 2: Price Table and Usage Parser (Steps 4 to 6) #
Step 4: Write the Dated Price Table
The price table is plain JSON with one list of dated entries per model. Each entry holds the rates that apply from its from date forward, and the lookup picks the latest entry on or before the run date. That structure handles the December 1 jump for Gemini 4 Carbon without touching code. The table also records the reasoning mode and the Cursor Token Rate by plan.
{
"as_of": "2026-11-25",
"reasoning_mode": "separate",
"token_rate_per_million": {"individual": 0.0, "teams": 0.25, "enterprise": 0.25},
"models": {
"claude-opus-5-5": [
{"from": "2000-01-01", "input": 4.00, "output": 20.00}
],
"claude-sonnet-5-5": [
{"from": "2000-01-01", "input": 2.00, "output": 10.00}
],
"claude-fable-5-2": [
{"from": "2000-01-01", "input": 8.00, "cache_write": 10.00, "cache_read": 0.20, "output": 40.00}
],
"gemini-4-carbon": [
{"from": "2000-01-01", "input": 2.00, "cache_read": 0.10, "output": 10.00},
{"from": "2026-12-01", "input": 4.00, "cache_read": 0.20, "output": 20.00}
]
}
}
Two settings need explanation. reasoning_mode says whether reasoning tokens arrive on top of output tokens (separate) or already sit inside them ( included). Cursor’s notes do not settle this for every model, so calibrate it in the advanced section. Most providers bill reasoning at the output rate, which is why separate is the default and the safer, higher estimate.
Any model whose cache price you have not confirmed falls back to the input rate in the calculator. That overstates cost whenever the run reuses cache, so treat those rows as an upper bound. Add the real cache numbers the moment you confirm them on Cursor’s model page for your account. For a comparison of Fable-class and Gemini-class token rates in a different tool, Gemini CLI against Claude Code compares the token rates of Gemini 4 Neon and Claude Fable models in a different tool.
Step 5: Build the Cost Calculator
The calculator has three jobs. It finds the right dated rate, applies the reasoning mode, and adds the Cursor Token Rate for Teams and Enterprise unless the model qualifies for the exemption. The exemption test is literal: every pricing tier must list a cache-read price strictly below $0.10 per million tokens. Carbon’s introductory cache-read price is exactly $0.10, so it does not qualify.
import json
MILLION = 1_000_000
EXEMPT_CACHE_READ = 0.10
def load(path):
with open(path, encoding="utf-8") as fh:
return json.load(fh)
def rate_for(table, model, day):
entries = table["models"].get(model)
if not entries:
known = ", ".join(sorted(table["models"]))
raise KeyError(f"no price for model '{model}'. Known: {known}")
live = [e for e in entries if e["from"] <= day]
if not live:
raise KeyError(f"no price for '{model}' on {day}")
return max(live, key=lambda e: e["from"])
def token_rate_exempt(table, model):
entries = table["models"][model]
return all(e.get("cache_read", float("inf")) < EXEMPT_CACHE_READ for e in entries)
def cost(table, model, day, usage, plan="individual"):
rate = rate_for(table, model, day)
mode = table.get("reasoning_mode", "separate")
out_tokens = usage["output"] + (usage["reasoning"] if mode == "separate" else 0)
read_rate = rate.get("cache_read", rate["input"])
write_rate = rate.get("cache_write", rate["input"])
base = (
usage["input"] * rate["input"]
+ usage["cache_read"] * read_rate
+ usage["cache_write"] * write_rate
+ out_tokens * rate["output"]
) / MILLION
extra = 0.0
surcharge = table.get("token_rate_per_million", {}).get(plan, 0.0)
if surcharge and not token_rate_exempt(table, model):
total = sum(usage.values())
extra = total * surcharge / MILLION
return round(base + extra, 6)
Notice what the function refuses to do. It raises KeyError for an unknown model and for a date before the first entry, instead of returning zero. A silent zero is the worst failure a cost tool can have, because it produces a reassuring report that is simply wrong. The token-rate branch counts every token category in the total, which makes the Teams surcharge a slight overestimate. Cursor’s page does not define precisely which tokens count, so the conservative choice protects your budget.
Step 6: Write the Usage Parser
The parser has two functions. last_json scans stdout for the last complete JSON object, which tolerates progress lines, banners and warnings printed before the result. find_usage walks the parsed object and collects every dictionary that carries token fields. If one of them sits under a key containing total, it wins. Otherwise the parser sums the shallowest blocks, which is the right move when a result lists only per-turn usage.
import json
FIELDS = {
"input": {"inputtokens", "prompttokens"},
"output": {"outputtokens", "completiontokens"},
"cache_read": {"cachereadtokens", "cachedreadtokens"},
"cache_write": {"cachewritetokens"},
"reasoning": {"reasoningtokens"},
}
def last_json(text):
"""Return the last top-level JSON object in text, or None."""
dec = json.JSONDecoder()
found = None
i = text.find("{")
while i != -1:
try:
obj, end = dec.raw_decode(text, i)
found = obj
i = text.find("{", end)
except ValueError:
i = text.find("{", i + 1)
return found
def _norm(node):
out = dict.fromkeys(FIELDS, 0)
for key, val in node.items():
if isinstance(val, bool) or not isinstance(val, (int, float)):
continue
flat = key.replace("_", "").replace("-", "").lower()
for name, aliases in FIELDS.items():
if flat in aliases:
out[name] += int(val)
return out
def find_usage(obj):
"""Pick the total usage block, or sum the shallowest per-turn blocks."""
cands = []
def walk(node, path):
if isinstance(node, dict):
norm = _norm(node)
if any(norm.values()):
cands.append((path, norm))
for k, v in node.items():
walk(v, path + (str(k),))
elif isinstance(node, list):
for i, v in enumerate(node):
walk(v, path + (str(i),))
walk(obj, ())
if not cands:
return None
totals = [c for c in cands if any("total" in p.lower() for p in c[0])]
if totals:
return min(totals, key=lambda c: len(c[0]))[1]
top = min(len(c[0]) for c in cands)
shallow = [c[1] for c in cands if len(c[0]) == top]
return {k: sum(s[k] for s in shallow) for k in FIELDS}
This design deliberately avoids hard-coding a path like result["usage"]["total"]. Output formats shift between CLI releases, and a parser that searches by field name survives a layout change that would crash a path-based one. The cost is a small risk of picking the wrong block, which the tests in Step 10 pin down. If no usage block exists at all, the function returns None and the wrapper flags the run instead of recording zeros.
Phase 3: Storage, Wrapper and Fake Agent (Steps 7 to 9) #
Step 7: Create the SQLite Store
One table holds one row per run. Besides the five token counters and the computed cost, each row records the tag, model, plan, exit code and duration, plus a usage_missing flag and an optional raw column. The day column carries the pricing date, so a report grouped by day matches the rate that applied. Group-by names are checked against an allow-list, because the column name goes into the SQL string.
import sqlite3
SCHEMA = """
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL,
day TEXT NOT NULL,
tag TEXT NOT NULL,
model TEXT NOT NULL,
plan TEXT NOT NULL,
exit_code INTEGER NOT NULL,
duration_s REAL NOT NULL,
input INTEGER NOT NULL,
output INTEGER NOT NULL,
cache_read INTEGER NOT NULL,
cache_write INTEGER NOT NULL,
reasoning INTEGER NOT NULL,
cost_usd REAL NOT NULL,
usage_missing INTEGER NOT NULL,
raw TEXT
);
CREATE INDEX IF NOT EXISTS runs_day ON runs(day);
"""
def connect(path):
db = sqlite3.connect(path)
db.row_factory = sqlite3.Row
db.executescript(SCHEMA)
return db
def insert(db, row):
cols = ",".join(row)
marks = ",".join("?" for _ in row)
db.execute(f"INSERT INTO runs ({cols}) VALUES ({marks})", list(row.values()))
db.commit()
def spend(db, since, tag=None):
sql = "SELECT COALESCE(SUM(cost_usd),0) AS usd, COALESCE(SUM(usage_missing),0) AS missing FROM runs WHERE day >= ?"
args = [since]
if tag:
sql += " AND tag = ?"
args.append(tag)
return db.execute(sql, args).fetchone()
def grouped(db, by, since):
allowed = {"model", "day", "tag"}
if by not in allowed:
raise ValueError(f"group by one of {sorted(allowed)}")
sql = (
f"SELECT {by} AS k, COUNT(*) AS runs, SUM(input) AS input, SUM(output) AS output, "
"SUM(cache_read) AS cache_read, SUM(reasoning) AS reasoning, SUM(cost_usd) AS usd "
f"FROM runs WHERE day >= ? GROUP BY {by} ORDER BY usd DESC"
)
return db.execute(sql, [since]).fetchall()
SQLite suits this job well. A single file travels with a CI cache, opens in any viewer and handles thousands of rows without tuning. Teams that outgrow it can export to CSV and load the data into whatever warehouse they already run. If you already ship traces to a metrics backend, the LLM observability tutorial in Python covers the wider habit of logging tokens, cost and latency for any model call.
Step 8: Write the Wrapper That Runs and Records
The wrapper is the heart of the project, and it sits in ledger/__main__.py so you can call it with python3 -m ledger. The run command validates the model against the price table before it launches anything. That order matters. A naive version prices the model after the agent finishes, so a typo in --model burns real tokens and then loses the row to a crash. Fail fast, spend nothing.
After the agent returns, the wrapper parses stdout, prices the usage, stores the row and prints a one-line summary to stderr. It then passes stdout through untouched, so a downstream step can still read the agent’s answer. The exit code of the agent becomes the exit code of the wrapper. The report and gate commands in the same file feed Steps 11 and 12.
import argparse
import datetime as dt
import json
import os
import shlex
import subprocess
import sys
import time
from . import prices, store, usage
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DB = os.environ.get("LEDGER_DB", os.path.join(ROOT, "ledger.db"))
PRICES = os.environ.get("LEDGER_PRICES", os.path.join(ROOT, "prices.json"))
AGENT = os.environ.get("LEDGER_AGENT", "agent")
def today():
return os.environ.get("LEDGER_TODAY") or dt.date.today().isoformat()
def cmd_run(args):
table = prices.load(PRICES)
try:
prices.rate_for(table, args.model, today())
except KeyError as err:
print(f"[ledger] refusing to run: {err}", file=sys.stderr)
return 4
argv = shlex.split(AGENT) + ["-p", args.prompt, "--model", args.model]
argv += shlex.split(args.agent_flags)
started = time.monotonic()
proc = subprocess.run(argv, capture_output=True, text=True, timeout=args.timeout)
elapsed = time.monotonic() - started
result = usage.last_json(proc.stdout)
found = usage.find_usage(result) if result else None
missing = found is None
found = found or dict.fromkeys(usage.FIELDS, 0)
day = today()
usd = prices.cost(table, args.model, day, found, args.plan)
row = {
"ts": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
"day": day, "tag": args.tag, "model": args.model, "plan": args.plan,
"exit_code": proc.returncode, "duration_s": round(elapsed, 2),
**found, "cost_usd": usd, "usage_missing": int(missing),
"raw": proc.stdout if (missing or args.keep_raw) else None,
}
db = store.connect(DB)
store.insert(db, row)
flag = " (NO USAGE BLOCK FOUND)" if missing else ""
print(f"[ledger] {args.tag} {args.model} ${usd:.4f} "
f"in={found['input']} out={found['output']} reasoning={found['reasoning']}{flag}",
file=sys.stderr)
sys.stdout.write(proc.stdout)
return proc.returncode
def cmd_report(args):
since = (dt.date.fromisoformat(today()) - dt.timedelta(days=args.days - 1)).isoformat()
rows = store.grouped(store.connect(DB), args.by, since)
print(f"{args.by:<22}{'runs':>5}{'input':>10}{'output':>9}{'reason':>9}{'usd':>10}")
for r in rows:
print(f"{r['k']:<22}{r['runs']:>5}{r['input']:>10}{r['output']:>9}"
f"{r['reasoning']:>9}{r['usd']:>10.4f}")
print(f"{'TOTAL':<22}{sum(r['runs'] for r in rows):>5}{'':>28}{sum(r['usd'] for r in rows):>10.4f}")
return 0
def cmd_gate(args):
if args.window == "day":
since = today()
else:
since = today()[:8] + "01"
row = store.spend(store.connect(DB), since, args.tag)
usd, missing = row["usd"], row["missing"]
print(f"[gate] {args.window} spend ${usd:.4f} of ${args.budget:.2f} budget, "
f"{missing} run(s) without usage data")
if missing:
print("[gate] FAIL: usage data missing, spend is understated", file=sys.stderr)
return 3
if usd > args.budget:
print("[gate] FAIL: budget exceeded", file=sys.stderr)
return 2
return 0
def main():
p = argparse.ArgumentParser(prog="ledger")
sub = p.add_subparsers(dest="cmd", required=True)
r = sub.add_parser("run")
r.add_argument("--tag", required=True)
r.add_argument("--model", required=True)
r.add_argument("--plan", default="individual", choices=["individual", "teams", "enterprise"])
r.add_argument("--timeout", type=int, default=900)
r.add_argument("--keep-raw", action="store_true")
r.add_argument("--agent-flags", default="--output-format json")
r.add_argument("prompt")
r.set_defaults(fn=cmd_run)
q = sub.add_parser("report")
q.add_argument("--by", default="model", choices=["model", "day", "tag"])
q.add_argument("--days", type=int, default=7)
q.set_defaults(fn=cmd_report)
g = sub.add_parser("gate")
g.add_argument("--budget", type=float, required=True)
g.add_argument("--window", default="day", choices=["day", "month"])
g.add_argument("--tag")
g.set_defaults(fn=cmd_gate)
args = p.parse_args()
sys.exit(args.fn(args))
main()
Three details deserve attention. The binary comes from the LEDGER_AGENT environment variable and defaults to agent, which lets the tests swap in a fake. The extra flags default to --output-format json and come from --agent-flags, so a CLI release that renames the flag needs no code change. The LEDGER_TODAY override lets you test price changes without waiting for the calendar.
Step 9: Add a Fake Agent for Free Testing
Real runs cost money and return different numbers each time, which makes them useless for regression tests. The fake agent below reads the same flags as the real one, prints a progress line and then emits a JSON result with two turns and a total block. It scales token counts with prompt length, so different prompts give different costs. Setting FAKE_NO_USAGE=1 makes it return a result with no usage block, which exercises the missing-data path.
#!/usr/bin/env python3
"""Stands in for the Cursor CLI so the ledger can be tested without spending tokens."""
import json
import os
import sys
args = sys.argv[1:]
prompt = args[args.index("-p") + 1] if "-p" in args else ""
model = args[args.index("--model") + 1] if "--model" in args else "unknown"
scale = max(1, len(prompt) // 10)
if os.environ.get("FAKE_NO_USAGE"):
print(json.dumps({"type": "result", "result": "done"}))
sys.exit(0)
turns = [
{"turn": 1, "usage": {"inputTokens": 1200 * scale, "outputTokens": 300, "cacheReadTokens": 0, "reasoningTokens": 150}},
{"turn": 2, "usage": {"inputTokens": 400 * scale, "outputTokens": 500, "cacheReadTokens": 1200 * scale, "reasoningTokens": 350}},
]
total = {k: sum(t["usage"][k] for t in turns) for k in turns[0]["usage"]}
print("agent: starting " + model, file=sys.stderr)
print("progress: 50%")
print(json.dumps({"type": "result", "result": "ok", "turns": turns, "usage": {"total": total}}))
The fixture mirrors a plausible layout, not the verified Cursor schema. That distinction matters. The fake proves your wrapper handles a total block, per-turn blocks, log noise and a missing block. Only your Step 2 capture proves the real CLI matches. Replace the fake’s JSON with your captured file once you have it, and keep both versions in the test folder.
Phase 4: Tests, Reports and the Budget Gate (Steps 10 to 12) #
Step 10: Lock the Behavior With Unit Tests
Nine tests cover the parts most likely to rot: log-line tolerance in the JSON scan, total-block preference, per-turn summing, missing usage, reasoning-as-output pricing, the December 1 step, the Teams surcharge, the unknown-model error and the included reasoning mode. The price tests use hand-checkable math. One million input tokens at $2 plus 150,000 output-side tokens at $10 equals $3.50, and the test asserts exactly that.
import json
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from ledger import prices, usage # noqa: E402
TABLE = prices.load(pathlib.Path(__file__).resolve().parent.parent / "prices.json")
U = {"input": 1_000_000, "output": 100_000, "cache_read": 0, "cache_write": 0, "reasoning": 50_000}
class UsageTests(unittest.TestCase):
def test_last_json_skips_log_lines(self):
text = 'progress: 50%\n{"a": 1}\nnoise {not json}\n{"b": {"c": 2}}\n'
self.assertEqual(usage.last_json(text), {"b": {"c": 2}})
def test_prefers_total_block(self):
obj = {"turns": [{"usage": {"inputTokens": 5}}], "usage": {"total": {"inputTokens": 9, "reasoningTokens": 4}}}
got = usage.find_usage(obj)
self.assertEqual((got["input"], got["reasoning"]), (9, 4))
def test_sums_per_turn_when_no_total(self):
obj = {"turns": [{"usage": {"inputTokens": 5}}, {"usage": {"inputTokens": 7}}]}
self.assertEqual(usage.find_usage(obj)["input"], 12)
def test_missing_usage_returns_none(self):
self.assertIsNone(usage.find_usage({"result": "ok"}))
class PriceTests(unittest.TestCase):
def test_sonnet_cost_counts_reasoning_as_output(self):
self.assertAlmostEqual(prices.cost(TABLE, "claude-sonnet-5-5", "2026-11-25", U), 3.5)
def test_carbon_price_steps_on_dec_1(self):
nov = prices.cost(TABLE, "gemini-4-carbon", "2026-11-30", U)
dec = prices.cost(TABLE, "gemini-4-carbon", "2026-12-01", U)
self.assertAlmostEqual(dec, nov * 2)
def test_teams_adds_token_rate(self):
base = prices.cost(TABLE, "claude-sonnet-5-5", "2026-11-25", U, "individual")
teams = prices.cost(TABLE, "claude-sonnet-5-5", "2026-11-25", U, "teams")
self.assertAlmostEqual(teams - base, 1_150_000 * 0.25 / 1_000_000)
def test_unknown_model_raises(self):
with self.assertRaises(KeyError):
prices.cost(TABLE, "made-up-model", "2026-11-25", U)
def test_reasoning_mode_included(self):
table = json.loads(json.dumps(TABLE))
table["reasoning_mode"] = "included"
self.assertAlmostEqual(prices.cost(table, "claude-sonnet-5-5", "2026-11-25", U), 3.0)
if __name__ == "__main__":
unittest.main()
python3 -m unittest discover -s tests -v
Expect nine lines ending in ok followed by Ran 9 tests and OK. If the Carbon test fails, check that the second price entry carries a from date of 2026-12-01 and that your edits did not break the date comparison. ISO dates compare correctly as strings, which is why the table uses that format and nothing else.
Step 11: Generate Reports by Model, Tag and Day
The report command groups the last N days by model, tag or day and prints token totals next to dollars. Run it once per grouping when you review a week. Grouping by tag shows which workflow costs the most, and grouping by model shows whether a cheaper model would do the same work. Pair the results with the Cursor model pricing walkthrough when you decide what to switch.
Use fake-agent runs first so you can see the shape of the output without cost. Set the environment, run four jobs with different tags and models, and then ask for the model report. The commands below are the ones that produced the example output in the next section.
export LEDGER_AGENT="python3 tests/fake_agent.py"
python3 -m ledger run --tag docs-sync --model claude-sonnet-5-5 "Update the README changelog section from the last ten commits" >/dev/null
python3 -m ledger run --tag docs-sync --model claude-opus-5-5 "Update the README changelog section from the last ten commits" >/dev/null
python3 -m ledger run --tag pr-review --model gemini-4-carbon --plan teams "Review the diff on this branch for missing tests and unsafe shell calls in scripts" >/dev/null
python3 -m ledger report --by model
python3 -m ledger report --by tag
Step 12: Gate CI on Budget and Missing Data
The gate command sums spend for the current day or month, optionally for one tag, and returns a distinct exit code per failure. Exit 2 means the budget is exceeded. Exit 3 means at least one run had no usage block, so the total is understated and cannot be trusted. Treating missing data as a failure is the design choice that keeps the tool honest. A gate that passes because the parser went blind is worse than no gate.
Put the gate after the agent step in a workflow. The ledger database needs to survive between runs, so cache it or store it as an artifact. Team admins can also switch headless mode off under Team Settings, then Security and automation, so confirm that setting before you debug a job that refuses to start. The YAML below shows the shape. Fill in the authentication and install steps the way your headless setup guide specifies.
name: agent-nightly
on:
schedule:
- cron: "0 5 * * *"
jobs:
docs-sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22.13"
- uses: actions/cache@v4
with:
path: ledger.db
key: ledger-${{ github.run_id }}
restore-keys: ledger-
- name: Run the agent through the ledger
run: python3 -m ledger run --tag docs-sync --model claude-sonnet-5-5 --plan teams "Update CHANGELOG.md from the last ten commits"
- name: Enforce the daily budget
run: python3 -m ledger gate --budget 5 --window day --tag docs-sync
What a Healthy Ledger Looks Like: Output Examples #
The outputs below come from the fake agent, so the token counts are synthetic. The structure and the arithmetic are real. Each run prints one summary line to stderr. The first two lines show the same prompt costing twice as much on Opus 5.5 as on Sonnet 5.5, which matches the 2x gap in their listed rates.
[ledger] docs-sync claude-sonnet-5-5 $0.0466 in=9600 out=800 reasoning=500
[ledger] docs-sync claude-opus-5-5 $0.0932 in=9600 out=800 reasoning=500
[ledger] pr-review gemini-4-carbon $0.0455 in=12800 out=800 reasoning=500
[ledger] pr-review claude-fable-5-2 $0.0000 in=0 out=0 reasoning=0 (NO USAGE BLOCK FOUND)
The fourth line is the one to study. The fake returned a result with no usage block, and the wrapper printed a loud flag instead of pretending the run was free. A $0.0000 with the flag means missing data. A $0.0000 without it would mean a genuinely empty run, which almost never happens. Now the grouped reports:
model runs input output reason usd
claude-opus-5-5 1 9600 800 500 0.0932
claude-sonnet-5-5 1 9600 800 500 0.0466
gemini-4-carbon 1 12800 800 500 0.0455
claude-fable-5-2 1 0 0 0 0.0000
TOTAL 4 0.1853
tag runs input output reason usd
docs-sync 2 19200 1600 1000 0.1398
pr-review 2 12800 800 500 0.0455
TOTAL 4 0.1853
Now the gate. With the missing-data run still in the database, the gate refuses to pass at all. On a clean database, the same $5 budget passes with exit 0, and a $0.03 budget fails with exit 2.
[gate] day spend $0.1853 of $5.00 budget, 1 run(s) without usage data
[gate] FAIL: usage data missing, spend is understated
exit=3
[gate] day spend $0.0466 of $5.00 budget, 0 run(s) without usage data
exit=0
[gate] day spend $0.0466 of $0.03 budget, 0 run(s) without usage data
[gate] FAIL: budget exceeded
exit=2
The price step is easy to verify too. Running the same Carbon prompt with LEDGER_TODAY=2026-12-01 should cost noticeably more than on November 25, with identical tokens. The rate doubles from $2 to $4 on input and from $10 to $20 on output, and the Teams token rate stays the same, so the total lands just under twice the earlier figure. Your real CLI output will show different counts, but the same relationships should hold.
Common Pitfalls That Skew Cursor Cost Numbers #
Pitfall 1: Double-counting reasoning tokens. If the CLI’s output tokens already include reasoning, adding reasoningTokens on top inflates cost. Calibrate once per model by running a reasoning-heavy prompt, comparing the output count with the reasoning count, and switching reasoning_mode to included if the first number already contains the second.
Pitfall 2: Running on automatic model routing. The CLI reportedly defaulted new installs to Auto routing from July 2026. Cursor Router, which sits behind Auto, is available only on Teams and Enterprise. Its Cost mode draws from the Cursor-model request pool, while Balance and Intelligence bill at the list price of whichever model the router picks. A ledger cannot price a run when it does not know the model, so pass --model explicitly on every scripted call.
Pitfall 3: Trusting the fixture over reality. The fake agent proves your plumbing, not the Cursor schema. Teams that skip Step 2 ship a parser that quietly records zeros. The missing-usage flag catches that case, but only if you read the gate output.
Pitfall 4: Forgetting hidden prompt overhead. Cursor’s notes say prompt hooks configured by team administrators now run in the CLI with their own prompt and model. Those hooks add tokens your script never wrote. If a job costs more than its prompt suggests, compare a run inside the team workspace with one outside it.
Pitfall 5: Treating list-price equivalents as invoices. Pool usage is not billed per token. The ledger’s dollar figure is a yardstick for comparing work, and your plan’s real bill depends on pool size and prepaid credit. Report both numbers side by side, and do not tell a manager the pool cost money it did not. The seat audit for Cursor and Copilot covers the per-developer side of that conversation.
Pitfall 6: Hard-coding prices without dates. Gemini 4 Carbon’s introductory rates end on November 30, 2026. A flat price table would keep charging the old rate to December jobs and under-report them by half. Date every entry, and add a calendar reminder for the next scheduled change.
Pitfall 7: Storing raw output carelessly. The wrapper keeps stdout in the raw column when a run lacks usage data, and when you pass --keep-raw. That text can contain source code, file paths and secrets the agent read. Treat the database like a log that may hold credentials, keep it out of version control and never upload it as a public CI artifact.
Troubleshooting: 10 Problems and Fixes #
| Symptom | Likely cause | Fix |
|---|---|---|
| agent: command not found | CLI not on PATH, or only the older alias is installed | Open a new shell, then try cursor-agent, and set LEDGER_AGENT to whichever name works |
| Headless run hangs and never prints | The agent waits on a workspace-trust prompt | Run inside a trusted folder, and check the CLI changelog for the flag that trusts the workspace in non-interactive mode |
| Gate exits 3 on every run | The parser cannot find a usage block in your output | Rerun with –keep-raw, open the raw column and add the missing field name to the alias table |
| Rows show tokens but cost is $0.0000 | The model key maps to a zero-priced entry or the rates are missing | Check prices.json for the model, and confirm no rate is set to 0 |
| Ledger refuses to run with exit 4 | The string in –model does not match any key in prices.json | Copy the exact ID from agent models and add it to the price table |
| Report shows the wrong day’s rate | LEDGER_TODAY still set from an earlier test session | Run unset LEDGER_TODAY and rerun the report |
| Spend resets every CI run | The database file is not restored between jobs | Cache ledger.db, or store it as an artifact and download it at the start |
| Teams runs cost more than local runs | The Cursor Token Rate applies on top of model pricing | Pass –plan teams so the calculator adds the $0.25 per million surcharge |
| database is locked during parallel jobs | Several processes write one SQLite file at once | Give each job its own database file and merge nightly, or enable WAL mode |
| Job refuses to start for team members only | An admin disabled headless mode | Ask an admin to check Team Settings under Security and automation |
| Totals differ from the dashboard | Cache fallback pricing, reasoning mode or settlement delay | Calibrate with one run, as described in the advanced tips below |
Work through the table from the top. The first three rows account for most first-day failures, and they all share a cause: the wrapper cannot see what the agent printed. When in doubt, run the agent command by hand with the same flags and read stdout yourself. A ledger can only be as accurate as the text it receives.
Advanced Tips: Calibration, Parallel Jobs and Team Reporting #
Calibrate against a trusted number. Cursor’s Agent SDK exposes agent.getUsage() in TypeScript and agent.get_usage() in Python. For cloud agents these calls return token usage, billed cost and per-run breakdowns, and the server-derived cost settles shortly after a run. Run one identical task through the SDK and through the ledger, then compare. A gap under a few percent means your price table is sound. A larger gap points to cache pricing or reasoning mode.
Run an A/B model harness. Loop one prompt over every model in your price table, tag each run with the model name and read the report. You get a measured cost per task instead of a guess from the rate card. Add a pass/fail check on the output, such as running the test suite, and you can compute cost per successful run, which is the only number that matters when a cheap model fails twice as often.
Add a residency multiplier. Cursor’s pricing page lists a 10% uplift on model pricing for regional data residency. If your team opts in, add a residency_uplift key to prices.json and multiply the base cost by 1.10 in the calculator. Keep it in config, not code, so the next policy change is a one-line diff.
Turn on WAL mode. When several jobs on one machine write the same file, run PRAGMA journal_mode=WAL once after connecting and set a busy timeout. That removes most lock errors without changing the schema. For jobs on separate machines, write one file each and merge them with a nightly ATTACH DATABASE script.
Join cost to outcomes. Add a commit or pr column and fill it from the CI environment. A query that divides spend by merged pull requests tells you what an agent-written change really costs. Teams that publish this number weekly tend to find one or two expensive tags that deserve a cheaper model or a tighter prompt.
Watch the calendar. Cursor’s model list and plan names are moving quickly. The pricing page you read this morning can change by Friday. Review prices.json on a schedule, and keep the as_of field honest so reviewers can see how stale it is.
The Complete Working Project #
The finished tree has seven files plus the database that appears on first run. The whole project fits in one repository and runs on Python’s standard library alone.
cursor-ledger/
prices.json dated per-model rates, reasoning mode, token rate
ledger.db created on first run (git-ignored)
ledger/
__init__.py
__main__.py run, report and gate commands
prices.py rate lookup and cost math
store.py SQLite schema, inserts, group-by queries
usage.py JSON scan and usage-block finder
tests/
fake_agent.py stand-in CLI for free tests
test_ledger.py nine unit tests
Use the ledger in a daily routine. Run every scripted agent call through python3 -m ledger run with a tag. Review report --by tag weekly. Let gate guard each pipeline. Swap the fake agent for the real CLI once Step 2 confirms the output shape. Browse more build guides in the coding and dev tools section if you want to extend the project into a full agent-ops toolkit.
Frequently Asked Questions #
How much does Cursor cost in November 2026?
Cursor lists Free, Plus, Premium, Super, Ultra, Teams and Enterprise plans. Annual billing runs $80 for Plus, $300 for Premium, $1,000 for Super and $2,000 for Ultra, excluding tax, and Teams seats cost $30, $100 or $200 each month. Enterprise uses custom pricing. Third-party models bill separately at API list price.
Does the Cursor CLI count against my plan usage?
According to Cursor’s pricing documentation, paid plans share one usage pool across the editor agent, the CLI and Cloud Agents. Heavy scripted runs therefore reduce what you can use in the editor. A ledger shows which jobs drain the pool fastest.
What is reasoningTokens in Cursor headless output?
It is a count of reasoning tokens that headless results began reporting in per-turn and total usage in November 2026 when a model uses reasoning. Scripts can read it to track fuller token consumption. Whether it overlaps with output tokens varies, so calibrate before you price it.
Can I run the Cursor CLI without a human in the loop?
Yes. Print mode, set with -p or --print, runs the agent non-interactively for scripts and CI. Team admins can disable headless mode in their settings, so confirm that switch before debugging a job that will not start.
Why does my ledger total differ from the Cursor dashboard?
Three causes dominate. Models without listed cache prices fall back to the input rate, reasoning tokens may or may not overlap with output tokens, and server-side cost can take a short while to settle after a run. Compare one identical task through the SDK usage call to find which cause applies.
Will Gemini 4 Carbon cost more in December?
Yes. Cursor’s model page lists introductory rates of $2 input, $0.10 cache read and $10 output per million tokens through November 30, 2026. From December 1 the documented rates become $4, $0.20 and $20. The dated entries in prices.json apply the change automatically.
Is the Cursor Token Rate charged on individual plans?
No. Cursor’s pricing page says the $0.25 per million token rate applies on Teams and Enterprise plans, including bring-your-own-key usage, and that individual plans do not pay it. Models whose cache-read price stays strictly below $0.10 per million tokens at every tier are exempt.
Do I need the real CLI to finish the tutorial?
No. The fake agent covers every step except Step 2, and the unit tests need no network. Use the real CLI once to capture a genuine result, then confirm the parser reads it.