Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
"name": "claude-code-cost",
"displayName": "Claude Code Cost",
"version": "1.1.0",
"version": "1.1.1",
"description": "See your Claude Code spend in USD per project, per git branch, and over time (by day, week, month), computed locally by reading the session logs Claude Code already writes to ~/.claude/projects. Never touches API traffic. Zero key, zero prompts, zero latency.",
"author": {
"name": "RoninForge",
Expand Down
4 changes: 2 additions & 2 deletions CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ abstract: >-
url: "https://roninforge.org/claude-code-cost"
repository-code: "https://github.com/RoninForge/claude-code-cost"
license: MIT
version: 1.1.0
date-released: 2026-06-23
version: 1.1.1
date-released: 2026-11-17
keywords:
- Claude Code
- plugin
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ claude plugin validate . --strict # validate the plugin manifest

Each command in `commands/` is a thin wrapper that runs `scripts/cost.mjs` with a `--mode`. The reader makes a single pass over the JSONL (dedup + point-in-time pricing) and every mode aggregates from that one priced-event list.

The pricing data under `scripts/vendor/ai-price-index/` is a bundled snapshot of the published `ai-price-index` package. To refresh it, re-copy `lib/{data.json,engine.js,index.js}` from a newer release and bump the plugin version. See `scripts/vendor/ai-price-index/VENDORED.md`.
The pricing data under `scripts/vendor/ai-price-index/` is a bundled snapshot of `ai-price-index`'s built `lib/`. To refresh it, re-copy `lib/{data.json,engine.js,index.js}` and `index.d.ts` from a newer release and bump the plugin version. See `scripts/vendor/ai-price-index/VENDORED.md`.

## License

Expand Down
9 changes: 7 additions & 2 deletions scripts/cost.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ async function collectEvents(opts) {
let malformed = 0;
const unpricedModels = new Map(); // model -> count
let unpricedCount = 0;
let tier2Count = 0; // responses billed at a prompt-length tier2 rate

for (const file of walkJsonl(rootAbs)) {
// eslint-disable-next-line no-await-in-loop
Expand All @@ -306,9 +307,11 @@ async function collectEvents(opts) {
if (seen.has(dedupKey)) return;
seen.add(dedupKey);

// Price at the event's UTC calendar date.
// Each deduped response is one request: price it at its UTC date, with the
// prompt-length tier applied (e.g. Haiku 5.5 prompts over 100k tokens).
const date = new Date(ev.ts).toISOString().slice(0, 10);
const { cents, modelKnown } = price.usdForRollup(ev.tokens, "anthropic", ev.model, date);
const { cents, modelKnown, tier2 } = price.usdForRequest(ev.tokens, "anthropic", ev.model, date);
if (tier2) tier2Count++;

if (!modelKnown) {
unpricedCount++;
Expand All @@ -332,6 +335,7 @@ async function collectEvents(opts) {
malformed,
unpricedModels,
unpricedCount,
tier2Count,
dataModified: price.meta.dataModified,
};
}
Expand Down Expand Up @@ -645,6 +649,7 @@ function writeMeta(result) {
unpricedCount: result.unpricedCount,
unpricedModels: [...result.unpricedModels.keys()].sort(),
malformedLines: result.malformed,
tier2Requests: result.tier2Count,
};
process.stderr.write("_meta " + JSON.stringify(meta) + "\n");
}
Expand Down
19 changes: 19 additions & 0 deletions scripts/test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,25 @@ check(
badMode.stderr.trim()
);

// --- Prompt-length tier: claude-haiku-5-5 on 2026-10-15. Prompt = input +
// cache_read + cache writes. gamma's prompt is 101,000 tokens (tier2, whole
// request incl. output); delta's is exactly 100,000 (base). Expected dollars are
// hand-computed from the published rates, not from the vendored lib. ---
const TIER_FIXTURES = join(REPO, "test", "fixtures", "tier-projects");
const tierRun = spawnSync(
process.execPath,
[COST, "--self", "--json", "--asof", "2026-10-15", "--projects-dir", TIER_FIXTURES],
{ encoding: "utf8" }
);
eq("tier run exits 0", tierRun.status, 0);
const tierRows = new Map(JSON.parse(tierRun.stdout || "[]").map((r) => [r.project, r]));
// 61k*0.50 + 100k*2.50 + 30k*0.05 + 10k*0.625 per MTok = $0.28825
eq("haiku-5-5 prompt 101k bills at tier2", tierRows.get("gamma")?.today, 0.29);
// 60k*0.10 + 100k*0.50 + 30k*0.01 + 10k*0.125 per MTok = $0.05755
eq("haiku-5-5 prompt exactly 100k stays base", tierRows.get("delta")?.today, 0.06);
const tierMeta = (tierRun.stderr || "").split("\n").find((l) => l.startsWith("_meta "));
eq("_meta counts one tier2 request", tierMeta && JSON.parse(tierMeta.slice(6)).tier2Requests, 1);

console.log("");
if (failures > 0) {
console.error(`${failures} check(s) failed.`);
Expand Down
17 changes: 10 additions & 7 deletions scripts/vendor/ai-price-index/VENDORED.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
# Vendored ai-price-index

Verbatim copy of the `lib/` output of the published
[ai-price-index](https://www.npmjs.com/package/ai-price-index) npm package,
Verbatim copy of the `lib/` output of
[ai-price-index](https://github.com/RoninForge/ai-price-index) (`node tools/build-npm.mjs`),
bundled so this plugin prices token usage with **zero runtime network** and
**no npm install** at plugin load.

- Source package: `ai-price-index@1.0.3` (npm, published)
- Data modified: `2026-06-22`
- Models covered: 95
- Source: ai-price-index `main` at `b3b09d3` (#96, per-request prompt-length tiers),
which is ahead of the latest npm release (1.0.62). `data.json` records the same ref
in `source`. Also vendors `index.d.ts`.
- Data modified: `2026-11-16`
- Models covered: 149
- Pricing data license: CC BY 4.0. Tooling: MIT.

The local `package.json` here (`{"type":"module"}`) is NOT from upstream; it exists
only so these `.js` files load as ES modules on every Node version (>= 18). Upstream
sets `type:module` at its package root, which is not vendored. Keep this file on refresh.

Refresh: `npm pack ai-price-index@latest`, copy `package/lib/{data.json,engine.js,index.js}`
here (leave this `package.json` and `VENDORED.md` in place), then bump the plugin version.
Refresh: `npm pack ai-price-index@latest` (or `node tools/build-npm.mjs` in a checkout),
copy `lib/{data.json,engine.js,index.js}` and `index.d.ts` here (leave this `package.json`
and `VENDORED.md` in place), record the source above, then bump the plugin version.
2 changes: 1 addition & 1 deletion scripts/vendor/ai-price-index/data.json

Large diffs are not rendered by default.

90 changes: 73 additions & 17 deletions scripts/vendor/ai-price-index/engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
// Goei's server engine (src/lib/server/pricing/{engine,bundle}.ts) so all three engines - the landing
// app, Goei, BudgetClaw - reproduce the SAME shared golden vectors (examples/pricing-vectors.json) to
// the cent. Half-open interval semantics: a rate applies for `from <= date && (to === null || date < to)`.
// Cache read = 0.1x input; cache write = 1.25x (5m) or 2x (1h).
// Cache read = the recorded cache_read rate, falling back to 0.1x input for a model with no cache_read
// series (same rule as BudgetClaw's cacheReadAt); cache write = 1.25x (5m) or 2x (1h).
//
// Prompt-length tiers (tier2_* variations, e.g. Claude Haiku 5.5 "for prompts over 100,000 tokens")
// bill a whole REQUEST at the tier2 rates once its prompt crosses the provider's threshold. Only
// usdForRequest/usdForRequestRaw apply them; usdForRollup prices a sum of requests at the base tier.
import { readFileSync } from 'node:fs';

/** @type {import('../index.js').PriceBundle} */
Expand All @@ -13,6 +18,10 @@ export const CACHE_READ_MULT = 0.1;
export const CACHE_WRITE_5M_MULT = 1.25;
export const CACHE_WRITE_1H_MULT = 2;

// Prompt size above which a provider bills a request at its tier2 rates. Only thresholds the provider
// publishes are listed; a tiered model from an unlisted provider prices at its base tier.
export const PROMPT_TIER_THRESHOLDS = Object.freeze({ anthropic: 100_000 });

// "provider/model" (and "provider/alias") -> series. Canonical model keys win over alias keys on a
// collision (canonical inserted last and overwrites), matching bundle.ts.
const SERIES_BY_KEY = new Map();
Expand Down Expand Up @@ -62,32 +71,79 @@ export function resolveSeries(provider, model) {
return null;
}

function ratesFrom(variations, prefix, date) {
const inIv = intervalAt(variations[`${prefix}input`] ?? [], date);
const outIv = intervalAt(variations[`${prefix}output`] ?? [], date);
if (!inIv || !outIv) return null;
const cr = variations[`${prefix}cache_read`];
const crIv = cr ? intervalAt(cr, date) : null;
return {
inputPerM: inIv.price_usd,
outputPerM: outIv.price_usd,
cacheReadPerM: crIv ? crIv.price_usd : CACHE_READ_MULT * inIv.price_usd,
};
}

/** Point-in-time per-million input/output rates for (provider, model) on `date`, or null if the model
* is unresolved or the date is not covered. */
export function rateAt(provider, model, date) {
const s = resolveSeries(provider, model);
if (!s) return null;
const inIv = intervalAt(s.variations.input, date);
const outIv = intervalAt(s.variations.output, date);
if (!inIv || !outIv) return null;
return { inputPerM: inIv.price_usd, outputPerM: outIv.price_usd };
return s ? ratesFrom(s.variations, '', date) : null;
}

/** USD value of a token rollup at a point in time. Returns 0 with modelKnown=false when the model is
* unknown (so callers can count unpriced rows rather than silently mis-bill). */
export function usdForRollupRaw(tokens, provider, model, date) {
const r = rateAt(provider, model, date);
if (!r) return { usd: 0, modelKnown: false };
/** The prompt-length tier's rates for (provider, model) on `date`, or null when the model has no tier
* in effect then. Same shape as rateAt. */
export function tier2RateAt(provider, model, date) {
const s = resolveSeries(provider, model);
return s ? ratesFrom(s.variations, 'tier2_', date) : null;
}

/** A request's prompt size as providers count it for prompt-length tiers: fresh input plus cache reads
* and cache writes. Output is not part of the prompt. */
export function promptTokens(tokens) {
return (
(tokens.input ?? 0) + (tokens.cache_read ?? 0) + (tokens.cache_write_5m ?? 0) + (tokens.cache_write_1h ?? 0)
);
}

function usdAt(tokens, r) {
const ip = r.inputPerM;
const op = r.outputPerM;
const usd =
return (
((tokens.input ?? 0) * ip +
(tokens.output ?? 0) * op +
(tokens.cache_read ?? 0) * (CACHE_READ_MULT * ip) +
(tokens.output ?? 0) * r.outputPerM +
(tokens.cache_read ?? 0) * r.cacheReadPerM +
(tokens.cache_write_5m ?? 0) * (CACHE_WRITE_5M_MULT * ip) +
(tokens.cache_write_1h ?? 0) * (CACHE_WRITE_1H_MULT * ip)) /
1_000_000;
return { usd, modelKnown: true };
1_000_000
);
}

/** USD value of a token rollup at a point in time, at the base tier. Returns 0 with modelKnown=false
* when the model is unknown (so callers can count unpriced rows rather than silently mis-bill). A
* rollup cannot tell which of its requests crossed a prompt-length threshold, so for a tiered model
* this is a lower bound; price each request with usdForRequestRaw when the per-request split exists. */
export function usdForRollupRaw(tokens, provider, model, date) {
const r = rateAt(provider, model, date);
if (!r) return { usd: 0, modelKnown: false };
return { usd: usdAt(tokens, r), modelKnown: true };
}

/** USD value of ONE request at a point in time. A request whose prompt exceeds the provider's
* PROMPT_TIER_THRESHOLDS entry on a model with a prompt-length tier is billed entirely at the tier2
* rates (tier2: true). Unknown model -> { usd: 0, modelKnown: false, tier2: false }. */
export function usdForRequestRaw(tokens, provider, model, date) {
const s = resolveSeries(provider, model);
const base = s ? ratesFrom(s.variations, '', date) : null;
if (!base) return { usd: 0, modelKnown: false, tier2: false };
const threshold = PROMPT_TIER_THRESHOLDS[s.provider];
const t2 = threshold !== undefined && promptTokens(tokens) > threshold ? ratesFrom(s.variations, 'tier2_', date) : null;
return { usd: usdAt(tokens, t2 ?? base), modelKnown: true, tier2: t2 !== null };
}

/** usdForRequestRaw in integer cents (Math.round). Never throws. */
export function usdForRequest(tokens, provider, model, date) {
const { usd, modelKnown, tier2 } = usdForRequestRaw(tokens, provider, model, date);
return { cents: Math.round(usd * 100), modelKnown, tier2 };
}

/** USD value of a token rollup in integer cents (Math.round). Never throws; an unknown model yields
Expand Down
35 changes: 34 additions & 1 deletion scripts/vendor/ai-price-index/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,22 @@ export function rateAt(
provider: string,
model: string,
date: string
): { inputPerM: number; outputPerM: number } | null;
): { inputPerM: number; outputPerM: number; cacheReadPerM: number } | null;

/** The prompt-length tier (tier2_*) rates in effect on `date`, or null when the model has none. */
export function tier2RateAt(
provider: string,
model: string,
date: string
): { inputPerM: number; outputPerM: number; cacheReadPerM: number } | null;

/** Prompt size for prompt-length tiers: input + cache_read + cache_write_5m + cache_write_1h. */
export function promptTokens(tokens: TokenRollup): number;

/** Prompt size above which a provider bills a request at its tier2 rates (anthropic: 100000). */
export const PROMPT_TIER_THRESHOLDS: Readonly<Record<string, number>>;

/** Values a rollup at the base tier; a lower bound for a model with a prompt-length tier. */
export function usdForRollup(
tokens: TokenRollup,
provider: string,
Expand All @@ -128,6 +142,21 @@ export function usdForRollupRaw(
date: string
): { usd: number; modelKnown: boolean };

/** Values ONE request; a prompt over the provider's threshold bills at the tier2 rates (tier2: true). */
export function usdForRequest(
tokens: TokenRollup,
provider: string,
model: string,
date: string
): { cents: number; modelKnown: boolean; tier2: boolean };

export function usdForRequestRaw(
tokens: TokenRollup,
provider: string,
model: string,
date: string
): { usd: number; modelKnown: boolean; tier2: boolean };

declare const _default: {
meta: typeof meta;
bundle: PriceBundle;
Expand All @@ -139,7 +168,11 @@ declare const _default: {
current: typeof current;
rate: typeof rate;
rateAt: typeof rateAt;
tier2RateAt: typeof tier2RateAt;
promptTokens: typeof promptTokens;
usdForRollup: typeof usdForRollup;
usdForRollupRaw: typeof usdForRollupRaw;
usdForRequest: typeof usdForRequest;
usdForRequestRaw: typeof usdForRequestRaw;
};
export default _default;
20 changes: 17 additions & 3 deletions scripts/vendor/ai-price-index/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,31 @@ import {
seriesFor,
intervalAt,
rateAt,
tier2RateAt,
promptTokens,
usdForRollup,
usdForRollupRaw,
usdForRequest,
usdForRequestRaw,
CACHE_READ_MULT,
CACHE_WRITE_5M_MULT,
CACHE_WRITE_1H_MULT
CACHE_WRITE_1H_MULT,
PROMPT_TIER_THRESHOLDS
} from './engine.js';

export {
bundle,
rateAt,
tier2RateAt,
promptTokens,
usdForRollup,
usdForRollupRaw,
usdForRequest,
usdForRequestRaw,
CACHE_READ_MULT,
CACHE_WRITE_5M_MULT,
CACHE_WRITE_1H_MULT
CACHE_WRITE_1H_MULT,
PROMPT_TIER_THRESHOLDS
};

/** Dataset metadata (version, dataModified date, license, DOI, source provenance). */
Expand Down Expand Up @@ -178,6 +188,10 @@ export default {
current,
rate,
rateAt,
tier2RateAt,
promptTokens,
usdForRollup,
usdForRollupRaw
usdForRollupRaw,
usdForRequest,
usdForRequestRaw
};
1 change: 1 addition & 0 deletions test/fixtures/tier-projects/delta/session-4.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"type":"assistant","uuid":"d-1","requestId":"req_H","timestamp":"2026-10-15T11:00:00.000Z","cwd":"/home/dev/delta","gitBranch":"main","message":{"id":"msg_H","model":"claude-haiku-5-5","usage":{"input_tokens":60000,"output_tokens":100000,"cache_read_input_tokens":30000,"cache_creation":{"ephemeral_5m_input_tokens":10000,"ephemeral_1h_input_tokens":0}}}}
1 change: 1 addition & 0 deletions test/fixtures/tier-projects/gamma/session-3.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"type":"assistant","uuid":"g-1","requestId":"req_G","timestamp":"2026-10-15T10:00:00.000Z","cwd":"/home/dev/gamma","gitBranch":"main","message":{"id":"msg_G","model":"claude-haiku-5-5","usage":{"input_tokens":61000,"output_tokens":100000,"cache_read_input_tokens":30000,"cache_creation":{"ephemeral_5m_input_tokens":10000,"ephemeral_1h_input_tokens":0}}}}
Loading