claude-code-cost 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,7 +33,7 @@ The dashboard is a PWA. With the server running, open it in Chrome or Edge and c
33
33
 
34
34
  - **Drill down from the total to one message.** Open a project to see its sessions, then a session to see each message. <kbd>Backspace</kbd> goes back one level.
35
35
  - **Session detail.** A cumulative cost curve, the tokens of each message, and a table with the model, the tools it called, and the running total. Subagents and Workflow runs are in the totals, with a row per agent. Compactions show with an estimated summarizer cost. A range brush picks which messages to show in long sessions.
36
- - **Date ranges.** Presets from Today and Last 24h up to 1 Year, or two dates on a calendar. The range and the project scope apply to every view.
36
+ - **Date ranges.** Presets from Today and Last 24h up to 1 Year, This Month and This Year, whole months or years (one or several), or two dates on a calendar. The range and the project scope apply to every view.
37
37
  - **Insights.** The active 5-hour block with its time left, burn rate, monthly run-rate, cache savings, and subagent share. Charts for token composition, top tools, an hourly heatmap, and weekly cost, plus a table of past 5-hour blocks.
38
38
  - **Plan usage.** Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>S</kbd> to see your plan windows, the percent used, and what drives the cost.
39
39
  - **Pricing.** Live prices from the [LiteLLM](https://github.com/BerriAI/litellm) price list, with the 200K-token tier, cache reads and writes, and fast mode. A built-in table fills in when the list cannot load. Streamed lines are counted once per `message.id` plus `requestId`.
package/lib/cli.js CHANGED
@@ -11,12 +11,42 @@ const LONG_PARSE_DAYS = 30;
11
11
  // The dashboard's longest preset. The overview has no all-time window.
12
12
  const MAX_DAYS = 365;
13
13
  const DAY_MS = 24 * 60 * 60 * 1000;
14
- const WINDOW_HINT = `today, 24h or <n>d up to ${MAX_DAYS}d`;
15
-
16
- function parseWindowValue(raw) {
14
+ const WINDOW_HINT = `today, 24h, <n>d up to ${MAX_DAYS}d, month, year, YYYY-MM or YYYY`;
15
+
16
+ const YEAR_RE = /^20\d{2}$/;
17
+ const MONTH_RE = /^(20\d{2})-(0[1-9]|1[0-2])$/;
18
+ const pad2 = (n) => String(n).padStart(2, '0');
19
+
20
+ // A year (YYYY) or month (YYYY-MM) as the first or last day it covers. Anything else comes back
21
+ // untouched, for parseCustomRange to read as a date or reject.
22
+ function expandBound(raw, edge) {
23
+ if (raw === undefined) return raw;
24
+ const v = String(raw).trim();
25
+ if (YEAR_RE.test(v)) return edge === 'from' ? `${v}-01-01` : `${v}-12-31`;
26
+ const m = MONTH_RE.exec(v);
27
+ if (!m) return v;
28
+ const [y, mo] = [Number(m[1]), Number(m[2])];
29
+ return edge === 'from' ? `${y}-${pad2(mo)}-01` : `${y}-${pad2(mo)}-${pad2(new Date(y, mo, 0).getDate())}`;
30
+ }
31
+
32
+ // A whole month or year as a custom window. The running one ends today: there is no cost data ahead.
33
+ function unitWindow(from, to, label, now) {
34
+ const today = costs.localDateStr(now);
35
+ if (from > today) throw usageError(`${label} has not started`);
36
+ const end = to > today ? today : to;
37
+ const days = Math.round((Date.parse(end) - Date.parse(from)) / DAY_MS) + 1;
38
+ return { ...customWindow(from, end, days), label };
39
+ }
40
+
41
+ function parseWindowValue(raw, now = new Date()) {
17
42
  const v = String(raw).trim().toLowerCase();
18
43
  if (v === 'today') return { range: 'today', days: 1, label: 'Today' };
19
44
  if (v === '24h') return { range: '24h', days: 1, label: 'Last 24 hours' };
45
+ const y = now.getFullYear();
46
+ const ym = `${y}-${pad2(now.getMonth() + 1)}`;
47
+ if (v === 'month') return unitWindow(expandBound(ym, 'from'), expandBound(ym, 'to'), 'This month', now);
48
+ if (v === 'year') return unitWindow(`${y}-01-01`, `${y}-12-31`, 'This year', now);
49
+ if (YEAR_RE.test(v) || MONTH_RE.test(v)) return unitWindow(expandBound(v, 'from'), expandBound(v, 'to'), v, now);
20
50
  const m = /^(\d{1,3})d?$/.exec(v);
21
51
  if (!m || Number(m[1]) < 1 || Number(m[1]) > MAX_DAYS) return null;
22
52
  const n = Number(m[1]);
@@ -35,10 +65,36 @@ function customWindow(from, to, days) {
35
65
  return { range: { from, to }, days, label: from === to ? from : `${from} – ${to}`, query: `from=${from}&to=${to}` };
36
66
  }
37
67
 
38
- // The same number of whole days, ending the day before `win` starts. The API has no rolling window
39
- // that ends in the past, so 24h has no window before it.
68
+ // The window before a window of calendar months, or null for any other window. The months are whole,
69
+ // or the last one runs to today. They move back by their count: September gives August, and
70
+ // Nov 1 - Nov 17 gives Oct 1 - Oct 17. A window from January that is whole years, or runs to today
71
+ // after January, moves back by its years: the year so far gives the same days of last year. An end
72
+ // day the month before does not have stops at that month's last day.
73
+ function calendarBefore(range, now) {
74
+ if (!range?.from || range.from === range.to) return null;
75
+ const [fy, fm, fd] = range.from.split('-').map(Number);
76
+ const [ty, tm, td] = range.to.split('-').map(Number);
77
+ const lastDay = (y, m0) => new Date(y, m0 + 1, 0).getDate();
78
+ const whole = td === lastDay(ty, tm - 1);
79
+ const running = range.to === costs.localDateStr(now);
80
+ if (fd !== 1 || !(whole || running)) return null;
81
+ const years = fm === 1 && (running ? tm !== 1 : tm === 12);
82
+ const shift = years ? (ty - fy + 1) * 12 : (ty - fy) * 12 + tm - fm + 1;
83
+ const start = new Date(fy, fm - 1 - shift, 1);
84
+ const end = new Date(ty, tm - 1 - shift, 1);
85
+ const last = lastDay(end.getFullYear(), end.getMonth());
86
+ end.setDate(whole && !(years && running) ? last : Math.min(td, last));
87
+ const [from, to] = [costs.localDateStr(start), costs.localDateStr(end)];
88
+ return customWindow(from, to, Math.round((Date.parse(to) - Date.parse(from)) / DAY_MS) + 1);
89
+ }
90
+
91
+ // Calendar months move back by months (see calendarBefore). Any other window gives the same number
92
+ // of whole days, ending the day before `win` starts. The API has no rolling window that ends in the
93
+ // past, so 24h has no window before it.
40
94
  function previousWindow(win, now = new Date()) {
41
95
  if (win.range === '24h') throw usageError('--compare needs today, <n>d or --from/--to, not 24h');
96
+ const calendar = calendarBefore(win.range, now);
97
+ if (calendar) return calendar;
42
98
  const start = costs.resolveWindow(win.range, now).cutoff;
43
99
  const day = (delta) => costs.localDateStr(new Date(start.getFullYear(), start.getMonth(), start.getDate() + delta));
44
100
  return customWindow(day(-win.days), day(-1), win.days);
@@ -47,12 +103,18 @@ function previousWindow(win, now = new Date()) {
47
103
  // The flag wins, then CLAUDE_COST_RANGE, then cli.defaultRange in <config dir>/.cost/config.json,
48
104
  // then 7 days. A bad flag is an error; a bad env or config value is skipped with a warning, so a
49
105
  // typo in a file does not break every command.
50
- function resolveWindow(flags, { claudeDir, parseCustomRange, env = process.env, warn = console.error }) {
106
+ function resolveWindow(flags, { claudeDir, parseCustomRange, env = process.env, warn = console.error, now = new Date() }) {
51
107
  if (flags.from !== undefined || flags.to !== undefined) {
52
- const custom = parseCustomRange({ from: flags.from, to: flags.to });
53
- if (!custom) throw usageError('--from and --to take local dates (YYYY-MM-DD) and come as a pair');
108
+ if (flags.from === undefined || flags.to === undefined) throw usageError('--from and --to come as a pair');
109
+ // A year or month bound reaches to the edge of its unit: `--from 2025 --to 2026` is Jan 1, 2025
110
+ // to Dec 31, 2026, and `--from 2026-09 --to 2026-11` is Sep 1 to Nov 30 (both end at today at most).
111
+ let [f, t] = [expandBound(flags.from, 'from'), expandBound(flags.to, 'to')];
112
+ // Reversed bounds swap before they reach their edges, or `--from 2026-11 --to 2026-09` would
113
+ // start at the end of September and stop at the start of November.
114
+ if (f && t && f > t) [f, t] = [expandBound(flags.to, 'from'), expandBound(flags.from, 'to')];
115
+ const custom = parseCustomRange({ from: f, to: t }, now);
116
+ if (!custom) throw usageError('--from and --to take YYYY-MM-DD, YYYY-MM or YYYY');
54
117
  const days = Math.round((Date.parse(custom.to) - Date.parse(custom.from)) / DAY_MS) + 1;
55
- if (days > MAX_DAYS) throw usageError(`--from/--to: at most ${MAX_DAYS} days`);
56
118
  return customWindow(custom.from, custom.to, days);
57
119
  }
58
120
  const sources = [
@@ -63,8 +125,8 @@ function resolveWindow(flags, { claudeDir, parseCustomRange, env = process.env,
63
125
  ];
64
126
  for (const [raw, source] of sources) {
65
127
  if (raw === undefined || raw === null || raw === '') continue;
66
- const w = parseWindowValue(raw);
67
- if (w) return { ...w, source, query: `range=${w.range}` };
128
+ const w = parseWindowValue(raw, now);
129
+ if (w) return { ...w, source, query: w.query || `range=${w.range}` };
68
130
  if (source === '--range') throw usageError(`--range ${raw}: use ${WINDOW_HINT}`);
69
131
  warn(`${source}: "${raw}" is not a window (${WINDOW_HINT}); skipped`);
70
132
  }
@@ -433,8 +495,8 @@ const BIN = 'claude-code-cost';
433
495
 
434
496
  const WINDOW_FLAGS = {
435
497
  '--range <r>': WINDOW_HINT,
436
- '--from <date>': 'Window start, YYYY-MM-DD (needs --to)',
437
- '--to <date>': 'Window end, YYYY-MM-DD',
498
+ '--from <date>': 'Window start: YYYY-MM-DD, YYYY-MM or YYYY (needs --to)',
499
+ '--to <date>': 'Window end: YYYY-MM-DD, YYYY-MM or YYYY',
438
500
  };
439
501
  const COMMON_FLAGS = {
440
502
  '--top <n>': 'Rows per list (default 5)',
@@ -448,8 +510,8 @@ const COMMANDS = {
448
510
  summary: 'Total cost, by model, by day and top projects; --compare to the window before',
449
511
  usage: `${BIN} overview [--range <r>] [--project <name>] [--compare] [--json]`,
450
512
  flags: { ...SCOPED_FLAGS, '--compare': 'Also the window before it, and the change' },
451
- notes: 'The window before has as many days and ends the day before. Today counts so far.\n--compare also parses the window before.',
452
- examples: [`${BIN} overview --range today`, `${BIN} overview --range 30d --project claude-code-hub`, `${BIN} overview --range 7d --compare`],
513
+ notes: 'The window before has as many days and ends the day before. Today counts so far.\nWhole months, or months up to today, compare with the months before; years with the years before.\n--compare also parses the window before.',
514
+ examples: [`${BIN} overview --range today`, `${BIN} overview --range 30d --project claude-code-hub`, `${BIN} overview --range 7d --compare`, `${BIN} overview --range 2026-09 --compare`, `${BIN} overview --from 2025 --to 2026`],
453
515
  window: true,
454
516
  project: true,
455
517
  },
package/lib/costs.js CHANGED
@@ -2,8 +2,6 @@
2
2
 
3
3
  const path = require('node:path');
4
4
  const fs = require('node:fs');
5
- const { createReadStream } = fs;
6
- const { createInterface } = require('node:readline');
7
5
  const os = require('node:os');
8
6
  const { probeUsage, normalizeUsage } = require('./usage-probe');
9
7
 
@@ -110,9 +108,19 @@ async function fetchPricing() {
110
108
  }
111
109
  }
112
110
 
111
+ // A miss on the exact and prefixed names falls to a scan of every LiteLLM model, run once per turn
112
+ // of that model, so the answer is memoized for each pricing table.
113
+ const pricingMemo = new WeakMap();
114
+
113
115
  function getModelPricing(pricing, modelName) {
114
116
  if (!modelName) return null;
117
+ if (!pricingMemo.has(pricing)) pricingMemo.set(pricing, new Map());
118
+ const memo = pricingMemo.get(pricing);
119
+ if (!memo.has(modelName)) memo.set(modelName, lookupModelPricing(pricing, modelName));
120
+ return memo.get(modelName);
121
+ }
115
122
 
123
+ function lookupModelPricing(pricing, modelName) {
116
124
  // Exact match
117
125
  const direct = pricing.get(modelName);
118
126
  if (direct) return direct;
@@ -146,20 +154,29 @@ function calculateTieredCost(totalTokens, basePrice, tieredPrice, threshold = TI
146
154
  return 0;
147
155
  }
148
156
 
157
+ function calculateCostParts(tokens, modelPricing) {
158
+ return {
159
+ input: calculateTieredCost(
160
+ tokens.input_tokens, modelPricing.input_cost_per_token,
161
+ modelPricing.input_cost_per_token_above_200k_tokens),
162
+ output: calculateTieredCost(
163
+ tokens.output_tokens, modelPricing.output_cost_per_token,
164
+ modelPricing.output_cost_per_token_above_200k_tokens),
165
+ cacheCreation: calculateTieredCost(
166
+ tokens.cache_creation_input_tokens, modelPricing.cache_creation_input_token_cost,
167
+ modelPricing.cache_creation_input_token_cost_above_200k_tokens),
168
+ cacheRead: calculateTieredCost(
169
+ tokens.cache_read_input_tokens, modelPricing.cache_read_input_token_cost,
170
+ modelPricing.cache_read_input_token_cost_above_200k_tokens),
171
+ };
172
+ }
173
+
174
+ function sumParts(p) {
175
+ return p.input + p.output + p.cacheCreation + p.cacheRead;
176
+ }
177
+
149
178
  function calculateCost(tokens, modelPricing) {
150
- const inputCost = calculateTieredCost(
151
- tokens.input_tokens, modelPricing.input_cost_per_token,
152
- modelPricing.input_cost_per_token_above_200k_tokens);
153
- const outputCost = calculateTieredCost(
154
- tokens.output_tokens, modelPricing.output_cost_per_token,
155
- modelPricing.output_cost_per_token_above_200k_tokens);
156
- const cacheCreationCost = calculateTieredCost(
157
- tokens.cache_creation_input_tokens, modelPricing.cache_creation_input_token_cost,
158
- modelPricing.cache_creation_input_token_cost_above_200k_tokens);
159
- const cacheReadCost = calculateTieredCost(
160
- tokens.cache_read_input_tokens, modelPricing.cache_read_input_token_cost,
161
- modelPricing.cache_read_input_token_cost_above_200k_tokens);
162
- return inputCost + outputCost + cacheCreationCost + cacheReadCost;
179
+ return sumParts(calculateCostParts(tokens, modelPricing));
163
180
  }
164
181
 
165
182
  function calculateCostForModel(tokens, modelName, pricing, speed) {
@@ -174,15 +191,241 @@ function calculateCostForModel(tokens, modelName, pricing, speed) {
174
191
 
175
192
  // #region JSONL_PARSING
176
193
 
177
- async function processJSONLFile(filePath, processLine) {
178
- const fileStream = createReadStream(filePath, { encoding: 'utf-8' });
179
- const rl = createInterface({ input: fileStream, crlfDelay: Infinity });
180
- let lineNumber = 0;
181
- for await (const line of rl) {
182
- lineNumber++;
183
- if (line.trim().length === 0) continue;
184
- await processLine(line, lineNumber);
194
+ const READ_CHUNK = 1 << 20;
195
+
196
+ function parseJsonLine(bytes) {
197
+ try {
198
+ const parsed = JSON.parse(bytes.toString('utf-8'));
199
+ return parsed && typeof parsed === 'object' ? parsed : undefined;
200
+ } catch {
201
+ return undefined;
202
+ }
203
+ }
204
+
205
+ // Calls onParsed for each JSON line that ends in [start, size) and returns the offset after the
206
+ // last one consumed. A line still being written has no newline yet, so it waits for the next read;
207
+ // a last line without one is taken only when it already parses.
208
+ async function readJsonLinesFrom(filePath, start, size, onParsed) {
209
+ const fh = await fs.promises.open(filePath, 'r');
210
+ const buf = Buffer.allocUnsafe(Math.min(READ_CHUNK, size - start));
211
+ let pos = start;
212
+ let tail = null;
213
+ try {
214
+ while (pos < size) {
215
+ const { bytesRead } = await fh.read(buf, 0, Math.min(buf.length, size - pos), pos);
216
+ if (!bytesRead) break;
217
+ pos += bytesRead;
218
+ const chunk = buf.subarray(0, bytesRead);
219
+ let from = 0;
220
+ for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, from)) {
221
+ const part = chunk.subarray(from, nl);
222
+ const parsed = parseJsonLine(tail ? Buffer.concat([tail, part]) : part);
223
+ tail = null;
224
+ if (parsed) onParsed(parsed);
225
+ from = nl + 1;
226
+ }
227
+ if (from < bytesRead) tail = Buffer.concat(tail ? [tail, chunk.subarray(from)] : [chunk.subarray(from)]);
228
+ }
229
+ } finally {
230
+ await fh.close();
231
+ }
232
+ if (!tail) return pos;
233
+ const last = parseJsonLine(tail);
234
+ if (!last) return pos - tail.length;
235
+ onParsed(last);
236
+ return pos;
237
+ }
238
+
239
+ function joinTools(a, b) {
240
+ return a && b ? a.concat(b) : a || b;
241
+ }
242
+
243
+ function indexByHash(f) {
244
+ return new Map(f.turns.filter((t) => t.hash).map((t) => [t.hash, t]));
245
+ }
246
+
247
+ // Parsed facts per transcript, kept for the server's lifetime. A transcript only grows, so an entry
248
+ // whose file has the same size and mtime is current, and a grown file is read from where the last
249
+ // read stopped. Facts hold token counts, not cost, so a pricing refresh needs no re-read.
250
+ const fileCache = new Map();
251
+ const fileReads = new Map();
252
+
253
+ // JSON.parse makes a new string for every model and tool name; one copy each is enough.
254
+ const interned = new Map();
255
+ function intern(s) {
256
+ if (typeof s !== 'string') return s;
257
+ const hit = interned.get(s);
258
+ if (hit !== undefined) return hit;
259
+ interned.set(s, s);
260
+ return s;
261
+ }
262
+
263
+ // Only what the turn needs: `parsed` also holds the turn's content blocks.
264
+ function turnFacts(parsed) {
265
+ const u = parsed.message.usage;
266
+ return {
267
+ ts: parsed.timestamp,
268
+ model: intern(parsed.message.model) || null,
269
+ speed: intern(u.speed) || 'standard',
270
+ costUSD: parsed.costUSD ?? null,
271
+ in: u.input_tokens || 0,
272
+ out: u.output_tokens || 0,
273
+ cw: u.cache_creation_input_tokens || 0,
274
+ cr: u.cache_read_input_tokens || 0,
275
+ };
276
+ }
277
+
278
+ function hasUsage(parsed) {
279
+ return (parsed.message?.usage?.input_tokens || parsed.message?.usage?.input_tokens === 0) && !!parsed.timestamp;
280
+ }
281
+
282
+ function internTools(content) {
283
+ const tools = extractTools(content);
284
+ return tools?.map(intern) ?? null;
285
+ }
286
+
287
+ const sessionParser = {
288
+ init: () => ({ customTitle: null, firstPrompt: '', turns: [], skillAgents: {}, skillCalls: {}, pending: null }),
289
+ line(f, byHash, parsed) {
290
+ noteSkillAgent(parsed, f.skillCalls, f.skillAgents);
291
+ if (parsed.type === 'custom-title' && parsed.customTitle) {
292
+ f.customTitle = parsed.customTitle;
293
+ return;
294
+ }
295
+ if (parsed.type === 'system' && parsed.subtype === 'compact_boundary' && parsed.timestamp) {
296
+ f.pending = compactionFacts(parsed);
297
+ return;
298
+ }
299
+ if (!hasUsage(parsed)) return;
300
+ const hash = createDedupeHash(parsed);
301
+ const tools = internTools(parsed.message?.content);
302
+ const prev = hash && byHash.get(hash);
303
+ if (prev) {
304
+ // Streaming writes one JSONL line per content block of the same API message. Usage is
305
+ // identical on every line (deduped), but each line carries different tool_use blocks,
306
+ // so tools must be unioned across duplicates or most calls are lost.
307
+ prev.tools = joinTools(prev.tools, tools);
308
+ return;
309
+ }
310
+ const turn = { ...turnFacts(parsed), hash, tools, compaction: f.pending };
311
+ f.pending = null;
312
+ f.turns.push(turn);
313
+ if (hash) byHash.set(hash, turn);
314
+ if (!f.firstPrompt && parsed.type === 'human' && parsed.message?.content) {
315
+ const content = Array.isArray(parsed.message.content)
316
+ ? parsed.message.content.map(c => c.text || '').join(' ')
317
+ : (typeof parsed.message.content === 'string' ? parsed.message.content : '');
318
+ if (content.trim()) f.firstPrompt = content.trim().slice(0, 120);
319
+ }
320
+ },
321
+ };
322
+
323
+ const agentParser = {
324
+ init: () => ({ turns: [], unhashed: [] }),
325
+ line(f, byHash, parsed) {
326
+ if (!hasUsage(parsed)) return;
327
+ const hash = createDedupeHash(parsed);
328
+ const turn = { ...turnFacts(parsed), hash, tools: internTools(parsed.message?.content) };
329
+ if (!hash) {
330
+ f.unhashed.push(turn);
331
+ return;
332
+ }
333
+ const prev = byHash.get(hash);
334
+ if (!prev) {
335
+ byHash.set(hash, turn);
336
+ f.turns.push(turn);
337
+ return;
338
+ }
339
+ const tools = joinTools(prev.tools, turn.tools);
340
+ if (turn.out > prev.out) Object.assign(prev, turn);
341
+ prev.tools = tools;
342
+ },
343
+ };
344
+
345
+ function statFile(filePath) {
346
+ try {
347
+ const st = fs.statSync(filePath);
348
+ return { size: st.size, mtimeMs: st.mtimeMs };
349
+ } catch {
350
+ return null;
351
+ }
352
+ }
353
+
354
+ const EDGE_BYTES = 64;
355
+
356
+ async function readEdges(filePath, offset) {
357
+ const n = Math.min(EDGE_BYTES, offset);
358
+ const head = Buffer.alloc(n);
359
+ const tail = Buffer.alloc(n);
360
+ const fh = await fs.promises.open(filePath, 'r');
361
+ try {
362
+ await fh.read(head, 0, n, 0);
363
+ await fh.read(tail, 0, n, offset - n);
364
+ } finally {
365
+ await fh.close();
366
+ }
367
+ return head.toString('latin1') + tail.toString('latin1');
368
+ }
369
+
370
+ async function readFacts(filePath, parser) {
371
+ const st = statFile(filePath);
372
+ if (!st) {
373
+ fileCache.delete(filePath);
374
+ return parser.init();
185
375
  }
376
+ let entry = fileCache.get(filePath);
377
+ if (entry && entry.size === st.size && entry.mtimeMs === st.mtimeMs) return entry.facts;
378
+ if (fileReads.has(filePath)) return fileReads.get(filePath);
379
+ const fresh = () => ({ size: 0, mtimeMs: 0, offset: 0, edges: '', facts: parser.init() });
380
+ // An appended file only grows, so a new mtime at the same size, a smaller size, or changed bytes
381
+ // around the old offset mean another tool rewrote it. The edge check is a cheap sample, not a
382
+ // full hash: a rewrite that keeps both edges is missed until the process restarts.
383
+ if (!entry || st.size <= entry.offset || st.size === entry.size) entry = fresh();
384
+ const read = (async () => {
385
+ if (entry.offset && entry.edges !== (await readEdges(filePath, entry.offset))) entry = fresh();
386
+ const byHash = indexByHash(entry.facts);
387
+ entry.offset = await readJsonLinesFrom(filePath, entry.offset, st.size, (parsed) => {
388
+ parser.line(entry.facts, byHash, parsed);
389
+ });
390
+ entry.size = st.size;
391
+ entry.mtimeMs = st.mtimeMs;
392
+ entry.edges = entry.offset ? await readEdges(filePath, entry.offset) : '';
393
+ fileCache.set(filePath, entry);
394
+ return entry.facts;
395
+ })();
396
+ fileReads.set(filePath, read);
397
+ try {
398
+ return await read;
399
+ } catch (err) {
400
+ // The facts may hold part of the read while the offset does not, so start over next time.
401
+ fileCache.delete(filePath);
402
+ throw err;
403
+ } finally {
404
+ fileReads.delete(filePath);
405
+ }
406
+ }
407
+
408
+ function turnCost(t, pricing) {
409
+ // Auto mode: use costUSD if present, otherwise calculate
410
+ if (t.costUSD != null) return t.costUSD;
411
+ if (!t.model) return 0;
412
+ return calculateCostForModel(
413
+ { input_tokens: t.in, output_tokens: t.out, cache_creation_input_tokens: t.cw, cache_read_input_tokens: t.cr },
414
+ t.model, pricing, t.speed);
415
+ }
416
+
417
+ function turnMessage(t, pricing) {
418
+ return {
419
+ timestamp: t.ts,
420
+ model: t.model || 'unknown',
421
+ cost: turnCost(t, pricing),
422
+ inputTokens: t.in,
423
+ outputTokens: t.out,
424
+ cacheCreationTokens: t.cw,
425
+ cacheReadTokens: t.cr,
426
+ speed: t.speed,
427
+ tools: t.tools,
428
+ };
186
429
  }
187
430
 
188
431
 
@@ -201,14 +444,6 @@ function extractTools(content) {
201
444
  return tools.length > 0 ? tools : null;
202
445
  }
203
446
 
204
- function calculateEntryCost(data, pricing) {
205
- // Auto mode: use costUSD if present, otherwise calculate
206
- if (data.costUSD != null) return data.costUSD;
207
- const model = data.message?.model;
208
- if (!model) return 0;
209
- const speed = data.message?.usage?.speed;
210
- return calculateCostForModel(data.message.usage, model, pricing, speed);
211
- }
212
447
 
213
448
  // The summarization call behind a compact_boundary is not logged with usage, so its cost is an
214
449
  // estimate: the whole pre-compaction context read from cache, and a summary no larger than the
@@ -521,36 +756,12 @@ function mostFrequentModel(counts) {
521
756
  // final usage on every line, which is why first-wins reads the same there.
522
757
  // Session and project loads read every agent log for its totals alone, so tools are opt-in.
523
758
  async function readAgentTurns(filePath, pricing, { withTools = false } = {}) {
524
- const kept = new Map();
525
- const unhashed = [];
526
- await processJSONLFile(filePath, async (line) => {
527
- let parsed;
528
- try { parsed = JSON.parse(line); } catch { return; }
529
- const usage = parsed.message?.usage;
530
- if (!usage?.input_tokens && usage?.input_tokens !== 0) return;
531
- if (!parsed.timestamp) return;
532
-
533
- // Only what the turn needs: `parsed` also holds the turn's content blocks.
534
- const entry = { costUSD: parsed.costUSD, timestamp: parsed.timestamp, message: { model: parsed.message.model, usage }, tools: null };
535
- const tools = withTools ? extractTools(parsed.message?.content) : null;
536
- const hash = createDedupeHash(parsed);
537
- if (!hash) { entry.tools = tools; unhashed.push(entry); return; }
538
- const prev = kept.get(hash);
539
- const allTools = prev?.tools && tools ? prev.tools.concat(tools) : prev?.tools || tools;
540
- if (!prev || (usage.output_tokens || 0) > (prev.message.usage.output_tokens || 0)) kept.set(hash, entry);
541
- kept.get(hash).tools = allTools;
759
+ const f = await readFacts(filePath, agentParser);
760
+ return f.turns.concat(f.unhashed).map((t) => {
761
+ const msg = turnMessage(t, pricing);
762
+ if (!withTools) msg.tools = null;
763
+ return msg;
542
764
  });
543
- return [...kept.values(), ...unhashed].map(e => ({
544
- cost: calculateEntryCost(e, pricing),
545
- inputTokens: e.message.usage.input_tokens || 0,
546
- outputTokens: e.message.usage.output_tokens || 0,
547
- cacheCreationTokens: e.message.usage.cache_creation_input_tokens || 0,
548
- cacheReadTokens: e.message.usage.cache_read_input_tokens || 0,
549
- speed: e.message.usage.speed || 'standard',
550
- model: e.message.model || 'unknown',
551
- timestamp: e.timestamp,
552
- tools: e.tools,
553
- }));
554
765
  }
555
766
 
556
767
  const SKILL_TEXT_MAX = 200;
@@ -564,15 +775,17 @@ function noteSkillAgent(parsed, calls, texts) {
564
775
  for (const b of content) {
565
776
  if (b.type === 'tool_use' && b.name === 'Skill' && b.input?.skill) {
566
777
  const text = `/${b.input.skill} ${b.input.args || ''}`.replace(/\s+/g, ' ').trim();
567
- calls.set(b.id, { skill: b.input.skill, text: text.length > SKILL_TEXT_MAX ? `${text.slice(0, SKILL_TEXT_MAX - 1)}…` : text });
778
+ calls[b.id] = { skill: b.input.skill, text: text.length > SKILL_TEXT_MAX ? `${text.slice(0, SKILL_TEXT_MAX - 1)}…` : text };
568
779
  }
569
780
  }
570
781
  return;
571
782
  }
572
783
  const agentId = parsed.toolUseResult?.agentId;
573
784
  if (!agentId) return;
574
- const call = calls.get(content.find(b => b.type === 'tool_result')?.tool_use_id);
575
- if (call) texts.set(`agent-${agentId}`, call);
785
+ const id = content.find(b => b.type === 'tool_result')?.tool_use_id;
786
+ if (!id || !Object.hasOwn(calls, id)) return;
787
+ texts[`agent-${agentId}`] = calls[id];
788
+ delete calls[id];
576
789
  }
577
790
 
578
791
  async function loadSubagentData(subagentInfos, pricing) {
@@ -624,87 +837,39 @@ async function loadProjectData(files, pricing) {
624
837
  });
625
838
  }
626
839
  const session = sessions.get(sessionId);
840
+ const f = await readFacts(file, sessionParser);
841
+ if (f.customTitle) session.customTitle = f.customTitle;
842
+ if (!session.firstPrompt) session.firstPrompt = f.firstPrompt;
843
+
627
844
  // A boundary is attributed to the next counted turn, so the message list is the only record
628
- // of compactions; a boundary with no turn after it has nothing to price and is dropped.
845
+ // of compactions; a boundary with no turn after it has nothing to price and is dropped. A turn
846
+ // that an earlier file of the project already counted passes its boundary on.
629
847
  let pendingCompaction = null;
630
- const skillCalls = new Map();
631
- const skillAgents = new Map();
632
-
633
- await processJSONLFile(file, async (line) => {
634
- let parsed;
635
- try { parsed = JSON.parse(line); } catch { return; }
636
-
637
- noteSkillAgent(parsed, skillCalls, skillAgents);
638
-
639
- if (parsed.type === 'custom-title' && parsed.customTitle) {
640
- session.customTitle = parsed.customTitle;
641
- return;
848
+ for (const t of f.turns) {
849
+ const orig = t.hash && seen.get(t.hash);
850
+ if (orig) {
851
+ orig.tools = joinTools(orig.tools, t.tools);
852
+ if (t.compaction) pendingCompaction = t.compaction;
853
+ continue;
642
854
  }
643
-
644
- if (parsed.type === 'system' && parsed.subtype === 'compact_boundary' && parsed.timestamp) {
645
- pendingCompaction = compactionFacts(parsed);
646
- return;
647
- }
648
-
649
- if (!parsed.message?.usage?.input_tokens && parsed.message?.usage?.input_tokens !== 0) return;
650
- if (!parsed.timestamp) return;
651
-
652
- const hash = createDedupeHash(parsed);
653
- if (hash && seen.has(hash)) {
654
- // Streaming writes one JSONL line per content block of the same API message. Usage is
655
- // identical on every line (deduped), but each line carries different tool_use blocks,
656
- // so tools must be unioned across duplicates or most calls are lost.
657
- const dupTools = extractTools(parsed.message?.content);
658
- if (dupTools) {
659
- const orig = seen.get(hash);
660
- orig.tools = (orig.tools || []).concat(dupTools);
661
- }
662
- return;
663
- }
664
-
665
- const cost = calculateEntryCost(parsed, pricing);
666
- const usage = parsed.message.usage;
667
- const model = parsed.message?.model || 'unknown';
668
- const ts = parsed.timestamp;
669
-
670
- session.totalCost += cost;
671
- session.inputTokens += usage.input_tokens || 0;
672
- session.outputTokens += usage.output_tokens || 0;
673
- session.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
674
- session.cacheReadTokens += (usage.cache_read_input_tokens || 0);
675
- if (isRealModel(model)) session.models.add(model);
855
+ const msg = turnMessage(t, pricing);
856
+ const ts = msg.timestamp;
857
+ session.totalCost += msg.cost;
858
+ session.inputTokens += msg.inputTokens;
859
+ session.outputTokens += msg.outputTokens;
860
+ session.cacheCreationTokens += msg.cacheCreationTokens;
861
+ session.cacheReadTokens += msg.cacheReadTokens;
862
+ if (isRealModel(msg.model)) session.models.add(msg.model);
676
863
 
677
864
  if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
678
865
  if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
679
866
 
680
- const msg = {
681
- timestamp: ts,
682
- model,
683
- cost,
684
- inputTokens: usage.input_tokens || 0,
685
- outputTokens: usage.output_tokens || 0,
686
- cacheCreationTokens: usage.cache_creation_input_tokens || 0,
687
- cacheReadTokens: usage.cache_read_input_tokens || 0,
688
- speed: usage.speed || 'standard',
689
- tools: extractTools(parsed.message?.content),
690
- };
691
- if (pendingCompaction) {
692
- msg.compaction = priceCompaction(pendingCompaction, msg, pricing);
693
- pendingCompaction = null;
694
- }
867
+ const facts = t.compaction || pendingCompaction;
868
+ if (facts) msg.compaction = priceCompaction(facts, msg, pricing);
869
+ pendingCompaction = null;
695
870
  session.messages.push(msg);
696
- if (hash) seen.set(hash, msg);
697
-
698
- // Capture first user prompt from the JSONL (look for human/user messages)
699
- if (!session.firstPrompt && parsed.type === 'human' && parsed.message?.content) {
700
- const content = Array.isArray(parsed.message.content)
701
- ? parsed.message.content.map(c => c.text || '').join(' ')
702
- : (typeof parsed.message.content === 'string' ? parsed.message.content : '');
703
- if (content.trim()) {
704
- session.firstPrompt = content.trim().slice(0, 120);
705
- }
706
- }
707
- });
871
+ if (t.hash) seen.set(t.hash, msg);
872
+ }
708
873
 
709
874
  // Fold subagent costs into session totals
710
875
  const sessionDir = path.join(path.dirname(file), sessionId);
@@ -716,7 +881,7 @@ async function loadProjectData(files, pricing) {
716
881
  // response — would fold in as a zero-cost message dated at the session's own start,
717
882
  // which stretches every span it lands in.
718
883
  if (sa.messageCount === 0) continue;
719
- const skill = skillAgents.get(sa.agentId);
884
+ const skill = f.skillAgents[sa.agentId];
720
885
  session.totalCost += sa.totalCost;
721
886
  session.inputTokens += sa.inputTokens;
722
887
  session.outputTokens += sa.outputTokens;
@@ -1455,11 +1620,21 @@ async function getInsightsData(range, projectFilter) {
1455
1620
  // getModelPricing falls back to a linear scan of the whole LiteLLM map on a miss, so resolve
1456
1621
  // it once per distinct model rather than once per message.
1457
1622
  const priceMemo = new Map();
1623
+ const tokenCosts = { input: 0, output: 0, cacheCreation: 0, cacheRead: 0 };
1458
1624
  for (const m of all) {
1625
+ if (!priceMemo.has(m.model)) priceMemo.set(m.model, getModelPricing(pricing, m.model));
1626
+ const mp = priceMemo.get(m.model);
1627
+ // Scaled to m.cost, so the parts carry the fast-mode multiplier and a logged costUSD.
1628
+ if (mp && m.cost > 0) {
1629
+ const parts = calculateCostParts({
1630
+ input_tokens: m.inputTokens, output_tokens: m.outputTokens,
1631
+ cache_creation_input_tokens: m.cacheCreationTokens, cache_read_input_tokens: m.cacheReadTokens,
1632
+ }, mp);
1633
+ const raw = sumParts(parts);
1634
+ if (raw > 0) for (const k of Object.keys(parts)) tokenCosts[k] += (parts[k] / raw) * m.cost;
1635
+ }
1459
1636
  // What the same tokens would have cost as fresh input, minus what cache reads actually cost.
1460
1637
  if (m.cacheReadTokens > 0) {
1461
- if (!priceMemo.has(m.model)) priceMemo.set(m.model, getModelPricing(pricing, m.model));
1462
- const mp = priceMemo.get(m.model);
1463
1638
  if (mp?.input_cost_per_token != null && mp?.cache_read_input_token_cost != null) {
1464
1639
  cacheSavings += m.cacheReadTokens * (mp.input_cost_per_token - mp.cache_read_input_token_cost);
1465
1640
  }
@@ -1506,6 +1681,7 @@ async function getInsightsData(range, projectFilter) {
1506
1681
 
1507
1682
  const result = {
1508
1683
  tokens,
1684
+ tokenCosts,
1509
1685
  cacheSavings,
1510
1686
  runRate: { dailyAvg, projectedMonthly: dailyAvg * 30, days: dayCount },
1511
1687
  blocks,
@@ -1554,13 +1730,13 @@ function parseDateParam(raw) {
1554
1730
  // Reversed pairs are ordered and both ends clamped to today — there is no cost data ahead of now,
1555
1731
  // and an inverted window would otherwise render as an unexplained empty chart.
1556
1732
  // Returns undefined when no window was requested, null when one was but is malformed.
1557
- function parseCustomRange(query) {
1733
+ function parseCustomRange(query, now = new Date()) {
1558
1734
  const from = parseDateParam(query.from);
1559
1735
  const to = parseDateParam(query.to);
1560
1736
  if (from === null || to === null) return null;
1561
1737
  if (from === undefined && to === undefined) return undefined;
1562
1738
  if (from === undefined || to === undefined) return null;
1563
- const today = localDateStr(new Date());
1739
+ const today = localDateStr(now);
1564
1740
  const [lo, hi] = from <= to ? [from, to] : [to, from];
1565
1741
  return { from: lo > today ? today : lo, to: hi > today ? today : hi };
1566
1742
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "1.7.0",
3
+ "version": "1.9.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "type": "commonjs",
package/public/app.js CHANGED
@@ -355,8 +355,54 @@ function normalizeRange(r) {
355
355
  return Number.isFinite(n) && n > 0 ? presetRange(n) : null;
356
356
  }
357
357
 
358
- // "AUG 1 - AUG 12"; a single-day window is just "AUG 12".
358
+ const pad2 = (n) => String(n).padStart(2, '0');
359
+
360
+ // The month at (y, m0) as a window: its 1st to its last day, or to today while it is still running.
361
+ function monthSpan(y, m0) {
362
+ const last = isoDate(new Date(y, m0 + 1, 0));
363
+ const today = todayIso();
364
+ return { from: isoDate(new Date(y, m0, 1)), to: last > today ? today : last };
365
+ }
366
+
367
+ function monthToDate() {
368
+ const now = new Date();
369
+ return monthSpan(now.getFullYear(), now.getMonth());
370
+ }
371
+
372
+ // Jan 1 to Dec 31 of `y`, or to today while the year is still running.
373
+ function yearSpan(y) {
374
+ const today = todayIso();
375
+ const last = `${y}-12-31`;
376
+ return { from: `${y}-01-01`, to: last > today ? today : last };
377
+ }
378
+
379
+ // What whole calendar units [from, to] covers, or null for any other window: whole months
380
+ // ({unit:'month', a:'2026-09', b:'2026-11'}) or whole years ({unit:'year', a:2025, b:2026}). The
381
+ // running month or year counts as whole when it ends today, except a running January, which is a
382
+ // month rather than the year it has barely started. Names a window "NOVEMBER 2026" or "2025"
383
+ // instead of by its two dates, and picks the picker's mode on open.
384
+ function periodOf(from, to) {
385
+ if (from === to) return null;
386
+ const [fy, fm, fd] = isoParts(from);
387
+ const [ty, tm] = isoParts(to);
388
+ if (fd !== 1 || monthSpan(ty, tm - 1).to !== to) return null;
389
+ const now = new Date();
390
+ const running = ty === now.getFullYear() && tm - 1 === now.getMonth();
391
+ if (fm === 1 && (tm === 12 || (running && tm !== 1))) return { unit: 'year', a: fy, b: ty };
392
+ return { unit: 'month', a: `${fy}-${pad2(fm)}`, b: `${ty}-${pad2(tm)}` };
393
+ }
394
+
395
+ function monthLabel(ym, style = 'long') {
396
+ const [y, m] = isoParts(`${ym}-01`);
397
+ return new Date(y, m - 1, 1).toLocaleDateString(undefined, { month: style, year: 'numeric' }).toUpperCase();
398
+ }
399
+
400
+ // "AUG 1 - AUG 12"; a single-day window is just "AUG 12"; whole units are "AUGUST 2026",
401
+ // "SEP 2026 - NOV 2026", "2025" or "2024 - 2025".
359
402
  function rangeSpanLabel(r) {
403
+ const p = periodOf(r.from, r.to);
404
+ if (p?.unit === 'year') return p.a === p.b ? String(p.a) : `${p.a} - ${p.b}`;
405
+ if (p) return p.a === p.b ? monthLabel(p.a) : `${monthLabel(p.a, 'short')} - ${monthLabel(p.b, 'short')}`;
360
406
  return r.from === r.to ? isoDayLabel(r.to) : `${isoDayLabel(r.from)} - ${isoDayLabel(r.to)}`;
361
407
  }
362
408
 
@@ -367,7 +413,15 @@ function rangeSpanLabel(r) {
367
413
  // pluralized as days, and the empty-state article only fits the rolling presets.
368
414
  function rangeText(r, prefix = {}) {
369
415
  const n = normalizeRange(r);
370
- const kind = !n ? 'all' : n.kind === 'custom' ? 'custom' : n.value === 'today' ? 'today' : 'rolling';
416
+ const kind = !n
417
+ ? 'all'
418
+ : n.kind === 'custom'
419
+ ? 'custom'
420
+ : n.value === 'today'
421
+ ? 'today'
422
+ : n.value === 'month' || n.value === 'year'
423
+ ? 'calendar'
424
+ : 'rolling';
371
425
  const base =
372
426
  kind === 'all'
373
427
  ? 'all time'
@@ -375,15 +429,17 @@ function rangeText(r, prefix = {}) {
375
429
  ? rangeSpanLabel(n)
376
430
  : kind === 'today'
377
431
  ? 'today'
378
- : n.value === '24h'
379
- ? '24 hours'
380
- : `${n.value} days`;
432
+ : kind === 'calendar'
433
+ ? `this ${n.value}`
434
+ : n.value === '24h'
435
+ ? '24 hours'
436
+ : `${n.value} days`;
381
437
  return (prefix[kind] || '') + base;
382
438
  }
383
439
 
384
440
  const rangeLabel = (r) => rangeText(r);
385
441
  const rangeScopeLabel = (r) => rangeText(r, { rolling: 'last ' });
386
- const rangeInLabel = (r) => rangeText(r, { all: 'in ', custom: 'in ', rolling: 'in the last ' });
442
+ const rangeInLabel = (r) => rangeText(r, { all: 'in ', custom: 'in ', calendar: 'in ', rolling: 'in the last ' });
387
443
 
388
444
  // Uppercase, for the picker trigger: the preset's own name, or the window's dates.
389
445
  const rangeTriggerLabel = (r) => {
@@ -408,7 +464,11 @@ const rangeCardLabel = (r) => {
408
464
  function isTodayOnlyRange(r) {
409
465
  const n = normalizeRange(r);
410
466
  if (!n) return false;
411
- return n.kind === 'custom' ? n.from === n.to && n.to === todayIso() : n.value === 'today';
467
+ if (n.kind === 'custom') return n.from === n.to && n.to === todayIso();
468
+ const t = todayIso();
469
+ return (
470
+ n.value === 'today' || (n.value === 'month' && t.endsWith('-01')) || (n.value === 'year' && t.endsWith('-01-01'))
471
+ );
412
472
  }
413
473
 
414
474
  function loadSort() {
@@ -536,9 +596,16 @@ function scopeParam() {
536
596
  }
537
597
 
538
598
  // Presets stay on the rolling `range` param, recomputed server-side; a custom window sends its two
539
- // local dates, which take precedence over `range`. Every range-consuming fetch goes through this.
599
+ // local dates, which take precedence over `range`. 'month' and 'year' are the presets resolved here, into
600
+ // the dates of the current month or year so far, so it rolls over on the 1st. Every range-consuming fetch goes
601
+ // through this.
540
602
  function rangeParams(r = dateRange) {
541
- return isCustomRange(r) ? `from=${r.from}&to=${r.to}` : `range=${encodeURIComponent(r.value)}`;
603
+ if (isCustomRange(r)) return `from=${r.from}&to=${r.to}`;
604
+ if (r.value === 'month' || r.value === 'year') {
605
+ const { from, to } = rangePresetSpan(r.value);
606
+ return `from=${from}&to=${to}`;
607
+ }
608
+ return `range=${encodeURIComponent(r.value)}`;
542
609
  }
543
610
 
544
611
  async function fetchOverview() {
@@ -949,7 +1016,12 @@ function renderInsights() {
949
1016
 
950
1017
  <div class="charts-row">
951
1018
  <div class="chart-box">
952
- <div class="chart-title">Token Composition <span class="chart-title-note">log scale</span></div>
1019
+ <div class="chart-title share-head">Token Composition
1020
+ <div class="seg" role="group" aria-label="Measure">
1021
+ <button type="button" class="seg-btn${tokenSplitMode === 'tokens' ? ' on' : ''}" data-token-split="tokens" onclick="setTokenSplitMode('tokens')">tokens</button>
1022
+ <button type="button" class="seg-btn${tokenSplitMode === 'cost' ? ' on' : ''}" data-token-split="cost" onclick="setTokenSplitMode('cost')">cost</button>
1023
+ </div>
1024
+ </div>
953
1025
  <canvas id="tokenSplitChart"></canvas>
954
1026
  </div>
955
1027
  <div class="chart-box">
@@ -1005,7 +1077,7 @@ function renderInsights() {
1005
1077
 
1006
1078
  initHeatmapTooltip();
1007
1079
  requestAnimationFrame(() => {
1008
- renderTokenSplitChart(d.tokens);
1080
+ renderTokenSplitChart(d);
1009
1081
  if (d.tools.length) renderToolsChart(d.tools);
1010
1082
  if (showWeekly) renderWeeklyChart(d.weekly);
1011
1083
  });
@@ -2160,11 +2232,25 @@ function drawRangeOverview(svg, messages) {
2160
2232
  }
2161
2233
  // #endregion
2162
2234
 
2163
- function renderTokenSplitChart(t) {
2235
+ let tokenSplitMode = localStorage.getItem('cc-cost:token-split') === 'cost' ? 'cost' : 'tokens';
2236
+ window.setTokenSplitMode = setTokenSplitMode;
2237
+
2238
+ function setTokenSplitMode(mode) {
2239
+ tokenSplitMode = mode;
2240
+ localStorage.setItem('cc-cost:token-split', mode);
2241
+ for (const b of document.querySelectorAll('[data-token-split]'))
2242
+ b.classList.toggle('on', b.dataset.tokenSplit === mode);
2243
+ if (insightsData) renderTokenSplitChart(insightsData);
2244
+ }
2245
+
2246
+ function renderTokenSplitChart(d) {
2164
2247
  const canvas = document.getElementById('tokenSplitChart');
2165
2248
  if (!canvas) return;
2166
2249
  destroyChart('tokenSplit');
2167
2250
 
2251
+ const byCost = tokenSplitMode === 'cost';
2252
+ const t = byCost ? d.tokenCosts : d.tokens;
2253
+ const fmt = byCost ? formatCost : formatTokens;
2168
2254
  const c = getChartColors();
2169
2255
  const defaults = chartDefaults();
2170
2256
  const rows = [
@@ -2191,13 +2277,16 @@ function renderTokenSplitChart(t) {
2191
2277
  indexAxis: 'y',
2192
2278
  interaction: { mode: 'index', axis: 'y', intersect: false },
2193
2279
  plugins: withTooltip(defaults, {
2194
- label: (ctx) => `${formatTokens(ctx.parsed.x)} (${formatPct(ctx.parsed.x, total)}%)`,
2280
+ label: (ctx) => `${fmt(ctx.parsed.x)} (${formatPct(ctx.parsed.x, total)}%)`,
2195
2281
  }),
2196
2282
  scales: {
2197
2283
  ...defaults.scales,
2198
2284
  // Log scale: cache reads structurally dwarf fresh input by 3-5 orders of magnitude,
2199
2285
  // so a linear axis renders every other bar invisible. Tooltip carries exact values + %.
2200
- x: logAxis(defaults.scales.x, Math.max(...rows.map((r) => r[1]))),
2286
+ // Cost parts sit within about one order of magnitude, so cost mode stays linear.
2287
+ x: byCost
2288
+ ? { ...defaults.scales.x, beginAtZero: true, ticks: { ...defaults.scales.x.ticks, callback: formatCost } }
2289
+ : logAxis(defaults.scales.x, Math.max(...rows.map((r) => r[1]))),
2201
2290
  },
2202
2291
  },
2203
2292
  });
@@ -2371,15 +2460,19 @@ function setColorTheme(id) {
2371
2460
  // #region DATE_PICKER
2372
2461
 
2373
2462
  // Presets are sticky: what is stored is the preset, and the server recomputes its rolling window on
2374
- // every request. `days` only previews the span inside the calendar.
2463
+ // every request.
2375
2464
  const RANGE_PRESETS = [
2376
- { value: 'today', label: 'Today', days: 0 },
2377
- { value: '24h', label: 'Last 24h', days: 1 },
2378
- { value: '3', label: '3 Days', days: 3 },
2379
- { value: '7', label: '7 Days', days: 7 },
2380
- { value: '30', label: '30 Days', days: 30 },
2381
- { value: '90', label: '90 Days', days: 90 },
2382
- { value: '365', label: '1 Year', days: 365, cardLabel: '365 Days' },
2465
+ { value: 'today', label: 'Today' },
2466
+ { value: '24h', label: 'Last 24h' },
2467
+ { value: '3', label: '3 Days' },
2468
+ { value: '7', label: '7 Days' },
2469
+ { value: '30', label: '30 Days' },
2470
+ // Calendar month to date. Sticky like the rolling presets, but resolved here (see monthToDate): the
2471
+ // server has no such preset and only ever sees its two dates.
2472
+ { value: 'month', label: 'This Month', cardLabel: 'This Month' },
2473
+ { value: '90', label: '90 Days' },
2474
+ { value: '365', label: '1 Year', cardLabel: '365 Days' },
2475
+ { value: 'year', label: 'This Year', cardLabel: 'This Year' },
2383
2476
  ];
2384
2477
  const RANGE_DOW = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
2385
2478
  // Two months do not fit a narrow window, so below this the calendar collapses to one. Kept in step
@@ -2412,6 +2505,8 @@ function oneMonthMode() {
2412
2505
  function rangePresetSpan(value) {
2413
2506
  const today = todayIso();
2414
2507
  if (value === '24h') return { from: isoShift(today, -1), to: today };
2508
+ if (value === 'month') return monthToDate();
2509
+ if (value === 'year') return yearSpan(new Date().getFullYear());
2415
2510
  const days = Number(value) || 1;
2416
2511
  return { from: days <= 1 ? today : isoShift(today, -(days - 1)), to: today };
2417
2512
  }
@@ -2453,6 +2548,14 @@ function openRangePicker() {
2453
2548
  // single month it is that month itself.
2454
2549
  const [ay, am] = isoParts(span.to);
2455
2550
  const first = new Date(ay, am - 1 - (oneMonthMode() ? 0 : 1), 1);
2551
+ // A window that is whole months or whole years opens on that grid, so it shows what is picked.
2552
+ const period =
2553
+ applied.kind === 'preset' && applied.value === 'month'
2554
+ ? { unit: 'month', a: span.from.slice(0, 7), b: span.to.slice(0, 7) }
2555
+ : applied.kind === 'preset' && applied.value === 'year'
2556
+ ? { unit: 'year', a: ay, b: ay }
2557
+ : periodOf(span.from, span.to);
2558
+ const thisYear = new Date().getFullYear();
2456
2559
  rangeDraft = {
2457
2560
  from: span.from,
2458
2561
  to: span.to,
@@ -2460,6 +2563,11 @@ function openRangePicker() {
2460
2563
  picking: 'from',
2461
2564
  hover: null,
2462
2565
  month: { y: first.getFullYear(), m: first.getMonth() },
2566
+ mode: period ? period.unit : 'period',
2567
+ // The month grid's year, and the last year of the year grid's page.
2568
+ year: period?.unit === 'month' ? Number(period.a.slice(0, 4)) : ay,
2569
+ yearEnd: period?.unit === 'year' ? Math.min(Math.max(period.b, period.a + 11), thisYear) : thisYear,
2570
+ sel: period ? { unit: period.unit, a: String(period.a), b: String(period.b) } : { unit: null, a: null, b: null },
2463
2571
  };
2464
2572
  document.getElementById('rangePop').classList.add('open');
2465
2573
  document.getElementById('rangeTrigger').classList.add('on');
@@ -2489,8 +2597,116 @@ function closeRangePicker() {
2489
2597
  // selectable days carry data-iso, so the lead padding and the days after today stay inert. It has to
2490
2598
  // be 'mouseover' — 'mouseenter' does not bubble, so it cannot be delegated.
2491
2599
  function onRangeDayClick(e) {
2492
- const iso = e.target.dataset?.iso;
2493
- if (iso) pickRangeDay(iso);
2600
+ const { month, year, iso } = e.target.dataset || {};
2601
+ if (month) pickRangeUnit('month', month);
2602
+ else if (year) pickRangeUnit('year', year);
2603
+ else if (iso) pickRangeDay(iso);
2604
+ }
2605
+
2606
+ // Months and years pick a span the way days do: the first click is the start, the second the end (a
2607
+ // click before the start swaps them), and a third starts over. One click and Apply is a single unit.
2608
+ function pickRangeUnit(unit, value) {
2609
+ const d = rangeDraft;
2610
+ const s = d.sel;
2611
+ d.preset = null;
2612
+ if (s.unit !== unit || !s.a || s.b) d.sel = { unit, a: value, b: null };
2613
+ else d.sel = value < s.a ? { unit, a: value, b: s.a } : { unit, a: s.a, b: value };
2614
+ renderRangePicker();
2615
+ }
2616
+
2617
+ // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
2618
+ function setRangeMode(mode) {
2619
+ const d = rangeDraft;
2620
+ if (!d || d.mode === mode) return;
2621
+ d.mode = mode;
2622
+ if (mode !== 'period' && d.sel.unit !== mode) d.sel = { unit: mode, a: null, b: null };
2623
+ renderRangePicker();
2624
+ }
2625
+
2626
+ // What the month or year selection applies. The running month or year is the sticky preset, so it
2627
+ // keeps following the calendar; any other span is a plain custom window.
2628
+ function selectionRange(sel) {
2629
+ const now = new Date();
2630
+ const b = sel.b || sel.a;
2631
+ if (sel.unit === 'year') {
2632
+ if (sel.a === b && Number(b) === now.getFullYear()) return presetRange('year');
2633
+ return { kind: 'custom', from: yearSpan(Number(sel.a)).from, to: yearSpan(Number(b)).to };
2634
+ }
2635
+ const [ay, am] = isoParts(`${sel.a}-01`);
2636
+ const [by, bm] = isoParts(`${b}-01`);
2637
+ if (sel.a === b && ay === now.getFullYear() && am - 1 === now.getMonth()) return presetRange('month');
2638
+ return { kind: 'custom', from: monthSpan(ay, am - 1).from, to: monthSpan(by, bm - 1).to };
2639
+ }
2640
+
2641
+ function unitIndex(value, mode) {
2642
+ if (mode === 'year') return Number(value);
2643
+ const [y, m] = isoParts(`${value}-01`);
2644
+ return y * 12 + m - 1;
2645
+ }
2646
+
2647
+ function rangeGridStep(step) {
2648
+ const d = rangeDraft;
2649
+ if (d.mode === 'year') d.yearEnd += step * 12;
2650
+ else d.year += step;
2651
+ renderRangePicker();
2652
+ }
2653
+
2654
+ // The month grid (one year, with year arrows) or the year grid (twelve years, paged). Both are
2655
+ // 3 x 4 cells that carry data-month / data-year for the delegated click.
2656
+ function renderRangeUnits(host) {
2657
+ const d = rangeDraft;
2658
+ const now = new Date();
2659
+ const isYear = d.mode === 'year';
2660
+ const first = d.yearEnd - 11;
2661
+ const wrap = document.createElement('div');
2662
+ wrap.className = 'range-cal range-years';
2663
+
2664
+ const head = document.createElement('div');
2665
+ head.className = 'range-cal-head';
2666
+ const step = (dir) => {
2667
+ const btn = document.createElement('button');
2668
+ btn.type = 'button';
2669
+ btn.className = 'range-nav';
2670
+ btn.innerHTML = `<svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">${RANGE_ARROWS[dir]}</svg>`;
2671
+ btn.disabled = dir === 'next' && (isYear ? d.yearEnd : d.year) >= now.getFullYear();
2672
+ btn.addEventListener('click', () => rangeGridStep(dir === 'next' ? 1 : -1));
2673
+ return btn;
2674
+ };
2675
+ const title = document.createElement('span');
2676
+ title.className = 'range-cal-title';
2677
+ title.textContent = isYear ? `${first} - ${d.yearEnd}` : String(d.year);
2678
+ head.append(step('prev'), title, step('next'));
2679
+ wrap.appendChild(head);
2680
+
2681
+ const sel = d.sel.unit === d.mode ? d.sel : { a: null, b: null };
2682
+ const lo = sel.a;
2683
+ const hi = sel.b || sel.a;
2684
+ const grid = document.createElement('div');
2685
+ grid.className = 'range-month-grid';
2686
+ for (let i = 0; i < 12; i++) {
2687
+ const y = isYear ? first + i : d.year;
2688
+ const value = isYear ? String(y) : `${y}-${pad2(i + 1)}`;
2689
+ const btn = document.createElement('button');
2690
+ btn.type = 'button';
2691
+ btn.className = 'range-month';
2692
+ btn.textContent = isYear
2693
+ ? String(y)
2694
+ : new Date(y, i, 1).toLocaleDateString(undefined, { month: 'short' }).toUpperCase();
2695
+ const future = isYear ? y > now.getFullYear() : new Date(y, i, 1) > now;
2696
+ if (future) {
2697
+ btn.disabled = true;
2698
+ btn.classList.add('off');
2699
+ } else {
2700
+ btn.dataset[isYear ? 'year' : 'month'] = value;
2701
+ }
2702
+ if (lo && (value === lo || value === hi)) btn.classList.add('on');
2703
+ else if (lo && value > lo && value < hi) btn.classList.add('in');
2704
+ const current = isYear ? y === now.getFullYear() : y === now.getFullYear() && i === now.getMonth();
2705
+ if (current) btn.classList.add('today');
2706
+ grid.appendChild(btn);
2707
+ }
2708
+ wrap.appendChild(grid);
2709
+ host.appendChild(wrap);
2494
2710
  }
2495
2711
 
2496
2712
  function onRangeDayHover(e) {
@@ -2516,8 +2732,8 @@ function aimRangePicker(which) {
2516
2732
  // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
2517
2733
  function applyRangeDraft() {
2518
2734
  const d = rangeDraft;
2519
- if (!d?.from || !d.to) return;
2520
- const next = { kind: 'custom', from: d.from, to: d.to };
2735
+ if (!d || (d.mode === 'period' ? !d.from || !d.to : !d.sel.a)) return;
2736
+ const next = d.mode === 'period' ? { kind: 'custom', from: d.from, to: d.to } : selectionRange(d.sel);
2521
2737
  closeRangePicker();
2522
2738
  applyRange(next);
2523
2739
  }
@@ -2588,6 +2804,22 @@ function renderRangePicker() {
2588
2804
  b.classList.toggle('on', b.dataset.value === d.preset);
2589
2805
  }
2590
2806
 
2807
+ document.getElementById('rangePop').classList.toggle('unit-mode', d.mode !== 'period');
2808
+ for (const btn of document.querySelectorAll('#rangeMode .range-mode-btn')) {
2809
+ btn.setAttribute('aria-pressed', String(btn.dataset.mode === d.mode));
2810
+ }
2811
+ if (d.mode !== 'period') {
2812
+ const unitHost = document.getElementById('rangeMonths');
2813
+ unitHost.innerHTML = '';
2814
+ renderRangeUnits(unitHost);
2815
+ const { a, b } = d.sel.unit === d.mode ? d.sel : {};
2816
+ const n = a ? Math.abs(unitIndex(b || a, d.mode) - unitIndex(a, d.mode)) + 1 : 0;
2817
+ const noun = d.mode === 'year' ? 'year' : 'month';
2818
+ document.getElementById('rangeSummary').textContent = n ? `${n} ${noun}${n === 1 ? '' : 's'}` : `pick a ${noun}`;
2819
+ document.getElementById('rangeApply').disabled = !a;
2820
+ return;
2821
+ }
2822
+
2591
2823
  const fromBox = document.getElementById('rangeFromBox');
2592
2824
  const toBox = document.getElementById('rangeToBox');
2593
2825
  fromBox.textContent = d.from ? isoDayLabel(d.from) : '—';
package/public/index.html CHANGED
@@ -53,6 +53,11 @@
53
53
  <div class="range-head-label">Shortcuts</div>
54
54
  </div>
55
55
  <div class="range-cal-side">
56
+ <div class="range-mode" id="rangeMode" role="group" aria-label="Pick by">
57
+ <button class="range-mode-btn" data-mode="period" aria-pressed="true" onclick="setRangeMode('period')">Days</button>
58
+ <button class="range-mode-btn" data-mode="month" aria-pressed="false" onclick="setRangeMode('month')">Months</button>
59
+ <button class="range-mode-btn" data-mode="year" aria-pressed="false" onclick="setRangeMode('year')">Years</button>
60
+ </div>
56
61
  <div class="range-fields">
57
62
  <div class="range-field">
58
63
  <span class="range-head-label">From</span>
package/public/style.css CHANGED
@@ -620,6 +620,84 @@ body {
620
620
  filter: none;
621
621
  }
622
622
 
623
+ /* Period | Month | Year switch above the calendar; month and year modes swap the day grid for twelve
624
+ cells and drop the From/To fields. Cells pick a span the way days do, then Apply. */
625
+ .range-mode {
626
+ display: inline-flex;
627
+ margin: 0 2px 8px;
628
+ border: 1px solid var(--border);
629
+ border-radius: 5px;
630
+ overflow: hidden;
631
+ }
632
+ .range-mode-btn {
633
+ border: 0;
634
+ background: var(--bg-surface);
635
+ color: var(--text-tertiary);
636
+ font-family: var(--mono);
637
+ font-size: 11px;
638
+ text-transform: uppercase;
639
+ letter-spacing: 0.03em;
640
+ padding: 4px 12px;
641
+ cursor: pointer;
642
+ }
643
+ .range-mode-btn + .range-mode-btn {
644
+ border-left: 1px solid var(--border);
645
+ }
646
+ .range-mode-btn:hover {
647
+ color: var(--text-primary);
648
+ }
649
+ .range-mode-btn[aria-pressed='true'] {
650
+ background: var(--accent-dim);
651
+ color: var(--accent-text);
652
+ }
653
+
654
+ .range-pop.unit-mode .range-fields {
655
+ display: none;
656
+ }
657
+ .range-years {
658
+ width: 100%;
659
+ min-width: 196px;
660
+ }
661
+ .range-month-grid {
662
+ display: grid;
663
+ grid-template-columns: repeat(3, 1fr);
664
+ gap: 4px;
665
+ }
666
+ .range-month {
667
+ height: 34px;
668
+ border: 1px solid var(--border);
669
+ border-radius: 5px;
670
+ background: var(--bg-surface);
671
+ color: var(--text-secondary);
672
+ font-family: var(--mono);
673
+ font-size: 11px;
674
+ letter-spacing: 0.04em;
675
+ cursor: pointer;
676
+ position: relative;
677
+ }
678
+ .range-month:hover:not(.off) {
679
+ border-color: var(--accent);
680
+ color: var(--text-primary);
681
+ }
682
+ .range-month.today {
683
+ color: var(--accent-text);
684
+ }
685
+ .range-month.in {
686
+ background: var(--accent-dim);
687
+ color: var(--text-primary);
688
+ }
689
+ .range-month.on {
690
+ background: var(--accent);
691
+ border-color: var(--accent);
692
+ color: #fff;
693
+ font-weight: 500;
694
+ }
695
+ .range-month.off {
696
+ color: var(--text-muted);
697
+ opacity: 0.5;
698
+ cursor: default;
699
+ }
700
+
623
701
  /* #endregion */
624
702
 
625
703
  /* #region LAYOUT */