claude-code-cost 1.3.1 → 1.4.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 +82 -26
- package/public/style.css +58 -0
- package/public/vendor/claude-hub-sdk.js +1 -1
- package/server.js +6 -1605
package/lib/cli.js
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const costs = require('./costs');
|
|
6
|
+
|
|
7
|
+
// #region WINDOW
|
|
8
|
+
|
|
9
|
+
const DEFAULT_RANGE = '7d';
|
|
10
|
+
const LONG_PARSE_DAYS = 30;
|
|
11
|
+
// The dashboard's longest preset. The overview has no all-time window.
|
|
12
|
+
const MAX_DAYS = 365;
|
|
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) {
|
|
17
|
+
const v = String(raw).trim().toLowerCase();
|
|
18
|
+
if (v === 'today') return { range: 'today', days: 1, label: 'Today' };
|
|
19
|
+
if (v === '24h') return { range: '24h', days: 1, label: 'Last 24 hours' };
|
|
20
|
+
const m = /^(\d{1,3})d?$/.exec(v);
|
|
21
|
+
if (!m || Number(m[1]) < 1 || Number(m[1]) > MAX_DAYS) return null;
|
|
22
|
+
const n = Number(m[1]);
|
|
23
|
+
return { range: n, days: n, label: n === 1 ? 'Today' : `Last ${n} days` };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function configRange(claudeDir) {
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(fs.readFileSync(path.join(claudeDir, '.cost', 'config.json'), 'utf8'))?.cli?.defaultRange;
|
|
29
|
+
} catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function customWindow(from, to, days) {
|
|
35
|
+
return { range: { from, to }, days, label: from === to ? from : `${from} – ${to}`, query: `from=${from}&to=${to}` };
|
|
36
|
+
}
|
|
37
|
+
|
|
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.
|
|
40
|
+
function previousWindow(win, now = new Date()) {
|
|
41
|
+
if (win.range === '24h') throw usageError('--compare needs today, <n>d or --from/--to, not 24h');
|
|
42
|
+
const start = costs.resolveWindow(win.range, now).cutoff;
|
|
43
|
+
const day = (delta) => costs.localDateStr(new Date(start.getFullYear(), start.getMonth(), start.getDate() + delta));
|
|
44
|
+
return customWindow(day(-win.days), day(-1), win.days);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The flag wins, then CLAUDE_COST_RANGE, then cli.defaultRange in <config dir>/.cost/config.json,
|
|
48
|
+
// then 7 days. A bad flag is an error; a bad env or config value is skipped with a warning, so a
|
|
49
|
+
// typo in a file does not break every command.
|
|
50
|
+
function resolveWindow(flags, { claudeDir, parseCustomRange, env = process.env, warn = console.error }) {
|
|
51
|
+
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');
|
|
54
|
+
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
|
+
return customWindow(custom.from, custom.to, days);
|
|
57
|
+
}
|
|
58
|
+
const sources = [
|
|
59
|
+
[flags.range, '--range'],
|
|
60
|
+
[env.CLAUDE_COST_RANGE, 'CLAUDE_COST_RANGE'],
|
|
61
|
+
[configRange(claudeDir), 'cli.defaultRange'],
|
|
62
|
+
[DEFAULT_RANGE, 'default'],
|
|
63
|
+
];
|
|
64
|
+
for (const [raw, source] of sources) {
|
|
65
|
+
if (raw === undefined || raw === null || raw === '') continue;
|
|
66
|
+
const w = parseWindowValue(raw);
|
|
67
|
+
if (w) return { ...w, source, query: `range=${w.range}` };
|
|
68
|
+
if (source === '--range') throw usageError(`--range ${raw}: use ${WINDOW_HINT}`);
|
|
69
|
+
warn(`${source}: "${raw}" is not a window (${WINDOW_HINT}); skipped`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// #endregion
|
|
74
|
+
|
|
75
|
+
// #region BACKEND
|
|
76
|
+
|
|
77
|
+
function serverFromFile(claudeDir) {
|
|
78
|
+
let rec;
|
|
79
|
+
try {
|
|
80
|
+
rec = JSON.parse(fs.readFileSync(path.join(claudeDir, '.cost', 'server.json'), 'utf8'));
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
if (!Number.isInteger(rec?.pid) || !Number.isInteger(rec?.port)) return null;
|
|
85
|
+
try {
|
|
86
|
+
process.kill(rec.pid, 0);
|
|
87
|
+
} catch (err) {
|
|
88
|
+
if (err.code !== 'EPERM') return null;
|
|
89
|
+
}
|
|
90
|
+
return `http://localhost:${rec.port}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// No blind try of port 3543: it can belong to another config dir's server, and parsing the files
|
|
94
|
+
// gives the right answer, only slower.
|
|
95
|
+
function findServer(claudeDir, env = process.env) {
|
|
96
|
+
if (env.COST_URL) return env.COST_URL.replace(/\/+$/, '');
|
|
97
|
+
return serverFromFile(claudeDir);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const enc = encodeURIComponent;
|
|
101
|
+
|
|
102
|
+
const scoped = (route) => (p) => `${route}?${p.win.query}${p.project ? `&project=${enc(p.project)}` : ''}`;
|
|
103
|
+
const sliced = (base) => base && costs.withSessionSlices(base, null);
|
|
104
|
+
|
|
105
|
+
const ENDPOINTS = {
|
|
106
|
+
overview: {
|
|
107
|
+
path: scoped('/api/overview'),
|
|
108
|
+
local: (c, p) => c.getOverviewData(p.win.range, p.project),
|
|
109
|
+
},
|
|
110
|
+
insights: {
|
|
111
|
+
path: scoped('/api/insights'),
|
|
112
|
+
local: (c, p) => c.getInsightsData(p.win.range, p.project),
|
|
113
|
+
},
|
|
114
|
+
projects: {
|
|
115
|
+
path: (p) => `/api/projects?${p.win.query}`,
|
|
116
|
+
local: (c, p) => c.getProjectsData(p.win.range),
|
|
117
|
+
},
|
|
118
|
+
sessions: {
|
|
119
|
+
path: (p) => (p.project ? `/api/projects/${enc(p.project)}/sessions?${p.win.query}` : `/api/sessions?${p.win.query}`),
|
|
120
|
+
local: (c, p) => (p.project ? c.getProjectSessionsData(p.project, p.win.range) : c.getAllSessionsData(p.win.range)),
|
|
121
|
+
},
|
|
122
|
+
agents: {
|
|
123
|
+
path: scoped('/api/agents'),
|
|
124
|
+
local: (c, p) => c.getAgentsData(p.win.range, p.project),
|
|
125
|
+
},
|
|
126
|
+
session: {
|
|
127
|
+
path: (p) => `/api/sessions/${enc(p.session)}`,
|
|
128
|
+
local: async (c, p) => sliced(await c.getSessionDetailData(p.session)),
|
|
129
|
+
},
|
|
130
|
+
agent: {
|
|
131
|
+
path: (p) => `/api/sessions/${enc(p.session)}/agents/${enc(p.agent)}`,
|
|
132
|
+
local: async (c, p) => sliced(await c.getAgentDetailData(p.session, p.agent)),
|
|
133
|
+
},
|
|
134
|
+
limits: {
|
|
135
|
+
path: (p) => `/api/usage-limits${p.refresh ? '?refresh=1' : ''}`,
|
|
136
|
+
local: (c, p) => c.loadUsage(p.refresh),
|
|
137
|
+
did: 'probed claude',
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
class HttpError extends Error {
|
|
142
|
+
constructor(status, message) {
|
|
143
|
+
super(message);
|
|
144
|
+
this.status = status;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function fetchServer(base, url) {
|
|
149
|
+
const res = await fetch(base + url, { signal: AbortSignal.timeout(60_000) });
|
|
150
|
+
if (res.status === 404) return null;
|
|
151
|
+
const body = await res.json().catch(() => null);
|
|
152
|
+
if (!res.ok) throw new HttpError(res.status, body?.error || `HTTP ${res.status}`);
|
|
153
|
+
return body;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Asks the server of this config dir; with none, or one that does not answer, parses the files in
|
|
157
|
+
// this process. Notes go to stderr, so --json output stays clean.
|
|
158
|
+
async function query(name, params, ctx) {
|
|
159
|
+
const ep = ENDPOINTS[name];
|
|
160
|
+
const base = ctx.server;
|
|
161
|
+
if (base) {
|
|
162
|
+
try {
|
|
163
|
+
return await fetchServer(base, ep.path(params));
|
|
164
|
+
} catch (err) {
|
|
165
|
+
if (err instanceof HttpError) throw err;
|
|
166
|
+
ctx.note(`cost server at ${base} did not answer (${err.cause?.code || err.message}); parsing files`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const win = params.win;
|
|
170
|
+
if (win && win.days > LONG_PARSE_DAYS) {
|
|
171
|
+
ctx.note(`parsing ${win.days} days of transcripts, this can take a while`);
|
|
172
|
+
}
|
|
173
|
+
const started = Date.now();
|
|
174
|
+
const data = await ep.local(costs, params);
|
|
175
|
+
ctx.note(`no cost server: ${ep.did || 'parsed files'} in ${((Date.now() - started) / 1000).toFixed(1)} s`);
|
|
176
|
+
return data;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// #endregion
|
|
180
|
+
|
|
181
|
+
// #region FORMAT
|
|
182
|
+
|
|
183
|
+
const WIDTH = 54;
|
|
184
|
+
|
|
185
|
+
function usd(n) {
|
|
186
|
+
const v = Number(n) || 0;
|
|
187
|
+
return v >= 1000 ? `$${Math.round(v).toLocaleString('en-US')}` : `$${v.toFixed(2)}`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function pct(part, total) {
|
|
191
|
+
return total > 0 ? `${Math.round((part / total) * 100)}%` : '0%';
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function tokens(n) {
|
|
195
|
+
const v = Number(n) || 0;
|
|
196
|
+
if (v >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
|
|
197
|
+
if (v >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
|
|
198
|
+
if (v >= 1e3) return `${(v / 1e3).toFixed(1)}k`;
|
|
199
|
+
return String(v);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function clip(s, n) {
|
|
203
|
+
const t = String(s ?? '').replace(/\s+/g, ' ').trim();
|
|
204
|
+
return t.length > n ? `${t.slice(0, n - 1)}…` : t;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const shortModel = (m) => String(m || '?').replace(/^claude-/, '');
|
|
208
|
+
|
|
209
|
+
function localStamp(iso, withDate = true) {
|
|
210
|
+
if (!iso) return '?';
|
|
211
|
+
const d = new Date(iso);
|
|
212
|
+
const p = (x) => String(x).padStart(2, '0');
|
|
213
|
+
const time = `${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
214
|
+
return withDate ? `${costs.localDateStr(d)} ${time}` : time;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function span(first, last) {
|
|
218
|
+
if (!first) return '?';
|
|
219
|
+
const sameDay = costs.localDateStr(new Date(first)) === costs.localDateStr(new Date(last));
|
|
220
|
+
return `${localStamp(first)} – ${localStamp(last, !sameDay)}`;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function dupNames(list) {
|
|
224
|
+
const seen = new Set();
|
|
225
|
+
const dups = new Set();
|
|
226
|
+
for (const p of list) (seen.has(p.name) ? dups : seen).add(p.name);
|
|
227
|
+
return dups;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const headline = (win, s) => `${win.label} · ${usd(s.totalCost)} · ${s.totalSessions} sessions`;
|
|
231
|
+
|
|
232
|
+
function sessionTitle(s) {
|
|
233
|
+
return clip(s.customTitle || s.firstPrompt || '(untitled)', 40);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const NAME_WIDTH = 30;
|
|
237
|
+
|
|
238
|
+
function row(left, cost, extra = '') {
|
|
239
|
+
return ` ${clip(left, NAME_WIDTH).padEnd(NAME_WIDTH)} ${usd(cost).padStart(9)}${extra ? ` ${extra}` : ''}`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function bucketLabel(key, bucket) {
|
|
243
|
+
return bucket === 'hour' ? `${key.slice(0, 10)} ${key.slice(11)}:00` : key;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function topTurns(messages, top) {
|
|
247
|
+
return messages
|
|
248
|
+
.filter((m) => !m._subagent)
|
|
249
|
+
.sort((a, b) => b.cost - a.cost)
|
|
250
|
+
.slice(0, top)
|
|
251
|
+
.map((m) => {
|
|
252
|
+
const tools = (m.tools || []).slice(0, 3).join(', ');
|
|
253
|
+
return ` #${String(m.index).padEnd(4)} ${usd(m.cost).padStart(7)} ${localStamp(m.timestamp, false)} ${clip(tools, WIDTH - 24)}`;
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function section(lines, title, items, toRow) {
|
|
258
|
+
if (items.length) lines.push('', title, ...items.map(toRow));
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function compactionLine(c) {
|
|
262
|
+
return `Compactions ${c.count} (${c.auto} auto) · ${usd(c.totalCost)}: summaries ~${usd(c.estCost)}, cache re-warm ${usd(c.rewarmCost)}`;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function matchSessions(d, text) {
|
|
266
|
+
const lower = text.toLowerCase();
|
|
267
|
+
return { ...d, sessions: (d.sessions || []).filter((s) => s.customTitle?.toLowerCase().includes(lower)) };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const FORMAT = {
|
|
271
|
+
overview(d, { win, top }) {
|
|
272
|
+
const s = d.summary;
|
|
273
|
+
const lines = [headline(win, s)];
|
|
274
|
+
if (s.todayCost !== null && s.todayCost !== undefined && win.range !== 'today') lines.push(`Today ${usd(s.todayCost)}`);
|
|
275
|
+
lines.push(`Tokens ${tokens(s.totalTokens)} · cache reads ${pct(s.totalCacheRead, s.totalTokens)}`);
|
|
276
|
+
section(lines, 'By model', (d.modelDistribution || []).slice(0, top), (m) => row(shortModel(m.model), m.cost, pct(m.cost, s.totalCost)));
|
|
277
|
+
const bucket = d.costSeries?.bucket;
|
|
278
|
+
const points = (d.costSeries?.points || []).filter((p) => p.cost > 0);
|
|
279
|
+
const bucketRow = (p) => row(bucketLabel(p.key, bucket), p.cost);
|
|
280
|
+
if (points.length <= 14) section(lines, `By ${bucket}`, points, bucketRow);
|
|
281
|
+
else section(lines, `Costliest ${bucket}s`, [...points].sort((a, b) => b.cost - a.cost).slice(0, top), bucketRow);
|
|
282
|
+
section(lines, 'Top projects', (d.projects || []).slice(0, top), (p) => row(p.name, p.totalCost, `${p.sessionCount} sess`));
|
|
283
|
+
return lines;
|
|
284
|
+
},
|
|
285
|
+
|
|
286
|
+
insights(d, { win, top }) {
|
|
287
|
+
const lines = [win.label];
|
|
288
|
+
if (d.runRate) lines.push(`Run rate ${usd(d.runRate.dailyAvg)}/day · ${usd(d.runRate.projectedMonthly)}/month (${d.runRate.days} days)`);
|
|
289
|
+
if (d.cacheSavings) lines.push(`Cache saved ${usd(d.cacheSavings)}`);
|
|
290
|
+
const sa = d.subagents;
|
|
291
|
+
if (sa) {
|
|
292
|
+
const total = sa.mainCost + sa.subagentCost;
|
|
293
|
+
lines.push(`Subagents ${usd(sa.subagentCost)} (${pct(sa.subagentCost, total)}) · workflows ${usd(sa.workflowCost)} in ${sa.workflowRuns} run${sa.workflowRuns === 1 ? '' : 's'}`);
|
|
294
|
+
}
|
|
295
|
+
if (d.compactions?.count) lines.push(compactionLine(d.compactions));
|
|
296
|
+
const block = (d.blocks || []).find((b) => b.active);
|
|
297
|
+
if (block) lines.push(`Current 5h block ${usd(block.cost)} since ${localStamp(block.start, false)}`);
|
|
298
|
+
const blocks = [...(d.blocks || [])].sort((a, b) => b.cost - a.cost).slice(0, top);
|
|
299
|
+
section(lines, 'Costliest 5h blocks', blocks, (b) => row(localStamp(b.start), b.cost, `${b.messageCount} turns`));
|
|
300
|
+
if (d.tools?.length) lines.push('', `Top tools: ${d.tools.slice(0, top).map((t) => `${t.name} ${t.count}`).join(', ')}`);
|
|
301
|
+
return lines;
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
projects(all, { win, top }) {
|
|
305
|
+
const list = all.filter((p) => p.totalCost > 0);
|
|
306
|
+
const lines = [`${win.label} · ${list.length} projects · ${usd(list.reduce((a, p) => a + p.totalCost, 0))}`];
|
|
307
|
+
const dups = dupNames(list);
|
|
308
|
+
for (const p of list.slice(0, top)) {
|
|
309
|
+
lines.push(row(p.name, p.totalCost, `${p.sessionCount} sess`));
|
|
310
|
+
if (dups.has(p.name)) lines.push(` ${p.encodedPath}`);
|
|
311
|
+
}
|
|
312
|
+
return lines;
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
sessions(d, { win, top, project, match }) {
|
|
316
|
+
const list = [...(d.sessions || [])].sort((a, b) => b.totalCost - a.totalCost);
|
|
317
|
+
const total = list.reduce((a, s) => a + s.totalCost, 0);
|
|
318
|
+
const matching = match ? ` matching "${match}"` : '';
|
|
319
|
+
const lines = [`${project ? project.name : 'All projects'} · ${win.label} · ${list.length} sessions${matching} · ${usd(total)}`];
|
|
320
|
+
for (const s of list.slice(0, top)) {
|
|
321
|
+
lines.push(`${usd(s.totalCost).padStart(9)} ${sessionTitle(s)}`);
|
|
322
|
+
const where = s.projectName ? `${clip(s.projectName, NAME_WIDTH)} · ` : '';
|
|
323
|
+
lines.push(`${' '.repeat(11)}${where}${localStamp(s.firstTimestamp).slice(0, 10)} · ${s.durationMinutes} min · ${s.messageCount} turns`);
|
|
324
|
+
lines.push(`${' '.repeat(11)}${s.sessionId}`);
|
|
325
|
+
}
|
|
326
|
+
return lines;
|
|
327
|
+
},
|
|
328
|
+
|
|
329
|
+
agents(d, { win, top, project }) {
|
|
330
|
+
const list = d.agents || [];
|
|
331
|
+
const total = list.reduce((a, g) => a + g.totalCost, 0);
|
|
332
|
+
const runs = list.reduce((a, g) => a + g.runs, 0);
|
|
333
|
+
const lines = [`${project ? project.name : 'All projects'} · ${win.label} · ${runs} subagent runs · ${usd(total)}`];
|
|
334
|
+
for (const g of list.slice(0, top)) {
|
|
335
|
+
const name = g.kind === 'skill' ? `/${g.name}` : g.kind === 'workflow' ? `workflow · ${g.name}` : g.name;
|
|
336
|
+
lines.push(row(name, g.totalCost, `${g.runs} run${g.runs === 1 ? '' : 's'} · avg ${usd(g.avgCost)}`));
|
|
337
|
+
const c = g.costliest;
|
|
338
|
+
lines.push(` costliest ${usd(c.cost)} · ${clip(c.description, WIDTH - 20)}`);
|
|
339
|
+
lines.push(` ${c.sessionId} ${c.agentId}`);
|
|
340
|
+
}
|
|
341
|
+
return lines;
|
|
342
|
+
},
|
|
343
|
+
|
|
344
|
+
session(d, { top }) {
|
|
345
|
+
const turns = d.messages.filter((m) => !m._subagent);
|
|
346
|
+
const agents = d.messages.filter((m) => m._subagent).sort((a, b) => b.cost - a.cost);
|
|
347
|
+
const lines = [
|
|
348
|
+
sessionTitle(d),
|
|
349
|
+
`${d.projectPath} · ${span(d.firstTimestamp, d.lastTimestamp)}`,
|
|
350
|
+
`${usd(d.totalCost)} · ${turns.length} turns · ${(d.models || []).map(shortModel).join(', ')}`,
|
|
351
|
+
`Tokens in ${tokens(d.inputTokens)} · out ${tokens(d.outputTokens)} · cache write ${tokens(d.cacheCreationTokens)} · read ${tokens(d.cacheReadTokens)}`,
|
|
352
|
+
];
|
|
353
|
+
if (d.compactions?.count) lines.push(compactionLine(d.compactions));
|
|
354
|
+
if (agents.length) {
|
|
355
|
+
lines.push('', `Subagents ${agents.length} · ${usd(agents.reduce((a, m) => a + m.cost, 0))}`);
|
|
356
|
+
for (const m of agents.slice(0, top)) {
|
|
357
|
+
const sa = m._subagent;
|
|
358
|
+
const what = `${sa.workflowId ? 'workflow' : sa.agentType || 'agent'} · ${sa.description || ''}`;
|
|
359
|
+
lines.push(` ${usd(m.cost).padStart(7)} ${clip(what, WIDTH - 11)}`);
|
|
360
|
+
if (!sa.workflowId) lines.push(` ${sa.agentId}`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
section(lines, 'Costliest turns', topTurns(turns, top), (t) => t);
|
|
364
|
+
return lines;
|
|
365
|
+
},
|
|
366
|
+
|
|
367
|
+
agent(d, { top }) {
|
|
368
|
+
const lines = [
|
|
369
|
+
`${d.agentType || 'agent'} · ${clip(d.description, 40)}`,
|
|
370
|
+
`in ${clip(d.sessionTitle, 30)} (${d.projectPath})`,
|
|
371
|
+
`${usd(d.totalCost)} · ${d.messages.length} turns · ${span(d.firstTimestamp, d.lastTimestamp)} · ${(d.models || []).map(shortModel).join(', ')}`,
|
|
372
|
+
];
|
|
373
|
+
section(lines, 'Costliest turns', topTurns(d.messages, top), (t) => t);
|
|
374
|
+
return lines;
|
|
375
|
+
},
|
|
376
|
+
|
|
377
|
+
limits(d) {
|
|
378
|
+
const limitRow = (label, percent, suffix = '') => ` ${clip(label, 24).padEnd(24)} ${String(Math.round(percent || 0)).padStart(3)}%${suffix}`;
|
|
379
|
+
const lines = [d.subscription ? `Plan: ${d.subscription}` : 'Plan usage'];
|
|
380
|
+
for (const w of d.windows || []) {
|
|
381
|
+
const reset = w.resetsAt ? ` · resets ${localStamp(typeof w.resetsAt === 'number' && w.resetsAt < 1e12 ? w.resetsAt * 1000 : w.resetsAt)}` : '';
|
|
382
|
+
lines.push(limitRow(w.label, w.percent, reset));
|
|
383
|
+
}
|
|
384
|
+
if (d.spend?.enabled) lines.push(limitRow('Extra usage', d.spend.percent));
|
|
385
|
+
return lines;
|
|
386
|
+
},
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
function change(now, before) {
|
|
390
|
+
const d = now - before;
|
|
391
|
+
const sign = d < 0 ? '-' : '+';
|
|
392
|
+
let rel = '';
|
|
393
|
+
if (before > 0) rel = ` (${sign}${pct(Math.abs(d), before)})`;
|
|
394
|
+
else if (now > 0) rel = ' (new)';
|
|
395
|
+
return `${sign}${usd(Math.abs(d))}${rel}`;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Rows of both windows by key, biggest change first, so a model or project that stopped shows too.
|
|
399
|
+
function diffRows(cur, prev, key, cost, top) {
|
|
400
|
+
const rows = new Map();
|
|
401
|
+
for (const [list, side] of [[cur, 'now'], [prev, 'before']]) {
|
|
402
|
+
for (const x of list || []) {
|
|
403
|
+
const k = key(x);
|
|
404
|
+
if (!rows.has(k)) rows.set(k, { x, now: 0, before: 0 });
|
|
405
|
+
rows.get(k)[side] += cost(x);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return [...rows.values()].sort((a, b) => Math.abs(b.now - b.before) - Math.abs(a.now - a.before)).slice(0, top);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const diffTitle = (title) => `${title.padEnd(NAME_WIDTH + 2)} ${'now'.padStart(9)} ${'before'.padStart(9)} change`;
|
|
412
|
+
const diffRow = (name, r) => row(name, r.now, `${usd(r.before).padStart(9)} ${change(r.now, r.before)}`);
|
|
413
|
+
|
|
414
|
+
const COMPARE = {
|
|
415
|
+
overview({ current, previous }, { win, before, top }) {
|
|
416
|
+
const c = current.summary;
|
|
417
|
+
const p = previous.summary;
|
|
418
|
+
const lines = [headline(win, c), headline(before, p), `Change ${change(c.totalCost, p.totalCost)}`];
|
|
419
|
+
const models = diffRows(current.modelDistribution, previous.modelDistribution, (m) => m.model, (m) => m.cost, top);
|
|
420
|
+
section(lines, diffTitle('By model'), models, (r) => diffRow(shortModel(r.x.model), r));
|
|
421
|
+
const projects = diffRows(current.projects, previous.projects, (p) => p.encodedPath, (p) => p.totalCost, top);
|
|
422
|
+
const dups = dupNames(projects.map((r) => r.x));
|
|
423
|
+
section(lines, diffTitle('Projects'), projects, (r) => diffRow(r.x.name, r) + (dups.has(r.x.name) ? `\n ${r.x.encodedPath}` : ''));
|
|
424
|
+
return lines;
|
|
425
|
+
},
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
// #endregion
|
|
429
|
+
|
|
430
|
+
// #region COMMANDS
|
|
431
|
+
|
|
432
|
+
const BIN = 'claude-code-cost';
|
|
433
|
+
|
|
434
|
+
const WINDOW_FLAGS = {
|
|
435
|
+
'--range <r>': WINDOW_HINT,
|
|
436
|
+
'--from <date>': 'Window start, YYYY-MM-DD (needs --to)',
|
|
437
|
+
'--to <date>': 'Window end, YYYY-MM-DD',
|
|
438
|
+
};
|
|
439
|
+
const COMMON_FLAGS = {
|
|
440
|
+
'--top <n>': 'Rows per list (default 5)',
|
|
441
|
+
'--json': 'Print the API response as JSON',
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
const SCOPED_FLAGS = { ...WINDOW_FLAGS, '--project <name>': 'One project (name or encoded dir)', ...COMMON_FLAGS };
|
|
445
|
+
|
|
446
|
+
const COMMANDS = {
|
|
447
|
+
overview: {
|
|
448
|
+
summary: 'Total cost, by model, by day and top projects; --compare to the window before',
|
|
449
|
+
usage: `${BIN} overview [--range <r>] [--project <name>] [--compare] [--json]`,
|
|
450
|
+
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`],
|
|
453
|
+
window: true,
|
|
454
|
+
project: true,
|
|
455
|
+
},
|
|
456
|
+
insights: {
|
|
457
|
+
summary: 'Run rate, 5-hour blocks, subagent share, compactions, top tools',
|
|
458
|
+
usage: `${BIN} insights [--range <r>] [--project <name>] [--json]`,
|
|
459
|
+
flags: SCOPED_FLAGS,
|
|
460
|
+
notes: 'A compaction costs its summary call (an estimate: it is not logged)\nand the cache re-warm of the next turn (already in the total).',
|
|
461
|
+
window: true,
|
|
462
|
+
project: true,
|
|
463
|
+
},
|
|
464
|
+
projects: {
|
|
465
|
+
summary: 'Projects by cost',
|
|
466
|
+
usage: `${BIN} projects [--range <r>] [--json]`,
|
|
467
|
+
flags: { ...WINDOW_FLAGS, ...COMMON_FLAGS },
|
|
468
|
+
window: true,
|
|
469
|
+
},
|
|
470
|
+
sessions: {
|
|
471
|
+
summary: 'Sessions by cost, with their ids: all projects or one; --match <title>',
|
|
472
|
+
usage: `${BIN} sessions [<project>] [--match <text>] [--range <r>] [--json]`,
|
|
473
|
+
flags: {
|
|
474
|
+
'<project>': 'Project name, or the encoded dir from projects --json',
|
|
475
|
+
'--match <text>': 'Only sessions whose title has <text> (ignores case)',
|
|
476
|
+
...WINDOW_FLAGS,
|
|
477
|
+
...COMMON_FLAGS,
|
|
478
|
+
},
|
|
479
|
+
notes: 'The title is the name set with /rename. The total covers the matching sessions.',
|
|
480
|
+
examples: [`${BIN} sessions --range 30d --top 10`, `${BIN} sessions claude-code-hub --range 30d`, `${BIN} sessions --match rate-limiter --range 30d`],
|
|
481
|
+
match: matchSessions,
|
|
482
|
+
window: true,
|
|
483
|
+
project: true,
|
|
484
|
+
optionalArgs: ['project'],
|
|
485
|
+
},
|
|
486
|
+
agents: {
|
|
487
|
+
summary: 'Subagents by skill or agent type: runs, total, average',
|
|
488
|
+
usage: `${BIN} agents [--range <r>] [--project <name>] [--json]`,
|
|
489
|
+
flags: SCOPED_FLAGS,
|
|
490
|
+
notes: `A subagent started by a skill groups under /<skill>. Each row names its costliest run; open it with ${BIN} agent <session id> <agent id>.`,
|
|
491
|
+
examples: [`${BIN} agents --range 30d`, `${BIN} agents --project claude-code-hub --top 10`],
|
|
492
|
+
window: true,
|
|
493
|
+
project: true,
|
|
494
|
+
},
|
|
495
|
+
session: {
|
|
496
|
+
summary: 'One session: totals, subagents, costliest turns',
|
|
497
|
+
usage: `${BIN} session <id> [--json]`,
|
|
498
|
+
flags: { '<id>': 'Full session id', ...COMMON_FLAGS },
|
|
499
|
+
notes: 'Covers the whole session; --range does not apply. Find an id with sessions --match <title>, or claude-code-kanban session search.',
|
|
500
|
+
examples: [`${BIN} session 3fa9c1d2-…`],
|
|
501
|
+
args: ['session'],
|
|
502
|
+
notFound: 'Session not found',
|
|
503
|
+
},
|
|
504
|
+
agent: {
|
|
505
|
+
summary: 'One subagent of a session: totals, costliest turns',
|
|
506
|
+
usage: `${BIN} agent <session id> <agent id> [--json]`,
|
|
507
|
+
flags: { '<agent id>': 'agent-… id, as session prints it', ...COMMON_FLAGS },
|
|
508
|
+
args: ['session', 'agent'],
|
|
509
|
+
notFound: 'Subagent not found',
|
|
510
|
+
},
|
|
511
|
+
limits: {
|
|
512
|
+
summary: 'Plan usage limits (5-hour and weekly windows)',
|
|
513
|
+
usage: `${BIN} limits [--refresh] [--json]`,
|
|
514
|
+
flags: { '--refresh': 'Probe again instead of using the 5-minute cache', '--json': COMMON_FLAGS['--json'] },
|
|
515
|
+
notes: 'Probes the claude CLI: a few seconds without a server.',
|
|
516
|
+
},
|
|
517
|
+
};
|
|
518
|
+
|
|
519
|
+
const BOOLEAN_FLAGS = new Set(['--json', '--refresh', '--compare', '--help', '-h']);
|
|
520
|
+
const HELP = new Set(['help', '--help', '-h']);
|
|
521
|
+
|
|
522
|
+
function parseArgs(args) {
|
|
523
|
+
const flags = {};
|
|
524
|
+
const positional = [];
|
|
525
|
+
for (let i = 0; i < args.length; i++) {
|
|
526
|
+
const a = args[i];
|
|
527
|
+
if (!a.startsWith('-')) {
|
|
528
|
+
positional.push(a);
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
const eq = a.indexOf('=');
|
|
532
|
+
const name = eq === -1 ? a : a.slice(0, eq);
|
|
533
|
+
const key = name.replace(/^-+/, '');
|
|
534
|
+
if (BOOLEAN_FLAGS.has(name)) flags[key] = true;
|
|
535
|
+
else if (eq !== -1) flags[key] = a.slice(eq + 1);
|
|
536
|
+
else flags[key] = args[++i];
|
|
537
|
+
}
|
|
538
|
+
return { flags, positional };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function usageError(message) {
|
|
542
|
+
const err = new Error(message);
|
|
543
|
+
err.usage = true;
|
|
544
|
+
return err;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function topHelp() {
|
|
548
|
+
const names = Object.keys(COMMANDS);
|
|
549
|
+
const w = Math.max(...names.map((n) => n.length));
|
|
550
|
+
return [
|
|
551
|
+
`${BIN} — Claude Code costs from the command line`,
|
|
552
|
+
'',
|
|
553
|
+
`Usage: ${BIN} <command> [flags]`,
|
|
554
|
+
` ${BIN} [--port <n>] [--dir <config dir>] [--open] start the dashboard`,
|
|
555
|
+
'',
|
|
556
|
+
'Commands:',
|
|
557
|
+
...names.map((n) => ` ${n.padEnd(w)} ${COMMANDS[n].summary}`),
|
|
558
|
+
'',
|
|
559
|
+
`Window: --range, else CLAUDE_COST_RANGE, else cli.defaultRange in`,
|
|
560
|
+
'<config dir>/.cost/config.json, else 7d.',
|
|
561
|
+
'Asks the running dashboard of the config dir (COST_URL, else',
|
|
562
|
+
'<config dir>/.cost/server.json); with none, parses the transcripts.',
|
|
563
|
+
`--dir <config dir> picks the config dir. Details: ${BIN} help <command>`,
|
|
564
|
+
].join('\n');
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function leafHelp(name) {
|
|
568
|
+
const c = COMMANDS[name];
|
|
569
|
+
const lines = [c.summary, '', `Usage: ${c.usage}`];
|
|
570
|
+
const flags = Object.entries(c.flags || {});
|
|
571
|
+
if (flags.length) {
|
|
572
|
+
const w = Math.max(...flags.map(([f]) => f.length));
|
|
573
|
+
lines.push('', 'Flags:', ...flags.map(([f, d]) => ` ${f.padEnd(w)} ${d}`));
|
|
574
|
+
}
|
|
575
|
+
if (c.notes) lines.push('', c.notes);
|
|
576
|
+
if (c.examples?.length) lines.push('', 'Examples:', ...c.examples.map((e) => ` ${e}`));
|
|
577
|
+
return lines.join('\n');
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function isCommand(arg) {
|
|
581
|
+
return HELP.has(arg) || Object.hasOwn(COMMANDS, arg || '');
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function resolveProject(list, raw) {
|
|
585
|
+
const exact = list.find((p) => p.encodedPath === raw);
|
|
586
|
+
if (exact) return exact;
|
|
587
|
+
const lower = raw.toLowerCase();
|
|
588
|
+
const named = list.filter((p) => p.name.toLowerCase() === lower);
|
|
589
|
+
const hits = named.length ? named : list.filter((p) => p.name.toLowerCase().includes(lower));
|
|
590
|
+
if (hits.length === 1) return hits[0];
|
|
591
|
+
if (!hits.length) throw usageError(`No project matches "${raw}" in this window. Try a wider --range, or ${BIN} projects`);
|
|
592
|
+
throw usageError(`"${raw}" matches ${hits.length} projects; pass the encoded dir:\n${hits.map((p) => ` ${p.name} ${p.encodedPath}`).join('\n')}`);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
async function main(args, { out = (s) => process.stdout.write(`${s}\n`), err = (s) => process.stderr.write(`${s}\n`) } = {}) {
|
|
596
|
+
// The data layer logs pricing fetches with console.log; stdout is for the answer.
|
|
597
|
+
console.log = () => {};
|
|
598
|
+
const [name, ...rest] = args;
|
|
599
|
+
if (HELP.has(name)) {
|
|
600
|
+
out(rest[0] && Object.hasOwn(COMMANDS, rest[0]) ? leafHelp(rest[0]) : topHelp());
|
|
601
|
+
return 0;
|
|
602
|
+
}
|
|
603
|
+
const cmd = COMMANDS[name];
|
|
604
|
+
const { flags, positional } = parseArgs(rest);
|
|
605
|
+
if (flags.help || flags.h) {
|
|
606
|
+
out(leafHelp(name));
|
|
607
|
+
return 0;
|
|
608
|
+
}
|
|
609
|
+
if ((cmd.args || []).length > positional.length) {
|
|
610
|
+
err(leafHelp(name));
|
|
611
|
+
return 1;
|
|
612
|
+
}
|
|
613
|
+
try {
|
|
614
|
+
const top = flags.top === undefined ? 5 : Number.parseInt(flags.top, 10);
|
|
615
|
+
if (!Number.isInteger(top) || top < 1) throw usageError('--top takes a positive number');
|
|
616
|
+
if (cmd.match && Object.hasOwn(flags, 'match') && !flags.match) throw usageError('--match takes text');
|
|
617
|
+
const match = cmd.match && flags.match;
|
|
618
|
+
const { CLAUDE_DIR, parseCustomRange } = costs;
|
|
619
|
+
const ctx = { server: findServer(CLAUDE_DIR), note: (s) => err(`(${s})`) };
|
|
620
|
+
const params = { refresh: flags.refresh === true };
|
|
621
|
+
[...(cmd.args || []), ...(cmd.optionalArgs || [])].forEach((a, i) => {
|
|
622
|
+
params[a] = positional[i];
|
|
623
|
+
});
|
|
624
|
+
if (params.agent && !params.agent.startsWith('agent-')) params.agent = `agent-${params.agent}`;
|
|
625
|
+
if (cmd.window) params.win = resolveWindow(flags, { claudeDir: CLAUDE_DIR, parseCustomRange, warn: err });
|
|
626
|
+
const view = { win: params.win, top, match };
|
|
627
|
+
|
|
628
|
+
const raw = params.project ?? flags.project;
|
|
629
|
+
if (cmd.project && raw) {
|
|
630
|
+
if (typeof raw !== 'string') throw usageError('--project takes a project name');
|
|
631
|
+
const list = await query('projects', { win: params.win }, ctx);
|
|
632
|
+
view.project = resolveProject(list || [], raw);
|
|
633
|
+
params.project = view.project.encodedPath;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const compare = flags.compare && COMPARE[name];
|
|
637
|
+
let data;
|
|
638
|
+
if (compare) {
|
|
639
|
+
view.before = previousWindow(params.win);
|
|
640
|
+
const [current, previous] = await Promise.all([query(name, params, ctx), query(name, { ...params, win: view.before }, ctx)]);
|
|
641
|
+
data = current && previous && { current, previous, previousWindow: view.before.range };
|
|
642
|
+
} else {
|
|
643
|
+
data = await query(name, params, ctx);
|
|
644
|
+
}
|
|
645
|
+
if (!data) {
|
|
646
|
+
err(cmd.notFound || 'No data');
|
|
647
|
+
return 1;
|
|
648
|
+
}
|
|
649
|
+
if (match) data = cmd.match(data, match);
|
|
650
|
+
if (flags.json) out(JSON.stringify(data, null, 2));
|
|
651
|
+
else out((compare || FORMAT[name])(data, view).join('\n'));
|
|
652
|
+
return 0;
|
|
653
|
+
} catch (e) {
|
|
654
|
+
err(e.usage ? e.message : `Error: ${e.message}`);
|
|
655
|
+
return 1;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// #endregion
|
|
660
|
+
|
|
661
|
+
module.exports = { isCommand, main, resolveWindow, previousWindow, parseWindowValue, findServer, parseArgs, matchSessions };
|