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 CHANGED
@@ -78,6 +78,8 @@ A flag wins over its environment variable. Flags take a value as `--port 3000` o
78
78
 
79
79
  With a custom config dir, the server reads only `<dir>/projects`. With the default dir, it also reads `~/.config/claude/projects`.
80
80
 
81
+ `claude-code-cost <command>` prints costs in the terminal: `overview`, `insights`, `projects`, `sessions`, `session`, `agent` and `limits`. Run `claude-code-cost help` for the flags. A command asks the running dashboard of the config dir, else parses the transcripts itself.
82
+
81
83
  The server has no authentication. Bind a non-loopback address only on a network you trust. See [Configuration and CLI](https://nikiforovall.blog/claude-code-cost/reference/configuration/) for the network rules and the HTTP API.
82
84
 
83
85
  ## Documentation
package/hub-app.json CHANGED
@@ -19,7 +19,8 @@
19
19
  },
20
20
  "actions": {
21
21
  "handles": {
22
- "session.cost": { "params": { "session": "string?" }, "url": "?view=detail&session={session}", "mode": "message" }
22
+ "session.cost": { "params": { "session": "string?" }, "url": "?view=detail&session={session}", "mode": "message" },
23
+ "agent.cost": { "params": { "session": "string", "agent": "string" }, "url": "?view=detail&session={session}&agent={agent}", "mode": "message" }
23
24
  }
24
25
  }
25
26
  }
package/lib/app.js ADDED
@@ -0,0 +1,227 @@
1
+ 'use strict';
2
+
3
+ const express = require('express');
4
+ const path = require('node:path');
5
+ const fs = require('node:fs');
6
+ const { createNetGuard } = require('./net-guard');
7
+ const {
8
+ getArg,
9
+ CLAUDE_DIR,
10
+ fetchPricing,
11
+ invalidateAllCache,
12
+ getOverviewData,
13
+ getInsightsData,
14
+ getProjectsData,
15
+ getProjectSessionsData,
16
+ getAllSessionsData,
17
+ getAgentsData,
18
+ getSessionDetailData,
19
+ getAgentDetailData,
20
+ withSessionSlices,
21
+ loadUsage,
22
+ parseRange,
23
+ parseCustomRange,
24
+ parseProject,
25
+ } = require('./costs');
26
+
27
+ const PORT = getArg('port') || process.env.PORT || 3543;
28
+
29
+ // #region EXPRESS
30
+
31
+ const app = express();
32
+
33
+ // Mounted before express.json() so a rejected request never buffers a body.
34
+ const net = createNetGuard({ appName: 'Claude Code Cost Dashboard' });
35
+ app.use(net.hostGuard);
36
+ app.use(net.frameGuard);
37
+ app.use(net.originGuard);
38
+
39
+ app.use(express.json());
40
+ // Under a hub, the hub hands over its SDK. Alone, public/vendor/claude-hub-sdk.js is a stub.
41
+ if (process.env.HUB_SDK_SERVER) require(process.env.HUB_SDK_SERVER).mount(app);
42
+
43
+ app.use(express.static(path.join(__dirname, '..', 'public')));
44
+
45
+ // Resolves a request's range onto req.range: a custom from/to window wins over `range`. A resolved
46
+ // range cannot signal malformed input with null (null *is* the all-time range), so the rejection
47
+ // happens here, ahead of the handler, instead of being threaded back to it as a sentinel value.
48
+ // Only the range — a route that also scopes by project keeps its own parseProject guard, because
49
+ // the routes that don't call parseProject must go on ignoring a malformed `project`.
50
+ const withRange = (fallback = null) => (req, res, next) => {
51
+ const custom = parseCustomRange(req.query);
52
+ if (custom === null) return res.status(400).json({ error: 'Invalid date range' });
53
+ req.range = custom || parseRange(req.query.range, fallback);
54
+ next();
55
+ };
56
+
57
+ app.get('/api/overview', withRange(30), async (req, res) => {
58
+ try {
59
+ const project = parseProject(req.query.project);
60
+ if (project === null) return res.status(400).json({ error: 'Invalid project' });
61
+ const data = await getOverviewData(req.range, project);
62
+ res.json(data);
63
+ } catch (err) {
64
+ console.error('[API] overview error:', err);
65
+ res.status(500).json({ error: 'Failed to load overview data' });
66
+ }
67
+ });
68
+
69
+ app.get('/api/insights', withRange(30), async (req, res) => {
70
+ try {
71
+ const project = parseProject(req.query.project);
72
+ if (project === null) return res.status(400).json({ error: 'Invalid project' });
73
+ const data = await getInsightsData(req.range, project);
74
+ res.json(data);
75
+ } catch (err) {
76
+ console.error('[API] insights error:', err);
77
+ res.status(500).json({ error: 'Failed to load insights data' });
78
+ }
79
+ });
80
+
81
+ app.get('/api/projects', withRange(), async (req, res) => {
82
+ try {
83
+ const project = parseProject(req.query.project);
84
+ if (project === null) return res.status(400).json({ error: 'Invalid project' });
85
+ const data = await getProjectsData(req.range, project);
86
+ res.json(data);
87
+ } catch (err) {
88
+ console.error('[API] projects error:', err);
89
+ res.status(500).json({ error: 'Failed to load projects data' });
90
+ }
91
+ });
92
+
93
+ app.get('/api/projects/:path/sessions', withRange(), async (req, res) => {
94
+ try {
95
+ const data = await getProjectSessionsData(req.params.path, req.range);
96
+ res.json(data);
97
+ } catch (err) {
98
+ console.error('[API] sessions error:', err);
99
+ res.status(500).json({ error: 'Failed to load sessions data' });
100
+ }
101
+ });
102
+
103
+ app.get('/api/sessions', withRange(), async (req, res) => {
104
+ try {
105
+ res.json(await getAllSessionsData(req.range));
106
+ } catch (err) {
107
+ console.error('[API] sessions error:', err);
108
+ res.status(500).json({ error: 'Failed to load sessions data' });
109
+ }
110
+ });
111
+
112
+ app.get('/api/agents', withRange(30), async (req, res) => {
113
+ try {
114
+ const project = parseProject(req.query.project);
115
+ if (project === null) return res.status(400).json({ error: 'Invalid project' });
116
+ res.json(await getAgentsData(req.range, project));
117
+ } catch (err) {
118
+ console.error('[API] agents error:', err);
119
+ res.status(500).json({ error: 'Failed to load agents data' });
120
+ }
121
+ });
122
+
123
+ app.get('/api/sessions/:id', withRange(), async (req, res) => {
124
+ try {
125
+ const base = await getSessionDetailData(req.params.id);
126
+ if (!base) return res.status(404).json({ error: 'Session not found' });
127
+ res.json(withSessionSlices(base, req.range));
128
+ } catch (err) {
129
+ console.error('[API] session detail error:', err);
130
+ res.status(500).json({ error: 'Failed to load session detail' });
131
+ }
132
+ });
133
+
134
+ app.get('/api/sessions/:id/agents/:agentId', withRange(), async (req, res) => {
135
+ try {
136
+ const base = await getAgentDetailData(req.params.id, req.params.agentId);
137
+ if (!base) return res.status(404).json({ error: 'Agent not found' });
138
+ res.json(withSessionSlices(base, req.range));
139
+ } catch (err) {
140
+ console.error('[API] agent detail error:', err);
141
+ res.status(500).json({ error: 'Failed to load agent detail' });
142
+ }
143
+ });
144
+
145
+ app.get('/api/usage-limits', async (req, res) => {
146
+ try {
147
+ const data = await loadUsage(req.query.refresh === '1');
148
+ if (!data) return res.status(503).json({ error: 'No usage data returned' });
149
+ res.json(data);
150
+ } catch (err) {
151
+ console.error('[API] usage-limits error:', err.message);
152
+ res.status(503).json({ error: err.message });
153
+ }
154
+ });
155
+
156
+ app.get('/api/pricing', async (_req, res) => {
157
+ try {
158
+ const pricing = await fetchPricing();
159
+ const models = {};
160
+ for (const [name, info] of pricing) {
161
+ if (name.startsWith('anthropic/') || name.startsWith('claude')) {
162
+ models[name] = info;
163
+ }
164
+ }
165
+ res.json(models);
166
+ } catch (err) {
167
+ console.error('[API] pricing error:', err);
168
+ res.status(500).json({ error: 'Failed to load pricing data' });
169
+ }
170
+ });
171
+
172
+ app.post('/api/refresh', (_req, res) => {
173
+ invalidateAllCache();
174
+ res.json({ ok: true });
175
+ });
176
+
177
+ // #endregion
178
+
179
+ // #region STARTUP
180
+
181
+ const SERVER_FILE = path.join(CLAUDE_DIR, '.cost', 'server.json');
182
+
183
+ // The CLI reads this to reach the server of its config dir, and cck reads `script` to name the CLI
184
+ // to Kanbot, since under the hub it is not on PATH. A killed server leaves it behind, so readers
185
+ // check the pid.
186
+ function writeServerFile(port) {
187
+ try {
188
+ fs.mkdirSync(path.dirname(SERVER_FILE), { recursive: true });
189
+ fs.writeFileSync(SERVER_FILE, JSON.stringify({ pid: process.pid, port, script: path.join(__dirname, '..', 'server.js') }));
190
+ } catch (err) {
191
+ console.warn('[Startup] cannot write server.json:', err.message);
192
+ }
193
+ }
194
+
195
+ process.on('exit', () => {
196
+ try {
197
+ if (JSON.parse(fs.readFileSync(SERVER_FILE, 'utf8')).pid === process.pid) fs.unlinkSync(SERVER_FILE);
198
+ } catch {}
199
+ });
200
+ for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(0));
201
+
202
+ const onReady = (actualPort) => {
203
+ console.log(`Claude Code Cost Dashboard running at http://localhost:${actualPort}`);
204
+ writeServerFile(actualPort);
205
+ const warning = net.exposureWarning();
206
+ if (warning) console.log(warning);
207
+
208
+ if (process.argv.includes('--open')) {
209
+ import('open').then(mod => mod.default(`http://localhost:${actualPort}`));
210
+ }
211
+ };
212
+
213
+ const server = net.listenLoopback(app, PORT, onReady);
214
+
215
+ server.on('error', (err) => {
216
+ if (err.code === 'EADDRINUSE') {
217
+ console.log(`Port ${PORT} in use, trying random port...`);
218
+ net.listenLoopback(app, 0, onReady);
219
+ } else {
220
+ throw err;
221
+ }
222
+ });
223
+
224
+ // Pre-fetch pricing on startup
225
+ fetchPricing().catch(() => {});
226
+
227
+ // #endregion