Files
gabrielvidalandClaude Opus 5.5 4842063c04 chore: stand-alone repo (moved out of ai-agent tools/cache-score)
- the repo root is both the plugin and its marketplace:
  /plugin marketplace add https://git.gabvdl.xyz/gabrielvidal/cache-score.git
  /plugin install cache-score@cache-score
- URLs point here; calibration doc linked on the ai-agent
- curl install of the bare script, package.json (npm test, bin), MIT LICENSE

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:55:46 +01:00

641 lines
37 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
// cache-score: how well do you keep Claude Code's prompt cache warm?
//
// Claude Code caches the conversation for 1 hour on a subscription (5 minutes
// on an API key, on extra usage, and for subagents), and every hit restarts
// the clock. A message sent after that re-writes the whole context at 2× the
// input price instead of reading it at 0.05–0.1×. This file measures what
// that cost you, shows the cache state live, and asks once before you send a
// message into an expired cache.
//
// One file, no dependencies, Node ≥ 18.
// cache-score [--days 30] [--list] [--json] [--no-color] the report
// cache-score statusline status line (reads Claude Code's JSON on stdin)
// cache-score nudge UserPromptSubmit hook (the plugin wires it)
// cache-score install status line + a `cache-score` command
// cache-score uninstall put the previous status line back
//
// Docs: https://git.gabvdl.xyz/gabrielvidal/cache-score
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import readline from "node:readline";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
export const VERSION = "0.1.0";
// ── prices ────────────────────────────────────────────────────────────────
// $ per million tokens: input, output, cache read (list price, Nov 2026).
// Cache writes are 1.25× input on the 5-minute TTL and 2× on the 1-hour TTL.
const PRICES = {
"claude-fable-5-2": [8, 40, 0.2], "claude-fable-5-1": [10, 50, 0.25], "claude-fable-5": [10, 50, 1],
"claude-mythos-5-1": [10, 50, 0.25], "claude-mythos-5": [10, 50, 1],
"claude-opus-5-5": [4, 20, 0.2], "claude-opus-5": [5, 25, 0.5], "claude-opus-4-8": [5, 25, 0.5],
"claude-opus-4-7": [5, 25, 0.5], "claude-opus-4-6": [5, 25, 0.5], "claude-opus-4-5": [5, 25, 0.5],
"claude-opus-4-1": [15, 75, 1.5], "claude-opus-4": [15, 75, 1.5],
"claude-sonnet-5-5": [2, 10, 0.1], "claude-sonnet-5": [2, 10, 0.2], "claude-sonnet-4-6": [3, 15, 0.3],
"claude-sonnet-4-5": [3, 15, 0.3], "claude-sonnet-4": [3, 15, 0.3],
"claude-haiku-5-5": [0.1, 0.5, 0.01], "claude-haiku-4-5": [1, 5, 0.1],
};
// An id this table doesn't know yet is priced as the newest of its family.
const FAMILY = { fable: "claude-fable-5-2", mythos: "claude-mythos-5-1", opus: "claude-opus-5-5",
sonnet: "claude-sonnet-5-5", haiku: "claude-haiku-5-5" };
export function priceOf(model) {
const id = String(model || "").toLowerCase().replace(/\[.*$/, "").replace(/-\d{8}$/, "");
if (PRICES[id]) return PRICES[id];
for (const [fam, ref] of Object.entries(FAMILY)) if (id.includes(fam)) return PRICES[ref];
return null;
}
// ── plan rates: list $ per 1 % of a window ────────────────────────────────
// The plan meters list-price dollars (cache reads at their own price), so a
// lost dollar maps to a share of the 5-hour window and of the week. Measured
// by fitting the reported % against transcript spend (the ai-agent's
// docs/usage-calibration.md, git.gabvdl.xyz/gabrielvidal/ai-agent). The tiers
// don't scale linearly: a Max 20× week holds ≈ 2× a Max 5× week, not 4×, so a
// tier we haven't measured is a guess until this machine's own readings
// calibrate it (see calibrate()).
export const SEEDS = {
default_claude_max_5x: { label: "Max 5×", week: 12.8, h5: 2.14, how: "measured, Team seat, Nov 2026" },
default_claude_max_20x: { label: "Max 20×", week: 25.9, h5: 5.6, how: "measured, Max 20×, Nov 2026" },
default_claude_ai: { label: "Pro", week: 3.7, h5: 0.43, how: "estimate (Max 5× ÷ 3.5 week, ÷ 5 for 5 h)" },
};
const GUESS = { label: "unknown tier", week: 3.7, h5: 0.43, how: "guess (Pro estimate)" };
// ── where things live ─────────────────────────────────────────────────────
const HOME = os.homedir();
export const CONFIG = process.env.CLAUDE_CONFIG_DIR || path.join(HOME, ".claude");
const DATA = process.env.CACHE_SCORE_DATA || path.join(CONFIG, "cache-score");
const SELF = fileURLToPath(import.meta.url);
const STABLE = path.join(DATA, "cache-score.mjs");
function readJson(p) { try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch { return null; } }
function ensureDir(d) { try { fs.mkdirSync(d, { recursive: true }); } catch {} }
/** The signed-in account's plan, from the profile Claude Code caches in
* `.claude.json` (no token is read). A Team seat's own tier wins over its org's. */
export function account(configDir = CONFIG, env = process.env) {
const candidates = env.CLAUDE_CONFIG_DIR
? [path.join(configDir, ".claude.json")]
: [path.join(HOME, ".claude.json"), path.join(configDir, ".claude.json")];
let oa = null;
for (const p of candidates) { const j = readJson(p); if (j?.oauthAccount) { oa = j.oauthAccount; break; } }
if (!oa) return { kind: env.ANTHROPIC_API_KEY ? "api" : "unknown", tier: null, label: env.ANTHROPIC_API_KEY ? "API key" : "not signed in" };
const tier = oa.userRateLimitTier || oa.organizationRateLimitTier || null;
const seat = { claude_team: "Team seat", claude_enterprise: "Enterprise seat", claude_max: "Max plan", claude_pro: "Pro plan" }[oa.organizationType] || "subscription";
const seed = SEEDS[tier];
return { kind: "subscription", tier, seat, label: seed ? `${seat} (${seed.label} tier)` : `${seat}${tier ? ` (${tier})` : ""}` };
}
// ── transcripts ───────────────────────────────────────────────────────────
const MISS_SHARE = 0.05, MISS_MIN = 2000; // Claude Code's own rule for prompt_cache.misses
const INTERACTIVE = new Set(["cli", "claude-vscode", "claude-desktop", "claude-jetbrains"]);
function isHumanPrompt(r) {
if (r.isSidechain || r.isMeta) return false;
const c = r.message?.content;
if (typeof c === "string") return !/^<(local-command|command-name>\/(compact|clear))/.test(c);
return Array.isArray(c) && c.some((b) => b?.type === "text") && !c.some((b) => b?.type === "tool_result");
}
function wanted(line) {
// Cheap filters before JSON.parse: most of a transcript is tool output.
if (line.includes('"usage":{')) return true;
if (line.includes("compact_boundary") || line.includes("Compacted while idle") || line.includes('"ai-title"')) return true;
return line.includes('"type":"user"') && !line.includes('"tool_use_id"');
}
async function eachRecord(file, fn) {
const rl = readline.createInterface({ input: fs.createReadStream(file, { encoding: "utf8" }), crlfDelay: Infinity });
for await (const line of rl) {
if (!wanted(line)) continue;
let r; try { r = JSON.parse(line); } catch { continue; }
fn(r);
}
}
function callOf(r) {
const m = r.message || {}; const u = m.usage;
if (!u || !r.timestamp) return null;
const cc = u.cache_creation || {};
return { key: `${m.id}:${r.requestId}`, t: Date.parse(r.timestamp) / 1000, model: m.model,
side: !!r.isSidechain, inp: u.input_tokens || 0, out: u.output_tokens || 0,
cr: u.cache_read_input_tokens || 0, cw: u.cache_creation_input_tokens || 0,
w1h: cc.ephemeral_1h_input_tokens || 0, w5m: cc.ephemeral_5m_input_tokens || 0,
fast: u.speed === "fast", entry: r.entrypoint, version: r.version };
}
export function costOf(c) {
const p = priceOf(c.model); if (!p) return 0;
const [I, O, R] = p; let w5 = c.w5m, w1 = c.w1h;
if (!w5 && !w1 && c.cw) w1 = c.cw; // an old record without the TTL split
return (c.fast ? 2 : 1) * (c.inp * I + c.out * O + c.cr * R + w1 * I * 2 + w5 * I * 1.25) / 1e6;
}
/** One transcript: its main-thread cold returns and other cache breaks, the
* follow-up messages (for the score), idle compactions, and every call's
* (time, $) for the calibration. `seen` drops calls a fork copied. */
export async function scanFile(file, { since, seen = new Set() } = {}) {
const calls = []; const keys = new Set(); const compacts = []; const prompts = []; const idle = [];
let title = null;
await eachRecord(file, (r) => {
const t = r.timestamp ? Date.parse(r.timestamp) / 1000 : null;
if (r.type === "ai-title") title = r.aiTitle || r.title || title;
else if (r.type === "system" && r.subtype === "compact_boundary" && t)
compacts.push({ t, pre: r.compactMetadata?.preTokens || 0 });
else if (r.type === "system" && t && /^Compacted while idle/.test(r.content || "")) idle.push(t);
else if (r.type === "user" && t && isHumanPrompt(r)) prompts.push(t);
else if (r.type === "assistant") {
const c = callOf(r);
if (c && !keys.has(c.key)) { keys.add(c.key); calls.push(c); }
}
});
calls.sort((a, b) => a.t - b.t);
const out = { file, title, events: [], followups: [], spend: 0, spendCalls: [], idle: idle.filter((t) => t >= since).length, calls: 0 };
const between = (arr, a, b) => arr.some((x) => (x.t ?? x) > a && (x.t ?? x) <= b);
let ttl = 3600; let prev = null;
for (const c of calls) {
const isNew = !seen.has(c.key); seen.add(c.key);
const cost = costOf(c);
if (isNew && c.t >= since) { out.spend += cost; out.spendCalls.push([c.t, cost]); out.calls++; }
if (c.side) continue; // subagents have their own 5-minute caches
const p = priceOf(c.model);
if (prev && p && isNew && c.t >= since) {
const [I, , R] = p; const k = c.fast ? 2 : 1;
const W = I * (c.w5m > c.w1h ? 1.25 : 2);
const gap = c.t - prev.t;
const expected = prev.cr + prev.cw + prev.inp; // what this call could have read
const human = between(prompts, prev.t, c.t);
const compacted = between(compacts, prev.t, c.t);
if (human && !compacted && expected > 0) out.followups.push({ t: c.t, gap, ctx: expected, warm: gap <= ttl });
const short = expected - c.cr;
if (!compacted && short > MISS_SHARE * expected && short >= MISS_MIN) {
const rewritten = Math.min(c.cw + c.inp, short);
const cause = gap > ttl ? "expired" : (prev.model !== c.model ? "model" : "other");
out.events.push({ t: c.t, gap, ttl, ctx: expected, rewritten, lost: k * rewritten * (W - R) / 1e6,
cause, human, model: c.model, entry: c.entry, title, file });
}
}
if (c.w1h || c.w5m) ttl = c.w5m > c.w1h ? 300 : 3600;
prev = c;
}
return out;
}
export function* transcripts(roots, since) {
for (const root of roots) {
const stack = [root];
while (stack.length) {
const dir = stack.pop(); let ents;
try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
for (const e of ents) {
const p = path.join(dir, e.name);
let st = null;
if (e.isSymbolicLink()) { try { st = fs.statSync(p); } catch { continue; } }
if (st ? st.isDirectory() : e.isDirectory()) stack.push(p);
else if (e.name.endsWith(".jsonl")) {
try { if ((st || fs.statSync(p)).mtimeMs / 1000 >= since) yield p; } catch {}
}
}
}
}
}
export async function scanAll(roots, { days = 30, now = Date.now() / 1000 } = {}) {
const since = now - days * 86400; const seen = new Set();
const all = { since, now, days, events: [], followups: [], spend: 0, spendCalls: [], idle: 0, sessions: 0, files: 0 };
for (const f of transcripts(roots, since)) {
all.files++;
const r = await scanFile(f, { since, seen });
all.events.push(...r.events); all.followups.push(...r.followups);
all.spend += r.spend; all.idle += r.idle;
for (const x of r.spendCalls) all.spendCalls.push(x);
if (r.calls && !f.includes(`${path.sep}subagents${path.sep}`)) all.sessions++;
}
all.spendCalls.sort((a, b) => a[0] - b[0]);
return all;
}
// ── summary ───────────────────────────────────────────────────────────────
const F_AFTER = 58_000; // what the next call replays after a /compact (ai-agent, 24 real ones)
const SUMMARY_OUT = 10_000;
export function summarize(scan, rates) {
const cold = scan.events.filter((e) => e.cause === "expired").sort((a, b) => a.t - b.t);
const other = scan.events.filter((e) => e.cause !== "expired");
const fu = scan.followups;
const ctxAll = fu.reduce((s, f) => s + f.ctx, 0);
const ctxWarm = fu.filter((f) => f.warm).reduce((s, f) => s + f.ctx, 0);
const score = ctxAll ? Math.round(100 * ctxWarm / ctxAll) : null;
const lost = cold.reduce((s, e) => s + e.lost, 0);
const rewritten = cold.reduce((s, e) => s + e.rewritten, 0);
const ttls = cold.map((e) => e.ttl); const ttl = ttls.filter((x) => x === 300).length > ttls.length / 2 ? 300 : 3600;
// When you came back: lateness past the TTL.
const edges = [[0, 900], [900, 3600], [3600, 3 * 3600], [3 * 3600, 11 * 3600], [11 * 3600, Infinity]];
const buckets = edges.map(([lo, hi]) => {
const xs = cold.filter((e) => e.gap - e.ttl > lo && e.gap - e.ttl <= hi);
return { lo, hi, n: xs.length, lost: xs.reduce((s, e) => s + e.lost, 0) };
});
// Had the thread been /compact-ed while still warm: the return replays ≈ 58K
// instead of the context; the compaction reads the context from cache.
let compactSave = 0;
for (const e of cold) {
const p = priceOf(e.model); if (!p || e.ctx <= F_AFTER) continue;
const [I, O, R] = p; const W = I * (e.ttl === 300 ? 1.25 : 2);
compactSave += Math.max(0, (e.ctx - F_AFTER) * (W - R) / 1e6 - (e.ctx * R + SUMMARY_OUT * O) / 1e6);
}
const bySource = {};
for (const e of cold) { const s = INTERACTIVE.has(e.entry) ? "terminal" : (e.entry === "ai-agent-sidecar" ? "ai-agent" : (e.entry ? "headless" : "terminal")); bySource[s] = (bySource[s] || 0) + 1; }
const median = (xs) => { if (!xs.length) return 0; const s = [...xs].sort((a, b) => a - b); return s[Math.floor(s.length / 2)]; };
return {
score, followups: fu.length, warm: fu.filter((f) => f.warm).length, cold, other, lost, rewritten,
medianCtx: median(cold.map((e) => e.ctx)), medianLost: median(cold.map((e) => e.lost)),
spend: scan.spend, ttl, buckets, compactSave, idle: scan.idle, bySource,
pctWeek: rates?.week ? lost / rates.week : null, pct5hEach: rates?.h5 ? median(cold.map((e) => e.lost)) / rates.h5 : null,
pct5hTotal: rates?.h5 ? lost / rates.h5 : null,
};
}
// ── self-calibration ──────────────────────────────────────────────────────
// The status line sees the plan's own % (`rate_limits`) on every render; we
// keep a reading whenever it moves. The report then divides the list $ this
// machine's transcripts spent between readings by the points the window rose.
const SAMPLES = path.join(DATA, "samples.jsonl");
const TRUST_POINTS = { h5: 30, week: 12 };
export function recordSample(rl, now = Date.now() / 1000) {
if (!rl) return;
const s = { t: Math.round(now), h5: rl.five_hour?.used_percentage, h5r: rl.five_hour?.resets_at,
wk: rl.seven_day?.used_percentage, wkr: rl.seven_day?.resets_at };
if (s.h5 == null && s.wk == null) return;
const lastFile = path.join(DATA, "last-sample.json"); const last = readJson(lastFile);
if (last && last.h5 === s.h5 && last.wk === s.wk && last.h5r === s.h5r && last.wkr === s.wkr) return;
ensureDir(DATA);
try { fs.appendFileSync(SAMPLES, JSON.stringify(s) + "\n"); fs.writeFileSync(lastFile, JSON.stringify(s)); } catch {}
}
export function calibrate(spendCalls, samples) {
const cum = []; let acc = 0; for (const [t, c] of spendCalls) { acc += c; cum.push([t, acc]); }
const spentUntil = (t) => { let lo = 0, hi = cum.length; while (lo < hi) { const m = (lo + hi) >> 1; if (cum[m][0] <= t) lo = m + 1; else hi = m; } return lo ? cum[lo - 1][1] : 0; };
const out = {};
for (const [w, pk, rk] of [["h5", "h5", "h5r"], ["week", "wk", "wkr"]]) {
let dp = 0, dd = 0; let prev = null;
for (const s of samples) {
if (s[pk] == null) continue;
if (prev && Math.abs((s[rk] || 0) - (prev[rk] || 0)) < 900 && s[pk] >= prev[pk]) {
dp += s[pk] - prev[pk]; dd += spentUntil(s.t) - spentUntil(prev.t);
}
prev = s;
}
out[w] = { points: dp, usd: dd, usdPerPct: dp > 0 && dd > 0 ? dd / dp : null, trusted: dp >= TRUST_POINTS[w] && dd > 0 };
}
return out;
}
export function readSamples() {
try { return fs.readFileSync(SAMPLES, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)); } catch { return []; }
}
export function ratesFor(acct, cal) {
if (acct.kind === "api") return null;
const seed = SEEDS[acct.tier] || GUESS;
const r = { tier: acct.tier, label: seed.label, week: seed.week, h5: seed.h5, how: { week: seed.how, h5: seed.how } };
for (const w of ["week", "h5"]) if (cal?.[w]?.trusted) { r[w] = cal[w].usdPerPct; r.how[w] = `calibrated here (${cal[w].points} points)`; }
return r;
}
// The status line and the nudge can't afford a transcript scan: they reuse the
// rate the last report calibrated, as long as the plan hasn't changed since.
const RATES_FILE = path.join(DATA, "rates.json");
function liveRates() {
const acct = account(); const saved = readJson(RATES_FILE);
return saved && saved.tier === acct.tier && acct.kind !== "api" ? saved : ratesFor(acct, null);
}
// ── formatting ────────────────────────────────────────────────────────────
let COLOR = true;
const A = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : String(s));
const dim = A("2"), bold = A("1"), green = A("32"), yellow = A("33"), red = A("31"), cyan = A("36");
const stripAnsi = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, "");
const pad = (s, n) => { const v = stripAnsi(s).length; return v >= n ? s : s + " ".repeat(n - v); };
const lpad = (s, n) => { const v = stripAnsi(s).length; return v >= n ? s : " ".repeat(n - v) + s; };
export function tok(n) { return n >= 1e6 ? `${(n / 1e6).toFixed(1)} M` : n >= 1e3 ? `${Math.round(n / 1e3)}K` : String(Math.round(n)); }
export function usd(x) { return x >= 100 ? `$${Math.round(x).toLocaleString("en-US")}` : `$${x.toFixed(2)}`; }
export function dur(s) {
const mins = Math.max(1, Math.round(s / 60));
if (mins < 60) return `${mins} min`;
const h = Math.floor(mins / 60), m = mins % 60;
return h < 10 && m ? `${h}h${String(m).padStart(2, "0")}` : `${Math.round(mins / 60)} h`;
}
const shortDur = (s) => (s < 3600 ? `${Math.max(1, Math.round(s / 60))}m` : s < 86400 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`);
function when(t) {
const d = new Date(t * 1000);
return `${d.toLocaleDateString("en-GB", { weekday: "short" })} ${String(d.getDate()).padStart(2, "0")} ${d.toLocaleDateString("en-GB", { month: "short" })} ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
}
const pct = (x) => (x == null ? "?" : x >= 10 ? `${Math.round(x)} %` : x >= 1 ? `${x.toFixed(1)} %` : `${x.toFixed(2)} %`);
const grade = (s) => (s >= 95 ? ["excellent", green] : s >= 85 ? ["good", green] : s >= 70 ? ["fair", yellow] : ["poor", red]);
function bucketLabel(b, ttl) {
if (b.lo === 0) return "≤ 15 min late";
if (!isFinite(b.hi)) return ttl === 3600 ? "next day" : "11 h+ late";
const f = (s) => { const h = Math.floor(s / 3600), m = Math.round((s % 3600) / 60); return h ? (m ? `${h}h${String(m).padStart(2, "0")}` : `${h}h`) : `${m} min`; };
return `${f(ttl + b.lo)}–${f(ttl + b.hi)}`;
}
export function renderReport(sum, ctx) {
const { acct, rates, days, version, cal } = ctx;
const L = [];
const ttlName = sum.ttl === 300 ? "5 min cache" : "1 h cache";
L.push(`${bold("cache-score")} ${dim(`· last ${days} days · ${acct.label} · ${ttlName}${version ? ` · claude ${version}` : ""}`)}`);
L.push("");
if (sum.score == null) { L.push(" No follow-up messages in this window: nothing to score yet."); return L.join("\n"); }
const [g, gc] = grade(sum.score);
const width = 44, fill = Math.round(width * sum.score / 100);
L.push(` ${dim("╭────────╮")} ${bold("CACHE SCORE")}`);
L.push(` ${dim("│")} ${gc(bold(String(sum.score).padStart(3)))} ${dim("│")} ${gc("█".repeat(fill))}${dim("░".repeat(width - fill))} ${gc(g)}`);
L.push(` ${dim("│")} ${dim("/100")} ${dim("│")} ${sum.score} of every 100 context tokens your messages re-sent came from cache`);
L.push(` ${dim("╰────────╯")} ${dim(`${sum.followups} messages ·`)} ${sum.cold.length ? yellow(`${sum.cold.length} sent to an expired cache`) : green("none sent to an expired cache")}`);
if (sum.cold.length) {
L.push("");
L.push(bold("WHAT THE COLD RETURNS COST"));
L.push(` re-written context ${pad(bold(`${tok(sum.rewritten)} tokens`), 18)}${dim(`median ${tok(sum.medianCtx)} per return`)}`);
L.push(` list price ${pad(bold(usd(sum.lost)), 18)}${dim(`${pct(100 * sum.lost / Math.max(sum.spend, 1e-9))} of your ${usd(sum.spend)} spend`)}`);
if (rates) L.push(` plan usage ${pad(yellow(bold(`≈ ${pct(sum.pctWeek)} of a week`)), 18)} ${dim(`≈ ${pct(sum.pct5hEach)} of a 5-hour window per return`)}`);
else L.push(` plan usage ${dim("— API key: these dollars are billed as they are")}`);
L.push("");
L.push(`${bold("WHEN YOU CAME BACK")}${" ".repeat(46)}${dim("returns lost")}`);
const max = Math.max(...sum.buckets.map((b) => b.n), 1);
sum.buckets.forEach((b, i) => {
const color = i < 2 ? yellow : red;
const bar = color("█".repeat(Math.round(30 * b.n / max)));
const note = i === 0 && b.n ? dim("← just missed it") : "";
L.push(` ${pad(bucketLabel(b, sum.ttl), 15)}${pad(bar, 31)}${pad(note, 17)}${lpad(String(b.n), 4)} ${lpad(usd(b.lost), 7)}`);
});
L.push("");
L.push(bold("COSTLIEST RETURNS"));
for (const e of [...sum.cold].sort((a, b) => b.lost - a.lost).slice(0, 5)) {
const c = e.lost >= 4 ? red : yellow;
const wk = rates?.week ? dim(`${(e.lost / rates.week).toFixed(2)} % wk`) : "";
L.push(` ${when(e.t)} ${pad(`idle ${dur(e.gap)}`, 11)} ${lpad(tok(e.ctx), 5)} ${lpad(c(usd(e.lost)), 6)} ${pad(wk, 10)} ${(e.title || path.basename(e.file, ".jsonl")).slice(0, 44)}`);
}
const src = Object.entries(sum.bySource);
if (src.length > 1) L.push(dim(` from: ${src.map(([k, v]) => `${k} ${v}`).join(" · ")}`));
}
if (sum.other.length) {
const m = sum.other.filter((e) => e.cause === "model"), o = sum.other.filter((e) => e.cause === "other");
const s = (xs) => usd(xs.reduce((a, e) => a + e.lost, 0));
L.push("");
L.push(`${bold("OTHER CACHE BREAKS")} ${dim("(cache still alive, prefix changed)")}${" ".repeat(9)}${lpad(String(sum.other.length), 4)} ${lpad(s(sum.other), 7)}`);
L.push(` model switch ${m.length} · ${s(m)} tools / MCP / CLI upgrade ${o.length} · ${s(o)}`);
}
if (sum.idle) L.push("", `${green("✓")} Claude Code compacted ${sum.idle} idle conversation${sum.idle > 1 ? "s" : ""} for you before the cache expired.`);
L.push("");
if (sum.cold.length) {
L.push(`${cyan(bold("TIP"))} Stepping away from a big thread? ${cyan("/compact")} while the cache is warm: it reads from cache.`);
L.push(` A cold ${cyan("/compact")} re-reads everything. Back cold on a new task? ${cyan("/clear")} is free.`);
if (sum.compactSave > 1) L.push(` Compacting before you left would have saved ${green(bold(`≈ ${usd(sum.compactSave)}`))}${rates ? ` ${dim(`(≈ ${pct(sum.compactSave / rates.week)} of a week)`)}` : ""} here.`);
} else L.push(`${green("✓")} Every message you sent landed on a warm cache.`);
if (rates) {
const c = cal?.week; const calNote = c?.trusted ? "" : ` · calibrating ${Math.round(c?.points || 0)}/${TRUST_POINTS.week}`;
L.push(dim(` 1 % = ${usd(rates.week)} week · ${usd(rates.h5)} 5 h · ${rates.label}, ${rates.how.week}${calNote}`));
}
L.push(dim(" cache-score --list every cold return · --json · --days 7"));
return L.join("\n");
}
function renderList(sum, rates) {
const L = [dim(" when idle context lost % wk conversation")];
for (const e of sum.cold) {
const late = e.gap - e.ttl < 900 ? dim(` ← ${Math.round((e.gap - e.ttl) / 60)} min late`) : "";
L.push(` ${when(e.t)} ${pad(dur(e.gap), 8)} ${lpad(tok(e.ctx), 7)} ${lpad(usd(e.lost), 6)} ${lpad(rates?.week ? (e.lost / rates.week).toFixed(2) : "–", 5)} ${(e.title || path.basename(e.file, ".jsonl")).slice(0, 44)}${late}`);
}
return L.join("\n");
}
// ── live state: transcript tail (nudge, and the status line's fallback) ───
export function tailState(transcript, maxBytes = 1 << 20) {
let buf;
try {
const fd = fs.openSync(transcript, "r"); const size = fs.fstatSync(fd).size;
const len = Math.min(size, maxBytes); buf = Buffer.alloc(len);
fs.readSync(fd, buf, 0, len, size - len); fs.closeSync(fd);
} catch { return null; }
const lines = buf.toString("utf8").split("\n");
let last = null, ttl = null, compactedAfter = false, entry = null;
for (let i = lines.length - 1; i >= 0; i--) {
const l = lines[i]; if (!l) continue;
if (!last && l.includes("compact_boundary")) { compactedAfter = true; continue; }
if (!l.includes('"usage":{')) { if (!entry && l.includes('"entrypoint"')) { try { entry = JSON.parse(l).entrypoint; } catch {} } continue; }
let r; try { r = JSON.parse(l); } catch { continue; }
if (r.type !== "assistant" || r.isSidechain) continue;
const c = callOf(r); if (!c) continue;
entry = entry || c.entry;
if (!last) last = c;
if (c.w1h || c.w5m) { ttl = c.w5m > c.w1h ? 300 : 3600; break; }
}
if (!last) return null;
return { t: last.t, model: last.model, ctx: last.cr + last.cw + last.inp + last.out, ttl: ttl || 3600, compactedAfter, entry, fast: last.fast };
}
/** What sending into a cold cache costs: the context minus the ~24K system
* prompt + tools other sessions keep warm, written at the TTL's rate. */
export function coldCost(ctx, model, ttl = 3600, fast = false) {
const p = priceOf(model) || PRICES["claude-opus-5-5"]; const [I, , R] = p;
const P = Math.min(24_000, ctx); const W = I * (ttl === 300 ? 1.25 : 2);
return (fast ? 2 : 1) * ((ctx - P) * W + P * R) / 1e6;
}
export function warmCompactCost(ctx, model) {
const p = priceOf(model) || PRICES["claude-opus-5-5"]; const [I, O, R] = p;
// the summary call reads the context from cache, writes ~10K of summary,
// and the next turn writes the ~58K it replays
return (ctx * R + SUMMARY_OUT * O + Math.min(ctx, F_AFTER) * I * 2) / 1e6;
}
// ── status line (S2) ──────────────────────────────────────────────────────
export function statusSegment(input, { now = Date.now() / 1000, rates = null, color = true } = {}) {
COLOR = color;
const pc = input?.prompt_cache; const model = input?.model?.id;
let warm, left, idleFor, ctx, ttl, hit = null;
if (pc && pc.caching_observed !== false && (pc.expires_at || pc.recache_tokens_if_cold)) {
ttl = pc.ttl === "5m" ? 300 : 3600;
ctx = pc.recache_tokens_if_cold ?? sumUsage(input?.context_window?.current_usage);
left = pc.expires_at ? pc.expires_at - now : -1;
warm = left > 0; idleFor = pc.expires_at ? now - (pc.expires_at - ttl) : null; hit = pc.hit_ratio;
} else {
const s = input?.transcript_path ? tailState(input.transcript_path) : null;
if (!s) return dim("cache –");
ttl = s.ttl; ctx = s.compactedAfter ? null : s.ctx; idleFor = now - s.t; left = ttl - idleFor; warm = left > 0;
}
if (!ctx) return warm ? `${green("●")} cache ${shortDur(left)}` : dim("cache –");
if (warm) {
const head = `${left <= 600 ? yellow("●") : green("●")} cache ${bold(shortDur(left))}`;
if (left > 600 || ctx < 50_000) return `${head} ${dim(`· ${hit != null ? `hit ${Math.round(hit * 100)} % · ` : ""}${tok(ctx)}`)}`;
return `${head} ${dim(`· ${tok(ctx)} ·`)} leaving? ${cyan("/compact")} now ≈ ${green(usd(warmCompactCost(ctx, model)))} ${dim(`(else ≈ ${usd(coldCost(ctx, model, ttl))} when back)`)}`;
}
const cost = coldCost(ctx, model, ttl, input?.fast_mode);
const share = rates?.h5 ? dim(` (${pct(cost / rates.h5)} 5h)`) : rates?.week ? dim(` (${pct(cost / rates.week)} wk)`) : "";
return `${red("○")} cold ${idleFor != null ? shortDur(idleFor) : ""} · next msg re-sends ${bold(tok(ctx))} ≈ ${red(usd(cost))}${share} · new task? ${cyan("/clear")} is free`;
}
const sumUsage = (u) => (u ? (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.cache_read_input_tokens || 0) : 0);
async function readStdin() {
if (process.stdin.isTTY) return "";
const chunks = []; for await (const c of process.stdin) chunks.push(c);
return Buffer.concat(chunks).toString("utf8");
}
async function cmdStatusline() {
const raw = await readStdin(); let input = {};
try { input = JSON.parse(raw); } catch {}
recordSample(input.rate_limits);
const prev = readJson(path.join(DATA, "previous-statusline.json"));
if (prev?.command) {
const r = spawnSync(prev.command, { input: raw, shell: true, encoding: "utf8", timeout: 3000 });
const out = (r.stdout || "").replace(/\n+$/, "");
if (out) process.stdout.write(out + "\n");
}
process.stdout.write(statusSegment(input, { rates: liveRates(), color: !process.env.NO_COLOR }) + "\n");
}
// ── nudge (UserPromptSubmit hook) ─────────────────────────────────────────
export function nudgeDecision(input, { now = Date.now() / 1000, env = process.env, rates = null, markerDir = path.join(DATA, "nudged") } = {}) {
if (env.CACHE_SCORE_NUDGE === "0") return null;
const prompt = String(input?.prompt || "").trim();
if (!prompt || prompt.startsWith("/") || prompt.startsWith("!")) return null;
const s = input?.transcript_path ? tailState(input.transcript_path) : null;
if (!s || s.compactedAfter) return null;
// Only someone at a terminal or an IDE gets asked: `-p` runs and apps that
// resume sessions (the ai-agent has its own prompt) go through. This run's
// entrypoint first; the transcript's tells only when it isn't exported.
if (env.CLAUDE_CODE_SESSION_ATTENDED === "0") return null;
const entry = env.CLAUDE_CODE_ENTRYPOINT || s.entry;
if (entry && !INTERACTIVE.has(entry)) return null;
const idleFor = now - s.t; if (idleFor <= s.ttl) return null;
const min = Number(env.CACHE_SCORE_NUDGE_MIN_TOKENS || 100_000);
if (s.ctx < min) return null;
const marker = path.join(markerDir, String(input.session_id || "x").replace(/[^\w-]/g, ""));
let seen = null; try { seen = fs.readFileSync(marker, "utf8"); } catch {}
if (seen === String(s.t)) { try { fs.unlinkSync(marker); } catch {} return null; } // asked once: let it through
ensureDir(markerDir); try { fs.writeFileSync(marker, String(s.t)); } catch {}
const cost = coldCost(s.ctx, s.model, s.ttl, s.fast);
const share = rates?.h5 ? ` (${pct(cost / rates.h5)} of your 5-hour window)` : rates?.week ? ` (${pct(cost / rates.week)} of your week)` : "";
return [
`⚠ cache expired ${dur(idleFor)} ago: this message would re-send ${tok(s.ctx)} tokens ≈ ${usd(cost)}${share}.`,
` New task? /clear is free. Same task? Press ↑ then Enter to send it as is (asked once).`,
].join("\n");
}
async function cmdNudge() {
let input = {}; try { input = JSON.parse(await readStdin()); } catch {}
syncStable();
const reason = nudgeDecision(input, { rates: liveRates() });
if (reason) process.stdout.write(JSON.stringify({ decision: "block", reason }) + "\n");
}
// ── install ───────────────────────────────────────────────────────────────
function syncStable() {
// Keep the status line's copy in step with the plugin's (its path is versioned).
try {
if (!fs.existsSync(STABLE) || path.resolve(SELF) === path.resolve(STABLE)) return;
const head = fs.readFileSync(STABLE, "utf8").slice(0, 4000);
if (!head.includes(`VERSION = "${VERSION}"`)) fs.copyFileSync(SELF, STABLE);
} catch {}
}
function cmdInstall(args) {
ensureDir(DATA);
if (path.resolve(SELF) !== path.resolve(STABLE)) fs.copyFileSync(SELF, STABLE);
fs.chmodSync(STABLE, 0o755);
const done = [`copied to ${STABLE}`];
if (!args.includes("--no-statusline")) {
const sp = path.join(CONFIG, "settings.json");
let settings = {};
if (fs.existsSync(sp)) {
settings = readJson(sp);
if (!settings) { console.error(`✗ ${sp} isn't plain JSON; add the status line by hand:\n "statusLine": {"type": "command", "command": "node \\"${STABLE}\\" statusline", "refreshInterval": 60}`); process.exit(1); }
fs.copyFileSync(sp, `${sp}.bak-cache-score`);
}
const cur = settings.statusLine;
if (cur?.command && !cur.command.includes("cache-score")) {
fs.writeFileSync(path.join(DATA, "previous-statusline.json"), JSON.stringify(cur, null, 2));
done.push(`kept your status line above it (${cur.command.slice(0, 60)})`);
}
settings.statusLine = { type: "command", command: `node "${STABLE}" statusline`, refreshInterval: 60 };
fs.writeFileSync(sp, JSON.stringify(settings, null, 2) + "\n");
done.push(`status line set in ${sp} (backup: settings.json.bak-cache-score)`);
}
if (!args.includes("--no-bin")) {
const binDir = path.join(HOME, ".local", "bin"); const link = path.join(binDir, "cache-score");
const onPath = (process.env.PATH || "").split(path.delimiter).includes(binDir);
if (fs.existsSync(binDir)) {
try { fs.rmSync(link, { force: true }); fs.symlinkSync(STABLE, link); done.push(`\`cache-score\` → ${link}${onPath ? "" : ` (add ${binDir} to your PATH)`}`); } catch (e) { done.push(`no command: ${e.message}`); }
} else done.push(`run it with: node "${STABLE}" (or: alias cache-score='node "${STABLE}"')`);
}
console.log(done.map((d) => `✓ ${d}`).join("\n"));
}
function cmdUninstall() {
const sp = path.join(CONFIG, "settings.json"); const settings = readJson(sp);
const prev = readJson(path.join(DATA, "previous-statusline.json"));
if (settings?.statusLine?.command?.includes("cache-score")) {
if (prev) settings.statusLine = prev; else delete settings.statusLine;
fs.writeFileSync(sp, JSON.stringify(settings, null, 2) + "\n");
console.log(prev ? "✓ previous status line restored" : "✓ status line removed");
}
try { const link = path.join(HOME, ".local", "bin", "cache-score"); if (fs.readlinkSync(link) === STABLE) fs.unlinkSync(link); } catch {}
try { fs.rmSync(path.join(DATA, "previous-statusline.json"), { force: true }); } catch {}
console.log(`✓ done (readings kept in ${DATA})`);
}
// ── report command ────────────────────────────────────────────────────────
function cliVersion() {
try { const r = spawnSync("claude", ["--version"], { encoding: "utf8", timeout: 5000 }); return (r.stdout || "").trim().split(" ")[0] || null; } catch { return null; }
}
async function cmdReport(args) {
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 && args[i + 1] ? args[i + 1] : d; };
const days = Number(opt("--days", 30));
COLOR = !args.includes("--no-color") && !process.env.NO_COLOR && !!process.stdout.isTTY;
const roots = args.includes("--dir") ? [opt("--dir")] : [path.join(CONFIG, "projects")];
const acct = account();
if (opt("--tier")) acct.tier = opt("--tier"), acct.label = `${SEEDS[acct.tier]?.label || acct.tier} (--tier)`;
const scan = await scanAll(roots, { days });
const cal = calibrate(scan.spendCalls, readSamples());
const rates = ratesFor(acct, cal);
if (rates && !opt("--tier") && (cal.week.trusted || cal.h5.trusted)) {
ensureDir(DATA); try { fs.writeFileSync(RATES_FILE, JSON.stringify(rates)); } catch {}
}
const sum = summarize(scan, rates);
if (args.includes("--json")) {
const { cold, other, ...rest } = sum;
console.log(JSON.stringify({ version: VERSION, days, account: acct, rates, calibration: cal, ...rest,
coldReturns: cold.map(({ file, ...e }) => e), otherBreaks: other.length }, null, 2));
return;
}
console.log(renderReport(sum, { acct, rates, days, version: cliVersion(), cal }));
if (args.includes("--list") && sum.cold.length) console.log("\n" + renderList(sum, rates));
}
async function main() {
const [cmd, ...rest] = process.argv.slice(2);
if (cmd === "statusline") return cmdStatusline();
if (cmd === "nudge") return cmdNudge();
if (cmd === "install") return cmdInstall(rest);
if (cmd === "uninstall") return cmdUninstall();
if (cmd === "--version" || cmd === "-v") return console.log(VERSION);
if (cmd === "--help" || cmd === "-h" || cmd === "help") {
return console.log(`cache-score ${VERSION}: how well you keep Claude Code's prompt cache warm
cache-score [--days N] [--list] [--json] [--no-color] [--tier T] [--dir D]
cache-score install [--no-statusline] [--no-bin] | uninstall
cache-score statusline | nudge (called by Claude Code)`);
}
return cmdReport(cmd === "report" ? rest : process.argv.slice(2));
}
const invoked = (() => { try { return fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF); } catch { return false; } })();
if (invoked) main().catch((e) => { console.error(`cache-score: ${e.message}`); process.exit(1); });