@aispendbook/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,170 @@
1
+ /**
2
+ * API-equivalent cost at list prices, offline. Prices come from prices.json, exported from the AI
3
+ * Spendbook seed catalog (scripts/export_cli_prices.py). Money is integer USD micros throughout.
4
+ *
5
+ * A model with no list price is reported as unpriced, never guessed. Model names are matched the way
6
+ * the AI Spendbook pricing engine matches them (services/api/app/intelligence/pricing.py): routing
7
+ * prefixes and date or version suffixes are removed, and the longest catalog id that the name starts
8
+ * with is used unless the rest of the name makes it a different model.
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ const PREFIXES = [
12
+ "bedrock/", "vertex_ai/", "azure/", "gemini/", "publishers/anthropic/models/", "publishers/google/models/",
13
+ "us.anthropic.", "eu.anthropic.", "apac.anthropic.", "jp.anthropic.", "au.anthropic.", "ca.anthropic.",
14
+ "us-gov.anthropic.", "global.anthropic.", "anthropic.", "anthropic/", "openai/", "models/", "google/",
15
+ ];
16
+ const DATE_SUFFIX = /(-\d{8}|-\d{4}-\d{2}-\d{2}|@\d{8}|-latest|-preview-\d{2}-\d{2})$/;
17
+ const VERSION_SUFFIX = /(-v\d+(:\d+)?|:\d+)$/;
18
+ const MINOR_VERSION = /^-\d{1,2}(-|$)/;
19
+ const DISTINCT_MODEL_WORDS = new Set([
20
+ "realtime", "audio", "transcribe", "tts", "search", "diarize", "translate", "whisper", "speech", "live",
21
+ "embedding", "embed", "image", "video", "research", "codex", "mini", "nano", "pro",
22
+ ]);
23
+ export const MICROS_PER_MTOK = 1000000n;
24
+ export function canonModel(raw) {
25
+ let s = raw.trim().toLowerCase();
26
+ let changed = true;
27
+ while (changed) {
28
+ changed = false;
29
+ for (const p of PREFIXES) {
30
+ if (s.startsWith(p) && s.length > p.length) {
31
+ s = s.slice(p.length);
32
+ changed = true;
33
+ }
34
+ }
35
+ }
36
+ return s;
37
+ }
38
+ /** Divide by 10^6 with round-half-even, as the API's round_micros does. */
39
+ export function divRoundHalfEven(n, d) {
40
+ const q = n / d;
41
+ const r = n % d;
42
+ const twice = r * 2n;
43
+ if (twice > d || (twice === d && q % 2n !== 0n))
44
+ return q + 1n;
45
+ return q;
46
+ }
47
+ export class CatalogPriceBook {
48
+ alias = new Map(); // "provider\u0000name" -> model_id
49
+ sheets = new Map(); // "provider\u0000model_id" -> rows
50
+ constructor(file) {
51
+ for (const row of file.prices) {
52
+ const k = `${row.provider}\u0000${row.model_id}`;
53
+ this.sheets.set(k, [...(this.sheets.get(k) ?? []), row]);
54
+ this.alias.set(k, row.model_id);
55
+ for (const a of row.aliases)
56
+ this.alias.set(`${row.provider}\u0000${canonModel(a)}`, row.model_id);
57
+ }
58
+ }
59
+ resolveModel(provider, model) {
60
+ const p = provider.toLowerCase();
61
+ let s = canonModel(model);
62
+ const hit = (name) => this.alias.get(`${p}\u0000${name}`);
63
+ const exact = hit(s);
64
+ if (exact)
65
+ return exact;
66
+ if (s.startsWith("claude-") && s.includes("."))
67
+ s = s.replaceAll(".", "-");
68
+ const unversioned = s.replace(VERSION_SUFFIX, "");
69
+ const stripped = unversioned.replace(DATE_SUFFIX, "");
70
+ for (const c of [s, unversioned, stripped]) {
71
+ const found = hit(c);
72
+ if (found)
73
+ return found;
74
+ }
75
+ let best = null;
76
+ let bestKey = "";
77
+ for (const [k, modelId] of this.alias) {
78
+ const [prov, key] = k.split("\u0000");
79
+ if (prov !== p || !stripped.startsWith(key))
80
+ continue;
81
+ const rest = stripped.slice(key.length);
82
+ if (rest.length > 0 && !"-@:_".includes(rest[0]))
83
+ continue;
84
+ if (MINOR_VERSION.test(rest))
85
+ continue; // claude-sonnet-4-7 is not a snapshot of claude-sonnet-4
86
+ if (rest.split(/[-@:_.]/).some((w) => DISTINCT_MODEL_WORDS.has(w)))
87
+ continue;
88
+ if (key.length > bestKey.length) {
89
+ best = modelId;
90
+ bestKey = key;
91
+ }
92
+ }
93
+ return best;
94
+ }
95
+ sheetFor(provider, modelId, day) {
96
+ const rows = this.sheets.get(`${provider.toLowerCase()}\u0000${modelId}`) ?? [];
97
+ return rows.find((r) => r.effective_from <= day && (r.effective_to === null || day < r.effective_to)) ?? null;
98
+ }
99
+ sheet(provider, model, day) {
100
+ const modelId = this.resolveModel(provider, model);
101
+ return modelId ? this.sheetFor(provider, modelId, day) : null;
102
+ }
103
+ cost(e) {
104
+ const modelId = this.resolveModel(e.provider, e.model);
105
+ if (!modelId)
106
+ return { costMicros: null, modelId: null, partial: false, notes: [`${e.model} has no list price`] };
107
+ const day = e.occurredAt.toISOString().slice(0, 10);
108
+ const sheet = this.sheetFor(e.provider, modelId, day);
109
+ if (!sheet)
110
+ return { costMicros: null, modelId, partial: false, notes: [`no list price for ${modelId} on ${day}`] };
111
+ const notes = [];
112
+ let partial = false;
113
+ let inp = sheet.input_per_mtok;
114
+ let out = sheet.output_per_mtok;
115
+ let cread = sheet.cache_read_per_mtok;
116
+ const prompt = e.inputTokens + e.cacheReadTokens + e.cacheWriteTokens;
117
+ if (sheet.long_context_threshold_tokens && prompt > sheet.long_context_threshold_tokens) {
118
+ inp = sheet.long_context_input_per_mtok ?? inp;
119
+ out = sheet.long_context_output_per_mtok ?? out;
120
+ cread = sheet.long_context_cache_read_per_mtok ?? cread;
121
+ notes.push("long-context rates");
122
+ }
123
+ let total = BigInt(e.inputTokens) * BigInt(inp) + BigInt(e.outputTokens) * BigInt(out);
124
+ if (e.cacheReadTokens) {
125
+ if (cread === null) {
126
+ partial = true;
127
+ notes.push("cache reads have no list price");
128
+ }
129
+ else
130
+ total += BigInt(e.cacheReadTokens) * BigInt(cread);
131
+ }
132
+ const w1h = Math.min(e.cacheWrite1hTokens, e.cacheWriteTokens);
133
+ const w5m = e.cacheWriteTokens - w1h;
134
+ if (w5m) {
135
+ if (sheet.cache_write_5m_per_mtok === null) {
136
+ partial = true;
137
+ notes.push("cache writes have no list price");
138
+ }
139
+ else
140
+ total += BigInt(w5m) * BigInt(sheet.cache_write_5m_per_mtok);
141
+ }
142
+ if (w1h) {
143
+ const rate = sheet.cache_write_1h_per_mtok ?? sheet.cache_write_5m_per_mtok;
144
+ if (rate === null) {
145
+ partial = true;
146
+ notes.push("1-hour cache writes have no list price");
147
+ }
148
+ else
149
+ total += BigInt(w1h) * BigInt(rate);
150
+ }
151
+ if (e.standardRateNote) {
152
+ partial = true;
153
+ notes.push(`${e.standardRateNote} priced at the standard rate`);
154
+ }
155
+ return {
156
+ costMicros: Number(divRoundHalfEven(total, MICROS_PER_MTOK)), modelId, partial, notes,
157
+ source: { url: sheet.source_url, observedAt: sheet.observed_at },
158
+ };
159
+ }
160
+ }
161
+ export function loadPriceFile(url = new URL("./prices.json", import.meta.url)) {
162
+ return JSON.parse(readFileSync(url, "utf8"));
163
+ }
164
+ export function formatUsd(micros) {
165
+ if (micros > 0 && micros < 10_000)
166
+ return "<$0.01";
167
+ const cents = Math.round(micros / 10_000);
168
+ const dollars = Math.floor(cents / 100);
169
+ return `$${dollars.toLocaleString("en-US")}.${String(cents % 100).padStart(2, "0")}`;
170
+ }
package/dist/range.js ADDED
@@ -0,0 +1,45 @@
1
+ /** Date ranges from flags: "7d" (today and the 6 days before it) or "YYYY-MM-DD", in local time. */
2
+ const DAYS = /^(\d{1,4})d$/;
3
+ const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
4
+ function startOfLocalDay(d) {
5
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate());
6
+ }
7
+ /** Start of the local day a flag names. Throws a plain message on bad input. */
8
+ export function parseDay(value, now, flag) {
9
+ const v = value.trim();
10
+ const days = v.match(DAYS);
11
+ if (days) {
12
+ const n = Number(days[1]);
13
+ if (n < 1)
14
+ throw new Error(`${flag} must be at least 1d`);
15
+ const d = startOfLocalDay(now);
16
+ d.setDate(d.getDate() - (n - 1));
17
+ return d;
18
+ }
19
+ const iso = v.match(ISO_DAY);
20
+ if (iso) {
21
+ const d = new Date(Number(iso[1]), Number(iso[2]) - 1, Number(iso[3]));
22
+ if (d.getMonth() === Number(iso[2]) - 1 && d.getDate() === Number(iso[3]))
23
+ return d;
24
+ }
25
+ throw new Error(`${flag} must look like 7d or 2026-11-01, got "${value}"`);
26
+ }
27
+ /** `until` names the last day included, so the range ends at the start of the next day. */
28
+ export function parseRange(since, until, now) {
29
+ const s = parseDay(since, now, "--since");
30
+ let u = null;
31
+ if (until) {
32
+ u = parseDay(until, now, "--until");
33
+ u.setDate(u.getDate() + 1);
34
+ if (u <= s)
35
+ throw new Error("--until must not be before --since");
36
+ }
37
+ return { since: s, until: u };
38
+ }
39
+ export function inRange(d, r) {
40
+ return d >= r.since && (r.until === null || d < r.until);
41
+ }
42
+ export function localDay(d) {
43
+ const p = (n) => String(n).padStart(2, "0");
44
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
45
+ }
package/dist/report.js ADDED
@@ -0,0 +1,112 @@
1
+ /** Reading every selected source for a date range, and the totals tables of `report` and the MCP tool. */
2
+ import { formatUsd } from "./pricing.js";
3
+ import { inRange, localDay } from "./range.js";
4
+ export const GROUPINGS = ["day", "project", "model", "tool"];
5
+ export const PRICE_BASIS = "API-equivalent cost: an estimate at public list prices per token, not a bill. Plans with a flat fee " +
6
+ "(such as Claude Pro or Max, or ChatGPT plans that include Codex) are not billed per token.";
7
+ export async function collectUsage(sources, range) {
8
+ const events = [];
9
+ const stats = {};
10
+ const notes = [];
11
+ for (const s of sources) {
12
+ const r = await s.read({ since: range.since });
13
+ stats[s.id] = r.stats;
14
+ notes.push(...r.notes);
15
+ for (const e of r.events)
16
+ if (inRange(e.occurredAt, range))
17
+ events.push(e);
18
+ }
19
+ events.sort((a, b) => a.occurredAt.getTime() - b.occurredAt.getTime());
20
+ return { events, sources: stats, notes };
21
+ }
22
+ function emptyRow(key) {
23
+ return {
24
+ key, requests: 0, inputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, outputTokens: 0,
25
+ totalTokens: 0, costMicros: 0, unpricedRequests: 0, partialRequests: 0,
26
+ };
27
+ }
28
+ function keyOf(e, by) {
29
+ switch (by) {
30
+ case "day":
31
+ return localDay(e.occurredAt);
32
+ case "project":
33
+ return e.project;
34
+ case "model":
35
+ return e.model;
36
+ case "tool":
37
+ return e.tool;
38
+ }
39
+ }
40
+ export function buildReport(usage, prices, by, range) {
41
+ const rows = new Map();
42
+ const totals = emptyRow("total");
43
+ const unpriced = new Set();
44
+ for (const e of usage.events) {
45
+ const key = keyOf(e, by);
46
+ const row = rows.get(key) ?? emptyRow(key);
47
+ rows.set(key, row);
48
+ const cost = prices.cost(e);
49
+ if (cost.costMicros === null)
50
+ unpriced.add(`${e.provider}/${e.model}`);
51
+ for (const r of [row, totals]) {
52
+ r.requests++;
53
+ r.inputTokens += e.inputTokens;
54
+ r.cacheWriteTokens += e.cacheWriteTokens;
55
+ r.cacheReadTokens += e.cacheReadTokens;
56
+ r.outputTokens += e.outputTokens;
57
+ r.totalTokens += e.inputTokens + e.cacheWriteTokens + e.cacheReadTokens + e.outputTokens;
58
+ if (cost.costMicros === null)
59
+ r.unpricedRequests++;
60
+ else
61
+ r.costMicros += cost.costMicros;
62
+ if (cost.partial)
63
+ r.partialRequests++;
64
+ }
65
+ }
66
+ const sorted = [...rows.values()].sort((a, b) => by === "day" ? a.key.localeCompare(b.key) : b.costMicros - a.costMicros || b.totalTokens - a.totalTokens);
67
+ const lastDay = range.until ? new Date(range.until.getTime() - 1) : null;
68
+ return {
69
+ by, since: localDay(range.since), until: lastDay ? localDay(lastDay) : null, basis: PRICE_BASIS,
70
+ rows: sorted, totals, unpricedModels: [...unpriced].sort(), sources: usage.sources, notes: usage.notes,
71
+ };
72
+ }
73
+ const n = (v) => v.toLocaleString("en-US");
74
+ export function formatTable(report) {
75
+ const head = [report.by, "requests", "input", "cache write", "cache read", "output", "total tokens", "cost (list)"];
76
+ const line = (r) => [
77
+ r.key, n(r.requests), n(r.inputTokens), n(r.cacheWriteTokens), n(r.cacheReadTokens), n(r.outputTokens),
78
+ n(r.totalTokens),
79
+ r.unpricedRequests === r.requests ? "unpriced *" : formatUsd(r.costMicros) + (r.unpricedRequests ? " *" : ""),
80
+ ];
81
+ const body = [head, ...report.rows.map(line), line(report.totals)];
82
+ const widths = head.map((_, i) => Math.max(...body.map((cells) => cells[i].length)));
83
+ const fmt = (cells) => cells.map((c, i) => (i === 0 ? c.padEnd(widths[i]) : c.padStart(widths[i]))).join(" ");
84
+ const rule = widths.map((w) => "-".repeat(w)).join(" ");
85
+ const out = [
86
+ `AI coding tool usage, ${report.since} to ${report.until ?? "now"}, by ${report.by}`,
87
+ "",
88
+ fmt(head),
89
+ rule,
90
+ ...report.rows.map((r) => fmt(line(r))),
91
+ rule,
92
+ fmt(line(report.totals)),
93
+ "",
94
+ totalsLine(report),
95
+ `Input is uncached input. ${report.basis}`,
96
+ ];
97
+ if (report.totals.unpricedRequests) {
98
+ out.push(`* ${n(report.totals.unpricedRequests)} request(s) have no list price and are not in the cost: ${report.unpricedModels.join(", ")}`);
99
+ }
100
+ if (report.totals.partialRequests) {
101
+ out.push(`${n(report.totals.partialRequests)} request(s) used a mode or token type without its own list price; the standard rate was used or those tokens were left out.`);
102
+ }
103
+ out.push(...report.notes);
104
+ return out.join("\n");
105
+ }
106
+ export function totalsLine(report) {
107
+ const t = report.totals;
108
+ return `Total: ${n(t.requests)} requests, ${n(t.totalTokens)} tokens, ${formatUsd(t.costMicros)} API-equivalent cost at list prices (estimate).`;
109
+ }
110
+ export function filterTools(sources, tools) {
111
+ return tools ? sources.filter((s) => tools.includes(s.id)) : sources;
112
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The savings skill installer and the local record that report --compare splits on: when the skill
3
+ * was installed (and removed), and named markers the user sets, like git tags for usage.
4
+ * Everything stays in the state directory (~/.aispendbook/savings.json); nothing is uploaded.
5
+ */
6
+ import { basename, join, relative } from "node:path";
7
+ import { DEFAULTS } from "./config.js";
8
+ export class FileSavingsState {
9
+ fs;
10
+ path;
11
+ constructor(fs, stateDir) {
12
+ this.fs = fs;
13
+ this.path = join(stateDir, DEFAULTS.savingsFileName);
14
+ }
15
+ async load() {
16
+ try {
17
+ const s = JSON.parse(await this.fs.readText(this.path));
18
+ const skill = s.skill ?? { installedAt: null, uninstalledAt: null, path: null };
19
+ return {
20
+ skill: { installedAt: skill.installedAt ?? null, uninstalledAt: skill.uninstalledAt ?? null, path: skill.path ?? null },
21
+ markers: s.markers && typeof s.markers === "object" ? s.markers : {},
22
+ };
23
+ }
24
+ catch {
25
+ return { skill: { installedAt: null, uninstalledAt: null, path: null }, markers: {} };
26
+ }
27
+ }
28
+ async save(state) {
29
+ await this.fs.writeText(this.path, `${JSON.stringify(state, null, 2)}\n`);
30
+ }
31
+ }
32
+ /**
33
+ * Copies the skill folder into <skills dir>/<skill name>/ and records the first install time. A
34
+ * reinstall over a live install refreshes the files and keeps the original time, so the comparison
35
+ * split does not move; an install after an uninstall starts a new period.
36
+ */
37
+ export class FileSkillInstaller {
38
+ fs;
39
+ sourceDir;
40
+ skillsDir;
41
+ state;
42
+ clock;
43
+ constructor(fs, sourceDir, skillsDir, state, clock) {
44
+ this.fs = fs;
45
+ this.sourceDir = sourceDir;
46
+ this.skillsDir = skillsDir;
47
+ this.state = state;
48
+ this.clock = clock;
49
+ }
50
+ target() {
51
+ return join(this.skillsDir, DEFAULTS.skillName);
52
+ }
53
+ async install() {
54
+ const files = await this.fs.listFiles(this.sourceDir, () => true);
55
+ if (!files.some((f) => f.path.endsWith("SKILL.md")))
56
+ throw new Error(`No SKILL.md in ${this.sourceDir}`);
57
+ const target = this.target();
58
+ for (const f of files)
59
+ await this.fs.writeText(join(target, relative(this.sourceDir, f.path)), await this.fs.readText(f.path));
60
+ const s = await this.state.load();
61
+ const live = s.skill.installedAt !== null && s.skill.uninstalledAt === null;
62
+ if (!live)
63
+ s.skill = { installedAt: this.clock.now().toISOString(), uninstalledAt: null, path: target };
64
+ else
65
+ s.skill.path = target;
66
+ await this.state.save(s);
67
+ return { path: target, files: files.length, installedAt: s.skill.installedAt, alreadyInstalled: live };
68
+ }
69
+ async uninstall() {
70
+ const s = await this.state.load();
71
+ const saved = s.skill.path;
72
+ // Only ever delete a folder with the skill's own name, whatever the state file says.
73
+ const target = saved && basename(saved) === DEFAULTS.skillName ? saved : this.target();
74
+ const removed = await this.fs.isDirectory(target);
75
+ if (removed)
76
+ await this.fs.removeDir(target);
77
+ const at = this.clock.now().toISOString();
78
+ if (s.skill.installedAt && !s.skill.uninstalledAt)
79
+ s.skill.uninstalledAt = at;
80
+ await this.state.save(s);
81
+ return { path: target, removed, uninstalledAt: at };
82
+ }
83
+ }
@@ -0,0 +1,76 @@
1
+ ---
2
+ name: aispendbook-savings
3
+ description: AI Spendbook savings. Working habits that cut the tokens a coding session sends and generates without lowering the quality of the result. Use for any coding, debugging, refactoring, review or repository exploration task in Claude Code.
4
+ license: MIT
5
+ metadata:
6
+ version: "1.0.0"
7
+ homepage: https://aispendbook.com/docs/savings-skill
8
+ ---
9
+
10
+ # AI Spendbook savings
11
+
12
+ Every request in a session resends the whole conversation, and output tokens cost more than input
13
+ tokens on current models. These habits keep both small. Quality comes first: when a rule would make
14
+ the answer worse, or the user asks for more, drop the rule for that step.
15
+
16
+ ## Answers
17
+
18
+ - Answer briefly by default: the result, the decision or the change, then stop. Give detail,
19
+ alternatives and background when the user asks for them or when a risk needs explaining.
20
+ - Do not restate the question, the plan or what was just done. One line of status is enough.
21
+ - Do not repeat the plan or the task list after each step. Update it only when it changes.
22
+ - Quote code only when the exact text matters. Point to `path:line` instead of pasting a file back.
23
+
24
+ ## Reading
25
+
26
+ - Do not re-read a file that is already in the conversation and has not changed since. Re-read only
27
+ after an edit by someone else, a tool that rewrites it, or when the earlier read was a partial range.
28
+ - Read the lines you need: search first (grep or a symbol lookup), then read a range around the hit.
29
+ Read a whole file when it is short or when the task needs all of it.
30
+ - Prefer a language server's go-to-definition or find-references, when available, over reading
31
+ several candidate files.
32
+
33
+ ## Tool output
34
+
35
+ - Limit long output at the source: `| tail -n 100`, `| head`, `grep`, `--quiet`, `-q`, a test
36
+ filter, `wc -l` before printing a big file.
37
+ - When a command still prints a lot, write a short summary of what matters (failing test names,
38
+ the error and its location, counts) and reason from that summary, not from the whole output again.
39
+ - Do not run the same command again to look at output you already have.
40
+
41
+ ## Delegation and models
42
+
43
+ - Send broad searches ("where is X used across the repo", "which files handle Y") to a subagent
44
+ with a narrow brief: the question, where to look, what is already ruled out, and the shape of the
45
+ answer wanted. Its file reads stay in its own context; only the answer comes back.
46
+ - Do a lookup yourself when you already know the file; a subagent costs a fresh context.
47
+ - For mechanical subtasks (renames, formatting, collecting file lists, summarising logs) use a
48
+ smaller, faster model where the host allows it, for example `model: haiku` in a subagent
49
+ definition. Keep the larger model for design, debugging and review.
50
+
51
+ ## Caching
52
+
53
+ - Keep stable content first and unchanged: project instructions, tool lists and long reference
54
+ text belong at the start and should not be edited mid-session. Prompt caching only reuses an
55
+ identical prefix; a change near the start makes everything after it uncached again.
56
+ - Do not switch models in the middle of a task without a reason: each model has its own cache.
57
+ - When the user is going to step away for longer than the cache lifetime, finish or summarise the
58
+ current step first; the first request after a long pause reprocesses the whole context.
59
+
60
+ ## Writing code
61
+
62
+ - Change only what the task needs. Use targeted edits; do not rewrite or re-print a whole file to
63
+ change a few lines.
64
+ - Do not regenerate code that has not changed, and do not paste the full new version of a file
65
+ after editing it.
66
+ - Run the narrowest check that proves the change (one test file, one target) before the full suite.
67
+
68
+ ## Planning
69
+
70
+ - Plan once for a multi-step task, then work through it. Ask one clarifying question when the
71
+ request is ambiguous instead of exploring every reading of it.
72
+ - Stop as soon as the task is done and verified.
73
+
74
+ For the reasons behind each rule and the sources, see [reference.md](reference.md). To see whether
75
+ these habits change your own usage, use `aispendbook report --compare` (see reference.md):
76
+ it reports observed differences in your logs, not promised savings.
@@ -0,0 +1,47 @@
1
+ # Why these rules, and how to check them
2
+
3
+ Each rule rests on how requests are billed, not on a promised saving. This skill makes no claim
4
+ about how much it saves you. Measure it on your own logs (below).
5
+
6
+ ## How a coding session is billed
7
+
8
+ - Claude Code sends the full conversation with every request, and each tool call adds another
9
+ request that carries the tool results. Source: "Why usage climbs in a long session",
10
+ https://code.claude.com/docs/en/costs (read 2026-12-01).
11
+ - Output tokens are priced above input tokens: on the Anthropic price page, output is five times
12
+ the input price for current Claude models. Thinking tokens are billed as output.
13
+ Source: https://platform.claude.com/docs/en/about-claude/pricing (read 2026-11-08) and
14
+ https://code.claude.com/docs/en/costs (read 2026-12-01).
15
+ - Prompt caching reuses only an identical prefix, built in the order tools, system, messages. A
16
+ change at one level makes that level and everything after it uncached. The default cache lifetime
17
+ is 5 minutes, refreshed on each use; a 1-hour lifetime is available. Caches are per model.
18
+ Source: https://platform.claude.com/docs/en/build-with-claude/prompt-caching (read 2026-12-01).
19
+
20
+ ## Rule by rule
21
+
22
+ | Rule | Mechanism |
23
+ | --- | --- |
24
+ | Brief answers, no repeated plan | Fewer output tokens, which are the higher-priced kind, and a shorter conversation for every later request to resend. |
25
+ | No re-reading files already in context | A second read adds the same tokens to the conversation again, and every later request resends them. |
26
+ | Targeted line ranges | Only the lines read enter the conversation. |
27
+ | Summarise long tool output | The summary is what later reasoning repeats, not the raw output. Claude Code's own guidance shows trimming test output with a hook. |
28
+ | Subagents for broad searches | "the verbose output stays in the subagent's context while only a summary returns to your main conversation" (Claude Code costs page). The subagent's own requests still count. |
29
+ | Smaller models for mechanical subtasks | The costs page suggests `model: haiku` for simple subagent tasks; smaller models have lower per-token prices. |
30
+ | Stable instructions first | Keeps the cached prefix identical, so it is read from cache instead of reprocessed. |
31
+ | No regenerated code | Unchanged code re-printed is output tokens with no new result. |
32
+
33
+ ## Measure it on your own usage
34
+
35
+ ```sh
36
+ npx -y @aispendbook/cli skill install # copies this skill and records the install time
37
+ # ... work as usual for a few weeks ...
38
+ npx -y @aispendbook/cli report --compare # sessions before and after the install
39
+ npx -y @aispendbook/cli cache-audit # repeated prompt prefixes and cache reads
40
+ ```
41
+
42
+ `report --compare` reads your local logs only. It shows, for each side, sessions, requests,
43
+ tokens, API-equivalent cost at dated list prices (with the price source and date), and cost per
44
+ session, per request and per 1,000 output tokens with the median and the 25th to 75th percentiles.
45
+ Below 20 sessions on either side (configurable with `--min-sessions`) it says "not enough data".
46
+ A difference is reported as an observed difference, never as a saving: the work in the two
47
+ periods is not the same, so read it next to the session length and request counts it prints.
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Claude Code transcripts: <config dir>/projects/<encoded project dir>/**\/*.jsonl.
3
+ *
4
+ * Assistant lines carry message.id, message.model and message.usage. Claude Code writes one line per
5
+ * content block of a response, each with the same message id and usage, and the same message can also
6
+ * appear in more than one file (a resumed session, a subagent transcript), so records are deduped
7
+ * globally by message id + requestId. Where the copies differ, the one with the most output tokens
8
+ * (the final count of a streamed response) is kept. Only usage fields are read.
9
+ */
10
+ import { join, relative, sep } from "node:path";
11
+ import { count, date, emptyStats, jsonLines, obj, projectFromCwd, str } from "./util.js";
12
+ const SYNTHETIC_MODEL = /^<.*>$/; // "<synthetic>": local messages that never reached a model
13
+ const STANDARD = new Set(["standard", "default"]);
14
+ export class ClaudeCodeSource {
15
+ fs;
16
+ configDirs;
17
+ id = "claude-code";
18
+ constructor(fs, configDirs) {
19
+ this.fs = fs;
20
+ this.configDirs = configDirs;
21
+ }
22
+ async read(options) {
23
+ const stats = emptyStats();
24
+ const byKey = new Map();
25
+ const sinceMs = options.since?.getTime() ?? -Infinity;
26
+ for (const dir of this.configDirs) {
27
+ const root = join(dir, "projects");
28
+ const files = await this.fs.listFiles(root, (n) => n.endsWith(".jsonl"));
29
+ for (const f of files) {
30
+ if (f.mtimeMs < sinceMs)
31
+ continue;
32
+ let text;
33
+ try {
34
+ text = await this.fs.readText(f.path);
35
+ }
36
+ catch {
37
+ stats.filesSkipped++;
38
+ continue;
39
+ }
40
+ stats.filesRead++;
41
+ const projectDir = relative(root, f.path).split(sep)[0] ?? "unknown";
42
+ for (const line of jsonLines(text, stats)) {
43
+ if (line.type !== "assistant")
44
+ continue;
45
+ const ev = toEvent(line, projectDir);
46
+ if (!ev) {
47
+ stats.linesSkipped++;
48
+ continue;
49
+ }
50
+ if (ev === "skip")
51
+ continue;
52
+ const prev = byKey.get(ev.dedupeKey);
53
+ if (prev) {
54
+ stats.duplicates++;
55
+ if (ev.outputTokens > prev.outputTokens)
56
+ byKey.set(ev.dedupeKey, ev);
57
+ }
58
+ else {
59
+ byKey.set(ev.dedupeKey, ev);
60
+ }
61
+ }
62
+ }
63
+ }
64
+ return { events: [...byKey.values()], stats, notes: [] };
65
+ }
66
+ }
67
+ /** An event, "skip" for a line that is valid but not billable, or null for an unknown shape. */
68
+ export function toEvent(line, projectDir) {
69
+ const message = obj(line.message);
70
+ const usage = obj(message?.usage);
71
+ const id = str(message?.id);
72
+ const model = str(message?.model);
73
+ const at = date(line.timestamp);
74
+ if (!message || !usage || !id || !model || !at)
75
+ return null;
76
+ if (SYNTHETIC_MODEL.test(model))
77
+ return "skip";
78
+ const creation = obj(usage.cache_creation);
79
+ const w5 = count(creation?.ephemeral_5m_input_tokens);
80
+ const w1h = count(creation?.ephemeral_1h_input_tokens);
81
+ const writes = Math.max(count(usage.cache_creation_input_tokens), w5 + w1h);
82
+ const requestId = str(line.requestId) ?? "";
83
+ const notes = [];
84
+ const speed = str(usage.speed);
85
+ if (speed && !STANDARD.has(speed))
86
+ notes.push(`speed ${speed}`);
87
+ const tier = str(usage.service_tier);
88
+ if (tier && !STANDARD.has(tier))
89
+ notes.push(`service tier ${tier}`);
90
+ const cwd = str(line.cwd);
91
+ return {
92
+ tool: "claude-code",
93
+ provider: "anthropic",
94
+ model,
95
+ occurredAt: at,
96
+ dedupeKey: `${id}:${requestId}`,
97
+ sessionId: str(line.sessionId),
98
+ project: cwd ? projectFromCwd(cwd) : projectDir,
99
+ inputTokens: count(usage.input_tokens),
100
+ outputTokens: count(usage.output_tokens),
101
+ cacheReadTokens: count(usage.cache_read_input_tokens),
102
+ cacheWriteTokens: writes,
103
+ cacheWrite1hTokens: Math.min(w1h, writes),
104
+ ...(notes.length ? { standardRateNote: notes.join(", ") } : {}),
105
+ };
106
+ }