claude-code-cost 1.3.2 → 1.5.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 +2 -0
- package/hub-app.json +2 -1
- package/lib/app.js +227 -0
- package/lib/cli.js +661 -0
- package/lib/costs.js +1634 -0
- package/package.json +1 -1
- package/public/app.js +236 -28
- package/public/style.css +142 -1
- package/server.js +6 -1605
package/server.js
CHANGED
|
@@ -1,1611 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
|
-
const
|
|
5
|
-
const path = require('node:path');
|
|
6
|
-
const fs = require('node:fs');
|
|
7
|
-
const { createReadStream } = fs;
|
|
8
|
-
const { createInterface } = require('node:readline');
|
|
9
|
-
const os = require('node:os');
|
|
10
|
-
const { createNetGuard } = require('./lib/net-guard');
|
|
11
|
-
const { probeUsage, normalizeUsage } = require('./lib/usage-probe');
|
|
4
|
+
const cli = require('./lib/cli');
|
|
12
5
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const eqIdx = process.argv.findIndex(a => a === `--${name}` || a.startsWith(`--${name}=`));
|
|
17
|
-
if (eqIdx === -1) return null;
|
|
18
|
-
const arg = process.argv[eqIdx];
|
|
19
|
-
if (arg.includes('=')) return arg.split('=').slice(1).join('=');
|
|
20
|
-
return process.argv[eqIdx + 1] || null;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const PORT = getArg('port') || process.env.PORT || 3543;
|
|
24
|
-
const claudeDirArg = getArg('dir') || process.env.CLAUDE_CONFIG_DIR || process.env.CLAUDE_DIR;
|
|
25
|
-
const DEFAULT_CLAUDE_DIR = path.join(os.homedir(), '.claude');
|
|
26
|
-
const CLAUDE_DIR = claudeDirArg ? claudeDirArg.replace(/^~/, os.homedir()) : DEFAULT_CLAUDE_DIR;
|
|
27
|
-
|
|
28
|
-
const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
|
|
29
|
-
// XDG-style location some builds used for the default profile only. A custom
|
|
30
|
-
// CLAUDE_CONFIG_DIR holds everything itself, so scanning it there would leak
|
|
31
|
-
// the home profile's sessions into the custom one.
|
|
32
|
-
const ALT_PROJECTS_DIR = path.resolve(CLAUDE_DIR) === path.resolve(DEFAULT_CLAUDE_DIR)
|
|
33
|
-
? path.join(os.homedir(), '.config', 'claude', 'projects')
|
|
34
|
-
: null;
|
|
35
|
-
|
|
36
|
-
function getProjectsDirs() {
|
|
37
|
-
const dirs = [];
|
|
38
|
-
if (fs.existsSync(PROJECTS_DIR)) dirs.push(PROJECTS_DIR);
|
|
39
|
-
if (ALT_PROJECTS_DIR && fs.existsSync(ALT_PROJECTS_DIR)) dirs.push(ALT_PROJECTS_DIR);
|
|
40
|
-
return dirs;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// #endregion
|
|
44
|
-
|
|
45
|
-
// #region PRICING
|
|
46
|
-
|
|
47
|
-
const LITELLM_PRICING_URL =
|
|
48
|
-
'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
|
|
49
|
-
|
|
50
|
-
const PROVIDER_PREFIXES = ['anthropic/', 'claude-3-5-', 'claude-3-', 'claude-'];
|
|
51
|
-
const TIERED_THRESHOLD = 200_000;
|
|
52
|
-
const PRICING_REFRESH_MS = 6 * 60 * 60 * 1000;
|
|
53
|
-
|
|
54
|
-
let cachedPricing = null;
|
|
55
|
-
let pricingFetchedAt = 0;
|
|
56
|
-
|
|
57
|
-
const OFFLINE_PRICING = {
|
|
58
|
-
'anthropic/claude-sonnet-4-20250514': {
|
|
59
|
-
input_cost_per_token: 3e-6, output_cost_per_token: 1.5e-5,
|
|
60
|
-
cache_creation_input_token_cost: 3.75e-6, cache_read_input_token_cost: 3e-7,
|
|
61
|
-
input_cost_per_token_above_200k_tokens: 6e-6, output_cost_per_token_above_200k_tokens: 2.25e-5,
|
|
62
|
-
cache_creation_input_token_cost_above_200k_tokens: 7.5e-6, cache_read_input_token_cost_above_200k_tokens: 6e-7,
|
|
63
|
-
},
|
|
64
|
-
'anthropic/claude-opus-4-20250514': {
|
|
65
|
-
input_cost_per_token: 1.5e-5, output_cost_per_token: 7.5e-5,
|
|
66
|
-
cache_creation_input_token_cost: 1.875e-5, cache_read_input_token_cost: 1.5e-6,
|
|
67
|
-
input_cost_per_token_above_200k_tokens: 3e-5, output_cost_per_token_above_200k_tokens: 1.125e-4,
|
|
68
|
-
cache_creation_input_token_cost_above_200k_tokens: 3.75e-5, cache_read_input_token_cost_above_200k_tokens: 3e-6,
|
|
69
|
-
provider_specific_entry: { fast: 6.0 },
|
|
70
|
-
},
|
|
71
|
-
'anthropic/claude-haiku-4-5-20251001': {
|
|
72
|
-
input_cost_per_token: 8e-7, output_cost_per_token: 4e-6,
|
|
73
|
-
cache_creation_input_token_cost: 1e-6, cache_read_input_token_cost: 8e-8,
|
|
74
|
-
input_cost_per_token_above_200k_tokens: 1.6e-6, output_cost_per_token_above_200k_tokens: 6e-6,
|
|
75
|
-
cache_creation_input_token_cost_above_200k_tokens: 2e-6, cache_read_input_token_cost_above_200k_tokens: 1.6e-7,
|
|
76
|
-
},
|
|
77
|
-
'anthropic/claude-3-5-sonnet-20241022': {
|
|
78
|
-
input_cost_per_token: 3e-6, output_cost_per_token: 1.5e-5,
|
|
79
|
-
cache_creation_input_token_cost: 3.75e-6, cache_read_input_token_cost: 3e-7,
|
|
80
|
-
},
|
|
81
|
-
'anthropic/claude-3-5-haiku-20241022': {
|
|
82
|
-
input_cost_per_token: 8e-7, output_cost_per_token: 4e-6,
|
|
83
|
-
cache_creation_input_token_cost: 1e-6, cache_read_input_token_cost: 8e-8,
|
|
84
|
-
},
|
|
85
|
-
};
|
|
86
|
-
|
|
87
|
-
async function fetchPricing() {
|
|
88
|
-
const now = Date.now();
|
|
89
|
-
if (cachedPricing && (now - pricingFetchedAt) < PRICING_REFRESH_MS) return cachedPricing;
|
|
90
|
-
|
|
91
|
-
try {
|
|
92
|
-
console.log('[Pricing] Fetching from LiteLLM...');
|
|
93
|
-
const resp = await fetch(LITELLM_PRICING_URL);
|
|
94
|
-
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
|
95
|
-
const data = await resp.json();
|
|
96
|
-
const pricing = new Map();
|
|
97
|
-
for (const [name, info] of Object.entries(data)) {
|
|
98
|
-
if (typeof info !== 'object' || info == null) continue;
|
|
99
|
-
if (info.input_cost_per_token != null || info.output_cost_per_token != null) {
|
|
100
|
-
pricing.set(name, info);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
cachedPricing = pricing;
|
|
104
|
-
pricingFetchedAt = now;
|
|
105
|
-
console.log(`[Pricing] Loaded ${pricing.size} models`);
|
|
106
|
-
return pricing;
|
|
107
|
-
} catch (err) {
|
|
108
|
-
console.warn('[Pricing] Fetch failed, using offline fallback:', err.message);
|
|
109
|
-
if (!cachedPricing) {
|
|
110
|
-
cachedPricing = new Map(Object.entries(OFFLINE_PRICING));
|
|
111
|
-
pricingFetchedAt = now;
|
|
112
|
-
}
|
|
113
|
-
return cachedPricing;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
function getModelPricing(pricing, modelName) {
|
|
118
|
-
if (!modelName) return null;
|
|
119
|
-
|
|
120
|
-
// Exact match
|
|
121
|
-
const direct = pricing.get(modelName);
|
|
122
|
-
if (direct) return direct;
|
|
123
|
-
|
|
124
|
-
// Try with provider prefixes
|
|
125
|
-
for (const prefix of PROVIDER_PREFIXES) {
|
|
126
|
-
const candidate = pricing.get(`${prefix}${modelName}`);
|
|
127
|
-
if (candidate) return candidate;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// Fuzzy lowercase match
|
|
131
|
-
const lower = modelName.toLowerCase();
|
|
132
|
-
for (const [key, value] of pricing) {
|
|
133
|
-
const cmp = key.toLowerCase();
|
|
134
|
-
if (cmp.includes(lower) || lower.includes(cmp)) return value;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
return null;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function calculateTieredCost(totalTokens, basePrice, tieredPrice, threshold = TIERED_THRESHOLD) {
|
|
141
|
-
if (!totalTokens || totalTokens <= 0) return 0;
|
|
142
|
-
if (totalTokens > threshold && tieredPrice != null) {
|
|
143
|
-
const below = Math.min(totalTokens, threshold);
|
|
144
|
-
const above = Math.max(0, totalTokens - threshold);
|
|
145
|
-
let cost = above * tieredPrice;
|
|
146
|
-
if (basePrice != null) cost += below * basePrice;
|
|
147
|
-
return cost;
|
|
148
|
-
}
|
|
149
|
-
if (basePrice != null) return totalTokens * basePrice;
|
|
150
|
-
return 0;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
function calculateCost(tokens, modelPricing) {
|
|
154
|
-
const inputCost = calculateTieredCost(
|
|
155
|
-
tokens.input_tokens, modelPricing.input_cost_per_token,
|
|
156
|
-
modelPricing.input_cost_per_token_above_200k_tokens);
|
|
157
|
-
const outputCost = calculateTieredCost(
|
|
158
|
-
tokens.output_tokens, modelPricing.output_cost_per_token,
|
|
159
|
-
modelPricing.output_cost_per_token_above_200k_tokens);
|
|
160
|
-
const cacheCreationCost = calculateTieredCost(
|
|
161
|
-
tokens.cache_creation_input_tokens, modelPricing.cache_creation_input_token_cost,
|
|
162
|
-
modelPricing.cache_creation_input_token_cost_above_200k_tokens);
|
|
163
|
-
const cacheReadCost = calculateTieredCost(
|
|
164
|
-
tokens.cache_read_input_tokens, modelPricing.cache_read_input_token_cost,
|
|
165
|
-
modelPricing.cache_read_input_token_cost_above_200k_tokens);
|
|
166
|
-
return inputCost + outputCost + cacheCreationCost + cacheReadCost;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
function calculateCostForModel(tokens, modelName, pricing, speed) {
|
|
170
|
-
const mp = getModelPricing(pricing, modelName);
|
|
171
|
-
if (!mp) return 0;
|
|
172
|
-
const baseCost = calculateCost(tokens, mp);
|
|
173
|
-
const multiplier = speed === 'fast' ? (mp.provider_specific_entry?.fast ?? 1) : 1;
|
|
174
|
-
return baseCost * multiplier;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// #endregion
|
|
178
|
-
|
|
179
|
-
// #region JSONL_PARSING
|
|
180
|
-
|
|
181
|
-
async function processJSONLFile(filePath, processLine) {
|
|
182
|
-
const fileStream = createReadStream(filePath, { encoding: 'utf-8' });
|
|
183
|
-
const rl = createInterface({ input: fileStream, crlfDelay: Infinity });
|
|
184
|
-
let lineNumber = 0;
|
|
185
|
-
for await (const line of rl) {
|
|
186
|
-
lineNumber++;
|
|
187
|
-
if (line.trim().length === 0) continue;
|
|
188
|
-
await processLine(line, lineNumber);
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
function createDedupeHash(data) {
|
|
194
|
-
const mid = data.message?.id;
|
|
195
|
-
const rid = data.requestId;
|
|
196
|
-
if (!mid || !rid) return null;
|
|
197
|
-
return `${mid}:${rid}`;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
function extractTools(content) {
|
|
201
|
-
if (!Array.isArray(content)) return null;
|
|
202
|
-
const tools = content
|
|
203
|
-
.filter(c => c.type === 'tool_use' && c.name)
|
|
204
|
-
.map(c => c.name);
|
|
205
|
-
return tools.length > 0 ? tools : null;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
function calculateEntryCost(data, pricing) {
|
|
209
|
-
// Auto mode: use costUSD if present, otherwise calculate
|
|
210
|
-
if (data.costUSD != null) return data.costUSD;
|
|
211
|
-
const model = data.message?.model;
|
|
212
|
-
if (!model) return 0;
|
|
213
|
-
const speed = data.message?.usage?.speed;
|
|
214
|
-
return calculateCostForModel(data.message.usage, model, pricing, speed);
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// The summarization call behind a compact_boundary is not logged with usage, so its cost is an
|
|
218
|
-
// estimate: the whole pre-compaction context read from cache, and a summary no larger than the
|
|
219
|
-
// post-compaction context written out.
|
|
220
|
-
function estimateCompactionCost(meta, model, pricing) {
|
|
221
|
-
return calculateCostForModel(
|
|
222
|
-
{ output_tokens: meta.postTokens, cache_read_input_tokens: meta.preTokens },
|
|
223
|
-
model, pricing);
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function compactionFacts(parsed) {
|
|
227
|
-
const meta = parsed.compactMetadata || {};
|
|
228
|
-
const preTokens = meta.preTokens || 0;
|
|
229
|
-
const postTokens = meta.postTokens || 0;
|
|
230
|
-
return {
|
|
231
|
-
timestamp: parsed.timestamp,
|
|
232
|
-
trigger: meta.trigger || 'unknown',
|
|
233
|
-
preTokens,
|
|
234
|
-
postTokens,
|
|
235
|
-
droppedTokens: Math.max(0, preTokens - postTokens),
|
|
236
|
-
durationMs: meta.durationMs || 0,
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
// The first turn after a boundary rebuilds the prompt cache from the summary, so its cache
|
|
241
|
-
// creation is spend the compaction caused. It is already in the session total; the record only
|
|
242
|
-
// attributes it. Models without pricing get null, not a zero that reads as "free".
|
|
243
|
-
function priceCompaction(facts, msg, pricing) {
|
|
244
|
-
const model = isRealModel(msg.model) ? msg.model : null;
|
|
245
|
-
return {
|
|
246
|
-
...facts,
|
|
247
|
-
estCost: model ? estimateCompactionCost(facts, model, pricing) : null,
|
|
248
|
-
rewarmTokens: msg.cacheCreationTokens,
|
|
249
|
-
rewarmCost: model
|
|
250
|
-
? calculateCostForModel({ cache_creation_input_tokens: msg.cacheCreationTokens }, model, pricing, msg.speed)
|
|
251
|
-
: null,
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// #endregion
|
|
256
|
-
|
|
257
|
-
// #region DATA_AGGREGATION
|
|
258
|
-
|
|
259
|
-
const CACHE_TTL = 30_000;
|
|
260
|
-
|
|
261
|
-
// Custom from/to windows make the key space unbounded, so the cache is capped, which would
|
|
262
|
-
// otherwise grow for the process lifetime. A Map keeps insertion order, so the oldest write is
|
|
263
|
-
// always the first key — no sort, no key array.
|
|
264
|
-
const MAX_CACHE_ENTRIES = 50;
|
|
265
|
-
const dataCache = new Map();
|
|
266
|
-
|
|
267
|
-
// undefined means "no usable entry": every cached payload is an object or an array, so it can
|
|
268
|
-
// never collide with a real one. A stale hit is dropped here rather than left resident until the
|
|
269
|
-
// cap pushes it out — detail_<id> entries carry a whole message array.
|
|
270
|
-
function getCache(key) {
|
|
271
|
-
const hit = dataCache.get(key);
|
|
272
|
-
if (!hit) return undefined;
|
|
273
|
-
if ((Date.now() - hit.ts) >= CACHE_TTL) {
|
|
274
|
-
dataCache.delete(key);
|
|
275
|
-
return undefined;
|
|
276
|
-
}
|
|
277
|
-
return hit.data;
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
function setCache(key, data) {
|
|
281
|
-
// Re-inserting moves an existing key to the back, so a rewrite resets its eviction priority.
|
|
282
|
-
dataCache.delete(key);
|
|
283
|
-
dataCache.set(key, { data, ts: Date.now() });
|
|
284
|
-
while (dataCache.size > MAX_CACHE_ENTRIES) {
|
|
285
|
-
dataCache.delete(dataCache.keys().next().value);
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function invalidateAllCache() {
|
|
290
|
-
dataCache.clear();
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
function localDateStr(d) {
|
|
294
|
-
const y = d.getFullYear();
|
|
295
|
-
const m = String(d.getMonth() + 1).padStart(2, '0');
|
|
296
|
-
const day = String(d.getDate()).padStart(2, '0');
|
|
297
|
-
return `${y}-${m}-${day}`;
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
function localHourStr(d) {
|
|
301
|
-
return `${localDateStr(d)}T${String(d.getHours()).padStart(2, '0')}`;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
// Cost is bucketed by one of these; the key doubles as the aggregation key and the wire label.
|
|
305
|
-
// An hour key extends the day key (YYYY-MM-DD -> YYYY-MM-DDTHH), so a startsWith test on a day
|
|
306
|
-
// string matches either granularity.
|
|
307
|
-
const BUCKETS = {
|
|
308
|
-
day: {
|
|
309
|
-
key: localDateStr,
|
|
310
|
-
floor: (d) => d.setHours(0, 0, 0, 0),
|
|
311
|
-
next: (d) => d.setDate(d.getDate() + 1),
|
|
312
|
-
},
|
|
313
|
-
hour: {
|
|
314
|
-
key: localHourStr,
|
|
315
|
-
floor: (d) => d.setMinutes(0, 0, 0),
|
|
316
|
-
next: (d) => d.setHours(d.getHours() + 1),
|
|
317
|
-
},
|
|
318
|
-
};
|
|
319
|
-
|
|
320
|
-
// A one-day window collapses the daily chart into a single bar, so those ranges bucket by hour.
|
|
321
|
-
function rangeBucket(range) {
|
|
322
|
-
if (isCustomRange(range)) return range.from === range.to ? 'hour' : 'day';
|
|
323
|
-
return range === 'today' || range === '24h' || range === 1 ? 'hour' : 'day';
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
// Non-real (synthetic) models group under 'other' so the series still sums to the true
|
|
327
|
-
// bucket total, unlike modelDistribution which drops them entirely.
|
|
328
|
-
function addBucketModelCost(acc, key, model, cost) {
|
|
329
|
-
const mk = isRealModel(model) ? model : 'other';
|
|
330
|
-
acc[key] ||= {};
|
|
331
|
-
acc[key][mk] = (acc[key][mk] || 0) + cost;
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
// Gap-filled so empty buckets stay visible in the chart. The bucket total is derived from
|
|
335
|
-
// the per-model map, so the two can never disagree.
|
|
336
|
-
function buildCostSeries(modelCostsByBucket, start, end, bucket) {
|
|
337
|
-
const b = BUCKETS[bucket];
|
|
338
|
-
const points = [];
|
|
339
|
-
if (Object.keys(modelCostsByBucket).length === 0) return points;
|
|
340
|
-
const d = new Date(start);
|
|
341
|
-
b.floor(d);
|
|
342
|
-
for (; d <= end; b.next(d)) {
|
|
343
|
-
const k = b.key(d);
|
|
344
|
-
const byModel = modelCostsByBucket[k] || {};
|
|
345
|
-
points.push({ key: k, cost: Object.values(byModel).reduce((s, v) => s + v, 0), byModel });
|
|
346
|
-
}
|
|
347
|
-
return points;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
function buildModelDistribution(modelCosts) {
|
|
351
|
-
return Object.entries(modelCosts)
|
|
352
|
-
.filter(([model, cost]) => cost > 0 && isRealModel(model))
|
|
353
|
-
.map(([model, cost]) => ({ model, cost }))
|
|
354
|
-
.sort((a, b) => b.cost - a.cost);
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
// onlyKey narrows the scan to encoded project dirs, comma-separated: a repo and its linked
|
|
358
|
-
// worktrees are separate dirs. The dir name *is* the key, so this skips the per-project readdir
|
|
359
|
-
// and per-file statSync for everything else.
|
|
360
|
-
function scanProjectDirs(cutoffDate, onlyKey) {
|
|
361
|
-
const projects = new Map();
|
|
362
|
-
const cutoffMs = cutoffDate ? cutoffDate.getTime() : 0;
|
|
363
|
-
const only = onlyKey ? new Set(onlyKey.split(',')) : null;
|
|
364
|
-
for (const baseDir of getProjectsDirs()) {
|
|
365
|
-
try {
|
|
366
|
-
const entries = fs.readdirSync(baseDir, { withFileTypes: true });
|
|
367
|
-
for (const entry of entries) {
|
|
368
|
-
if (!entry.isDirectory()) continue;
|
|
369
|
-
if (only && !only.has(entry.name)) continue;
|
|
370
|
-
const projDir = path.join(baseDir, entry.name);
|
|
371
|
-
const files = [];
|
|
372
|
-
try {
|
|
373
|
-
for (const f of fs.readdirSync(projDir)) {
|
|
374
|
-
if (!f.endsWith('.jsonl')) continue;
|
|
375
|
-
const filePath = path.join(projDir, f);
|
|
376
|
-
// Skip files not modified since cutoff date
|
|
377
|
-
if (cutoffMs) {
|
|
378
|
-
try {
|
|
379
|
-
const mtime = fs.statSync(filePath).mtimeMs;
|
|
380
|
-
if (mtime < cutoffMs) continue;
|
|
381
|
-
} catch { continue; }
|
|
382
|
-
}
|
|
383
|
-
files.push(filePath);
|
|
384
|
-
}
|
|
385
|
-
} catch { /* ignore */ }
|
|
386
|
-
if (files.length > 0) {
|
|
387
|
-
const key = entry.name;
|
|
388
|
-
if (!projects.has(key)) {
|
|
389
|
-
projects.set(key, { encodedPath: key, dir: projDir, files });
|
|
390
|
-
} else {
|
|
391
|
-
projects.get(key).files.push(...files);
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
} catch { /* dir doesn't exist */ }
|
|
396
|
-
}
|
|
397
|
-
return projects;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
function decodeProjectPath(encoded) {
|
|
401
|
-
try {
|
|
402
|
-
// Claude encodes paths as: C--Users-name-dev-project
|
|
403
|
-
// "C--" = drive prefix, then "-" separates path segments
|
|
404
|
-
// But hyphens in actual folder names also become "-" (ambiguous)
|
|
405
|
-
// Strategy: strip known prefixes to reveal project name
|
|
406
|
-
let name = encoded;
|
|
407
|
-
// Strip drive + common base paths: C--Users-username-dev- or similar
|
|
408
|
-
name = name.replace(/^[A-Z]--[^-]+-[^-]+-(dev|src|repos|projects|work|code)-/, '');
|
|
409
|
-
// Strip C--Users-username--config- or C--Users-username--claude- patterns
|
|
410
|
-
name = name.replace(/^[A-Z]--[^-]+-[^-]+--([^-]+)-/, '$1/');
|
|
411
|
-
// Strip C--Users-username- if still there
|
|
412
|
-
name = name.replace(/^[A-Z]--[^-]+-[^-]+-/, '');
|
|
413
|
-
return name || encoded;
|
|
414
|
-
} catch { return encoded; }
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
// The folder name is lossy (separators and hyphens both become "-"), so the cwd a transcript
|
|
418
|
-
// records names the project; the decode is the fallback for folders with no cwd line.
|
|
419
|
-
const CWD_RE = /"cwd":"((?:[^"\\]|\\.)*)"/;
|
|
420
|
-
const projectNames = new Map();
|
|
421
|
-
|
|
422
|
-
function readCwd(filePath) {
|
|
423
|
-
let fd;
|
|
424
|
-
try {
|
|
425
|
-
fd = fs.openSync(filePath, 'r');
|
|
426
|
-
const buf = Buffer.alloc(64 * 1024);
|
|
427
|
-
const n = fs.readSync(fd, buf, 0, buf.length, 0);
|
|
428
|
-
const m = buf.toString('utf-8', 0, n).match(CWD_RE);
|
|
429
|
-
return m ? JSON.parse(`"${m[1]}"`) : null;
|
|
430
|
-
} catch { return null; } finally {
|
|
431
|
-
if (fd !== undefined) fs.closeSync(fd);
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
function projectName(encodedPath, files) {
|
|
436
|
-
if (projectNames.has(encodedPath)) return projectNames.get(encodedPath);
|
|
437
|
-
const cwd = files.slice(0, 3).map(readCwd).find(Boolean);
|
|
438
|
-
if (!cwd) return decodeProjectPath(encodedPath);
|
|
439
|
-
const name = cwd.split(/[\\/]/).filter(Boolean).pop() || decodeProjectPath(encodedPath);
|
|
440
|
-
projectNames.set(encodedPath, name);
|
|
441
|
-
return name;
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
function getSessionIdFromFile(filePath) {
|
|
445
|
-
return path.basename(filePath, '.jsonl');
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
function readdirSafe(dir) {
|
|
449
|
-
try { return fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
// Agents sit at subagents/agent-*.jsonl, but a Workflow run nests its own under
|
|
453
|
-
// subagents/workflows/<wfId>/ — and a workflow that starts a workflow nests deeper still, so walk
|
|
454
|
-
// rather than hard-code the depth. Descending only into a listed entry also keeps the common
|
|
455
|
-
// no-workflow session at one readdir.
|
|
456
|
-
function collectAgents(dir, workflowId, out) {
|
|
457
|
-
for (const e of readdirSafe(dir)) {
|
|
458
|
-
if (e.isDirectory()) {
|
|
459
|
-
if (e.name !== 'workflows') continue;
|
|
460
|
-
const runsDir = path.join(dir, e.name);
|
|
461
|
-
for (const run of readdirSafe(runsDir)) {
|
|
462
|
-
if (run.isDirectory()) collectAgents(path.join(runsDir, run.name), run.name, out);
|
|
463
|
-
}
|
|
464
|
-
continue;
|
|
465
|
-
}
|
|
466
|
-
// A workflow run also drops its journal.jsonl next to the agents; only `agent-*.jsonl` is a
|
|
467
|
-
// transcript, and counting the journal inflated the run's agent count by one and stretched its
|
|
468
|
-
// span, since a file with no priced turns falls back to the session's own start time.
|
|
469
|
-
if (!e.name.startsWith('agent-') || !e.name.endsWith('.jsonl')) continue;
|
|
470
|
-
const agentId = e.name.replace('.jsonl', '');
|
|
471
|
-
let meta = {};
|
|
472
|
-
try { meta = JSON.parse(fs.readFileSync(path.join(dir, `${agentId}.meta.json`), 'utf-8')); } catch { /* no meta */ }
|
|
473
|
-
out.push({
|
|
474
|
-
agentId,
|
|
475
|
-
filePath: path.join(dir, e.name),
|
|
476
|
-
agentType: meta.agentType || 'unknown',
|
|
477
|
-
description: meta.description || '',
|
|
478
|
-
workflowId,
|
|
479
|
-
});
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
function scanSubagentDir(sessionDir) {
|
|
484
|
-
const result = [];
|
|
485
|
-
collectAgents(path.join(sessionDir, 'subagents'), null, result);
|
|
486
|
-
return result;
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
// The run's script is saved as <name>-<wfId>.js under a session dir keyed by the workflow's cwd,
|
|
490
|
-
// which need not be the project the session file lives in — so the session's own project dir is
|
|
491
|
-
// only the likely home, and a miss falls back to sweeping the rest.
|
|
492
|
-
function findWorkflowNames(sessionId, wantedIds, likelyProjectDir) {
|
|
493
|
-
const names = new Map();
|
|
494
|
-
const wanted = new Set(wantedIds);
|
|
495
|
-
const scan = (projectDir) => {
|
|
496
|
-
for (const f of readdirSafe(path.join(projectDir, sessionId, 'workflows', 'scripts'))) {
|
|
497
|
-
const m = f.name.match(/^(.*)-(wf_.+)\.js$/);
|
|
498
|
-
if (m && wanted.has(m[2])) names.set(m[2], m[1]);
|
|
499
|
-
}
|
|
500
|
-
return names.size === wanted.size;
|
|
501
|
-
};
|
|
502
|
-
for (const baseDir of getProjectsDirs()) {
|
|
503
|
-
if (scan(path.join(baseDir, likelyProjectDir))) return names;
|
|
504
|
-
}
|
|
505
|
-
for (const baseDir of getProjectsDirs()) {
|
|
506
|
-
for (const e of readdirSafe(baseDir)) {
|
|
507
|
-
if (e.isDirectory() && e.name !== likelyProjectDir && scan(path.join(baseDir, e.name))) return names;
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
return names;
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
// `<synthetic>` and friends are Claude Code bookkeeping entries, not models the user chose.
|
|
514
|
-
function isRealModel(model) {
|
|
515
|
-
return !!model && !model.startsWith('<');
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
function mostFrequentModel(counts) {
|
|
519
|
-
return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
async function loadSubagentData(subagentInfos, pricing) {
|
|
523
|
-
return Promise.all(subagentInfos.map(async (info) => {
|
|
524
|
-
const agent = {
|
|
525
|
-
agentId: info.agentId,
|
|
526
|
-
agentType: info.agentType,
|
|
527
|
-
description: info.description,
|
|
528
|
-
workflowId: info.workflowId || null,
|
|
529
|
-
totalCost: 0,
|
|
530
|
-
inputTokens: 0, outputTokens: 0,
|
|
531
|
-
cacheCreationTokens: 0, cacheReadTokens: 0,
|
|
532
|
-
messageCount: 0,
|
|
533
|
-
models: new Set(),
|
|
534
|
-
firstTimestamp: null,
|
|
535
|
-
lastTimestamp: null,
|
|
536
|
-
};
|
|
537
|
-
// An agent log writes one line per streamed content block, each carrying the usage as it stood
|
|
538
|
-
// then, so a turn's first line can report one output token and its last the whole reply: the
|
|
539
|
-
// turn is the largest usage logged for its (message.id, requestId). The session log repeats the
|
|
540
|
-
// final usage on every line, which is why first-wins reads the same there.
|
|
541
|
-
const kept = new Map();
|
|
542
|
-
const unhashed = [];
|
|
543
|
-
await processJSONLFile(info.filePath, async (line) => {
|
|
544
|
-
let parsed;
|
|
545
|
-
try { parsed = JSON.parse(line); } catch { return; }
|
|
546
|
-
const usage = parsed.message?.usage;
|
|
547
|
-
if (!usage?.input_tokens && usage?.input_tokens !== 0) return;
|
|
548
|
-
if (!parsed.timestamp) return;
|
|
549
|
-
|
|
550
|
-
// Only what the totals need: `parsed` also holds the turn's content blocks.
|
|
551
|
-
const entry = { costUSD: parsed.costUSD, timestamp: parsed.timestamp, message: { model: parsed.message.model, usage } };
|
|
552
|
-
const hash = createDedupeHash(parsed);
|
|
553
|
-
if (!hash) { unhashed.push(entry); return; }
|
|
554
|
-
const prev = kept.get(hash);
|
|
555
|
-
if (!prev || (usage.output_tokens || 0) > (prev.message.usage.output_tokens || 0)) kept.set(hash, entry);
|
|
556
|
-
});
|
|
557
|
-
const turns = [...kept.values(), ...unhashed].map(e => ({
|
|
558
|
-
cost: calculateEntryCost(e, pricing),
|
|
559
|
-
inputTokens: e.message.usage.input_tokens || 0,
|
|
560
|
-
outputTokens: e.message.usage.output_tokens || 0,
|
|
561
|
-
cacheCreationTokens: e.message.usage.cache_creation_input_tokens || 0,
|
|
562
|
-
cacheReadTokens: e.message.usage.cache_read_input_tokens || 0,
|
|
563
|
-
model: e.message.model || 'unknown',
|
|
564
|
-
timestamp: e.timestamp,
|
|
565
|
-
}));
|
|
566
|
-
Object.assign(agent, summarizeMessages(turns));
|
|
567
|
-
for (const t of turns) {
|
|
568
|
-
agent.models.add(t.model);
|
|
569
|
-
if (!agent.firstTimestamp || t.timestamp < agent.firstTimestamp) agent.firstTimestamp = t.timestamp;
|
|
570
|
-
if (!agent.lastTimestamp || t.timestamp > agent.lastTimestamp) agent.lastTimestamp = t.timestamp;
|
|
571
|
-
}
|
|
572
|
-
agent.models = [...agent.models];
|
|
573
|
-
return agent;
|
|
574
|
-
}));
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
async function loadProjectData(files, pricing) {
|
|
578
|
-
const sessions = new Map();
|
|
579
|
-
// hash -> pushed message, so tool_use blocks from duplicate lines can be folded in.
|
|
580
|
-
const seen = new Map();
|
|
581
|
-
|
|
582
|
-
for (const file of files) {
|
|
583
|
-
const sessionId = getSessionIdFromFile(file);
|
|
584
|
-
if (!sessions.has(sessionId)) {
|
|
585
|
-
sessions.set(sessionId, {
|
|
586
|
-
sessionId,
|
|
587
|
-
totalCost: 0,
|
|
588
|
-
inputTokens: 0, outputTokens: 0,
|
|
589
|
-
cacheCreationTokens: 0, cacheReadTokens: 0,
|
|
590
|
-
messages: [],
|
|
591
|
-
models: new Set(),
|
|
592
|
-
firstPrompt: '',
|
|
593
|
-
customTitle: null,
|
|
594
|
-
firstTimestamp: null,
|
|
595
|
-
lastTimestamp: null,
|
|
596
|
-
});
|
|
597
|
-
}
|
|
598
|
-
const session = sessions.get(sessionId);
|
|
599
|
-
// A boundary is attributed to the next counted turn, so the message list is the only record
|
|
600
|
-
// of compactions; a boundary with no turn after it has nothing to price and is dropped.
|
|
601
|
-
let pendingCompaction = null;
|
|
602
|
-
|
|
603
|
-
await processJSONLFile(file, async (line) => {
|
|
604
|
-
let parsed;
|
|
605
|
-
try { parsed = JSON.parse(line); } catch { return; }
|
|
606
|
-
|
|
607
|
-
if (parsed.type === 'custom-title' && parsed.customTitle) {
|
|
608
|
-
session.customTitle = parsed.customTitle;
|
|
609
|
-
return;
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
if (parsed.type === 'system' && parsed.subtype === 'compact_boundary' && parsed.timestamp) {
|
|
613
|
-
pendingCompaction = compactionFacts(parsed);
|
|
614
|
-
return;
|
|
615
|
-
}
|
|
616
|
-
|
|
617
|
-
if (!parsed.message?.usage?.input_tokens && parsed.message?.usage?.input_tokens !== 0) return;
|
|
618
|
-
if (!parsed.timestamp) return;
|
|
619
|
-
|
|
620
|
-
const hash = createDedupeHash(parsed);
|
|
621
|
-
if (hash && seen.has(hash)) {
|
|
622
|
-
// Streaming writes one JSONL line per content block of the same API message. Usage is
|
|
623
|
-
// identical on every line (deduped), but each line carries different tool_use blocks,
|
|
624
|
-
// so tools must be unioned across duplicates or most calls are lost.
|
|
625
|
-
const dupTools = extractTools(parsed.message?.content);
|
|
626
|
-
if (dupTools) {
|
|
627
|
-
const orig = seen.get(hash);
|
|
628
|
-
orig.tools = (orig.tools || []).concat(dupTools);
|
|
629
|
-
}
|
|
630
|
-
return;
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
const cost = calculateEntryCost(parsed, pricing);
|
|
634
|
-
const usage = parsed.message.usage;
|
|
635
|
-
const model = parsed.message?.model || 'unknown';
|
|
636
|
-
const ts = parsed.timestamp;
|
|
637
|
-
|
|
638
|
-
session.totalCost += cost;
|
|
639
|
-
session.inputTokens += usage.input_tokens || 0;
|
|
640
|
-
session.outputTokens += usage.output_tokens || 0;
|
|
641
|
-
session.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
|
|
642
|
-
session.cacheReadTokens += (usage.cache_read_input_tokens || 0);
|
|
643
|
-
if (isRealModel(model)) session.models.add(model);
|
|
644
|
-
|
|
645
|
-
if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
|
|
646
|
-
if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
|
|
647
|
-
|
|
648
|
-
const msg = {
|
|
649
|
-
timestamp: ts,
|
|
650
|
-
model,
|
|
651
|
-
cost,
|
|
652
|
-
inputTokens: usage.input_tokens || 0,
|
|
653
|
-
outputTokens: usage.output_tokens || 0,
|
|
654
|
-
cacheCreationTokens: usage.cache_creation_input_tokens || 0,
|
|
655
|
-
cacheReadTokens: usage.cache_read_input_tokens || 0,
|
|
656
|
-
speed: usage.speed || 'standard',
|
|
657
|
-
tools: extractTools(parsed.message?.content),
|
|
658
|
-
};
|
|
659
|
-
if (pendingCompaction) {
|
|
660
|
-
msg.compaction = priceCompaction(pendingCompaction, msg, pricing);
|
|
661
|
-
pendingCompaction = null;
|
|
662
|
-
}
|
|
663
|
-
session.messages.push(msg);
|
|
664
|
-
if (hash) seen.set(hash, msg);
|
|
665
|
-
|
|
666
|
-
// Capture first user prompt from the JSONL (look for human/user messages)
|
|
667
|
-
if (!session.firstPrompt && parsed.type === 'human' && parsed.message?.content) {
|
|
668
|
-
const content = Array.isArray(parsed.message.content)
|
|
669
|
-
? parsed.message.content.map(c => c.text || '').join(' ')
|
|
670
|
-
: (typeof parsed.message.content === 'string' ? parsed.message.content : '');
|
|
671
|
-
if (content.trim()) {
|
|
672
|
-
session.firstPrompt = content.trim().slice(0, 120);
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
});
|
|
676
|
-
|
|
677
|
-
// Fold subagent costs into session totals
|
|
678
|
-
const sessionDir = path.join(path.dirname(file), sessionId);
|
|
679
|
-
const subagentInfos = scanSubagentDir(sessionDir);
|
|
680
|
-
if (subagentInfos.length > 0) {
|
|
681
|
-
const subagents = await loadSubagentData(subagentInfos, pricing);
|
|
682
|
-
for (const sa of subagents) {
|
|
683
|
-
// An agent log with no priced turns — empty, truncated, or a crash before the first
|
|
684
|
-
// response — would fold in as a zero-cost message dated at the session's own start,
|
|
685
|
-
// which stretches every span it lands in.
|
|
686
|
-
if (sa.messageCount === 0) continue;
|
|
687
|
-
session.totalCost += sa.totalCost;
|
|
688
|
-
session.inputTokens += sa.inputTokens;
|
|
689
|
-
session.outputTokens += sa.outputTokens;
|
|
690
|
-
session.cacheCreationTokens += sa.cacheCreationTokens;
|
|
691
|
-
session.cacheReadTokens += sa.cacheReadTokens;
|
|
692
|
-
for (const m of sa.models) if (isRealModel(m)) session.models.add(m);
|
|
693
|
-
session.messages.push({
|
|
694
|
-
timestamp: sa.firstTimestamp || session.firstTimestamp,
|
|
695
|
-
model: sa.models[0] || 'unknown',
|
|
696
|
-
cost: sa.totalCost,
|
|
697
|
-
inputTokens: sa.inputTokens,
|
|
698
|
-
outputTokens: sa.outputTokens,
|
|
699
|
-
cacheCreationTokens: sa.cacheCreationTokens,
|
|
700
|
-
cacheReadTokens: sa.cacheReadTokens,
|
|
701
|
-
speed: 'standard',
|
|
702
|
-
_subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount, workflowId: sa.workflowId, lastTimestamp: sa.lastTimestamp },
|
|
703
|
-
});
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
return sessions;
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
// A range is either a preset — 'today', '24h', the last N calendar days, or null for all time, all
|
|
712
|
-
// anchored to the request — or a custom window of two local YYYY-MM-DD dates.
|
|
713
|
-
function isCustomRange(range) {
|
|
714
|
-
return !!range && typeof range === 'object' && !!range.from && !!range.to;
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
function localDayStart(dateStr) {
|
|
718
|
-
const [y, m, d] = dateStr.split('-').map(Number);
|
|
719
|
-
return new Date(y, m - 1, d, 0, 0, 0, 0);
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
// `to` names a whole day, so the window runs through the end of it — a midnight bound would
|
|
723
|
-
// silently drop that day's data.
|
|
724
|
-
function localDayEnd(dateStr) {
|
|
725
|
-
const d = localDayStart(dateStr);
|
|
726
|
-
d.setHours(23, 59, 59, 999);
|
|
727
|
-
return d;
|
|
728
|
-
}
|
|
729
|
-
|
|
730
|
-
function rangeToCutoff(range, now) {
|
|
731
|
-
if (isCustomRange(range)) return localDayStart(range.from);
|
|
732
|
-
if (range === 'today') {
|
|
733
|
-
const c = new Date(now);
|
|
734
|
-
c.setHours(0, 0, 0, 0);
|
|
735
|
-
return c;
|
|
736
|
-
}
|
|
737
|
-
// The one rolling preset left, and the reason it is labelled in hours: no midnight snap, so it
|
|
738
|
-
// spans two calendar days.
|
|
739
|
-
if (range === '24h') return new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
|
740
|
-
if (!range) return null;
|
|
741
|
-
// N calendar days ending today: identical to from=today-(N-1)&to=today, so the chart draws
|
|
742
|
-
// exactly N buckets instead of N+1 with a partial leading one.
|
|
743
|
-
const c = new Date(now);
|
|
744
|
-
c.setDate(c.getDate() - (range - 1));
|
|
745
|
-
c.setHours(0, 0, 0, 0);
|
|
746
|
-
return c;
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
// The window's upper bound, which used to be an implicit `now` in six places. Presets are rolling,
|
|
750
|
-
// so theirs still is; a custom window ends with its `to` day.
|
|
751
|
-
function rangeToEnd(range, now) {
|
|
752
|
-
return isCustomRange(range) ? localDayEnd(range.to) : new Date(now);
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
// Presets keep an open upper bound: they end at "whenever this request lands", so filtering
|
|
756
|
-
// against a captured `now` would only ever drop rows a live session wrote mid-request.
|
|
757
|
-
function windowEndStr(range, windowEnd) {
|
|
758
|
-
return isCustomRange(range) ? windowEnd.toISOString() : null;
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
// True when today falls inside the window. A null cutoff means open toward the past.
|
|
762
|
-
function windowContainsToday(cutoff, windowEnd, now) {
|
|
763
|
-
const todayStr = localDateStr(now);
|
|
764
|
-
return (!cutoff || localDateStr(cutoff) <= todayStr) && localDateStr(windowEnd) >= todayStr;
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
// Everything a range resolves to, anchored to one captured `now` so the bounds of a single request
|
|
768
|
-
// can never disagree with each other. `cutoff` stays null for the all-time range.
|
|
769
|
-
function resolveWindow(range, now = new Date()) {
|
|
770
|
-
const cutoff = rangeToCutoff(range, now);
|
|
771
|
-
const end = rangeToEnd(range, now);
|
|
772
|
-
return {
|
|
773
|
-
now, cutoff, end,
|
|
774
|
-
cutoffStr: cutoff ? cutoff.toISOString() : null,
|
|
775
|
-
endStr: windowEndStr(range, end),
|
|
776
|
-
hasToday: windowContainsToday(cutoff, end, now),
|
|
777
|
-
};
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
const byTimestamp = (a, b) => a.timestamp.localeCompare(b.timestamp);
|
|
781
|
-
|
|
782
|
-
// Two-sided when the window has an end, so a window that stops in the past excludes later
|
|
783
|
-
// messages. A null bound means open in that direction.
|
|
784
|
-
function filterWindow(messages, fromStr, toStr) {
|
|
785
|
-
if (!fromStr && !toStr) return messages;
|
|
786
|
-
return messages.filter((m) => (!fromStr || m.timestamp >= fromStr) && (!toStr || m.timestamp <= toStr));
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
// Custom windows key by their dates, which is why the cache is capped (see MAX_CACHE_ENTRIES).
|
|
790
|
-
function rangeKey(range) {
|
|
791
|
-
if (isCustomRange(range)) return `${range.from}_${range.to}`;
|
|
792
|
-
return range || 'all';
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
// True when the window is exactly today — a preset 'today' or a single-day pick landing on it.
|
|
796
|
-
function isTodayRange(range, now) {
|
|
797
|
-
if (isCustomRange(range)) return range.from === range.to && range.to === localDateStr(now);
|
|
798
|
-
return range === 'today';
|
|
799
|
-
}
|
|
800
|
-
|
|
801
|
-
function summarizeMessages(msgs) {
|
|
802
|
-
const sum = { messageCount: msgs.length, totalCost: 0, inputTokens: 0, outputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0 };
|
|
803
|
-
for (const m of msgs) {
|
|
804
|
-
sum.totalCost += m.cost;
|
|
805
|
-
sum.inputTokens += m.inputTokens;
|
|
806
|
-
sum.outputTokens += m.outputTokens;
|
|
807
|
-
sum.cacheCreationTokens += m.cacheCreationTokens;
|
|
808
|
-
sum.cacheReadTokens += m.cacheReadTokens;
|
|
809
|
-
}
|
|
810
|
-
return sum;
|
|
811
|
-
}
|
|
812
|
-
|
|
813
|
-
function summarizeCompactions(msgs) {
|
|
814
|
-
const sum = { count: 0, auto: 0, totalCost: 0, estCost: 0, rewarmCost: 0, rewarmTokens: 0, droppedTokens: 0 };
|
|
815
|
-
for (const { compaction: c } of msgs) {
|
|
816
|
-
if (!c) continue;
|
|
817
|
-
sum.count++;
|
|
818
|
-
if (c.trigger === 'auto') sum.auto++;
|
|
819
|
-
sum.estCost += c.estCost || 0;
|
|
820
|
-
sum.rewarmCost += c.rewarmCost || 0;
|
|
821
|
-
sum.rewarmTokens += c.rewarmTokens;
|
|
822
|
-
sum.droppedTokens += c.droppedTokens;
|
|
823
|
-
}
|
|
824
|
-
sum.totalCost = sum.estCost + sum.rewarmCost;
|
|
825
|
-
return sum;
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
async function getOverviewData(range, projectFilter) {
|
|
829
|
-
const cacheKey = `overview_${rangeKey(range)}_${projectFilter || 'all'}`;
|
|
830
|
-
const cached = getCache(cacheKey);
|
|
831
|
-
if (cached !== undefined) return cached;
|
|
832
|
-
|
|
833
|
-
const pricing = await fetchPricing();
|
|
834
|
-
const w = resolveWindow(range);
|
|
835
|
-
const now = w.now;
|
|
836
|
-
// The series needs a concrete start even for the all-time range, so a null cutoff falls back to
|
|
837
|
-
// now. Deliberately local: pushing it into resolveWindow would hand the other callers a non-null
|
|
838
|
-
// all-time cutoff and change what they filter on.
|
|
839
|
-
const cutoff = w.cutoff || w.now;
|
|
840
|
-
const windowEnd = w.end;
|
|
841
|
-
const projects = scanProjectDirs(cutoff, projectFilter);
|
|
842
|
-
const cutoffStr = cutoff.toISOString();
|
|
843
|
-
const endStr = w.endStr;
|
|
844
|
-
|
|
845
|
-
let totalCost = 0, totalSessions = 0;
|
|
846
|
-
let totalInput = 0, totalOutput = 0, totalCacheCreation = 0, totalCacheRead = 0;
|
|
847
|
-
const bucket = rangeBucket(range);
|
|
848
|
-
const bucketKey = BUCKETS[bucket].key;
|
|
849
|
-
const bucketModelCosts = {};
|
|
850
|
-
const modelCosts = {};
|
|
851
|
-
const projectSummaries = [];
|
|
852
|
-
|
|
853
|
-
for (const [encodedPath, proj] of projects) {
|
|
854
|
-
const sessions = await loadProjectData(proj.files, pricing);
|
|
855
|
-
let projCost = 0, projSessions = 0, projLastActive = null;
|
|
856
|
-
const projModels = new Set();
|
|
857
|
-
|
|
858
|
-
for (const [, session] of sessions) {
|
|
859
|
-
// Filter messages within date range
|
|
860
|
-
const inRange = filterWindow(session.messages, cutoffStr, endStr);
|
|
861
|
-
if (inRange.length === 0) continue;
|
|
862
|
-
|
|
863
|
-
let sessionCost = 0, sessionInput = 0, sessionOutput = 0, sessionCacheCreation = 0, sessionCacheRead = 0;
|
|
864
|
-
for (const m of inRange) {
|
|
865
|
-
sessionCost += m.cost;
|
|
866
|
-
sessionInput += m.inputTokens;
|
|
867
|
-
sessionOutput += m.outputTokens;
|
|
868
|
-
sessionCacheCreation += m.cacheCreationTokens;
|
|
869
|
-
sessionCacheRead += m.cacheReadTokens;
|
|
870
|
-
const k = bucketKey(new Date(m.timestamp));
|
|
871
|
-
addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
|
|
872
|
-
if (isRealModel(m.model)) {
|
|
873
|
-
modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
|
|
874
|
-
projModels.add(m.model);
|
|
875
|
-
}
|
|
876
|
-
if (!projLastActive || m.timestamp > projLastActive) projLastActive = m.timestamp;
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
totalCost += sessionCost;
|
|
880
|
-
totalInput += sessionInput;
|
|
881
|
-
totalOutput += sessionOutput;
|
|
882
|
-
totalCacheCreation += sessionCacheCreation;
|
|
883
|
-
totalCacheRead += sessionCacheRead;
|
|
884
|
-
totalSessions++;
|
|
885
|
-
projCost += sessionCost;
|
|
886
|
-
projSessions++;
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
if (projSessions > 0) {
|
|
890
|
-
projectSummaries.push({
|
|
891
|
-
encodedPath,
|
|
892
|
-
name: projectName(encodedPath, proj.files),
|
|
893
|
-
totalCost: projCost,
|
|
894
|
-
sessionCount: projSessions,
|
|
895
|
-
lastActive: projLastActive,
|
|
896
|
-
primaryModel: [...projModels].sort((a, b) => (modelCosts[b] || 0) - (modelCosts[a] || 0))[0] || 'unknown',
|
|
897
|
-
});
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
|
|
901
|
-
const costSeries = buildCostSeries(bucketModelCosts, cutoff, windowEnd, bucket);
|
|
902
|
-
|
|
903
|
-
// The today slice is scoped to the window. A window that ends before today has no today bucket,
|
|
904
|
-
// and a 0 there reads as "nothing spent today" rather than "outside the selected window" — so it
|
|
905
|
-
// is reported as null and the card is dropped instead.
|
|
906
|
-
const todayStr = localDateStr(now);
|
|
907
|
-
const todayCost = w.hasToday
|
|
908
|
-
? costSeries.filter((p) => p.key.startsWith(todayStr)).reduce((s, p) => s + p.cost, 0)
|
|
909
|
-
: null;
|
|
910
|
-
|
|
911
|
-
const totalInputAll = totalInput + totalCacheCreation + totalCacheRead;
|
|
912
|
-
const cacheEfficiency = totalInputAll > 0 ? totalCacheRead / totalInputAll : 0;
|
|
913
|
-
|
|
914
|
-
const modelDistribution = buildModelDistribution(modelCosts);
|
|
915
|
-
|
|
916
|
-
const result = {
|
|
917
|
-
summary: {
|
|
918
|
-
totalCost, todayCost,
|
|
919
|
-
totalSessions,
|
|
920
|
-
totalTokens: totalInput + totalOutput + totalCacheCreation + totalCacheRead,
|
|
921
|
-
totalInput, totalOutput, totalCacheCreation, totalCacheRead,
|
|
922
|
-
cacheEfficiency,
|
|
923
|
-
},
|
|
924
|
-
costSeries: { bucket, points: costSeries },
|
|
925
|
-
modelDistribution,
|
|
926
|
-
projects: projectSummaries.sort((a, b) => b.totalCost - a.totalCost),
|
|
927
|
-
};
|
|
928
|
-
|
|
929
|
-
setCache(cacheKey, result);
|
|
930
|
-
return result;
|
|
931
|
-
}
|
|
932
|
-
|
|
933
|
-
async function getProjectsData(range, projectFilter) {
|
|
934
|
-
const cacheKey = `projects_${rangeKey(range)}_${projectFilter || 'all'}`;
|
|
935
|
-
const cached = getCache(cacheKey);
|
|
936
|
-
if (cached !== undefined) return cached;
|
|
937
|
-
|
|
938
|
-
const pricing = await fetchPricing();
|
|
939
|
-
const w = resolveWindow(range);
|
|
940
|
-
const projects = scanProjectDirs(w.cutoff, projectFilter);
|
|
941
|
-
const result = [];
|
|
942
|
-
|
|
943
|
-
for (const [encodedPath, proj] of projects) {
|
|
944
|
-
const sessions = await loadProjectData(proj.files, pricing);
|
|
945
|
-
let totalCost = 0, sessionCount = 0, lastActive = null;
|
|
946
|
-
const projModelCounts = {};
|
|
947
|
-
|
|
948
|
-
for (const [, session] of sessions) {
|
|
949
|
-
const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
|
|
950
|
-
if (msgs.length === 0) continue;
|
|
951
|
-
|
|
952
|
-
const cost = msgs.reduce((s, m) => s + m.cost, 0);
|
|
953
|
-
totalCost += cost;
|
|
954
|
-
sessionCount++;
|
|
955
|
-
for (const m of msgs) {
|
|
956
|
-
if (isRealModel(m.model)) {
|
|
957
|
-
projModelCounts[m.model] = (projModelCounts[m.model] || 0) + 1;
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
if (!lastActive || (session.lastTimestamp && session.lastTimestamp > lastActive)) {
|
|
961
|
-
lastActive = session.lastTimestamp;
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
if (sessionCount > 0) {
|
|
966
|
-
result.push({
|
|
967
|
-
encodedPath,
|
|
968
|
-
name: projectName(encodedPath, proj.files),
|
|
969
|
-
totalCost,
|
|
970
|
-
sessionCount,
|
|
971
|
-
lastActive,
|
|
972
|
-
primaryModel: mostFrequentModel(projModelCounts),
|
|
973
|
-
});
|
|
974
|
-
}
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
const sorted = result.sort((a, b) => b.totalCost - a.totalCost);
|
|
978
|
-
setCache(cacheKey, sorted);
|
|
979
|
-
return sorted;
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
async function getProjectSessionsData(encodedPath, range) {
|
|
983
|
-
const cacheKey = `sessions_${encodedPath}_${rangeKey(range)}`;
|
|
984
|
-
const cached = getCache(cacheKey);
|
|
985
|
-
if (cached !== undefined) return cached;
|
|
986
|
-
|
|
987
|
-
const pricing = await fetchPricing();
|
|
988
|
-
const w = resolveWindow(range);
|
|
989
|
-
const projects = scanProjectDirs(w.cutoff, encodedPath);
|
|
990
|
-
const bucket = rangeBucket(range);
|
|
991
|
-
if (!projects.size) return { sessions: [], costSeries: { bucket, points: [] }, modelDistribution: [] };
|
|
992
|
-
|
|
993
|
-
const sessions = await loadProjectData([...projects.values()].flatMap((p) => p.files), pricing);
|
|
994
|
-
const result = [];
|
|
995
|
-
const bucketKey = BUCKETS[bucket].key;
|
|
996
|
-
const bucketModelCosts = {};
|
|
997
|
-
const modelCosts = {};
|
|
998
|
-
|
|
999
|
-
for (const [, session] of sessions) {
|
|
1000
|
-
const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
|
|
1001
|
-
if (msgs.length === 0) continue;
|
|
1002
|
-
|
|
1003
|
-
const sum = summarizeMessages(msgs);
|
|
1004
|
-
const sessionModelCounts = {};
|
|
1005
|
-
for (const m of msgs) {
|
|
1006
|
-
const k = bucketKey(new Date(m.timestamp));
|
|
1007
|
-
addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
|
|
1008
|
-
if (isRealModel(m.model)) {
|
|
1009
|
-
modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
|
|
1010
|
-
sessionModelCounts[m.model] = (sessionModelCounts[m.model] || 0) + 1;
|
|
1011
|
-
}
|
|
1012
|
-
}
|
|
1013
|
-
const durationMs = session.firstTimestamp && session.lastTimestamp
|
|
1014
|
-
? new Date(session.lastTimestamp) - new Date(session.firstTimestamp)
|
|
1015
|
-
: 0;
|
|
1016
|
-
const primaryModel = mostFrequentModel(sessionModelCounts);
|
|
1017
|
-
|
|
1018
|
-
result.push({
|
|
1019
|
-
sessionId: session.sessionId,
|
|
1020
|
-
customTitle: session.customTitle,
|
|
1021
|
-
...sum,
|
|
1022
|
-
totalTokens: sum.inputTokens + sum.outputTokens + sum.cacheCreationTokens + sum.cacheReadTokens,
|
|
1023
|
-
models: [...session.models],
|
|
1024
|
-
primaryModel,
|
|
1025
|
-
firstPrompt: session.firstPrompt,
|
|
1026
|
-
firstTimestamp: session.firstTimestamp,
|
|
1027
|
-
lastTimestamp: session.lastTimestamp,
|
|
1028
|
-
durationMinutes: Math.round(durationMs / 60000),
|
|
1029
|
-
compactions: summarizeCompactions(msgs),
|
|
1030
|
-
});
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
// No range means "everything", so the series starts at the first bucket that has cost.
|
|
1034
|
-
let seriesStart = w.cutoff;
|
|
1035
|
-
if (!seriesStart) {
|
|
1036
|
-
const keys = Object.keys(bucketModelCosts).sort();
|
|
1037
|
-
seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : w.now;
|
|
1038
|
-
}
|
|
1039
|
-
const costSeries = buildCostSeries(bucketModelCosts, seriesStart, w.end, bucket);
|
|
1040
|
-
|
|
1041
|
-
const modelDistribution = buildModelDistribution(modelCosts);
|
|
1042
|
-
|
|
1043
|
-
const sorted = result.sort((a, b) => (b.lastTimestamp || '').localeCompare(a.lastTimestamp || ''));
|
|
1044
|
-
const response = {
|
|
1045
|
-
sessions: sorted,
|
|
1046
|
-
costSeries: { bucket, points: costSeries },
|
|
1047
|
-
modelDistribution,
|
|
1048
|
-
};
|
|
1049
|
-
setCache(cacheKey, response);
|
|
1050
|
-
return response;
|
|
1051
|
-
}
|
|
1052
|
-
|
|
1053
|
-
// The detail view is always the whole session, unlike every other view. `inRange`/`today` carry
|
|
1054
|
-
// the slices the UI needs to reconcile itself with the range-scoped session row that linked here,
|
|
1055
|
-
// instead of silently disagreeing with it. They are derived outside the cache so switching ranges
|
|
1056
|
-
// does not re-parse the session's JSONL.
|
|
1057
|
-
function withSessionSlices(base, range) {
|
|
1058
|
-
const w = resolveWindow(range);
|
|
1059
|
-
const slice = (fromStr) => summarizeMessages(filterWindow(base.messages, fromStr, w.endStr));
|
|
1060
|
-
const inRange = w.cutoffStr ? slice(w.cutoffStr) : null;
|
|
1061
|
-
const todayStart = rangeToCutoff('today', w.now);
|
|
1062
|
-
// Scoped to the window like the overview's today card: a window ending in the past has no
|
|
1063
|
-
// today to report, and a zeroed slice would read as "nothing spent today".
|
|
1064
|
-
return {
|
|
1065
|
-
...base,
|
|
1066
|
-
range,
|
|
1067
|
-
inRange,
|
|
1068
|
-
today: isTodayRange(range, w.now) ? inRange : w.hasToday ? slice(todayStart.toISOString()) : null,
|
|
1069
|
-
};
|
|
1070
|
-
}
|
|
1071
|
-
|
|
1072
|
-
async function getSessionDetailData(sessionId) {
|
|
1073
|
-
const cacheKey = `detail_${sessionId}`;
|
|
1074
|
-
const cached = getCache(cacheKey);
|
|
1075
|
-
if (cached !== undefined) return cached;
|
|
1076
|
-
|
|
1077
|
-
const pricing = await fetchPricing();
|
|
1078
|
-
const projects = scanProjectDirs();
|
|
1079
|
-
|
|
1080
|
-
// Find the session across all projects
|
|
1081
|
-
for (const [encodedPath, proj] of projects) {
|
|
1082
|
-
const matchingFile = proj.files.find(f => getSessionIdFromFile(f) === sessionId);
|
|
1083
|
-
if (!matchingFile) continue;
|
|
1084
|
-
|
|
1085
|
-
const sessions = await loadProjectData([matchingFile], pricing);
|
|
1086
|
-
const session = sessions.get(sessionId);
|
|
1087
|
-
if (!session) continue;
|
|
1088
|
-
|
|
1089
|
-
// Sort messages by timestamp
|
|
1090
|
-
session.messages.sort(byTimestamp);
|
|
1091
|
-
|
|
1092
|
-
// Add cumulative cost
|
|
1093
|
-
let cumulative = 0;
|
|
1094
|
-
const messages = session.messages.map((m, i) => {
|
|
1095
|
-
cumulative += m.cost;
|
|
1096
|
-
return { ...m, index: i + 1, cumulativeCost: cumulative };
|
|
1097
|
-
});
|
|
1098
|
-
|
|
1099
|
-
// One folded-in message per agent, and `messages` is already sorted, so a group's ends are
|
|
1100
|
-
// the run's first and last agent.
|
|
1101
|
-
const byWorkflow = new Map();
|
|
1102
|
-
for (const m of messages) {
|
|
1103
|
-
const wf = m._subagent?.workflowId;
|
|
1104
|
-
if (!wf) continue;
|
|
1105
|
-
if (!byWorkflow.has(wf)) byWorkflow.set(wf, []);
|
|
1106
|
-
byWorkflow.get(wf).push(m);
|
|
1107
|
-
}
|
|
1108
|
-
const names = byWorkflow.size > 0
|
|
1109
|
-
? findWorkflowNames(sessionId, byWorkflow.keys(), encodedPath)
|
|
1110
|
-
: new Map();
|
|
1111
|
-
const workflows = [...byWorkflow].map(([id, msgs]) => {
|
|
1112
|
-
const { messageCount, ...totals } = summarizeMessages(msgs);
|
|
1113
|
-
// A folded message carries its agent's start time, so the run ends at the latest agent's
|
|
1114
|
-
// own last turn — the last folded message only says when that agent started.
|
|
1115
|
-
const end = msgs.reduce((max, m) => {
|
|
1116
|
-
const t = m._subagent.lastTimestamp || m.timestamp;
|
|
1117
|
-
return t > max ? t : max;
|
|
1118
|
-
}, msgs[0].timestamp);
|
|
1119
|
-
return {
|
|
1120
|
-
id,
|
|
1121
|
-
name: names.get(id) || id,
|
|
1122
|
-
agents: messageCount,
|
|
1123
|
-
firstTimestamp: msgs[0].timestamp,
|
|
1124
|
-
lastTimestamp: end,
|
|
1125
|
-
// Where the run sits in `messages`, for the timeline band.
|
|
1126
|
-
startIndex: msgs[0].index,
|
|
1127
|
-
endIndex: msgs.at(-1).index,
|
|
1128
|
-
...totals,
|
|
1129
|
-
};
|
|
1130
|
-
}).sort((a, b) => b.totalCost - a.totalCost);
|
|
1131
|
-
|
|
1132
|
-
const result = {
|
|
1133
|
-
sessionId,
|
|
1134
|
-
customTitle: session.customTitle,
|
|
1135
|
-
projectPath: projectName(encodedPath, [matchingFile]),
|
|
1136
|
-
encodedProjectPath: encodedPath,
|
|
1137
|
-
totalCost: session.totalCost,
|
|
1138
|
-
inputTokens: session.inputTokens,
|
|
1139
|
-
outputTokens: session.outputTokens,
|
|
1140
|
-
cacheCreationTokens: session.cacheCreationTokens,
|
|
1141
|
-
cacheReadTokens: session.cacheReadTokens,
|
|
1142
|
-
models: [...session.models],
|
|
1143
|
-
firstPrompt: session.firstPrompt,
|
|
1144
|
-
firstTimestamp: session.firstTimestamp,
|
|
1145
|
-
lastTimestamp: session.lastTimestamp,
|
|
1146
|
-
workflows,
|
|
1147
|
-
compactions: summarizeCompactions(messages),
|
|
1148
|
-
messages,
|
|
1149
|
-
};
|
|
1150
|
-
|
|
1151
|
-
setCache(cacheKey, result);
|
|
1152
|
-
return result;
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
return null;
|
|
1156
|
-
}
|
|
1157
|
-
|
|
1158
|
-
// Claude's usage limits work in rolling 5-hour billing windows. A block starts at the first
|
|
1159
|
-
// activity (floored to the hour, mirroring ccusage) and spans exactly 5h; activity past the end
|
|
1160
|
-
// opens a new block anchored to its own hour.
|
|
1161
|
-
const BLOCK_MS = 5 * 60 * 60 * 1000;
|
|
1162
|
-
const HEATMAP_DAYS = 7;
|
|
1163
|
-
const MAX_BLOCKS = 24;
|
|
1164
|
-
const MAX_TOOLS = 20;
|
|
1165
|
-
|
|
1166
|
-
// The real window boundary comes from Claude Code's statusline payload (rate_limits.five_hour),
|
|
1167
|
-
// spied to disk by the cck plugin. The ccusage hour-floor heuristic can be hours off the actual
|
|
1168
|
-
// API window, so when a live resets_at is available it anchors the active block instead.
|
|
1169
|
-
function readRateLimits(now) {
|
|
1170
|
-
const dir = path.join(CLAUDE_DIR, '.cck', 'context-status');
|
|
1171
|
-
let newest = null;
|
|
1172
|
-
try {
|
|
1173
|
-
for (const f of fs.readdirSync(dir)) {
|
|
1174
|
-
if (!f.endsWith('.json')) continue;
|
|
1175
|
-
const fp = path.join(dir, f);
|
|
1176
|
-
try {
|
|
1177
|
-
const mtime = fs.statSync(fp).mtimeMs;
|
|
1178
|
-
if (!newest || mtime > newest.mtime) newest = { fp, mtime };
|
|
1179
|
-
} catch { /* ignore */ }
|
|
1180
|
-
}
|
|
1181
|
-
} catch { return null; }
|
|
1182
|
-
if (!newest) return null;
|
|
1183
|
-
try {
|
|
1184
|
-
const rl = JSON.parse(fs.readFileSync(newest.fp, 'utf8'))?.rate_limits;
|
|
1185
|
-
const fh = rl?.five_hour;
|
|
1186
|
-
// A resets_at in the past means the snapshot predates the current window — don't trust it.
|
|
1187
|
-
if (!fh?.resets_at || fh.resets_at * 1000 <= now.getTime()) return null;
|
|
1188
|
-
return { usedPct: fh.used_percentage ?? null, resetsAtMs: fh.resets_at * 1000 };
|
|
1189
|
-
} catch { return null; }
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
function computeBlocks(messages, now, realResetMs) {
|
|
1193
|
-
// When the API told us the live window, the active block spans exactly [reset-5h, reset].
|
|
1194
|
-
const activeStartMs = realResetMs && now.getTime() < realResetMs ? realResetMs - BLOCK_MS : null;
|
|
1195
|
-
const blocks = [];
|
|
1196
|
-
let cur = null;
|
|
1197
|
-
for (const m of messages) {
|
|
1198
|
-
const t = new Date(m.timestamp).getTime();
|
|
1199
|
-
if (!Number.isFinite(t)) continue;
|
|
1200
|
-
if (activeStartMs !== null && t >= activeStartMs) {
|
|
1201
|
-
if (!cur || cur.startMs !== activeStartMs) {
|
|
1202
|
-
cur = { startMs: activeStartMs, real: true, lastMs: t, cost: 0, tokens: 0, messageCount: 0, models: new Set() };
|
|
1203
|
-
blocks.push(cur);
|
|
1204
|
-
}
|
|
1205
|
-
} else if (!cur || t >= cur.startMs + BLOCK_MS) {
|
|
1206
|
-
const start = new Date(t);
|
|
1207
|
-
start.setMinutes(0, 0, 0);
|
|
1208
|
-
cur = { startMs: start.getTime(), lastMs: t, cost: 0, tokens: 0, messageCount: 0, models: new Set() };
|
|
1209
|
-
blocks.push(cur);
|
|
1210
|
-
}
|
|
1211
|
-
if (t > cur.lastMs) cur.lastMs = t;
|
|
1212
|
-
cur.cost += m.cost;
|
|
1213
|
-
cur.tokens += m.inputTokens + m.outputTokens + m.cacheCreationTokens + m.cacheReadTokens;
|
|
1214
|
-
cur.messageCount++;
|
|
1215
|
-
if (isRealModel(m.model)) cur.models.add(m.model);
|
|
1216
|
-
}
|
|
1217
|
-
// A live window with no in-range messages yet still exists — surface it as an empty block.
|
|
1218
|
-
if (activeStartMs !== null && !blocks.some((b) => b.startMs === activeStartMs)) {
|
|
1219
|
-
blocks.push({ startMs: activeStartMs, real: true, lastMs: activeStartMs, cost: 0, tokens: 0, messageCount: 0, models: new Set() });
|
|
1220
|
-
}
|
|
1221
|
-
const nowMs = now.getTime();
|
|
1222
|
-
return blocks
|
|
1223
|
-
.reverse()
|
|
1224
|
-
.slice(0, MAX_BLOCKS)
|
|
1225
|
-
.map((b) => {
|
|
1226
|
-
const endMs = b.startMs + BLOCK_MS;
|
|
1227
|
-
// Only the API-anchored window counts as active: the hour-floor heuristic can be hours
|
|
1228
|
-
// off the real boundary, so without live data no block is presented as current.
|
|
1229
|
-
const active = b.real === true && nowMs < endMs;
|
|
1230
|
-
// Floored at 1 so a block opened seconds ago doesn't project an absurd rate.
|
|
1231
|
-
const elapsedMin = active ? Math.max(1, (nowMs - b.startMs) / 60000) : null;
|
|
1232
|
-
return {
|
|
1233
|
-
start: new Date(b.startMs).toISOString(),
|
|
1234
|
-
end: new Date(endMs).toISOString(),
|
|
1235
|
-
lastActivity: new Date(b.lastMs).toISOString(),
|
|
1236
|
-
cost: b.cost,
|
|
1237
|
-
tokens: b.tokens,
|
|
1238
|
-
messageCount: b.messageCount,
|
|
1239
|
-
models: [...b.models],
|
|
1240
|
-
active,
|
|
1241
|
-
burn: active
|
|
1242
|
-
? {
|
|
1243
|
-
costPerHour: (b.cost / elapsedMin) * 60,
|
|
1244
|
-
tokensPerMin: b.tokens / elapsedMin,
|
|
1245
|
-
projectedCost: (b.cost / elapsedMin) * (BLOCK_MS / 60000),
|
|
1246
|
-
remainingMin: Math.round((endMs - nowMs) / 60000),
|
|
1247
|
-
}
|
|
1248
|
-
: null,
|
|
1249
|
-
};
|
|
1250
|
-
});
|
|
1251
|
-
}
|
|
1252
|
-
|
|
1253
|
-
async function getInsightsData(range, projectFilter) {
|
|
1254
|
-
const cacheKey = `insights_${rangeKey(range)}_${projectFilter || 'all'}`;
|
|
1255
|
-
const cached = getCache(cacheKey);
|
|
1256
|
-
if (cached !== undefined) return cached;
|
|
1257
|
-
|
|
1258
|
-
const pricing = await fetchPricing();
|
|
1259
|
-
const w = resolveWindow(range);
|
|
1260
|
-
|
|
1261
|
-
// The heatmap covers the last 7 real days ending at the selected window's end — each row
|
|
1262
|
-
// is an actual date, so a short range (today, 3d) still shows a full week of context.
|
|
1263
|
-
const windowEnd = w.end < w.now ? w.end : w.now;
|
|
1264
|
-
const hmStart = new Date(windowEnd);
|
|
1265
|
-
hmStart.setHours(0, 0, 0, 0);
|
|
1266
|
-
hmStart.setDate(hmStart.getDate() - (HEATMAP_DAYS - 1));
|
|
1267
|
-
const hmStartStr = hmStart.toISOString();
|
|
1268
|
-
const scanCutoff = w.cutoff === null ? null : w.cutoff < hmStart ? w.cutoff : hmStart;
|
|
1269
|
-
const projects = scanProjectDirs(scanCutoff, projectFilter);
|
|
1270
|
-
|
|
1271
|
-
// When the cost window already covers the heatmap window, the heatmap rows are a subset of
|
|
1272
|
-
// `all` — filter it instead of re-scanning every session a second time.
|
|
1273
|
-
const hmInAll = w.cutoff === null || w.cutoff <= hmStart;
|
|
1274
|
-
const allParts = [];
|
|
1275
|
-
const hmParts = [];
|
|
1276
|
-
for (const [, proj] of projects) {
|
|
1277
|
-
const sessions = await loadProjectData(proj.files, pricing);
|
|
1278
|
-
for (const [, session] of sessions) {
|
|
1279
|
-
allParts.push(filterWindow(session.messages, w.cutoffStr, w.endStr));
|
|
1280
|
-
if (!hmInAll) hmParts.push(filterWindow(session.messages, hmStartStr, w.endStr));
|
|
1281
|
-
}
|
|
1282
|
-
}
|
|
1283
|
-
const all = allParts.flat().sort(byTimestamp);
|
|
1284
|
-
const hmMsgs = hmInAll ? all.filter((m) => m.timestamp >= hmStartStr) : hmParts.flat();
|
|
1285
|
-
|
|
1286
|
-
// The live 5h window can open before the selected range starts (a Today filter after midnight
|
|
1287
|
-
// cuts a block that opened the evening before), so block stats are computed over the block's
|
|
1288
|
-
// own span. A live block always starts within the last 5h, inside the heatmap window, so its
|
|
1289
|
-
// messages are a subset of hmMsgs — no extra scan needed.
|
|
1290
|
-
const limits = w.hasToday ? readRateLimits(w.now) : null;
|
|
1291
|
-
const blockStart = limits ? new Date(limits.resetsAtMs - BLOCK_MS) : null;
|
|
1292
|
-
const blockInAll = !blockStart || w.cutoff === null || w.cutoff <= blockStart;
|
|
1293
|
-
let blockMsgs = all;
|
|
1294
|
-
if (!blockInAll) {
|
|
1295
|
-
const fromStr = blockStart.toISOString();
|
|
1296
|
-
blockMsgs = hmMsgs.filter((m) => m.timestamp >= fromStr).sort(byTimestamp);
|
|
1297
|
-
}
|
|
1298
|
-
|
|
1299
|
-
const sum = summarizeMessages(all);
|
|
1300
|
-
const tokens = { input: sum.inputTokens, output: sum.outputTokens, cacheCreation: sum.cacheCreationTokens, cacheRead: sum.cacheReadTokens };
|
|
1301
|
-
let cacheSavings = 0;
|
|
1302
|
-
// One row per real day, oldest first; row index = whole days since hmStart.
|
|
1303
|
-
const heatmap = Array.from({ length: HEATMAP_DAYS }, () => new Array(24).fill(0));
|
|
1304
|
-
const heatmapDays = Array.from({ length: HEATMAP_DAYS }, (_, i) => {
|
|
1305
|
-
const d = new Date(hmStart);
|
|
1306
|
-
d.setDate(d.getDate() + i);
|
|
1307
|
-
return localDateStr(d);
|
|
6
|
+
if (cli.isCommand(process.argv[2])) {
|
|
7
|
+
cli.main(process.argv.slice(2)).then((code) => {
|
|
8
|
+
process.exitCode = code;
|
|
1308
9
|
});
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
let subagentCost = 0;
|
|
1312
|
-
let workflowCost = 0;
|
|
1313
|
-
const workflowRuns = new Set();
|
|
1314
|
-
const weekly = {};
|
|
1315
|
-
|
|
1316
|
-
// getModelPricing falls back to a linear scan of the whole LiteLLM map on a miss, so resolve
|
|
1317
|
-
// it once per distinct model rather than once per message.
|
|
1318
|
-
const priceMemo = new Map();
|
|
1319
|
-
for (const m of all) {
|
|
1320
|
-
// What the same tokens would have cost as fresh input, minus what cache reads actually cost.
|
|
1321
|
-
if (m.cacheReadTokens > 0) {
|
|
1322
|
-
if (!priceMemo.has(m.model)) priceMemo.set(m.model, getModelPricing(pricing, m.model));
|
|
1323
|
-
const mp = priceMemo.get(m.model);
|
|
1324
|
-
if (mp?.input_cost_per_token != null && mp?.cache_read_input_token_cost != null) {
|
|
1325
|
-
cacheSavings += m.cacheReadTokens * (mp.input_cost_per_token - mp.cache_read_input_token_cost);
|
|
1326
|
-
}
|
|
1327
|
-
}
|
|
1328
|
-
|
|
1329
|
-
const monday = new Date(m.timestamp);
|
|
1330
|
-
monday.setHours(0, 0, 0, 0);
|
|
1331
|
-
monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7));
|
|
1332
|
-
const wk = localDateStr(monday);
|
|
1333
|
-
weekly[wk] = (weekly[wk] || 0) + m.cost;
|
|
1334
|
-
|
|
1335
|
-
if (m._subagent) {
|
|
1336
|
-
subagentCost += m.cost;
|
|
1337
|
-
if (m._subagent.workflowId) {
|
|
1338
|
-
workflowCost += m.cost;
|
|
1339
|
-
workflowRuns.add(m._subagent.workflowId);
|
|
1340
|
-
}
|
|
1341
|
-
} else {
|
|
1342
|
-
mainCost += m.cost;
|
|
1343
|
-
if (m.tools) for (const t of m.tools) toolCounts[t] = (toolCounts[t] || 0) + 1;
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
|
|
1347
|
-
for (const m of hmMsgs) {
|
|
1348
|
-
const d = new Date(m.timestamp);
|
|
1349
|
-
const day = new Date(d);
|
|
1350
|
-
day.setHours(0, 0, 0, 0);
|
|
1351
|
-
// Round to survive DST shifts making a "day" 23/25 hours.
|
|
1352
|
-
const idx = Math.round((day - hmStart) / 86400000);
|
|
1353
|
-
if (idx >= 0 && idx < HEATMAP_DAYS) heatmap[idx][d.getHours()] += m.cost;
|
|
1354
|
-
}
|
|
1355
|
-
|
|
1356
|
-
// A window ending in the past has no "current" block — limits are only read when the window
|
|
1357
|
-
// reaches today, so the live block is never synthesized for a historical range.
|
|
1358
|
-
const blocks = computeBlocks(blockMsgs, w.now, limits?.resetsAtMs || null);
|
|
1359
|
-
const activeBlk = blocks.find((b) => b.active);
|
|
1360
|
-
if (activeBlk) activeBlk.usedPct = limits?.usedPct ?? null;
|
|
1361
|
-
|
|
1362
|
-
// Run-rate over the window actually observed: a custom window ending in the past uses its own
|
|
1363
|
-
// span; open-ended ranges run from the first message (all-time) or the cutoff to now.
|
|
1364
|
-
const windowStart = w.cutoff || (all.length ? new Date(all[0].timestamp) : w.now);
|
|
1365
|
-
const dayCount = Math.max(1, Math.ceil((windowEnd - windowStart) / 86400000));
|
|
1366
|
-
const dailyAvg = sum.totalCost / dayCount;
|
|
1367
|
-
|
|
1368
|
-
const result = {
|
|
1369
|
-
tokens,
|
|
1370
|
-
cacheSavings,
|
|
1371
|
-
runRate: { dailyAvg, projectedMonthly: dailyAvg * 30, days: dayCount },
|
|
1372
|
-
blocks,
|
|
1373
|
-
heatmap,
|
|
1374
|
-
heatmapDays,
|
|
1375
|
-
heatmapToday: localDateStr(w.now),
|
|
1376
|
-
tools: Object.entries(toolCounts)
|
|
1377
|
-
.map(([name, count]) => ({ name, count }))
|
|
1378
|
-
.sort((a, b) => b.count - a.count)
|
|
1379
|
-
.slice(0, MAX_TOOLS),
|
|
1380
|
-
// workflowCost is the slice of subagentCost spent inside Workflow runs, not a third peer —
|
|
1381
|
-
// mainCost + subagentCost is still the whole.
|
|
1382
|
-
subagents: { mainCost, subagentCost, workflowCost, workflowRuns: workflowRuns.size },
|
|
1383
|
-
weekly: Object.entries(weekly)
|
|
1384
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
1385
|
-
.map(([weekStart, cost]) => ({ weekStart, cost })),
|
|
1386
|
-
};
|
|
1387
|
-
|
|
1388
|
-
setCache(cacheKey, result);
|
|
1389
|
-
return result;
|
|
1390
|
-
}
|
|
1391
|
-
|
|
1392
|
-
// #endregion
|
|
1393
|
-
|
|
1394
|
-
// #region EXPRESS
|
|
1395
|
-
|
|
1396
|
-
const app = express();
|
|
1397
|
-
|
|
1398
|
-
// Mounted before express.json() so a rejected request never buffers a body.
|
|
1399
|
-
const net = createNetGuard({ appName: 'Claude Code Cost Dashboard' });
|
|
1400
|
-
app.use(net.hostGuard);
|
|
1401
|
-
app.use(net.frameGuard);
|
|
1402
|
-
app.use(net.originGuard);
|
|
1403
|
-
|
|
1404
|
-
app.use(express.json());
|
|
1405
|
-
// Under a hub, the hub hands over its SDK. Alone, public/vendor/claude-hub-sdk.js is a stub.
|
|
1406
|
-
if (process.env.HUB_SDK_SERVER) require(process.env.HUB_SDK_SERVER).mount(app);
|
|
1407
|
-
|
|
1408
|
-
app.use(express.static(path.join(__dirname, 'public')));
|
|
1409
|
-
|
|
1410
|
-
function parseRange(raw, fallback = null) {
|
|
1411
|
-
if (raw === 'today') return 'today';
|
|
1412
|
-
if (raw === '24h') return '24h';
|
|
1413
|
-
const n = parseInt(raw, 10);
|
|
1414
|
-
return Number.isFinite(n) ? n : fallback;
|
|
1415
|
-
}
|
|
1416
|
-
|
|
1417
|
-
const DATE_PARAM = /^\d{4}-\d{2}-\d{2}$/;
|
|
1418
|
-
|
|
1419
|
-
// A local calendar date, normalized so it can safely reach a cache key — same discipline as
|
|
1420
|
-
// parseProject. Returns undefined for absent, null for malformed.
|
|
1421
|
-
function parseDateParam(raw) {
|
|
1422
|
-
if (raw === undefined || raw === '') return undefined;
|
|
1423
|
-
if (typeof raw !== 'string' || !DATE_PARAM.test(raw)) return null;
|
|
1424
|
-
return localDateStr(localDayStart(raw)) === raw ? raw : null;
|
|
1425
|
-
}
|
|
1426
|
-
|
|
1427
|
-
// A custom window, if the request asked for one: `from`/`to` take precedence over `range`.
|
|
1428
|
-
// Reversed pairs are ordered and both ends clamped to today — there is no cost data ahead of now,
|
|
1429
|
-
// and an inverted window would otherwise render as an unexplained empty chart.
|
|
1430
|
-
// Returns undefined when no window was requested, null when one was but is malformed.
|
|
1431
|
-
function parseCustomRange(query) {
|
|
1432
|
-
const from = parseDateParam(query.from);
|
|
1433
|
-
const to = parseDateParam(query.to);
|
|
1434
|
-
if (from === null || to === null) return null;
|
|
1435
|
-
if (from === undefined && to === undefined) return undefined;
|
|
1436
|
-
if (from === undefined || to === undefined) return null;
|
|
1437
|
-
const today = localDateStr(new Date());
|
|
1438
|
-
const [lo, hi] = from <= to ? [from, to] : [to, from];
|
|
1439
|
-
return { from: lo > today ? today : lo, to: hi > today ? today : hi };
|
|
10
|
+
} else {
|
|
11
|
+
require('./lib/app');
|
|
1440
12
|
}
|
|
1441
|
-
|
|
1442
|
-
// Encoded project-dir name (the hub sends it pre-encoded — see encodeProjectPath in the hub's
|
|
1443
|
-
// public/app.js; this regex must stay a superset of that transform's output). Only ever used as
|
|
1444
|
-
// a Map key, never joined into a path — the regex exists to keep unbounded strings out of the
|
|
1445
|
-
// cache keys.
|
|
1446
|
-
// Returns undefined for absent, null for malformed, so callers can 400 instead of silently
|
|
1447
|
-
// dropping the scope.
|
|
1448
|
-
function parseProject(raw) {
|
|
1449
|
-
if (raw === undefined || raw === '') return undefined;
|
|
1450
|
-
if (typeof raw !== 'string' || !/^[A-Za-z0-9._-]+(,[A-Za-z0-9._-]+)*$/.test(raw)) return null;
|
|
1451
|
-
return raw;
|
|
1452
|
-
}
|
|
1453
|
-
|
|
1454
|
-
// Resolves a request's range onto req.range: a custom from/to window wins over `range`. A resolved
|
|
1455
|
-
// range cannot signal malformed input with null (null *is* the all-time range), so the rejection
|
|
1456
|
-
// happens here, ahead of the handler, instead of being threaded back to it as a sentinel value.
|
|
1457
|
-
// Only the range — a route that also scopes by project keeps its own parseProject guard, because
|
|
1458
|
-
// the routes that don't call parseProject must go on ignoring a malformed `project`.
|
|
1459
|
-
const withRange = (fallback = null) => (req, res, next) => {
|
|
1460
|
-
const custom = parseCustomRange(req.query);
|
|
1461
|
-
if (custom === null) return res.status(400).json({ error: 'Invalid date range' });
|
|
1462
|
-
req.range = custom || parseRange(req.query.range, fallback);
|
|
1463
|
-
next();
|
|
1464
|
-
};
|
|
1465
|
-
|
|
1466
|
-
app.get('/api/overview', withRange(30), async (req, res) => {
|
|
1467
|
-
try {
|
|
1468
|
-
const project = parseProject(req.query.project);
|
|
1469
|
-
if (project === null) return res.status(400).json({ error: 'Invalid project' });
|
|
1470
|
-
const data = await getOverviewData(req.range, project);
|
|
1471
|
-
res.json(data);
|
|
1472
|
-
} catch (err) {
|
|
1473
|
-
console.error('[API] overview error:', err);
|
|
1474
|
-
res.status(500).json({ error: 'Failed to load overview data' });
|
|
1475
|
-
}
|
|
1476
|
-
});
|
|
1477
|
-
|
|
1478
|
-
app.get('/api/insights', withRange(30), async (req, res) => {
|
|
1479
|
-
try {
|
|
1480
|
-
const project = parseProject(req.query.project);
|
|
1481
|
-
if (project === null) return res.status(400).json({ error: 'Invalid project' });
|
|
1482
|
-
const data = await getInsightsData(req.range, project);
|
|
1483
|
-
res.json(data);
|
|
1484
|
-
} catch (err) {
|
|
1485
|
-
console.error('[API] insights error:', err);
|
|
1486
|
-
res.status(500).json({ error: 'Failed to load insights data' });
|
|
1487
|
-
}
|
|
1488
|
-
});
|
|
1489
|
-
|
|
1490
|
-
app.get('/api/projects', withRange(), async (req, res) => {
|
|
1491
|
-
try {
|
|
1492
|
-
const project = parseProject(req.query.project);
|
|
1493
|
-
if (project === null) return res.status(400).json({ error: 'Invalid project' });
|
|
1494
|
-
const data = await getProjectsData(req.range, project);
|
|
1495
|
-
res.json(data);
|
|
1496
|
-
} catch (err) {
|
|
1497
|
-
console.error('[API] projects error:', err);
|
|
1498
|
-
res.status(500).json({ error: 'Failed to load projects data' });
|
|
1499
|
-
}
|
|
1500
|
-
});
|
|
1501
|
-
|
|
1502
|
-
app.get('/api/projects/:path/sessions', withRange(), async (req, res) => {
|
|
1503
|
-
try {
|
|
1504
|
-
const data = await getProjectSessionsData(req.params.path, req.range);
|
|
1505
|
-
res.json(data);
|
|
1506
|
-
} catch (err) {
|
|
1507
|
-
console.error('[API] sessions error:', err);
|
|
1508
|
-
res.status(500).json({ error: 'Failed to load sessions data' });
|
|
1509
|
-
}
|
|
1510
|
-
});
|
|
1511
|
-
|
|
1512
|
-
app.get('/api/sessions/:id', withRange(), async (req, res) => {
|
|
1513
|
-
try {
|
|
1514
|
-
const base = await getSessionDetailData(req.params.id);
|
|
1515
|
-
if (!base) return res.status(404).json({ error: 'Session not found' });
|
|
1516
|
-
res.json(withSessionSlices(base, req.range));
|
|
1517
|
-
} catch (err) {
|
|
1518
|
-
console.error('[API] session detail error:', err);
|
|
1519
|
-
res.status(500).json({ error: 'Failed to load session detail' });
|
|
1520
|
-
}
|
|
1521
|
-
});
|
|
1522
|
-
|
|
1523
|
-
// Each probe spawns a CLI process and fires the config dir's SessionStart hooks, so we cache the
|
|
1524
|
-
// result and let concurrent callers share one in-flight run.
|
|
1525
|
-
//
|
|
1526
|
-
// The TTL mirrors the CLI's own: it refetches plan utilization at most every 5 minutes and shares
|
|
1527
|
-
// the answer through an on-disk cache, so probing faster re-reads the same numbers. A manual
|
|
1528
|
-
// refresh bypasses this cache but still cannot beat that floor.
|
|
1529
|
-
const USAGE_TTL_MS = 5 * 60 * 1000;
|
|
1530
|
-
let usageCache = null;
|
|
1531
|
-
let usageInFlight = null;
|
|
1532
|
-
|
|
1533
|
-
function loadUsage(force = false) {
|
|
1534
|
-
if (!force && usageCache && Date.now() - usageCache.ts < USAGE_TTL_MS) {
|
|
1535
|
-
return Promise.resolve(usageCache.data);
|
|
1536
|
-
}
|
|
1537
|
-
// A forced call still joins an in-flight probe: two spawns would only race for the same answer.
|
|
1538
|
-
if (usageInFlight) return usageInFlight;
|
|
1539
|
-
usageInFlight = probeUsage({ claudeDir: CLAUDE_DIR })
|
|
1540
|
-
.then((raw) => {
|
|
1541
|
-
const data = normalizeUsage(raw);
|
|
1542
|
-
if (data) usageCache = { data, ts: Date.now() };
|
|
1543
|
-
return data;
|
|
1544
|
-
})
|
|
1545
|
-
.finally(() => {
|
|
1546
|
-
usageInFlight = null;
|
|
1547
|
-
});
|
|
1548
|
-
return usageInFlight;
|
|
1549
|
-
}
|
|
1550
|
-
|
|
1551
|
-
app.get('/api/usage-limits', async (req, res) => {
|
|
1552
|
-
try {
|
|
1553
|
-
const data = await loadUsage(req.query.refresh === '1');
|
|
1554
|
-
if (!data) return res.status(503).json({ error: 'No usage data returned' });
|
|
1555
|
-
res.json(data);
|
|
1556
|
-
} catch (err) {
|
|
1557
|
-
console.error('[API] usage-limits error:', err.message);
|
|
1558
|
-
res.status(503).json({ error: err.message });
|
|
1559
|
-
}
|
|
1560
|
-
});
|
|
1561
|
-
|
|
1562
|
-
app.get('/api/pricing', async (_req, res) => {
|
|
1563
|
-
try {
|
|
1564
|
-
const pricing = await fetchPricing();
|
|
1565
|
-
const models = {};
|
|
1566
|
-
for (const [name, info] of pricing) {
|
|
1567
|
-
if (name.startsWith('anthropic/') || name.startsWith('claude')) {
|
|
1568
|
-
models[name] = info;
|
|
1569
|
-
}
|
|
1570
|
-
}
|
|
1571
|
-
res.json(models);
|
|
1572
|
-
} catch (err) {
|
|
1573
|
-
console.error('[API] pricing error:', err);
|
|
1574
|
-
res.status(500).json({ error: 'Failed to load pricing data' });
|
|
1575
|
-
}
|
|
1576
|
-
});
|
|
1577
|
-
|
|
1578
|
-
app.post('/api/refresh', (_req, res) => {
|
|
1579
|
-
invalidateAllCache();
|
|
1580
|
-
res.json({ ok: true });
|
|
1581
|
-
});
|
|
1582
|
-
|
|
1583
|
-
// #endregion
|
|
1584
|
-
|
|
1585
|
-
// #region STARTUP
|
|
1586
|
-
|
|
1587
|
-
const onReady = (actualPort) => {
|
|
1588
|
-
console.log(`Claude Code Cost Dashboard running at http://localhost:${actualPort}`);
|
|
1589
|
-
const warning = net.exposureWarning();
|
|
1590
|
-
if (warning) console.log(warning);
|
|
1591
|
-
|
|
1592
|
-
if (process.argv.includes('--open')) {
|
|
1593
|
-
import('open').then(mod => mod.default(`http://localhost:${actualPort}`));
|
|
1594
|
-
}
|
|
1595
|
-
};
|
|
1596
|
-
|
|
1597
|
-
const server = net.listenLoopback(app, PORT, onReady);
|
|
1598
|
-
|
|
1599
|
-
server.on('error', (err) => {
|
|
1600
|
-
if (err.code === 'EADDRINUSE') {
|
|
1601
|
-
console.log(`Port ${PORT} in use, trying random port...`);
|
|
1602
|
-
net.listenLoopback(app, 0, onReady);
|
|
1603
|
-
} else {
|
|
1604
|
-
throw err;
|
|
1605
|
-
}
|
|
1606
|
-
});
|
|
1607
|
-
|
|
1608
|
-
// Pre-fetch pricing on startup
|
|
1609
|
-
fetchPricing().catch(() => {});
|
|
1610
|
-
|
|
1611
|
-
// #endregion
|