SLOPSHOPPER

cost-ledger

Tracks what Claude Code costs — session, calendar-week and calendar-month totals with the month's pace and week-over-week change, a /costs pane with a spend…

panebandguardcommandtoaststatus
★ 2v0.6.0MITupdated 2026-10-14bobtat/claude-plugins/plugins/cost-ledger
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cost-ledger
│ ┃ Costs ✕ › fix the failing auth test and add an audit log call │ ┃ Session $0.42 │ ┃ Today $0.00 ⏺ Read(src/auth.ts) │ ┃ This week $0.00 since 2025-10-06 ⎿ Read 6 lines │ ┃ This month $0.00 on pace for $0.00 ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ p: ◀ October 2025 ⏺ Bash(bun test) │ ┃ Mo Tu We Th Fr Sa Su ⎿ 3 pass, 1 fail │ ┃ 1 2 3 4 5 │ ┃ 6 7 8 9 10 11 12 ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ 13 14 15 16 17 18 19 │ ┃ 20 21 22 23 24 25 26 ✻ Worked for 42s · done 4:20 PM │ ┃ 27 28 29 30 31 │ ┃ less more $0.00 total › /costs │ ┃ Shade by s: total spend ⎿ cost-ledger: Costs pane opened. │ ┃ │ ┃ Prompt cache, October 2025 (estimated at │ ┃ list prices) │ ┃ No requests recorded. │ ┃ │ ┃ Most expensive prompts, October 2025 │ ┃ (estimated, subagents included) │ ┃ None recorded. │ ┃ │ ┃ What filled the context, October 2025 (tool │ ┃ results, ≈ tokens) $0.42 session · $0.00 week · $0.00 month ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ cost-ledger: $0.42 session · $0.00 week · $0.00 month

Draws

Band
$0.42 session · $0.00 week · $0.00 month
Pane · Costs
Session $0.42 Today $0.00 This week $0.00 since 2025-10-06 This month $0.00 on pace for $0.00 p: ◀ October 2025 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 less more $0.00 total Shade by s: total spend Prompt cache, October 2025 (estimated at list prices) No requests recorded. Most expensive prompts, October 2025 (estimated, subagents included) None recorded. What filled the context, October 2025 (tool results, ≈ tokens) tool calls tokens write re-read Read 1 49 $0.00 $0.00 Grep 1 8 $0.00 $0.00 Edit 1 12 $0.00 $0.00 Write 2 26 $0.00 $0.00 Bash 3 76 $0.00 $0.00 By project, October 2025 No spend recorded. Daily, October 2025 No spend recorded.
README

cost-ledger

A Claude Code mod that keeps a running ledger of what Claude Code costs: this session, this calendar week (Monday to Sunday) and this calendar month, in local time. It also makes prompt-cache spend visible, since on long agentic sessions cache_read and cache_write are usually most of the bill, says what letting the cache go cold will cost, and can keep it warm while a session sits idle.

Unlike the other plugins in this marketplace, cost-ledger is code: a TypeScript hooks module that Claude Code loads and runs inside the session, not skills or commands for Claude to read.

Installation

/plugin marketplace add bobtat/claude-plugins
/plugin install cost-ledger@bobtat-plugins

What it shows

WhereWhat
Status line and a band above the prompt$1.84 session · $23.10 week · $96.40 month · ctx 150k ≈$0.03/step · cache warm 3m; once the cache has gone cold, cache cold (re-cache ≈$0.34–$0.57); while the keep-alive holds it, cache warm 41m (kept warm: 2 pings $0.03)
/costs paneTotals with budget progress, the change against the same point last week and the month's pace (with the day a monthly budget would be reached), a heat-map calendar per month (shade by total spend or by cache writes, p/n to change month, s to switch shading), the month's prompt-cache breakdown, the subagent share, the most expensive prompts, what filled the context, spend by project, and daily bars
/costs exportWrites ~/claude-costs/claude-costs-<date>.csv: one row per day and project with the total, tokens and estimated cost per category, and subagent cost
/costs doctorChecks the assumptions the totals rest on (see below)
`/costs keepalive [on\off]`Turns the keep-alive on or off for this session, overriding the keepAlive setting; with no argument, says whether it is on, the pings so far and when the next is due
ToastsBefore a prompt is sent once the cache has likely expired, and on resuming a session whose cache has likely expired, with what re-caching will cost; when the keep-alive stops; before a model switch that drops a warm cache; after one request writes a large amount to the cache; after a prompt whose cost passes a threshold; at 80% and 100% of a budget

All warnings are informational: nothing is ever blocked.

Where the numbers come from

 session.measure ── cost.usd (Claude Code's running total) ──► spend per session and day
 turn.step ──────── usage per request (tokens, model) ───────► priced per category
                                                                  │
                    $.store: one entry per session, ◄─────────────┘
                    archived per project after 60 days, kept 400 days
                                   │
                                   ▼
                status line · band · /costs pane · CSV export
  • Totals (session, week, month, calendar, budgets) are Claude Code's own figure, the one /cost shows. It is list price unless an administrator has set the managed modelPricing setting.
  • The category breakdown (input, output, cache write, cache read) is estimated by the mod from each request's token counts, at Anthropic list prices or at the rates you give it. Token counts and the cache-hit percentage are exact; the dollars are estimates.
  • The cost of a prompt is the estimated cost of every request made between the prompt and its answer, its subagents' included, with the first 80 characters of the prompt. The month's ten most expensive are kept. Prompt text stays in the local store; it is not exported.
  • What filled the context measures each tool result as the model reads it, at roughly four characters a token, then charges it a cache write on the first request that sends it and a cache read on every request after, until /clear or /compact drops it. A large file read early in a long turn shows up here as the re-reads it caused. The tokens are approximate, so the dollars are a guide to where the cache spend comes from rather than a bill.
  • Pace extrapolates the month's spend at its average daily rate so far, counting at least one day. Week over week compares Monday to today with Monday to the same weekday last week.
  • Only sessions that ran with the mod enabled are counted. There is no backfill from older transcripts.
  • The cache lifetime is read from Claude Code's own pricing: after each turn, the turn's requests are priced at list rates with five-minute and with one-hour cache writes, and whichever matches what the turn moved Claude Code's running total by is the lifetime it charged. A model switch's report also sets it. Under managed rates, which list prices cannot match, only the report does.
  • The cost of a cold cache is the context's tokens at the cache write rate, less the opening other sessions keep cached: the system prompt and tool definitions, measured as what a new conversation's first request reads from the cache. That opening stays cached only while something else uses it, so the whole context is shown as the worst case: ≈$0.34–$0.57.

Keeping the cache warm

With keepAlive on (or /costs keepalive on), once a turn ends the mod waits nine tenths of the cache lifetime, 54 minutes on the one-hour cache, and then sends the conversation again with a one-word question through Claude Code's own client ($.model.fork). That request reads the context from the cache, which renews the cache's lifetime, and writes nothing to the transcript. It repeats until you send a prompt, which cancels the pending ping, or until the session has been idle for keepAliveMaxIdleMinutes; the cache then lapses one lifetime after the last ping.

  • What a ping costs is a cache read of the context plus about four output tokens, and the first ping after a turn also writes the last answer: about $0.014–0.02 at 62–67k tokens on Opus 5.5. The cold re-cache it avoids was about $0.33 at that size. Each ping is in Claude Code's running total like any request, and in the category breakdown.
  • A ping that finds the cache already cold (it writes the conversation rather than reading it) stops the keep-alive, as does a failed request.
  • On the five-minute cache a ping goes out every 4.5 minutes, which costs more per idle hour; the break-even against one cold re-cache is roughly 25 pings.
  • On a subscription, pings count against the 5-hour and 7-day limits like any request, weighted by their API-equivalent price as far as measured: on a Pro account, about 0.045% of the 5-hour window per ping at 62k tokens, so three hourly pings cost about 0.13% against about 1% for one cold re-cache of a conversation that size.

The measurements behind these numbers are in tests/cost-ledger-probe/README.md at the repository root.

Checking the setup

/costs doctor reports, each line marked ✓, ⚠ or ℹ:

  • Time zone: whether the mod's local time matches the host clock (Get-Date on Windows, date elsewhere), since days, weeks and months are split by it.
  • Store file: whether a write reaches the store file on disk at once, whether this session's view of the store matches the file (if it does not, another session's writes may be getting lost), and how close the file is to the 4 MiB limit.
  • Another install: a store file left by a differently installed copy of the mod. Each install source (marketplace, --plugin-dir, a session's mods folder) has its own store, so history recorded by one is not in another's totals.
  • Claude Code pricing: whether Claude Code prices at your organisation's managed rates or at list price, once it has said so, which it does when you switch models.
  • Cache lifetime and where it was learned, the shared opening, the keep-alive, baseline, rates and models without a rate.

It cannot check the /resume accounting: for that, compare /costs before and after resuming a session whose spend you know.

Settings

Set in /config under cost-ledger.

SettingDefaultMeaning
billingapisubscription labels figures as API-equivalent and adds the 5-hour and 7-day rate-limit percentages
statusLine, bandonShow the summary in the status line and in the band
ratesemptyJSON of USD per million tokens by model family, overriding list prices for some or all fields, for example {"opus-5-5": {"input": 4, "output": 20, "cacheRead": 0.2, "cacheWrite5m": 5, "cacheWrite1h": 8}}. A family matches any model id that contains it and does not continue with another version number, so Bedrock ids such as us.anthropic.claude-opus-5-5-v1:0 resolve. A family with no list price needs input, output and cacheRead
cacheTtlautoPrompt-cache lifetime used for the countdown, the idle warning, the keep-alive and write pricing. auto learns it from Claude Code's pricing of each turn or from a model switch, and uses 5 minutes until then
keepAliveoffon keeps the prompt cache warm while the session is idle (see above)
keepAliveMaxIdleMinutes180Stop pinging once the session has had no prompt for this long
keepAliveMinContextTokens20000Send no pings while the context is smaller than this
largeWriteTokens50000Toast when one request writes at least this many tokens to the cache; 0 turns it off
contextNudgeTokens150000Suggest /compact once the context reaches this size; 0 turns it off
dailyBudget, weeklyBudget, monthlyBudget0USD; toast at 80% and 100%; 0 turns each off
expensiveTurnUsd2Toast when one prompt, its subagents included, costs at least this much (estimated); 0 turns it off

Models with no list price in the bundled reference (Opus 4.5, Opus 4.1, Sonnet 4.5) are not guessed at: their tokens are reported as unpriced in the pane until rates names them.

Known limits

  • Week and day boundaries use the local time of the process running Claude Code.
  • The store is one JSON file shared by every Claude Code process on the machine. Two sessions writing at the same moment have not been tested for lost updates, and two sessions can both show the same budget toast.
  • After an in-process /resume, the mod takes Claude Code's running cost at that moment as the new baseline. If Claude Code restores the resumed session's earlier cost only after that point, the earlier cost would be counted again. This has been reasoned from the API documentation and covered by tests, not yet observed in a live resume.
  • Spend from a subagent that finishes after the session's last turn is recorded when the session ends; a process that is killed outright loses it.
  • The keep-alive's timer lives in the running process: a computer that sleeps, a closed terminal or a reload of the mod drops it until the next turn arms it again.
  • A turn whose interval also holds other spend (a background subagent, managed rates) matches neither write rate and teaches nothing about the cache lifetime.

Development

The module is hooks/register.tsx. Date and summary logic is in hooks/ledger.ts, pricing in hooks/pricing.ts, the per-prompt, context and pace arithmetic in hooks/insights.ts, and the cache-lifetime, cold-cost and keep-alive rules in hooks/keepalive.ts; all four are free of engine calls so they can be tested directly.

claude plugin validate plugins/cost-ledger
claude plugin test plugins/cost-ledger

tsc -p plugins/cost-ledger type-checks it once Claude Code has loaded the mod from the folder (for example with claude --plugin-dir plugins/cost-ledger), which writes the API declarations to .claude-plugin/types/. That folder is regenerated on every load and is not committed.

License

MIT

Source 6 files
hooks/register.tsx 1223 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register } from 'claude-code'
3
4import type { Breakdown, Context, KeepAlive, RateLimit, ToolUse, Totals } from '../types'
5import {
6  addStepToTurn,
7  addToolResult,
8  budgetReachDay,
9  chargesAsUse,
10  chargeStep,
11  emptyLoop,
12  estimateTokens,
13  finishTurn,
14  monthPace,
15  startTurn,
16  toolLabel,
17  topTools,
18  turnsIn,
19  turnUsd,
20  weekOverWeek,
21} from './insights'
22import {
23  addSpend,
24  addTools,
25  addTurn,
26  addUsage,
27  applyTools,
28  applyTurn,
29  applyUsage,
30  budgetAlert,
31  cacheMinutesLeft,
32  dayKey,
33  daysIn,
34  exportCsv,
35  formatTokens,
36  formatUsd,
37  heatLevel,
38  mergeEntries,
39  monthView,
40  OLDEST_MONTH_OFFSET,
41  projectName,
42  pruneDays,
43  shouldArchive,
44  spendSince,
45  summarize,
46  sumMonth,
47  UNKNOWN_PROJECT,
48  weekStartKey,
49} from './ledger'
50import type { SessionEntry } from './ledger'
51import {
52  addBreakdown,
53  CATEGORIES,
54  hitRate,
55  priceUsage,
56  rateTable,
57  ratesFor,
58  totalUsd,
59  writeRate,
60} from './pricing'
61import type { CacheTtl, RateTable, Usage } from './pricing'
62import { checkPing, coldEstimate, impliedTtl, pingDelay, pingHit, TTL_MS } from './keepalive'
63import type { ColdEstimate, PricedRequest } from './keepalive'
64
65const PANE = 'cost-ledger'
66const SESSION_PREFIX = 'session:'
67const ARCHIVE_PREFIX = 'archive:'
68const LEARNED_TTL_KEY = 'learnedCacheTtl'
69const LEARNED_TTL_SOURCE_KEY = 'learnedCacheTtlSource'
70const SHARED_PREFIX_KEY = 'sharedPrefixTokens'
71const LEARNED_PRICING_KEY = 'learnedPricing'
72const UNPRICED_MODELS_KEY = 'unpricedModels'
73const PROBE_KEY = 'doctorProbe'
74const STORE_LIMIT_BYTES = 4 * 1024 * 1024
75const SHOWN_TURNS = 10
76const SHOWN_TOOLS = 8
77const BUDGET_PREFIX = 'budget:'
78const TICK_MS = 30_000
79const SHOWN_PROJECTS = 8
80const WEEKDAYS = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']
81const HEAT = ['', '#0e4429', '#006d32', '#26a641', '#39d353'] as const
82const RATE_LIMIT_NAMES: Record<string, string> = { five_hour: '5h', seven_day: '7d' }
83const CATEGORY_NAMES = { input: 'Input', output: 'Output', cacheWrite: 'Cache write', cacheRead: 'Cache read' }
84
85const totals = atom({ plugin: 'cost-ledger', key: 'totals' } as const, null)
86const lastUsd = atom({ plugin: 'cost-ledger', key: 'lastUsd' } as const, null)
87const monthOffset = atom({ plugin: 'cost-ledger', key: 'monthOffset' } as const, 0)
88const context = atom({ plugin: 'cost-ledger', key: 'context' } as const, null)
89const shadeBy = atom({ plugin: 'cost-ledger', key: 'shadeBy' } as const, 'total')
90const tick = atom({ plugin: 'cost-ledger', key: 'tick' } as const, 0)
91const activeTurn = atom({ plugin: 'cost-ledger', key: 'activeTurn' } as const, null)
92const turnPrompts = atom({ plugin: 'cost-ledger', key: 'turnPrompts' } as const, {})
93const loops = atom({ plugin: 'cost-ledger', key: 'loops' } as const, {})
94const NO_KEEP_ALIVE: KeepAlive = { override: null, idleSince: null, pings: 0, usd: 0, stopped: null }
95const keepAlive = atom({ plugin: 'cost-ledger', key: 'keepAlive' } as const, NO_KEEP_ALIVE)
96const sharedPrefix = atom({ plugin: 'cost-ledger', key: 'sharedPrefix' } as const, null)
97
98// Claude Code prices at list rates unless an administrator set managed rates,
99// so the cache lifetime it charged is read against list prices, never the
100// rates setting.
101const LIST_TABLE = rateTable('')
102
103// Short, tool-free and asking for one word, so a ping's output stays at a
104// handful of tokens.
105const PING_PROMPT =
106  'This is an automated prompt-cache keep-alive check, not a request from the user. ' +
107  'Do not use any tools. Reply with exactly: ok'
108
109type Settings = {
110  isSubscription: boolean
111  hasStatusLine: boolean
112  table: RateTable
113  hasCustomRates: boolean
114  ttlSetting: string
115  largeWriteTokens: number
116  contextNudgeTokens: number
117  budgets: { day: number; week: number; month: number }
118  expensiveTurnUsd: number
119  keepAlive: boolean
120  keepAliveMaxIdleMs: number
121  keepAliveMinTokens: number
122}
123
124function readSettings(options: PluginOptions): Settings {
125  const rates = typeof options.rates === 'string' ? options.rates : ''
126  return {
127    isSubscription: options.billing === 'subscription',
128    hasStatusLine: options.statusLine === true,
129    table: rateTable(rates),
130    hasCustomRates: rates.trim() !== '',
131    ttlSetting: typeof options.cacheTtl === 'string' ? options.cacheTtl : 'auto',
132    largeWriteTokens: typeof options.largeWriteTokens === 'number' ? options.largeWriteTokens : 0,
133    contextNudgeTokens: typeof options.contextNudgeTokens === 'number' ? options.contextNudgeTokens : 0,
134    budgets: {
135      day: typeof options.dailyBudget === 'number' ? options.dailyBudget : 0,
136      week: typeof options.weeklyBudget === 'number' ? options.weeklyBudget : 0,
137      month: typeof options.monthlyBudget === 'number' ? options.monthlyBudget : 0,
138    },
139    expensiveTurnUsd: typeof options.expensiveTurnUsd === 'number' ? options.expensiveTurnUsd : 0,
140    keepAlive: options.keepAlive === 'on',
141    keepAliveMaxIdleMs: (typeof options.keepAliveMaxIdleMinutes === 'number' ? options.keepAliveMaxIdleMinutes : 0) * 60_000,
142    keepAliveMinTokens: typeof options.keepAliveMinContextTokens === 'number' ? options.keepAliveMinContextTokens : 0,
143  }
144}
145
146async function loadEntries($: EngineInterface): Promise<[string, SessionEntry][]> {
147  const keys = (await $.store.keys()).filter(key => key.startsWith(SESSION_PREFIX) || key.startsWith(ARCHIVE_PREFIX))
148  return Promise.all(
149    keys.map(async key => [key, (await $.store.get(key)) as SessionEntry] as [string, SessionEntry]),
150  )
151}
152
153async function cacheTtl($: EngineInterface, settings: Settings): Promise<CacheTtl> {
154  if (settings.ttlSetting === '5m' || settings.ttlSetting === '1h') return settings.ttlSetting
155  const learned = await $.store.get(LEARNED_TTL_KEY)
156  return learned === '1h' ? '1h' : '5m'
157}
158
159function rateLimitText(limits: readonly RateLimit[]): string {
160  return limits.map(l => `${RATE_LIMIT_NAMES[l.kind] ?? l.kind} ${Math.round(l.percentUsed)}%`).join(' · ')
161}
162
163function perStepText(ctx: Context, settings: Settings): string {
164  const rates = ratesFor(settings.table, ctx.model)
165  return rates ? ` ≈${formatUsd((ctx.tokens * rates.cacheRead) / 1_000_000)}/step` : ''
166}
167
168function nudgeText(ctx: Context, settings: Settings): string {
169  return settings.contextNudgeTokens > 0 && ctx.tokens >= settings.contextNudgeTokens ? ', consider /compact' : ''
170}
171
172// What re-caching the context would cost now that it has gone cold, priced
173// at the rates in use; undefined for a model with no rate. The shared opening
174// is this session's, else the last one any session measured.
175async function coldCost($: EngineInterface, settings: Settings, ctx: Context, ttl: CacheTtl): Promise<ColdEstimate | undefined> {
176  const rates = ratesFor(settings.table, ctx.model)
177  if (rates === undefined) return undefined
178  const prefix = (await read($, sharedPrefix)) ?? Number((await $.store.get(SHARED_PREFIX_KEY)) ?? 0)
179  return coldEstimate(ctx.tokens, prefix, writeRate(rates, ttl))
180}
181
182// "≈$0.33–$0.57" when part of the context is likely still cached by other
183// sessions, else the one figure.
184function coldText(cold: ColdEstimate): string {
185  return cold.likelyTokens < cold.worstTokens
186    ? `≈${formatUsd(cold.likelyUsd)}–${formatUsd(cold.worstUsd)}`
187    : `≈${formatUsd(cold.worstUsd)}`
188}
189
190function cacheText(ctx: Context, ttl: CacheTtl, now: number, ka: KeepAlive, cold: ColdEstimate | undefined): string {
191  const left = cacheMinutesLeft(ctx.at, TTL_MS[ttl], now)
192  if (left > 0) {
193    const kept = ka.pings > 0 && ka.stopped === null ? ` (kept warm: ${ka.pings} ping${ka.pings === 1 ? '' : 's'} ${formatUsd(ka.usd)})` : ''
194    return ` · cache warm ${left}m${kept}`
195  }
196  return ` · cache cold${cold ? ` (re-cache ${coldText(cold)})` : ''}`
197}
198
199// The context segment of the status line and band; empty before the first
200// main-thread response of the session.
201async function contextLine($: EngineInterface, settings: Settings, ctx: Context | null): Promise<string> {
202  if (ctx === null || ctx.tokens === 0) return ''
203  const ttl = await cacheTtl($, settings)
204  const cache = cacheText(ctx, ttl, await $.clock.now(), await read($, keepAlive), await coldCost($, settings, ctx, ttl))
205  return ` · ctx ${formatTokens(ctx.tokens)}${perStepText(ctx, settings)}${cache}${nudgeText(ctx, settings)}`
206}
207
208function summaryLine(t: Totals, settings: Settings, contextPart: string): string {
209  const qualifier = settings.isSubscription ? ' (API-equiv.)' : ''
210  const costs = `${formatUsd(t.session)} session · ${formatUsd(t.week)} week · ${formatUsd(t.month)} month${qualifier}`
211  const limits = settings.isSubscription && t.rateLimits.length > 0 ? ` · ${rateLimitText(t.rateLimits)}` : ''
212  return costs + limits + contextPart
213}
214
215async function updateStatus($: EngineInterface, settings: Settings) {
216  if (!settings.hasStatusLine) {
217    $.ui.status(undefined)
218    return
219  }
220  const t = await read($, totals)
221  if (t === null) return
222  const ctx = await read($, context)
223  $.ui.status(summaryLine(t, settings, await contextLine($, settings, ctx)))
224}
225
226async function onTick($: EngineInterface, settings: Settings) {
227  const now = await $.clock.now()
228  await update($, tick, () => now)
229  await updateStatus($, settings)
230}
231
232async function checkBudgets($: EngineInterface, settings: Settings, t: Totals) {
233  const today = dayKey(await $.clock.now())
234  const periods = [
235    { name: 'Daily', key: `day:${today}`, spent: t.today, limit: settings.budgets.day },
236    { name: 'Weekly', key: `week:${t.weekStart}`, spent: t.week, limit: settings.budgets.week },
237    { name: 'Monthly', key: `month:${today.slice(0, 7)}`, spent: t.month, limit: settings.budgets.month },
238  ]
239  for (const period of periods) {
240    const storeKey = `${BUDGET_PREFIX}${period.key}:${period.limit}`
241    const announced = Number((await $.store.get(storeKey)) ?? 0)
242    const reached = budgetAlert(period.spent, period.limit, announced)
243    if (reached === null) continue
244
245    await $.store.set(storeKey, reached)
246    const verb = reached >= 1 ? 'reached' : `at ${Math.round(reached * 100)}%`
247    $.ui.toast(`${period.name} budget ${verb}: ${formatUsd(period.spent)} of ${formatUsd(period.limit)}.`, {
248      timeoutMs: 10_000,
249    })
250  }
251}
252
253async function pruneBudgetKeys($: EngineInterface, now: number) {
254  const today = dayKey(now)
255  const current = [`day:${today}:`, `week:${weekStartKey(now)}:`, `month:${today.slice(0, 7)}:`]
256  const isCurrent = (period: string) => current.some(prefix => period.startsWith(prefix))
257  for (const key of await $.store.keys()) {
258    if (key.startsWith(BUDGET_PREFIX) && !isCurrent(key.slice(BUDGET_PREFIX.length))) await $.store.delete(key)
259  }
260}
261
262async function writeExport($: EngineInterface): Promise<string> {
263  const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
264  if (home === undefined) return 'Could not find a home folder to write the export to.'
265
266  const csv = exportCsv((await loadEntries($)).map(([, entry]) => entry))
267  const path = `${home}/claude-costs/claude-costs-${dayKey(await $.clock.now())}.csv`
268  await $.fs.write(path, csv)
269  return `Wrote ${csv.trimEnd().split('\n').length - 1} rows to ${path}`
270}
271
272// Module scope on purpose: one notice per load of the mod is enough.
273let hasWarnedSaveFailure = false
274
275async function saveEntry($: EngineInterface, key: string, entry: SessionEntry): Promise<boolean> {
276  try {
277    await $.store.set(key, entry)
278    return true
279  } catch (error) {
280    if (!hasWarnedSaveFailure) {
281      hasWarnedSaveFailure = true
282      $.ui.toast(`cost-ledger could not save spend, so totals will fall behind: ${String(error)}`, {
283        timeoutMs: 15_000,
284      })
285    }
286    return false
287  }
288}
289
290// Sessions untouched for 60 days are folded into one archive entry per
291// project, and days past retention are dropped, which keeps the store far
292// below its 4 MiB limit however many sessions run.
293async function compactStore($: EngineInterface, now: number) {
294  for (const [key, entry] of await loadEntries($)) {
295    if (!key.startsWith(SESSION_PREFIX) || !shouldArchive(entry, now)) continue
296    const archiveKey = ARCHIVE_PREFIX + (entry.project ?? UNKNOWN_PROJECT)
297    const archive = (await $.store.get(archiveKey)) as SessionEntry | undefined
298    if (await saveEntry($, archiveKey, mergeEntries(archive, entry))) await $.store.delete(key)
299  }
300  for (const [key, entry] of await loadEntries($)) {
301    const pruned = pruneDays(entry, now)
302    const dayCount = (e: SessionEntry) =>
303      [e.days, e.cache, e.subagentCache].reduce((sum, days) => sum + Object.keys(days ?? {}).length, 0)
304    if (pruned === undefined) await $.store.delete(key)
305    else if (dayCount(pruned) !== dayCount(entry)) await saveEntry($, key, pruned)
306  }
307}
308
309async function rebaseline($: EngineInterface) {
310  const usage = await $.session.usage()
311  const usd = usage.cost?.usd ?? 0
312  await update($, lastUsd, () => usd)
313}
314
315async function refresh(
316  $: EngineInterface,
317  settings: Settings,
318  sessionUsd?: number,
319  rateLimits?: readonly RateLimit[],
320) {
321  const now = await $.clock.now()
322  const previous = await read($, totals)
323  const entries = (await loadEntries($)).map(([, entry]) => entry)
324  const next: Totals = {
325    session: sessionUsd ?? previous?.session ?? 0,
326    ...summarize(entries, now),
327    rateLimits: [...(rateLimits ?? previous?.rateLimits ?? [])],
328  }
329  await update($, totals, () => next)
330  await updateStatus($, settings)
331  await checkBudgets($, settings, next)
332}
333
334async function recordSpend($: EngineInterface, usd: number) {
335  const spent = spendSince(await read($, lastUsd), usd)
336  if (spent > 0) {
337    const key = SESSION_PREFIX + (await $.session.id())
338    const entry = (await $.store.get(key)) as SessionEntry | undefined
339    // The baseline moves only once the spend is saved, so a failed save is
340    // counted again by the next measurement instead of being lost.
341    if (!(await saveEntry($, key, addSpend(entry, await $.clock.now(), spent, await $.session.root())))) return
342  }
343  await update($, lastUsd, () => usd)
344}
345
346type Step = { turnId: string; agentId?: string; startedAt: number }
347
348async function recordStep($: EngineInterface, settings: Settings, usage: Usage & { model: string }, step: Step) {
349  const isMainThread = step.agentId === undefined
350  const ttl = await cacheTtl($, settings)
351  const rates = ratesFor(settings.table, usage.model)
352  const priced = priceUsage(usage, rates, ttl)
353  if (rates === undefined) await noteUnpricedModel($, usage.model)
354
355  const measured = turnCosts.get(step.turnId)
356  if (measured !== undefined) {
357    const listRates = ratesFor(LIST_TABLE, usage.model)
358    if (listRates === undefined) measured.isSpoiled = true
359    else measured.requests.push({ usage, rates: listRates })
360  }
361
362  const loopId = step.agentId ?? 'main'
363  const loopsNow = await read($, loops)
364  const charged = chargeStep(
365    loopsNow[loopId] ?? emptyLoop(),
366    (rates?.cacheRead ?? 0) / 1_000_000,
367    (rates ? writeRate(rates, ttl) : 0) / 1_000_000,
368  )
369  await update($, loops, all => ({ ...all, [loopId]: charged.loop }))
370  const toolCosts = chargesAsUse(charged.charges)
371
372  const now = await $.clock.now()
373  const project = await $.session.root()
374  const key = SESSION_PREFIX + (await $.session.id())
375  const entry = (await $.store.get(key)) as SessionEntry | undefined
376  await saveEntry($, key, addTools(addUsage(entry, now, priced, project, !isMainThread), now, toolCosts))
377  await update($, totals, t => (t === null ? t : applyTools(t, now, toolCosts)))
378  await addToActiveTurn($, step, priced, isMainThread, now)
379  await update($, totals, t => (t === null ? t : applyUsage(t, now, priced, project, !isMainThread)))
380
381  if (isMainThread) {
382    const previous = await read($, context)
383    const tokens =
384      usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens + usage.output_tokens
385    // A conversation's first request, and the first after its cache went
386    // cold, reads from the cache only the opening other sessions keep warm.
387    if (previous === null || step.startedAt - previous.at > TTL_MS[ttl]) await noteSharedPrefix($, usage.cache_read_input_tokens)
388    await update($, context, () => ({ tokens, model: usage.model, at: step.startedAt, tail: usage.output_tokens }))
389    // A real request ends any idle stretch, and with it a stop the last one caused.
390    await update($, keepAlive, ka => ({ ...ka, idleSince: step.startedAt, stopped: null }))
391  }
392
393  const written = usage.cache_creation_input_tokens
394  if (settings.largeWriteTokens > 0 && written >= settings.largeWriteTokens) {
395    const cost = rates ? `≈ ${formatUsd(priced.usd.cacheWrite)}` : '(no rate for this model)'
396    $.ui.toast(`One request wrote ${formatTokens(written)} tokens to the prompt cache ${cost} on ${usage.model}.`, {
397      timeoutMs: 8000,
398    })
399  }
400
401  await updateStatus($, settings)
402}
403
404async function noteUnpricedModel($: EngineInterface, model: string) {
405  const seen = ((await $.store.get(UNPRICED_MODELS_KEY)) as string[] | undefined) ?? []
406  if (!seen.includes(model)) await $.store.set(UNPRICED_MODELS_KEY, [...seen, model].slice(-20))
407}
408
409// A turn becomes the prompt's record at its first main-thread request, since
410// turn.start does not say which loop it belongs to. Subagent requests made
411// while it runs are charged to it.
412async function addToActiveTurn(
413  $: EngineInterface,
414  step: Step,
415  priced: Breakdown,
416  isMainThread: boolean,
417  now: number,
418) {
419  const current = await read($, activeTurn)
420  if (isMainThread && current?.turnId !== step.turnId) {
421    const prompt = (await read($, turnPrompts))[step.turnId]
422    const started = startTurn(step.turnId, prompt?.text || '(continuation)', prompt?.at ?? now)
423    await update($, activeTurn, () => addStepToTurn(started, priced, false))
424    return
425  }
426  if (current !== null) await update($, activeTurn, turn => (turn === null ? turn : addStepToTurn(turn, priced, !isMainThread)))
427}
428
429async function finishActiveTurn($: EngineInterface, settings: Settings, turnId: string) {
430  const turn = await read($, activeTurn)
431  await update($, turnPrompts, prompts => {
432    const { [turnId]: _done, ...rest } = prompts
433    return rest
434  })
435  if (turn === null || turn.turnId !== turnId) return
436  await update($, activeTurn, () => null)
437
438  const now = await $.clock.now()
439  const record = finishTurn(turn, await $.session.root())
440  const key = SESSION_PREFIX + (await $.session.id())
441  const entry = (await $.store.get(key)) as SessionEntry | undefined
442  await saveEntry($, key, addTurn(entry, now, record))
443  await update($, totals, t => (t === null ? t : applyTurn(t, record)))
444
445  const usd = turnUsd(record)
446  if (settings.expensiveTurnUsd > 0 && usd >= settings.expensiveTurnUsd) {
447    const detail = `${record.steps} requests${record.subagentSteps > 0 ? ` + ${record.subagentSteps} by subagents` : ''}`
448    $.ui.toast(`That prompt cost ≈ ${formatUsd(usd)} (${detail}): “${record.prompt}”`, { timeoutMs: 10_000 })
449  }
450}
451
452async function recordToolResult($: EngineInterface, tool: string, agentId: string | undefined, text: string) {
453  const tokens = estimateTokens(text)
454  const loopId = agentId ?? 'main'
455  await update($, loops, all => ({ ...all, [loopId]: addToolResult(all[loopId], tool, tokens) }))
456
457  const now = await $.clock.now()
458  const use: Record<string, ToolUse> = { [tool]: { calls: 1, tokens, writeUsd: 0, rereadUsd: 0 } }
459  const key = SESSION_PREFIX + (await $.session.id())
460  const entry = (await $.store.get(key)) as SessionEntry | undefined
461  await saveEntry($, key, addTools(entry, now, use))
462  await update($, totals, t => (t === null ? t : applyTools(t, now, use)))
463}
464
465const localStamp = (ms: number) => {
466  const d = new Date(ms)
467  const pad = (n: number) => String(n).padStart(2, '0')
468  const offset = -d.getTimezoneOffset()
469  const sign = offset >= 0 ? '+' : '-'
470  const hhmm = `${pad(Math.floor(Math.abs(offset) / 60))}:${pad(Math.abs(offset) % 60)}`
471  return `${dayKey(ms)} ${pad(d.getHours())}:${pad(d.getMinutes())} ${sign}${hhmm}`
472}
473
474async function hostLocalTime($: EngineInterface): Promise<string | undefined> {
475  const isWindows = (await $.env.get('OS')) === 'Windows_NT'
476  const argv = isWindows
477    ? ['powershell', '-NoProfile', '-Command', "Get-Date -Format 'yyyy-MM-dd HH:mm zzz'"]
478    : ['date', '+%Y-%m-%d %H:%M %z']
479  try {
480    const { exitCode, stdout } = await $.process.run(argv, { timeoutMs: 10_000 })
481    return exitCode === 0 ? stdout.trim().replace(/([+-]\d{2})(\d{2})$/, '$1:$2') : undefined
482  } catch {
483    return undefined
484  }
485}
486
487async function readOwnStoreFiles($: EngineInterface): Promise<{ path: string; text: string }[] | undefined> {
488  const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
489  const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? (home && `${home}/.claude`)
490  if (!configDir) return undefined
491  const dir = `${configDir}/plugins/store`
492  try {
493    const files = (await $.fs.list(dir)).filter(f => f.kind === 'file' && f.name.startsWith(`${$.plugin.name}_`))
494    return Promise.all(files.map(async f => ({ path: `${dir}/${f.name}`, text: (await $.fs.read(`${dir}/${f.name}`)) as string })))
495  } catch {
496    return undefined
497  }
498}
499
500function storeKeysOf(text: string): string[] | undefined {
501  try {
502    const parsed: unknown = JSON.parse(text)
503    return typeof parsed === 'object' && parsed !== null ? Object.keys(parsed).sort() : undefined
504  } catch {
505    return undefined
506  }
507}
508
509// Each check reports what it saw; nothing here changes the ledger except the
510// probe key, which is removed again.
511async function runDoctor($: EngineInterface, settings: Settings): Promise<string> {
512  const lines = ['cost-ledger self-check', '']
513  const say = (isOk: boolean | null, label: string, detail: string) =>
514    lines.push(`${isOk === null ? 'ℹ' : isOk ? '✓' : '⚠'} ${label}: ${detail}`)
515  const now = await $.clock.now()
516
517  const mine = localStamp(now)
518  const host = await hostLocalTime($)
519  if (host === undefined) say(null, 'Time zone', `the mod sees ${mine}; the host's clock could not be read to compare`)
520  else {
521    const isSame = host.slice(0, 13) === mine.slice(0, 13) && host.slice(-6) === mine.slice(-6)
522    say(isSame, 'Time zone', isSame ? `day boundaries follow local time (${mine})` : `the mod sees ${mine} but the host says ${host}, so days are split at the wrong hour`)
523  }
524
525  const probe = `${now}-${Math.random().toString(36).slice(2)}`
526  await $.store.set(PROBE_KEY, probe)
527  try {
528    const files = await readOwnStoreFiles($)
529    const own = files?.find(f => f.text.includes(probe))
530    const ownKeys = own && storeKeysOf(own.text)
531    if (own === undefined || ownKeys === undefined) {
532      say(false, 'Store file', 'a write could not be found on disk, so the checks that compare the file were skipped')
533    } else {
534      say(true, 'Store file', `writes reach disk at once (${own.path})`)
535      const inView = [...(await $.store.keys())].sort()
536      const isSameView = ownKeys.join('\n') === inView.join('\n')
537      say(
538        isSameView,
539        'Other sessions',
540        isSameView
541          ? 'this session sees exactly what is on disk, so writes from other sessions are not being overwritten'
542          : `this session sees ${inView.length} keys and the file has ${ownKeys.length}; another session's writes may be lost`,
543      )
544      const percent = Math.round((own.text.length / STORE_LIMIT_BYTES) * 100)
545      say(percent < 75, 'Store size', `${Math.round(own.text.length / 1024)} KiB, ${percent}% of the 4 MiB limit`)
546    }
547    for (const other of files?.filter(f => f !== own) ?? []) {
548      const sessions = storeKeysOf(other.text)?.filter(k => k.startsWith(SESSION_PREFIX)).length
549      say(
550        null,
551        'Another install',
552        sessions === undefined
553          ? `${other.path} could not be read`
554          : `${other.path} holds ${sessions} sessions recorded by a differently installed copy; they are not in these totals`,
555      )
556    }
557  } finally {
558    await $.store.delete(PROBE_KEY)
559  }
560
561  const pricing = await $.store.get(LEARNED_PRICING_KEY)
562  say(
563    null,
564    'Claude Code pricing',
565    pricing === 'configured'
566      ? "your organisation's managed modelPricing, so the totals follow your rates"
567      : pricing === 'catalog'
568        ? 'Anthropic list prices; on Bedrock the totals may differ from your bill'
569        : 'not reported yet; Claude Code reports it when you switch models with /model',
570  )
571
572  const learnedTtl = await $.store.get(LEARNED_TTL_KEY)
573  const learnedFrom = (await $.store.get(LEARNED_TTL_SOURCE_KEY)) === 'pricing' ? "from Claude Code's pricing of a turn" : 'reported by Claude Code'
574  say(
575    null,
576    'Cache lifetime',
577    `using ${await cacheTtl($, settings)} (setting: ${settings.ttlSetting}; ${typeof learnedTtl === 'string' ? `${learnedFrom}: ${learnedTtl}` : 'not learned yet'})`,
578  )
579  const prefix = await $.store.get(SHARED_PREFIX_KEY)
580  say(
581    null,
582    'Shared opening',
583    typeof prefix === 'number'
584      ? `${formatTokens(prefix)} tokens stay cached between sessions; cold-resume estimates leave them out of the likely cost`
585      : 'not measured yet; it is read from the first request of a new conversation',
586  )
587  const ka = await read($, keepAlive)
588  say(
589    null,
590    'Keep-alive',
591    `${(await isKeepAliveOn($, settings)) ? 'on' : 'off'}${ka.override === null ? '' : ' for this session'}; ${ka.pings} ping${ka.pings === 1 ? '' : 's'} this session${ka.stopped ? `, stopped: ${ka.stopped}` : ''}`,
592  )
593
594  const usd = (await $.session.usage()).cost?.usd ?? 0
595  const recorded = await read($, lastUsd)
596  if (recorded === null) say(false, 'Baseline', 'not set; spend is recorded from the next measurement')
597  else if (recorded > usd + 0.005) say(false, 'Baseline', `recorded up to ${formatUsd(recorded)}, above the session's ${formatUsd(usd)}`)
598  else say(true, 'Baseline', `session at ${formatUsd(usd)}, recorded up to ${formatUsd(recorded)}${usd - recorded >= 0.005 ? '; the rest is recorded after the next turn' : ''}`)
599
600  if (settings.table.error) say(false, 'Rates', settings.table.error)
601  const unpriced = ((await $.store.get(UNPRICED_MODELS_KEY)) as string[] | undefined) ?? []
602  say(unpriced.length === 0, 'Models', unpriced.length === 0 ? 'every model seen has a rate' : `no rate for ${unpriced.join(', ')}; add them to the rates setting`)
603
604  say(null, 'Resume', 'cannot be checked from here: compare /costs before and after a /resume of a session with known spend')
605  return lines.join('\n')
606}
607
608async function noteSharedPrefix($: EngineInterface, tokens: number) {
609  if (tokens <= 0) return
610  await update($, sharedPrefix, () => tokens)
611  if ((await $.store.get(SHARED_PREFIX_KEY)) !== tokens) await $.store.set(SHARED_PREFIX_KEY, tokens)
612}
613
614// Module scope: the keep-alive timer, the running turn and the turns being
615// measured belong to this load of the mod. A reload starts them over, and the
616// next turn re-arms the timer.
617let keepAliveTimer: { cancel: () => void } | null = null
618let runningTurn: string | null = null
619let warnedColdAt: number | null = null
620const turnCosts = new Map<string, { startUsd: number; requests: PricedRequest[]; isSpoiled: boolean }>()
621
622// Steps of parallel subagents finish concurrently, and a keep-alive ping can
623// land between them; each read-modify-write of this session's store entry
624// must see the previous one's result.
625let queue: Promise<void> = Promise.resolve()
626function serially(task: () => Promise<void>) {
627  const run = queue.then(task)
628  queue = run.catch(() => undefined)
629  return run
630}
631
632function resetModuleState() {
633  keepAliveTimer?.cancel()
634  keepAliveTimer = null
635  runningTurn = null
636  warnedColdAt = null
637  turnCosts.clear()
638  queue = Promise.resolve()
639}
640
641function cancelKeepAlive() {
642  keepAliveTimer?.cancel()
643  keepAliveTimer = null
644}
645
646async function startTurnCost($: EngineInterface, turnId: string) {
647  const usd = (await $.session.usage()).cost?.usd
648  if (usd !== undefined) turnCosts.set(turnId, { startUsd: usd, requests: [], isSpoiled: false })
649}
650
651// The cache lifetime Claude Code charged, read from what one turn moved its
652// running total by. Skipped under managed rates, which list prices cannot
653// match, and for any turn that does not add up either way.
654async function learnTtlFromTurn($: EngineInterface, turnId: string) {
655  const measured = turnCosts.get(turnId)
656  turnCosts.delete(turnId)
657  if (measured === undefined || measured.isSpoiled) return
658  if ((await $.store.get(LEARNED_PRICING_KEY)) === 'configured') return
659  const usd = (await $.session.usage()).cost?.usd
660  if (usd === undefined) return
661  const ttl = impliedTtl(usd - measured.startUsd, measured.requests)
662  if (ttl === undefined) return
663  if ((await $.store.get(LEARNED_TTL_KEY)) !== ttl) await $.store.set(LEARNED_TTL_KEY, ttl)
664  if ((await $.store.get(LEARNED_TTL_SOURCE_KEY)) !== 'pricing') await $.store.set(LEARNED_TTL_SOURCE_KEY, 'pricing')
665}
666
667async function isKeepAliveOn($: EngineInterface, settings: Settings): Promise<boolean> {
668  const { override } = await read($, keepAlive)
669  return override === null ? settings.keepAlive : override === 'on'
670}
671
672// One timer at a time, due nine tenths of a cache lifetime after the cache
673// was last used.
674async function armKeepAlive($: EngineInterface, settings: Settings) {
675  cancelKeepAlive()
676  if (!(await isKeepAliveOn($, settings))) return
677  const ctx = await read($, context)
678  if (ctx === null || ctx.tokens === 0) return
679  const delay = pingDelay(ctx.at, await cacheTtl($, settings), await $.clock.now())
680  keepAliveTimer = $.clock.after(delay, () => void keepAlivePing($, settings))
681}
682
683async function stopKeepAlive($: EngineInterface, settings: Settings, ctx: Context, why: string) {
684  await update($, keepAlive, ka => ({ ...ka, stopped: why }))
685  const cold = await coldCost($, settings, ctx, await cacheTtl($, settings))
686  const cost = cold ? ` ${coldText(cold)}` : ''
687  $.ui.toast(`Keep-alive stopped (${why}). Once the cache goes cold, the next prompt re-caches it${cost}.`, {
688    timeoutMs: 10_000,
689  })
690}
691
692// One ping: the session's own transcript sent again through $.model.fork,
693// which reads it from the cache and so renews the cache's lifetime. Its cost
694// is already in Claude Code's running total, so it is added to the category
695// breakdown only. A fork's own writes are charged at the five-minute rate.
696async function keepAlivePing($: EngineInterface, settings: Settings) {
697  keepAliveTimer = null
698  const ctx = await read($, context)
699  const ka = await read($, keepAlive)
700  const now = await $.clock.now()
701  const check = checkPing({
702    isOn: await isKeepAliveOn($, settings),
703    isTurnRunning: runningTurn !== null,
704    contextTokens: ctx?.tokens ?? null,
705    minContextTokens: settings.keepAliveMinTokens,
706    idleSince: ka.idleSince ?? ctx?.at ?? now,
707    maxIdleMs: settings.keepAliveMaxIdleMs,
708    now,
709  })
710  if (ctx === null || !check.isDue) {
711    if (ctx !== null && !check.isDue && check.why === 'idle too long') {
712      await stopKeepAlive($, settings, ctx, `idle ${Math.round((now - (ka.idleSince ?? ctx.at)) / 60_000)} min`)
713    }
714    return
715  }
716
717  const result = await $.model.fork({ prompt: PING_PROMPT })
718  if (!result.isAnswered && result.reason === 'nothing-to-fork') return
719  await serially(() => recordPing($, settings, result.usage, ctx.model))
720  if (!result.isAnswered && result.reason !== 'empty-reply') {
721    await stopKeepAlive($, settings, ctx, result.reason === 'api-error' ? `ping failed: ${result.error}` : 'ping interrupted')
722    return
723  }
724  if (!pingHit(result.usage, ctx.tail)) {
725    await stopKeepAlive($, settings, ctx, 'a ping found the cache already cold')
726    return
727  }
728  // The cache's lifetime runs from the ping's start. A turn that began while
729  // the ping ran has moved the context on already and re-arms on its own.
730  await update($, context, current => (current !== null && current.at < now ? { ...current, at: now } : current))
731  if (runningTurn === null) await armKeepAlive($, settings)
732  await updateStatus($, settings)
733}
734
735async function recordPing($: EngineInterface, settings: Settings, usage: Usage, model: string) {
736  const priced = priceUsage(usage, ratesFor(settings.table, model), '5m')
737  const now = await $.clock.now()
738  const project = await $.session.root()
739  const key = SESSION_PREFIX + (await $.session.id())
740  const entry = (await $.store.get(key)) as SessionEntry | undefined
741  await saveEntry($, key, addUsage(entry, now, priced, project, false))
742  await update($, totals, t => (t === null ? t : applyUsage(t, now, priced, project, false)))
743  await update($, keepAlive, ka => ({ ...ka, pings: ka.pings + 1, usd: ka.usd + totalUsd(priced) }))
744}
745
746async function warnIfCacheExpired($: EngineInterface, settings: Settings) {
747  const ctx = await read($, context)
748  if (ctx === null || ctx.tokens === 0 || warnedColdAt === ctx.at) return
749
750  const ttl = await cacheTtl($, settings)
751  const idleMs = (await $.clock.now()) - ctx.at
752  if (idleMs <= TTL_MS[ttl]) return
753
754  warnedColdAt = ctx.at
755  const cold = await coldCost($, settings, ctx, ttl)
756  $.ui.toast(
757    `Prompt cache has likely expired (idle ${Math.round(idleMs / 60_000)} min, ${ttl} cache): ` +
758      `this prompt re-writes ${cold ? `${coldTokens(cold)} tokens ${coldText(cold)}` : `~${formatTokens(ctx.tokens)} tokens`}.`,
759    { timeoutMs: 10_000 },
760  )
761}
762
763// /costs keepalive [on|off]: the choice holds for this session and overrides
764// the keepAlive setting; with no argument, what the keep-alive is doing.
765async function keepAliveCommand($: EngineInterface, settings: Settings, arg: string): Promise<string> {
766  if (arg === 'on' || arg === 'off') {
767    const override: 'on' | 'off' = arg
768    await update($, keepAlive, ka => ({ ...ka, override, stopped: null }))
769    if (override === 'off') cancelKeepAlive()
770    else if (runningTurn === null) await armKeepAlive($, settings)
771  } else if (arg !== '') {
772    return 'Usage: /costs keepalive [on|off]'
773  }
774  const ka = await read($, keepAlive)
775  const isOn = await isKeepAliveOn($, settings)
776  const ttl = await cacheTtl($, settings)
777  const source = ka.override === null ? 'the keepAlive setting' : '/costs keepalive for this session'
778  const lines = [`Keep-alive is ${isOn ? 'on' : 'off'} (${source}); cache lifetime ${ttl}.`]
779  if (ka.pings > 0) lines.push(`${ka.pings} ping${ka.pings === 1 ? '' : 's'} this session, ≈${formatUsd(ka.usd)}.`)
780  if (ka.stopped !== null) lines.push(`Stopped: ${ka.stopped}. It starts again after your next prompt.`)
781  const ctx = await read($, context)
782  if (isOn && ka.stopped === null && ctx !== null && ctx.tokens > 0) {
783    if (ctx.tokens < settings.keepAliveMinTokens) {
784      lines.push(`The context (${formatTokens(ctx.tokens)}) is below keepAliveMinContextTokens, so no pings are sent.`)
785    } else if (runningTurn === null) {
786      lines.push(`Next ping in ${Math.ceil(pingDelay(ctx.at, ttl, await $.clock.now()) / 60_000)} min.`)
787    }
788  }
789  return lines.join('\n')
790}
791
792function coldTokens(cold: ColdEstimate): string {
793  return cold.likelyTokens < cold.worstTokens
794    ? `~${formatTokens(cold.likelyTokens)}–${formatTokens(cold.worstTokens)}`
795    : `~${formatTokens(cold.worstTokens)}`
796}
797
798export const register: Register = (on, options) => {
799  const settings = readSettings(options)
800  const { isSubscription } = settings
801  resetModuleState()
802
803  on('session.start', async ($, e, next) => {
804    await $.command.register({
805      name: 'costs',
806      description:
807        'Show session, weekly and monthly Claude Code costs; "export" writes a CSV, "doctor" checks the setup, "keepalive on|off" keeps this session\'s prompt cache warm',
808      argumentHint: '[export|doctor|keepalive on|off]',
809    })
810    if (settings.table.error) $.ui.toast(`cost-ledger: ${settings.table.error}`)
811
812    const now = await $.clock.now()
813    await compactStore($, now)
814    await pruneBudgetKeys($, now)
815    $.clock.every(TICK_MS, () => void onTick($, settings))
816
817    const usage = await $.session.usage()
818    const usd = usage.cost?.usd ?? 0
819    // A resumed session can start with spend that an earlier run already
820    // recorded; only growth from here on is new. A reload keeps the baseline.
821    if ((await read($, lastUsd)) === null) await update($, lastUsd, () => usd)
822    await refresh($, settings, usd, usage.rateLimits)
823
824    return next(e)
825  })
826
827  on('classic.SessionStart', async ($, e, next) => {
828    // session.start fires once per process, but /clear, /resume and a fork
829    // switch sessions inside it: the new session's running total starts from
830    // whatever it carries, and none of that is new spend.
831    if (e.source === 'clear' || e.source === 'resume' || e.source === 'fork') await serially(() => rebaseline($))
832    if (e.source === 'clear' || e.source === 'compact') {
833      await update($, context, () => null)
834      await update($, loops, () => ({}))
835    }
836    if (e.source === 'clear') {
837      await update($, activeTurn, () => null)
838      await update($, turnPrompts, () => ({}))
839    }
840    // The keep-alive follows the conversation: a new one starts with no pings,
841    // and is armed by its first turn. A /costs keepalive choice stays.
842    if (e.source !== 'startup') {
843      cancelKeepAlive()
844      await update($, keepAlive, ka => ({ ...NO_KEEP_ALIVE, override: ka.override }))
845    }
846
847    // A resumed transcript's cache is as old as its last response, so the
848    // idle warning on the first prompt covers resumes too; when Claude Code
849    // says it has likely expired, the cost is shown now, before any prompt.
850    if (e.context_tokens && e.seconds_since_last_response !== undefined && e.model) {
851      const at = (await $.clock.now()) - e.seconds_since_last_response * 1000
852      const ctx: Context = { tokens: e.context_tokens, model: e.model, at }
853      await update($, context, () => ctx)
854      if (e.prompt_cache_likely_expired) {
855        warnedColdAt = at
856        const cold = await coldCost($, settings, ctx, await cacheTtl($, settings))
857        const idle = Math.round(e.seconds_since_last_response / 60)
858        $.ui.toast(
859          `This session's prompt cache has likely expired (idle ${idle} min): ` +
860            `the first prompt re-writes ${cold ? `${coldTokens(cold)} tokens ${coldText(cold)}` : `~${formatTokens(ctx.tokens)} tokens`}.`,
861          { timeoutMs: 10_000 },
862        )
863      }
864    }
865    return next(e)
866  })
867
868  on('classic.PreModelSwitch', async ($, e, next) => {
869    await $.store.set(LEARNED_TTL_KEY, e.cache_ttl)
870    await $.store.set(LEARNED_TTL_SOURCE_KEY, 'claude-code')
871    await $.store.set(LEARNED_PRICING_KEY, e.pricing)
872    if (e.prompt_cache_warm && e.context_tokens > 0) {
873      const rates = ratesFor(settings.table, e.to_model)
874      const usd = rates
875        ? (e.context_tokens * writeRate(rates, e.cache_ttl)) / 1_000_000
876        : e.estimated_cache_write_usd
877      $.ui.toast(
878        `Switching to ${e.to_model} gives up a warm prompt cache: ` +
879          `the next request re-writes ~${formatTokens(e.context_tokens)} tokens ≈ ${formatUsd(usd)}.`,
880        { timeoutMs: 10_000 },
881      )
882    }
883    return next(e)
884  })
885
886  on('classic.PostModelSwitch', async ($, e, next) => {
887    await $.store.set(LEARNED_TTL_KEY, e.cache_ttl)
888    await $.store.set(LEARNED_TTL_SOURCE_KEY, 'claude-code')
889    await $.store.set(LEARNED_PRICING_KEY, e.pricing)
890    return next(e)
891  })
892
893  // Spend after the last measurement (a background subagent, an exit right
894  // after a turn) is otherwise never recorded; a /clear or /resume ends the
895  // old session here before its successor's baseline is taken.
896  on('session.end', async ($, e, next) => {
897    cancelKeepAlive()
898    const usage = await $.session.usage()
899    const usd = usage.cost?.usd
900    if (usd !== undefined) await serially(() => recordSpend($, usd))
901    return next(e)
902  })
903
904  on('prompt.submit', async ($, e, next) => {
905    await warnIfCacheExpired($, settings)
906    return next(e)
907  })
908
909  on('turn.start', async ($, e, next) => {
910    runningTurn = e.turnId
911    cancelKeepAlive()
912    const at = await $.clock.now()
913    await update($, turnPrompts, prompts => ({ ...prompts, [e.turnId]: { text: e.text, at } }))
914    await startTurnCost($, e.turnId)
915    return next(e)
916  })
917
918  on('turn.step', async function* ($, e, next) {
919    const step = { turnId: e.turnId, agentId: e.agentId, startedAt: await $.clock.now() }
920    const result = yield* next(e)
921    const usage = result.usage
922    if (usage) await serially(() => recordStep($, settings, usage, step))
923    return result
924  })
925
926  on('turn.complete', async ($, e, next) => {
927    const result = await next(e)
928    const agentId = e.agentId
929    if (agentId === undefined) {
930      await serially(() => finishActiveTurn($, settings, e.turnId))
931      await serially(() => learnTtlFromTurn($, e.turnId))
932      runningTurn = null
933      await armKeepAlive($, settings)
934    } else
935      await update($, loops, all => {
936        const { [agentId]: _done, ...rest } = all
937        return rest
938      })
939    return result
940  })
941
942  on('tool.call', async ($, e, next) => {
943    const result = await next(e)
944    const text = result.text
945    if (typeof text === 'string' && text.length > 0) {
946      await serially(() => recordToolResult($, String(e.tool), e.agentId, text))
947    }
948    return result
949  })
950
951  on('session.measure', async ($, e, next) => {
952    const cost = e.cost
953    if (cost) await serially(() => recordSpend($, cost.usd))
954    await refresh($, settings, e.cost?.usd ?? 0, e.rateLimits)
955
956    return next(e)
957  })
958
959  on('command.run', { command: 'costs' }, async ($, e) => {
960    const args = e.args.trim()
961    if (args === 'export') return { text: await writeExport($) }
962    if (args === 'doctor') return { text: await runDoctor($, settings) }
963    if (args === 'keepalive' || args.startsWith('keepalive ')) return { text: await keepAliveCommand($, settings, args.slice(9).trim()) }
964
965    const usage = await $.session.usage()
966    await refresh($, settings, usage.cost?.usd ?? 0, usage.rateLimits)
967    await update($, monthOffset, () => 0)
968    await $.ui.open({ id: PANE, title: 'Costs' })
969
970    return { text: 'Costs pane opened.' }
971  })
972
973  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
974    const t = await read($, totals)
975    if (!options.band || e.props.hasSurvey || t === null) return next(e)
976
977    await read($, tick)
978    const { Text } = $.ui.resolve(e)
979    const contextPart = await contextLine($, settings, await read($, context))
980    return <Text dimColor>{summaryLine(t, settings, contextPart)}</Text>
981  })
982
983  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
984    const { Box, Button, Text } = $.ui.resolve(e)
985    const t = await read($, totals)
986    if (t === null) return <Text dimColor>No cost recorded yet.</Text>
987
988    const now = await $.clock.now()
989    const today = dayKey(now)
990    const offset = await read($, monthOffset)
991    const shading = await read($, shadeBy)
992    const ctx = await read($, context)
993    const ka = await read($, keepAlive)
994    await read($, tick)
995    const shown = monthView(now, offset)
996    const days = daysIn(t.days, shown.key)
997    const shownTotal = days.reduce((sum, [, usd]) => sum + usd, 0)
998    const cache = sumMonth<Breakdown>(t.cacheDays, shown.key, addBreakdown)
999    const cacheSum = cache ? totalUsd(cache) : 0
1000    const subagents = sumMonth<Breakdown>(t.subagentDays, shown.key, addBreakdown)
1001    const subagentSum = subagents ? totalUsd(subagents) : 0
1002    const projects = Object.entries(t.projectDays)
1003      .map(([root, projectDays]) => {
1004        const month = Object.entries(projectDays).filter(([day]) => day.startsWith(shown.key))
1005        return {
1006          name: projectName(root),
1007          usd: month.reduce((sum, [, d]) => sum + d.usd, 0),
1008          cacheWriteUsd: month.reduce((sum, [, d]) => sum + d.cacheWriteUsd, 0),
1009        }
1010      })
1011      .filter(p => p.usd > 0 || p.cacheWriteUsd > 0)
1012      .sort((a, b) => b.usd - a.usd)
1013    const ttl = await cacheTtl($, settings)
1014    const cold = ctx !== null && ctx.tokens > 0 ? await coldCost($, settings, ctx, ttl) : undefined
1015    const pace = monthPace(t.month, now)
1016    const reachDay = budgetReachDay(t.month, settings.budgets.month, now)
1017    const wow = weekOverWeek(t.days, now)
1018    const monthFrom = `${shown.key}-01`
1019    const monthTo = `${shown.key}-31`
1020    const expensive = turnsIn(t.turns, monthFrom, monthTo).slice(0, SHOWN_TURNS)
1021    const tools = topTools(t.toolDays, monthFrom, monthTo).slice(0, SHOWN_TOOLS)
1022
1023    const shadeValue = (day: string) =>
1024      shading === 'cacheWrite' ? (t.cacheDays[day]?.usd.cacheWrite ?? 0) : (t.days[day] ?? 0)
1025    const monthKeys = Object.keys({ ...t.days, ...t.cacheDays }).filter(day => day.startsWith(shown.key))
1026    const shadePeak = Math.max(0, ...monthKeys.map(shadeValue))
1027    const barPeak = Math.max(0, ...days.map(([, usd]) => usd))
1028    const barRoom = Math.max(4, (e.props.bodyColumns ?? 40) - 24)
1029
1030    const row = (label: string, usd: number, note = '', budget = 0) => (
1031      <Text>
1032        {label.padEnd(12)}
1033        {formatUsd(usd).padStart(10)}
1034        {budget > 0 && (
1035          <Text color={usd >= budget ? 'error' : usd >= budget * 0.8 ? 'warning' : undefined}>
1036            {` of ${formatUsd(budget)} (${Math.round((usd / budget) * 100)}%)`}
1037          </Text>
1038        )}
1039        <Text dimColor>{note}</Text>
1040      </Text>
1041    )
1042    const cell = (day: number | null) => {
1043      if (day === null) return <Text>{'   '}</Text>
1044      const key = `${shown.key}-${String(day).padStart(2, '0')}`
1045      const level = heatLevel(shadeValue(key), shadePeak)
1046      return (
1047        <Text>
1048          {' '}
1049          <Text
1050            backgroundColor={level > 0 ? HEAT[level] : undefined}
1051            color={level > 0 ? '#ffffff' : undefined}
1052            dimColor={level === 0}
1053            bold={key === today}
1054            underline={key === today}
1055          >
1056            {String(day).padStart(2)}
1057          </Text>
1058        </Text>
1059      )
1060    }
1061
1062    return (
1063      <Box flexDirection="column">
1064        {isSubscription && <Text dimColor>Figures are API-equivalent, not billed amounts.</Text>}
1065        {row('Session', t.session)}
1066        {row('Today', t.today, '', settings.budgets.day)}
1067        {row(
1068          'This week',
1069          t.week,
1070          wow.change === null
1071            ? `  since ${t.weekStart}`
1072            : `  ${wow.change >= 0 ? '+' : ''}${Math.round(wow.change * 100)}% vs this point last week`,
1073          settings.budgets.week,
1074        )}
1075        {row(
1076          'This month',
1077          t.month,
1078          `  on pace for ${formatUsd(pace)}${reachDay ? `, budget reached ~${reachDay}` : ''}`,
1079          settings.budgets.month,
1080        )}
1081        {isSubscription && t.rateLimits.length > 0 && <Text>Rate limits: {rateLimitText(t.rateLimits)}</Text>}
1082        <Text> </Text>
1083        <Box flexDirection="row">
1084          {offset > OLDEST_MONTH_OFFSET ? (
1085            <Button key="prev" label="◀" plain hotkey="p" onPress={() => update($, monthOffset, n => n - 1)} />
1086          ) : (
1087            <Text> </Text>
1088          )}
1089          <Text bold> {shown.name.padEnd(15)}</Text>
1090          {offset < 0 ? (
1091            <Button key="next" label="▶" plain hotkey="n" onPress={() => update($, monthOffset, n => n + 1)} />
1092          ) : (
1093            <Text> </Text>
1094          )}
1095        </Box>
1096        <Text dimColor>{WEEKDAYS.map(d => ` ${d}`).join('')}</Text>
1097        {shown.weeks.map(week => (
1098          <Text>{week.map(cell)}</Text>
1099        ))}
1100        <Text>
1101          <Text dimColor>{'less '}</Text>
1102          {HEAT.slice(1).map(color => (
1103            <Text backgroundColor={color}>{'  '}</Text>
1104          ))}
1105          <Text dimColor>{' more'}</Text>
1106          {'   '}
1107          {formatUsd(shownTotal)}
1108          <Text dimColor> total</Text>
1109        </Text>
1110        <Box flexDirection="row">
1111          <Text dimColor>Shade by </Text>
1112          <Button
1113            key="shade"
1114            label={shading === 'total' ? 'total spend' : 'cache writes'}
1115            plain
1116            hotkey="s"
1117            onPress={() => update($, shadeBy, s => (s === 'total' ? 'cacheWrite' : 'total'))}
1118          />
1119        </Box>
1120        <Text> </Text>
1121        <Text bold>
1122          Prompt cache, {shown.name}
1123          <Text dimColor> (estimated at {settings.hasCustomRates ? 'your rates' : 'list prices'})</Text>
1124        </Text>
1125        {cache === undefined ? (
1126          <Text dimColor>No requests recorded.</Text>
1127        ) : (
1128          <Box flexDirection="column">
1129            <Text dimColor>{'            '}{'tokens'.padStart(8)}{'cost'.padStart(11)}{'share'.padStart(7)}</Text>
1130            {CATEGORIES.map(c => (
1131              <Text>
1132                {CATEGORY_NAMES[c].padEnd(12)}
1133                {formatTokens(cache.tokens[c]).padStart(8)}
1134                {formatUsd(cache.usd[c]).padStart(11)}
1135                <Text dimColor>{`${cacheSum > 0 ? Math.round((cache.usd[c] / cacheSum) * 100) : 0}%`.padStart(7)}</Text>
1136              </Text>
1137            ))}
1138            {(cache.unpricedTokens ?? 0) > 0 && (
1139              <Text color="warning">
1140                {formatTokens(cache.unpricedTokens ?? 0)} tokens from models with no rate are not priced; add them to
1141                the rates setting
1142              </Text>
1143            )}
1144            <Text dimColor>
1145              Cache hit {Math.round(hitRate(cache) * 100)}% of prompt tokens
1146              {settings.hasCustomRates ? '; totals above use Claude Code’s own pricing' : ''}
1147            </Text>
1148            <Text>
1149              {'Subagents'.padEnd(12)}
1150              {formatUsd(subagentSum).padStart(19)}
1151              <Text dimColor>
1152                {`${cacheSum > 0 ? Math.round((subagentSum / cacheSum) * 100) : 0}%`.padStart(7)}
1153                {subagents ? `  incl. ${formatUsd(subagents.usd.cacheWrite)} cache writes` : ''}
1154              </Text>
1155            </Text>
1156          </Box>
1157        )}
1158        {ctx !== null && ctx.tokens > 0 && (
1159          <Text dimColor>
1160            Current context {formatTokens(ctx.tokens)} on {ctx.model}
1161            {perStepText(ctx, settings)}
1162            {cacheText(ctx, ttl, now, ka, cold)}
1163            {nudgeText(ctx, settings)}
1164          </Text>
1165        )}
1166        <Text> </Text>
1167        <Text bold>
1168          Most expensive prompts, {shown.name}
1169          <Text dimColor> (estimated, subagents included)</Text>
1170        </Text>
1171        {expensive.length === 0 && <Text dimColor>None recorded.</Text>}
1172        {expensive.map(turn => (
1173          <Text>
1174            {formatUsd(turnUsd(turn)).padStart(9)}{' '}
1175            <Text dimColor>{`${turn.steps}${turn.subagentSteps > 0 ? `+${turn.subagentSteps}` : ''} req `.padStart(10)}</Text>
1176            {turn.prompt.slice(0, Math.max(10, (e.props.bodyColumns ?? 60) - 22))}
1177          </Text>
1178        ))}
1179        <Text> </Text>
1180        <Text bold>
1181          What filled the context, {shown.name}
1182          <Text dimColor> (tool results, ≈ tokens)</Text>
1183        </Text>
1184        {tools.length === 0 && <Text dimColor>No tool results recorded.</Text>}
1185        {tools.length > 0 && (
1186          <Text dimColor>{'tool'.padEnd(22)}{'calls'.padStart(6)}{'tokens'.padStart(8)}{'write'.padStart(9)}{'re-read'.padStart(10)}</Text>
1187        )}
1188        {tools.map(([tool, use]) => (
1189          <Text>
1190            {toolLabel(tool).slice(0, 21).padEnd(22)}
1191            {String(use.calls).padStart(6)}
1192            {formatTokens(use.tokens).padStart(8)}
1193            {formatUsd(use.writeUsd).padStart(9)}
1194            {formatUsd(use.rereadUsd).padStart(10)}
1195          </Text>
1196        ))}
1197        <Text> </Text>
1198        <Text bold>By project, {shown.name}</Text>
1199        {projects.length === 0 && <Text dimColor>No spend recorded.</Text>}
1200        {projects.slice(0, SHOWN_PROJECTS).map(p => (
hooks/insights.ts 195 lines
1import { addBreakdown, emptyBreakdown, totalUsd } from './pricing'
2import type { ActiveTurn, Breakdown, LoopContext, ToolUse, TurnRecord } from '../types'
3
4const DAY_MS = 24 * 60 * 60 * 1000
5const PROMPT_CHARS = 80
6export const TURNS_PER_MONTH = 10
7
8const pad = (n: number) => String(n).padStart(2, '0')
9const localDay = (ms: number) => {
10  const d = new Date(ms)
11  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
12}
13
14// ---- Cost per prompt -------------------------------------------------------
15
16export function startTurn(turnId: string, text: string, now: number): ActiveTurn {
17  const prompt = text.replace(/\s+/g, ' ').trim()
18  return {
19    turnId,
20    prompt: prompt.length > PROMPT_CHARS ? `${prompt.slice(0, PROMPT_CHARS - 1)}…` : prompt,
21    at: now,
22    steps: 0,
23    subagentSteps: 0,
24    usage: emptyBreakdown(),
25    subagentUsage: emptyBreakdown(),
26  }
27}
28
29export function addStepToTurn(turn: ActiveTurn, usage: Breakdown, isSubagent: boolean): ActiveTurn {
30  return {
31    ...turn,
32    steps: turn.steps + (isSubagent ? 0 : 1),
33    subagentSteps: turn.subagentSteps + (isSubagent ? 1 : 0),
34    usage: addBreakdown(turn.usage, usage),
35    subagentUsage: isSubagent ? addBreakdown(turn.subagentUsage, usage) : turn.subagentUsage,
36  }
37}
38
39export function finishTurn(turn: ActiveTurn, project: string): TurnRecord {
40  const { turnId: _turnId, ...record } = turn
41  return { ...record, project }
42}
43
44export function turnUsd(turn: TurnRecord): number {
45  return totalUsd(turn.usage)
46}
47
48// Keeps the most expensive prompts of each month, so a month's top list
49// survives however many cheap prompts follow it.
50export function keepTopTurns(turns: readonly TurnRecord[]): TurnRecord[] {
51  const byMonth = new Map<string, TurnRecord[]>()
52  for (const turn of turns) {
53    const month = localDay(turn.at).slice(0, 7)
54    byMonth.set(month, [...(byMonth.get(month) ?? []), turn])
55  }
56  return [...byMonth.values()].flatMap(month =>
57    [...month].sort((a, b) => turnUsd(b) - turnUsd(a)).slice(0, TURNS_PER_MONTH),
58  )
59}
60
61export function turnsIn(turns: readonly TurnRecord[], fromDay: string, toDay: string): TurnRecord[] {
62  return turns
63    .filter(turn => {
64      const day = localDay(turn.at)
65      return day >= fromDay && day <= toDay
66    })
67    .sort((a, b) => turnUsd(b) - turnUsd(a))
68}
69
70// ---- What fills the context --------------------------------------------------
71
72// Tool results are measured in characters; four per token is the usual rough
73// ratio for English and code, so these figures are approximate by design.
74export function estimateTokens(text: string): number {
75  return Math.ceil(text.length / 4)
76}
77
78export function toolLabel(tool: string): string {
79  const mcp = /^mcp__(.+?)__(.+)$/.exec(tool)
80  return mcp ? `${mcp[1]}/${mcp[2]}` : tool
81}
82
83export function emptyLoop(): LoopContext {
84  return { pending: {}, resident: {} }
85}
86
87export function addToolResult(loop: LoopContext | undefined, tool: string, tokens: number): LoopContext {
88  const current = loop ?? emptyLoop()
89  return { ...current, pending: { ...current.pending, [tool]: (current.pending[tool] ?? 0) + tokens } }
90}
91
92export type ToolCharges = Record<string, { writeUsd: number; rereadUsd: number }>
93
94// One model request of a loop: results already cached are read again at the
95// read rate, and results added since the last request are written at the write
96// rate, after which they are cached too.
97export function chargeStep(
98  loop: LoopContext,
99  readPerToken: number,
100  writePerToken: number,
101): { loop: LoopContext; charges: ToolCharges } {
102  const charges: ToolCharges = {}
103  const charge = (tool: string) => (charges[tool] ??= { writeUsd: 0, rereadUsd: 0 })
104  for (const [tool, tokens] of Object.entries(loop.resident)) charge(tool).rereadUsd += tokens * readPerToken
105  const resident = { ...loop.resident }
106  for (const [tool, tokens] of Object.entries(loop.pending)) {
107    charge(tool).writeUsd += tokens * writePerToken
108    resident[tool] = (resident[tool] ?? 0) + tokens
109  }
110  return { loop: { pending: {}, resident }, charges }
111}
112
113const emptyToolUse = (): ToolUse => ({ calls: 0, tokens: 0, writeUsd: 0, rereadUsd: 0 })
114
115export function addToolUse(a: ToolUse | undefined, b: ToolUse): ToolUse {
116  const sum = a ?? emptyToolUse()
117  return {
118    calls: sum.calls + b.calls,
119    tokens: sum.tokens + b.tokens,
120    writeUsd: sum.writeUsd + b.writeUsd,
121    rereadUsd: sum.rereadUsd + b.rereadUsd,
122  }
123}
124
125export function mergeToolMaps(
126  a: Record<string, ToolUse> | undefined,
127  b: Record<string, ToolUse> | undefined,
128): Record<string, ToolUse> {
129  const merged = { ...a }
130  for (const [tool, use] of Object.entries(b ?? {})) merged[tool] = addToolUse(merged[tool], use)
131  return merged
132}
133
134export function chargesAsUse(charges: ToolCharges): Record<string, ToolUse> {
135  return Object.fromEntries(
136    Object.entries(charges).map(([tool, c]) => [tool, { ...emptyToolUse(), writeUsd: c.writeUsd, rereadUsd: c.rereadUsd }]),
137  )
138}
139
140export function topTools(
141  toolDays: Record<string, Record<string, ToolUse>>,
142  fromDay: string,
143  toDay: string,
144): [string, ToolUse][] {
145  let merged: Record<string, ToolUse> = {}
146  for (const [day, tools] of Object.entries(toolDays)) {
147    if (day >= fromDay && day <= toDay) merged = mergeToolMaps(merged, tools)
148  }
149  return Object.entries(merged).sort(([, a], [, b]) => b.writeUsd + b.rereadUsd - (a.writeUsd + a.rereadUsd))
150}
151
152// ---- Pace and week over week ------------------------------------------------
153
154export function monthBounds(now: number): { start: number; end: number; days: number } {
155  const d = new Date(now)
156  const start = new Date(d.getFullYear(), d.getMonth(), 1).getTime()
157  const end = new Date(d.getFullYear(), d.getMonth() + 1, 1).getTime()
158  return { start, end, days: Math.round((end - start) / DAY_MS) }
159}
160
161// Month-to-date spend extrapolated at its average daily rate; at least one
162// day has elapsed so a busy first morning does not project a fortune.
163export function monthPace(monthUsd: number, now: number): number {
164  const { start, days } = monthBounds(now)
165  const elapsed = Math.max(1, (now - start) / DAY_MS)
166  return (monthUsd / elapsed) * days
167}
168
169// The local day on which spend at the month's average daily rate reaches the
170// budget, or null when it is already reached or will not be this month.
171export function budgetReachDay(monthUsd: number, budget: number, now: number): string | null {
172  if (budget <= 0 || monthUsd >= budget || monthUsd <= 0) return null
173  const { start, end } = monthBounds(now)
174  const rate = monthUsd / Math.max(1, (now - start) / DAY_MS)
175  const reachAt = now + ((budget - monthUsd) / rate) * DAY_MS
176  return reachAt < end ? localDay(reachAt) : null
177}
178
179// This week so far against last week up to the same weekday, by local day.
180export function weekOverWeek(
181  days: Record<string, number>,
182  now: number,
183): { thisWeek: number; lastWeek: number; change: number | null } {
184  const d = new Date(now)
185  const sinceMonday = (d.getDay() + 6) % 7
186  const dayAt = (offset: number) => localDay(new Date(d.getFullYear(), d.getMonth(), d.getDate() + offset).getTime())
187  let thisWeek = 0
188  let lastWeek = 0
189  for (let i = -sinceMonday; i <= 0; i++) {
190    thisWeek += days[dayAt(i)] ?? 0
191    lastWeek += days[dayAt(i - 7)] ?? 0
192  }
193  return { thisWeek, lastWeek, change: lastWeek > 0 ? (thisWeek - lastWeek) / lastWeek : null }
194}
195
hooks/ledger.ts 334 lines
1import { keepTopTurns, mergeToolMaps } from './insights'
2import { addBreakdown, CATEGORIES, emptyBreakdown } from './pricing'
3import type { Breakdown, ProjectDay, ToolUse, Totals, TurnRecord } from '../types'
4
5export type SessionEntry = {
6  project?: string
7  days: Record<string, number>
8  cache?: Record<string, Breakdown>
9  subagentCache?: Record<string, Breakdown>
10  turns?: TurnRecord[]
11  tools?: Record<string, Record<string, ToolUse>>
12  updatedAt: number
13}
14
15export type Summary = {
16  today: number
17  week: number
18  month: number
19  weekStart: string
20  days: Record<string, number>
21  cacheDays: Record<string, Breakdown>
22  subagentDays: Record<string, Breakdown>
23  projectDays: Record<string, Record<string, ProjectDay>>
24  turns: TurnRecord[]
25  toolDays: Record<string, Record<string, ToolUse>>
26}
27
28export type MonthView = { key: string; name: string; weeks: (number | null)[][] }
29
30const DAY_MS = 24 * 60 * 60 * 1000
31const RETENTION_MS = 400 * DAY_MS
32const ARCHIVE_AFTER_MS = 60 * DAY_MS
33export const OLDEST_MONTH_OFFSET = -13
34export const UNKNOWN_PROJECT = '(unknown)'
35export const BUDGET_THRESHOLDS = [0.8, 1] as const
36
37const MONTH_NAMES = [
38  'January', 'February', 'March', 'April', 'May', 'June',
39  'July', 'August', 'September', 'October', 'November', 'December',
40]
41
42const pad = (n: number) => String(n).padStart(2, '0')
43
44export function dayKey(ms: number): string {
45  const d = new Date(ms)
46  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
47}
48
49export function weekStartKey(ms: number): string {
50  const d = new Date(ms)
51  const sinceMonday = (d.getDay() + 6) % 7
52  return dayKey(new Date(d.getFullYear(), d.getMonth(), d.getDate() - sinceMonday).getTime())
53}
54
55// The engine's figure is a running total that a /clear may reset to zero, so a
56// drop means a fresh total rather than a refund.
57export function spendSince(previous: number | null, usd: number): number {
58  if (previous === null || usd < previous) return usd
59  return usd - previous
60}
61
62export function addSpend(
63  entry: SessionEntry | undefined,
64  now: number,
65  usd: number,
66  project: string,
67): SessionEntry {
68  const day = dayKey(now)
69  const days = { ...entry?.days }
70  days[day] = (days[day] ?? 0) + usd
71  return { ...entry, project, days, updatedAt: now }
72}
73
74export function addUsage(
75  entry: SessionEntry | undefined,
76  now: number,
77  usage: Breakdown,
78  project: string,
79  isSubagent: boolean,
80): SessionEntry {
81  const day = dayKey(now)
82  const cache = { ...entry?.cache }
83  cache[day] = addBreakdown(cache[day], usage)
84  const subagentCache = { ...entry?.subagentCache }
85  if (isSubagent) subagentCache[day] = addBreakdown(subagentCache[day], usage)
86  return { days: {}, ...entry, project, cache, subagentCache, updatedAt: now }
87}
88
89export function addTurn(entry: SessionEntry | undefined, now: number, turn: TurnRecord): SessionEntry {
90  return { days: {}, ...entry, turns: keepTopTurns([...(entry?.turns ?? []), turn]), updatedAt: now }
91}
92
93export function addTools(entry: SessionEntry | undefined, now: number, tools: Record<string, ToolUse>): SessionEntry {
94  const day = dayKey(now)
95  const all = { ...entry?.tools }
96  all[day] = mergeToolMaps(all[day], tools)
97  return { days: {}, ...entry, tools: all, updatedAt: now }
98}
99
100export function shouldArchive(entry: SessionEntry, now: number): boolean {
101  return now - entry.updatedAt > ARCHIVE_AFTER_MS
102}
103
104function mergeDays<T>(a: Record<string, T> | undefined, b: Record<string, T> | undefined, add: (x: T, y: T) => T) {
105  const merged = { ...a }
106  for (const [day, value] of Object.entries(b ?? {})) {
107    const existing = merged[day]
108    merged[day] = existing === undefined ? value : add(existing, value)
109  }
110  return merged
111}
112
113// Folds a finished session into its project's archive entry, so the store
114// holds one entry per project for old history instead of one per session.
115export function mergeEntries(archive: SessionEntry | undefined, entry: SessionEntry): SessionEntry {
116  return {
117    project: entry.project ?? archive?.project,
118    days: mergeDays(archive?.days, entry.days, (x, y) => x + y),
119    cache: mergeDays(archive?.cache, entry.cache, addBreakdown),
120    subagentCache: mergeDays(archive?.subagentCache, entry.subagentCache, addBreakdown),
121    turns: keepTopTurns([...(archive?.turns ?? []), ...(entry.turns ?? [])]),
122    tools: mergeDays(archive?.tools, entry.tools, mergeToolMaps),
123    updatedAt: Math.max(archive?.updatedAt ?? 0, entry.updatedAt),
124  }
125}
126
127// Drops the days past retention; undefined once nothing is left.
128export function pruneDays(entry: SessionEntry, now: number): SessionEntry | undefined {
129  const cutoff = dayKey(now - RETENTION_MS)
130  const keep = <T>(days: Record<string, T> | undefined) =>
131    Object.fromEntries(Object.entries(days ?? {}).filter(([day]) => day >= cutoff))
132  const pruned = {
133    ...entry,
134    days: keep(entry.days),
135    cache: keep(entry.cache),
136    subagentCache: keep(entry.subagentCache),
137    tools: keep(entry.tools),
138    turns: (entry.turns ?? []).filter(turn => dayKey(turn.at) >= cutoff),
139  }
140  const isEmpty =
141    [pruned.days, pruned.cache, pruned.subagentCache, pruned.tools].every(d => Object.keys(d).length === 0) &&
142    pruned.turns.length === 0
143  return isEmpty ? undefined : pruned
144}
145
146// Adds one request's usage to the drawn totals in place of a full store scan,
147// which would run on every model response.
148export function applyUsage(t: Totals, now: number, usage: Breakdown, project: string, isSubagent: boolean): Totals {
149  const day = dayKey(now)
150  const projectDays = { ...t.projectDays[project] }
151  const projectDay = projectDays[day] ?? { usd: 0, cacheWriteUsd: 0 }
152  projectDays[day] = { ...projectDay, cacheWriteUsd: projectDay.cacheWriteUsd + usage.usd.cacheWrite }
153  return {
154    ...t,
155    cacheDays: { ...t.cacheDays, [day]: addBreakdown(t.cacheDays[day], usage) },
156    subagentDays: isSubagent ? { ...t.subagentDays, [day]: addBreakdown(t.subagentDays[day], usage) } : t.subagentDays,
157    projectDays: { ...t.projectDays, [project]: projectDays },
158  }
159}
160
161export function applyTurn(t: Totals, turn: TurnRecord): Totals {
162  return { ...t, turns: keepTopTurns([...t.turns, turn]) }
163}
164
165export function applyTools(t: Totals, now: number, tools: Record<string, ToolUse>): Totals {
166  const day = dayKey(now)
167  return { ...t, toolDays: { ...t.toolDays, [day]: mergeToolMaps(t.toolDays[day], tools) } }
168}
169
170export function summarize(entries: readonly SessionEntry[], now: number): Summary {
171  const today = dayKey(now)
172  const weekStart = weekStartKey(now)
173  const month = today.slice(0, 7)
174  const summary: Summary = {
175    today: 0,
176    week: 0,
177    month: 0,
178    weekStart,
179    days: {},
180    cacheDays: {},
181    subagentDays: {},
182    projectDays: {},
183    turns: [],
184    toolDays: {},
185  }
186  const turns: TurnRecord[] = []
187
188  for (const entry of entries) {
189    const projectDays = (summary.projectDays[entry.project ?? UNKNOWN_PROJECT] ??= {})
190    const projectDay = (day: string) => (projectDays[day] ??= { usd: 0, cacheWriteUsd: 0 })
191    for (const [day, usd] of Object.entries(entry.days)) {
192      if (day > today) continue
193      if (day === today) summary.today += usd
194      if (day >= weekStart) summary.week += usd
195      if (day.startsWith(month)) summary.month += usd
196      summary.days[day] = (summary.days[day] ?? 0) + usd
197      projectDay(day).usd += usd
198    }
199    for (const [day, usage] of Object.entries(entry.cache ?? {})) {
200      summary.cacheDays[day] = addBreakdown(summary.cacheDays[day], usage)
201      projectDay(day).cacheWriteUsd += usage.usd.cacheWrite
202    }
203    for (const [day, usage] of Object.entries(entry.subagentCache ?? {})) {
204      summary.subagentDays[day] = addBreakdown(summary.subagentDays[day], usage)
205    }
206    for (const [day, tools] of Object.entries(entry.tools ?? {})) {
207      summary.toolDays[day] = mergeToolMaps(summary.toolDays[day], tools)
208    }
209    turns.push(...(entry.turns ?? []))
210  }
211  summary.turns = keepTopTurns(turns)
212  return summary
213}
214
215export function formatUsd(usd: number): string {
216  return `$${usd.toFixed(2)}`
217}
218
219export function monthView(now: number, offset: number): MonthView {
220  const today = new Date(now)
221  const first = new Date(today.getFullYear(), today.getMonth() + offset, 1)
222  const year = first.getFullYear()
223  const month = first.getMonth()
224  const length = new Date(year, month + 1, 0).getDate()
225  const cells: (number | null)[] = Array((first.getDay() + 6) % 7).fill(null)
226  for (let day = 1; day <= length; day++) cells.push(day)
227  while (cells.length % 7 !== 0) cells.push(null)
228
229  const weeks: (number | null)[][] = []
230  for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i + 7))
231
232  const name = `${MONTH_NAMES[month]} ${year}`
233  return { key: `${year}-${pad(month + 1)}`, name, weeks }
234}
235
236export function daysIn(days: Record<string, number>, monthKey: string): [string, number][] {
237  return Object.entries(days)
238    .filter(([day]) => day.startsWith(monthKey))
239    .sort(([a], [b]) => a.localeCompare(b))
240}
241
242export function heatLevel(usd: number, peak: number): 0 | 1 | 2 | 3 | 4 {
243  if (usd <= 0 || peak <= 0) return 0
244  return Math.min(4, Math.max(1, Math.ceil((usd / peak) * 4))) as 1 | 2 | 3 | 4
245}
246
247export function formatTokens(tokens: number): string {
248  if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`
249  if (tokens >= 1_000) return `${Math.round(tokens / 1_000)}k`
250  return String(tokens)
251}
252
253export function projectName(root: string): string {
254  return root.split(/[\\/]/).filter(Boolean).at(-1) ?? root
255}
256
257export function sumMonth<T>(days: Record<string, T>, monthKey: string, add: (sum: T | undefined, day: T) => T) {
258  return Object.entries(days)
259    .filter(([day]) => day.startsWith(monthKey))
260    .reduce<T | undefined>((sum, [, value]) => add(sum, value), undefined)
261}
262
263// The highest threshold the spend has reached that has not been announced yet,
264// so 80% and 100% are each said once per period.
265export function budgetAlert(spent: number, limit: number, announced: number): number | null {
266  if (limit <= 0) return null
267  const reached = BUDGET_THRESHOLDS.filter(t => spent >= limit * t).at(-1)
268  return reached !== undefined && reached > announced ? reached : null
269}
270
271export function cacheMinutesLeft(lastRequestAt: number, ttlMs: number, now: number): number {
272  return Math.max(0, Math.ceil((lastRequestAt + ttlMs - now) / 60_000))
273}
274
275const CSV_HEADER = [
276  'date',
277  'project',
278  'total_usd',
279  ...CATEGORIES.map(c => `${c}_tokens`),
280  ...CATEGORIES.map(c => `${c}_usd_estimated`),
281  'subagent_usd_estimated',
282]
283
284const csvField = (value: string | number) => {
285  const text = String(value)
286  return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text
287}
288
289type CsvRow = { usd: number; usage: Breakdown; subagent: Breakdown }
290
291export function exportCsv(entries: readonly SessionEntry[]): string {
292  const byDay = new Map<string, Map<string, CsvRow>>()
293  const row = (day: string, project: string) => {
294    const projects = byDay.get(day) ?? new Map<string, CsvRow>()
295    byDay.set(day, projects)
296    const found = projects.get(project) ?? { usd: 0, usage: emptyBreakdown(), subagent: emptyBreakdown() }
297    projects.set(project, found)
298    return found
299  }
300
301  for (const entry of entries) {
302    const project = entry.project ?? UNKNOWN_PROJECT
303    for (const [day, usd] of Object.entries(entry.days)) row(day, project).usd += usd
304    for (const [day, usage] of Object.entries(entry.cache ?? {})) {
305      const r = row(day, project)
306      r.usage = addBreakdown(r.usage, usage)
307    }
308    for (const [day, usage] of Object.entries(entry.subagentCache ?? {})) {
309      const r = row(day, project)
310      r.subagent = addBreakdown(r.subagent, usage)
311    }
312  }
313
314  const lines: string[] = [CSV_HEADER.join(',')]
315  for (const day of [...byDay.keys()].sort()) {
316    const projects = byDay.get(day) ?? new Map<string, CsvRow>()
317    for (const project of [...projects.keys()].sort()) {
318      const r = projects.get(project)
319      if (!r) continue
320      const subagentUsd = CATEGORIES.reduce((sum, c) => sum + r.subagent.usd[c], 0)
321      const fields = [
322        day,
323        project,
324        r.usd.toFixed(4),
325        ...CATEGORIES.map(c => r.usage.tokens[c]),
326        ...CATEGORIES.map(c => r.usage.usd[c].toFixed(4)),
327        subagentUsd.toFixed(4),
328      ]
329      lines.push(fields.map(csvField).join(','))
330    }
331  }
332  return lines.join('\n') + '\n'
333}
334
hooks/pricing.ts 175 lines
1import type { Breakdown, Category } from '../types'
2
3export type Rates = {
4  input: number
5  output: number
6  cacheRead: number
7  cacheWrite5m: number
8  cacheWrite1h: number
9}
10
11export type CacheTtl = '5m' | '1h'
12
13export type Usage = {
14  input_tokens: number
15  output_tokens: number
16  cache_read_input_tokens: number
17  cache_creation_input_tokens: number
18}
19
20export const CATEGORIES: readonly Category[] = ['input', 'output', 'cacheRead', 'cacheWrite']
21
22const listRates = (input: number, output: number, cacheRead: number): Rates => ({
23  input,
24  output,
25  cacheRead,
26  cacheWrite5m: input * 1.25,
27  cacheWrite1h: input * 2,
28})
29
30// Anthropic list prices in USD per million tokens. Models without a price in
31// the bundled reference (Opus 4.5, Opus 4.1, Sonnet 4.5) are left out rather
32// than guessed: their tokens are counted as unpriced until the rates setting
33// names them.
34export const LIST_RATES: readonly [string, Rates][] = [
35  ['mythos-5-1', listRates(10, 50, 0.25)],
36  ['mythos-5', listRates(10, 50, 1)],
37  ['fable-5-1', listRates(10, 50, 0.25)],
38  ['fable-5', listRates(10, 50, 1)],
39  ['opus-5-5', listRates(4, 20, 0.2)],
40  ['opus-5', listRates(5, 25, 0.5)],
41  ['opus-4-8', listRates(5, 25, 0.5)],
42  ['opus-4-7', listRates(5, 25, 0.5)],
43  ['opus-4-6', listRates(5, 25, 0.5)],
44  ['sonnet-5-5', listRates(2, 10, 0.2)],
45  ['sonnet-5', listRates(2, 10, 0.2)],
46  ['sonnet-4-6', listRates(3, 15, 0.3)],
47  ['haiku-4-5', listRates(1, 5, 0.1)],
48]
49
50const RATE_FIELDS: readonly (keyof Rates)[] = ['input', 'output', 'cacheRead', 'cacheWrite5m', 'cacheWrite1h']
51
52export type RateTable = { rates: readonly [string, Rates][]; error?: string }
53
54const isRecord = (value: unknown): value is Record<string, unknown> =>
55  typeof value === 'object' && value !== null && !Array.isArray(value)
56
57const isRate = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0
58
59// Overrides are per family and may name only some fields, so an AWS price list
60// can be pasted in for the models actually used. A family that has no list
61// price must give input, output and cacheRead; anything malformed is skipped
62// and named in the error rather than failing the mod.
63export function rateTable(overridesJson: string): RateTable {
64  if (overridesJson.trim() === '') return { rates: LIST_RATES }
65
66  let overrides: unknown
67  try {
68    overrides = JSON.parse(overridesJson)
69  } catch {
70    return { rates: LIST_RATES, error: 'the rates setting is not valid JSON; list prices are used' }
71  }
72  if (!isRecord(overrides)) {
73    return { rates: LIST_RATES, error: 'the rates setting must be a JSON object; list prices are used' }
74  }
75
76  const merged = new Map(LIST_RATES)
77  const skipped: string[] = []
78  for (const [family, value] of Object.entries(overrides)) {
79    if (!isRecord(value)) {
80      skipped.push(family)
81      continue
82    }
83    const partial: Partial<Rates> = {}
84    for (const field of RATE_FIELDS) {
85      if (isRate(value[field])) partial[field] = value[field]
86    }
87    const base = merged.get(family)
88    if (base) {
89      merged.set(family, { ...base, ...partial })
90    } else if (partial.input !== undefined && partial.output !== undefined && partial.cacheRead !== undefined) {
91      merged.set(family, { ...listRates(partial.input, partial.output, partial.cacheRead), ...partial })
92    } else {
93      skipped.push(family)
94    }
95  }
96  const error = skipped.length > 0 ? `rates for ${skipped.join(', ')} were skipped as incomplete or malformed` : undefined
97  return { rates: [...merged.entries()], error }
98}
99
100// A family matches where the id continues with something other than another
101// version number, so "claude-opus-5" does not claim "claude-opus-5-5" while a
102// date ("-20250929") or a Bedrock suffix ("-v1:0") still matches.
103function matchesFamily(model: string, family: string): boolean {
104  let at = model.indexOf(family)
105  while (at !== -1) {
106    const rest = model.slice(at + family.length)
107    if (!/^(\d|-\d{1,2}(?!\d))/.test(rest)) return true
108    at = model.indexOf(family, at + 1)
109  }
110  return false
111}
112
113export function ratesFor(table: RateTable, model: string): Rates | undefined {
114  let best: [string, Rates] | undefined
115  for (const entry of table.rates) {
116    if (matchesFamily(model, entry[0]) && (best === undefined || entry[0].length > best[0].length)) best = entry
117  }
118  return best?.[1]
119}
120
121export function writeRate(rates: Rates, ttl: CacheTtl): number {
122  return ttl === '1h' ? rates.cacheWrite1h : rates.cacheWrite5m
123}
124
125export function emptyBreakdown(): Breakdown {
126  return {
127    tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
128    usd: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
129    unpricedTokens: 0,
130  }
131}
132
133export function priceUsage(usage: Usage, rates: Rates | undefined, ttl: CacheTtl): Breakdown {
134  const tokens = {
135    input: usage.input_tokens,
136    output: usage.output_tokens,
137    cacheRead: usage.cache_read_input_tokens,
138    cacheWrite: usage.cache_creation_input_tokens,
139  }
140  if (rates === undefined) {
141    const unpricedTokens = CATEGORIES.reduce((sum, c) => sum + tokens[c], 0)
142    return { tokens, usd: emptyBreakdown().usd, unpricedTokens }
143  }
144  const perToken = (rate: number) => rate / 1_000_000
145  return {
146    tokens,
147    usd: {
148      input: tokens.input * perToken(rates.input),
149      output: tokens.output * perToken(rates.output),
150      cacheRead: tokens.cacheRead * perToken(rates.cacheRead),
151      cacheWrite: tokens.cacheWrite * perToken(writeRate(rates, ttl)),
152    },
153    unpricedTokens: 0,
154  }
155}
156
157export function addBreakdown(a: Breakdown | undefined, b: Breakdown): Breakdown {
158  const sum = emptyBreakdown()
159  for (const c of CATEGORIES) {
160    sum.tokens[c] = (a?.tokens[c] ?? 0) + b.tokens[c]
161    sum.usd[c] = (a?.usd[c] ?? 0) + b.usd[c]
162  }
163  sum.unpricedTokens = (a?.unpricedTokens ?? 0) + (b.unpricedTokens ?? 0)
164  return sum
165}
166
167export function hitRate(b: Breakdown): number {
168  const prompt = b.tokens.input + b.tokens.cacheRead + b.tokens.cacheWrite
169  return prompt === 0 ? 0 : b.tokens.cacheRead / prompt
170}
171
172export function totalUsd(b: Breakdown): number {
173  return CATEGORIES.reduce((sum, c) => sum + b.usd[c], 0)
174}
175
hooks/keepalive.ts 95 lines
1// The cache-lifetime, cold-resume and keep-alive arithmetic, free of engine
2// calls so it can be tested directly. The numbers behind each rule are in
3// tests/cost-ledger-probe/README.md.
4
5import type { CacheTtl, Rates, Usage } from './pricing'
6
7export const TTL_MS: Record<CacheTtl, number> = { '5m': 5 * 60_000, '1h': 60 * 60_000 }
8
9// Below this many tokens written, a turn's other charges swamp the write and
10// its cost says nothing about which write rate was charged.
11const MIN_WRITE_FOR_TTL = 1_000
12
13export type PricedRequest = { usage: Usage; rates: Rates }
14
15// Which cache lifetime Claude Code charged a turn at: its requests priced with
16// five-minute and with one-hour writes, set against what its running total
17// moved. Undefined when the turn wrote too little to tell or neither adds up
18// (a background request landing in the same interval, managed rates).
19export function impliedTtl(deltaUsd: number, requests: readonly PricedRequest[]): CacheTtl | undefined {
20  let base = 0
21  let write5m = 0
22  let write1h = 0
23  let written = 0
24  for (const { usage, rates } of requests) {
25    base +=
26      (usage.input_tokens * rates.input + usage.cache_read_input_tokens * rates.cacheRead + usage.output_tokens * rates.output) /
27      1e6
28    write5m += (usage.cache_creation_input_tokens * rates.cacheWrite5m) / 1e6
29    write1h += (usage.cache_creation_input_tokens * rates.cacheWrite1h) / 1e6
30    written += usage.cache_creation_input_tokens
31  }
32  if (written < MIN_WRITE_FOR_TTL) return undefined
33  const near = (priced: number) => Math.abs(deltaUsd - priced) <= Math.max(0.0005, priced * 0.02)
34  if (near(base + write1h)) return '1h'
35  if (near(base + write5m)) return '5m'
36  return undefined
37}
38
39export type ColdEstimate = { likelyTokens: number; likelyUsd: number; worstTokens: number; worstUsd: number }
40
41// What re-caching a context costs once it has gone cold. The opening shared
42// with other sessions (system prompt and tools) usually stays cached when any
43// other session used it within the hour, so the likely cost is the rest of the
44// context; the worst case, nothing else having used it, is the whole context.
45export function coldEstimate(contextTokens: number, sharedPrefixTokens: number, writeRate: number): ColdEstimate {
46  const likelyTokens = Math.max(0, contextTokens - Math.min(sharedPrefixTokens, contextTokens))
47  return {
48    likelyTokens,
49    likelyUsd: (likelyTokens * writeRate) / 1e6,
50    worstTokens: contextTokens,
51    worstUsd: (contextTokens * writeRate) / 1e6,
52  }
53}
54
55// A ping goes out at nine tenths of the lifetime after the last request that
56// used the cache: 54 minutes on the one-hour cache, 4.5 on the five-minute
57// one, which leaves room for a slow reply before the entry lapses.
58export function pingDelay(lastCacheUseAt: number, ttl: CacheTtl, now: number): number {
59  return Math.max(0, lastCacheUseAt + TTL_MS[ttl] * 0.9 - now)
60}
61
62export type PingCheck = { isDue: true } | { isDue: false; why: 'off' | 'turn running' | 'no context' | 'small context' | 'idle too long' }
63
64export type PingConditions = {
65  isOn: boolean
66  isTurnRunning: boolean
67  contextTokens: number | null
68  minContextTokens: number
69  idleSince: number
70  maxIdleMs: number
71  now: number
72}
73
74export function checkPing(c: PingConditions): PingCheck {
75  if (!c.isOn) return { isDue: false, why: 'off' }
76  if (c.isTurnRunning) return { isDue: false, why: 'turn running' }
77  if (c.contextTokens === null || c.contextTokens === 0) return { isDue: false, why: 'no context' }
78  if (c.contextTokens < c.minContextTokens) return { isDue: false, why: 'small context' }
79  if (c.now - c.idleSince >= c.maxIdleMs) return { isDue: false, why: 'idle too long' }
80  return { isDue: true }
81}
82
83// A ping kept the cache when it wrote no more than the tail: the last answer,
84// which the request before it never sent back, and which on the one-hour cache
85// is written again by every hourly ping because a fork writes at the
86// five-minute rate. A ping that found the conversation cold writes all of it.
87// Without a known tail, nearly everything it sent must have been read.
88const TAIL_SLACK = 1_000
89
90export function pingHit(usage: Usage, tail?: number): boolean {
91  if (tail !== undefined) return usage.cache_creation_input_tokens <= tail + TAIL_SLACK && usage.cache_read_input_tokens > 0
92  const sent = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
93  return sent > 0 && usage.cache_read_input_tokens / sent >= 0.9
94}
95
types/index.d.ts 84 lines
1export type RateLimit = { kind: string; percentUsed: number; resetsAt?: string }
2
3export type Category = 'input' | 'output' | 'cacheRead' | 'cacheWrite'
4
5export type Breakdown = {
6  tokens: Record<Category, number>
7  usd: Record<Category, number>
8  // Tokens from models with no rate; absent in entries written before 0.4.0.
9  unpricedTokens?: number
10}
11
12export type ProjectDay = { usd: number; cacheWriteUsd: number }
13
14// One prompt's cost, its subagents included, estimated from its requests.
15export type TurnRecord = {
16  at: number
17  prompt: string
18  project: string
19  steps: number
20  subagentSteps: number
21  usage: Breakdown
22  subagentUsage: Breakdown
23}
24
25export type ActiveTurn = Omit<TurnRecord, 'project'> & { turnId: string }
26
27// What one tool's results cost while they sat in context: approximate tokens,
28// the cache write when first sent, and every cached re-read after that.
29export type ToolUse = { calls: number; tokens: number; writeUsd: number; rereadUsd: number }
30
31// A loop's tool results by tool, in approximate tokens: pending until the next
32// request sends them, resident once cached.
33export type LoopContext = { pending: Record<string, number>; resident: Record<string, number> }
34
35export type Totals = {
36  session: number
37  today: number
38  week: number
39  month: number
40  weekStart: string
41  days: Record<string, number>
42  cacheDays: Record<string, Breakdown>
43  subagentDays: Record<string, Breakdown>
44  projectDays: Record<string, Record<string, ProjectDay>>
45  turns: TurnRecord[]
46  toolDays: Record<string, Record<string, ToolUse>>
47  rateLimits: RateLimit[]
48}
49
50// at is when the cache was last used (a request's start, a keep-alive ping
51// included); tail is the last answer's tokens, which only the next request
52// sends back. tail is absent in a context restored on resume.
53export type Context = { tokens: number; model: string; at: number; tail?: number }
54
55// The session's keep-alive: the /costs keepalive override, when the last real
56// request was made (pings do not count), and what the pings so far cost.
57export type KeepAlive = {
58  override: 'on' | 'off' | null
59  idleSince: number | null
60  pings: number
61  usd: number
62  stopped: string | null
63}
64
65export type Shading = 'total' | 'cacheWrite'
66
67declare module 'claude-code' {
68  interface PluginState {
69    'cost-ledger': {
70      totals: Totals | null
71      lastUsd: number | null
72      monthOffset: number
73      context: Context | null
74      shadeBy: Shading
75      tick: number
76      activeTurn: ActiveTurn | null
77      turnPrompts: Record<string, { text: string; at: number }>
78      loops: Record<string, LoopContext>
79      keepAlive: KeepAlive
80      sharedPrefix: number | null
81    }
82  }
83}
84