tokmon 0.1.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -0
  3. package/dist/cli.js +328 -0
  4. package/package.json +46 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David Ilie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # tokmon
2
+
3
+ Terminal dashboard for Claude Code usage and costs. Refreshes every 2 seconds like `watch`.
4
+
5
+ Built with [Ink](https://github.com/vadimdemedes/ink), TypeScript.
6
+
7
+ ```
8
+ ◉ tokmon · refreshing every 2s
9
+
10
+ ┃ Claude
11
+
12
+ ┃ Today $122.78 179.9M tokens
13
+ ┃ This Week $356.47 535.4M tokens
14
+ ┃ This Month $1293.71 2.1B tokens
15
+
16
+ ┃ Active Block 35m remaining
17
+
18
+ ┃ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━──── 88%
19
+
20
+ ┃ $271.05 spent · ~$306.63 proj · $61.33/hr
21
+
22
+ ──────────────────────────────────────────────────
23
+ Total $1293.71 12:54:49 AM
24
+ ```
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ npm install -g tokmon
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```bash
35
+ tokmon
36
+ ```
37
+
38
+ Press `Ctrl+C` to exit.
39
+
40
+ ## What It Shows
41
+
42
+ - **Today / This Week / This Month** — cost and token totals from Claude Code JSONL logs
43
+ - **Active Block** — current 5-hour window with burn rate, projected cost, and time remaining
44
+ - Auto-refreshes every 2 seconds with mtime-based file caching
45
+
46
+ ## How It Works
47
+
48
+ Reads Claude Code's JSONL session logs directly from `~/.claude/projects/`. Calculates costs using Claude model pricing (Opus, Sonnet, Haiku). Caches file reads by mtime so subsequent refreshes are near-instant.
49
+
50
+ ## Requirements
51
+
52
+ - Node.js 20+
53
+ - [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (generates usage data in `~/.claude/projects/`)
54
+
55
+ ## Tech Stack
56
+
57
+ | Tool | Purpose |
58
+ |------|---------|
59
+ | Ink 5 | React terminal UI |
60
+ | TypeScript 5.7+ | Strict mode |
61
+ | tsup | Build |
62
+
63
+ ## Author
64
+
65
+ By [David Ilie](https://davidilie.com)
66
+
67
+ ## License
68
+
69
+ [MIT](LICENSE)
package/dist/cli.js ADDED
@@ -0,0 +1,328 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.tsx
4
+ import { render } from "ink";
5
+
6
+ // src/app.tsx
7
+ import { useState, useEffect } from "react";
8
+ import { Box, Text } from "ink";
9
+
10
+ // src/data.ts
11
+ import { readdir, stat as fsStat } from "fs/promises";
12
+ import { createReadStream } from "fs";
13
+ import { createInterface } from "readline";
14
+ import { join } from "path";
15
+ import { homedir } from "os";
16
+
17
+ // src/format.ts
18
+ function currency(value) {
19
+ return `$${value.toFixed(2)}`;
20
+ }
21
+ function tokens(value) {
22
+ if (value >= 1e9) return `${(value / 1e9).toFixed(1)}B`;
23
+ if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
24
+ if (value >= 1e3) return `${(value / 1e3).toFixed(1)}K`;
25
+ return String(value);
26
+ }
27
+ function time(date) {
28
+ return date.toLocaleTimeString(void 0, {
29
+ hour: "2-digit",
30
+ minute: "2-digit",
31
+ second: "2-digit"
32
+ });
33
+ }
34
+ function minutes(mins) {
35
+ const h = Math.floor(mins / 60);
36
+ const m = Math.round(mins % 60);
37
+ return h > 0 ? `${h}h ${m}m` : `${m}m`;
38
+ }
39
+
40
+ // src/data.ts
41
+ var PRICING = {
42
+ "claude-opus-4": { i: 5e-6, o: 25e-6, cc: 625e-8, cr: 5e-7 },
43
+ "claude-sonnet-4": { i: 3e-6, o: 15e-6, cc: 375e-8, cr: 3e-7 },
44
+ "claude-haiku-4": { i: 1e-6, o: 5e-6, cc: 125e-8, cr: 1e-7 }
45
+ };
46
+ var FALLBACK = PRICING["claude-opus-4"];
47
+ var fileCache = /* @__PURE__ */ new Map();
48
+ function getClaudeDirs() {
49
+ const home = homedir();
50
+ const dirs = [join(home, ".claude", "projects")];
51
+ if (process.env.XDG_CONFIG_HOME) {
52
+ dirs.push(join(process.env.XDG_CONFIG_HOME, "claude", "projects"));
53
+ } else if (process.platform !== "win32") {
54
+ dirs.push(join(home, ".config", "claude", "projects"));
55
+ }
56
+ if (process.env.APPDATA) {
57
+ dirs.push(join(process.env.APPDATA, "claude", "projects"));
58
+ }
59
+ if (process.env.CLAUDE_CONFIG_DIR) {
60
+ for (const p of process.env.CLAUDE_CONFIG_DIR.split(process.platform === "win32" ? ";" : ",")) {
61
+ dirs.push(join(p.trim(), "projects"));
62
+ }
63
+ }
64
+ return dirs;
65
+ }
66
+ function priceFor(model) {
67
+ for (const [prefix, p] of Object.entries(PRICING)) {
68
+ if (model.startsWith(prefix)) return p;
69
+ }
70
+ return FALLBACK;
71
+ }
72
+ function costOf(model, u) {
73
+ const p = priceFor(model);
74
+ return (u.input_tokens ?? 0) * p.i + (u.output_tokens ?? 0) * p.o + (u.cache_creation_input_tokens ?? 0) * p.cc + (u.cache_read_input_tokens ?? 0) * p.cr;
75
+ }
76
+ async function parseFile(path, since) {
77
+ const entries = [];
78
+ const rl = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
79
+ for await (const line of rl) {
80
+ if (!line.includes('"usage"')) continue;
81
+ try {
82
+ const obj = JSON.parse(line);
83
+ if (obj.type !== "assistant" || !obj.message?.usage) continue;
84
+ const ts = new Date(obj.timestamp ?? 0).getTime();
85
+ if (ts < since) continue;
86
+ const u = obj.message.usage;
87
+ entries.push({
88
+ ts,
89
+ cost: costOf(obj.message.model ?? "", u),
90
+ tokens: (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0)
91
+ });
92
+ } catch {
93
+ }
94
+ }
95
+ return entries;
96
+ }
97
+ async function loadEntries(since) {
98
+ const all = [];
99
+ const seen = /* @__PURE__ */ new Set();
100
+ for (const dir of getClaudeDirs()) {
101
+ let listing;
102
+ try {
103
+ listing = await readdir(dir, { recursive: true });
104
+ } catch {
105
+ continue;
106
+ }
107
+ const files = listing.filter((f) => f.endsWith(".jsonl"));
108
+ await Promise.all(files.map(async (f) => {
109
+ const path = join(dir, f);
110
+ if (seen.has(path)) return;
111
+ seen.add(path);
112
+ try {
113
+ const s = await fsStat(path);
114
+ if (s.mtimeMs < since) return;
115
+ const cached = fileCache.get(path);
116
+ if (cached && cached.mtimeMs === s.mtimeMs) {
117
+ all.push(...cached.data);
118
+ return;
119
+ }
120
+ const data = await parseFile(path, since);
121
+ fileCache.set(path, { mtimeMs: s.mtimeMs, data });
122
+ all.push(...data);
123
+ } catch {
124
+ }
125
+ }));
126
+ }
127
+ return all;
128
+ }
129
+ function sum(entries) {
130
+ let cost = 0, tokens2 = 0;
131
+ for (const e of entries) {
132
+ cost += e.cost;
133
+ tokens2 += e.tokens;
134
+ }
135
+ return { cost, tokens: tokens2 };
136
+ }
137
+ async function fetchUsage() {
138
+ const now = Date.now();
139
+ const d = /* @__PURE__ */ new Date();
140
+ const monthStart = new Date(d.getFullYear(), d.getMonth(), 1).getTime();
141
+ const todayStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
142
+ const weekDay = d.getDay();
143
+ const weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate() - (weekDay === 0 ? 6 : weekDay - 1)).getTime();
144
+ const entries = await loadEntries(monthStart);
145
+ const fiveHoursAgo = now - 5 * 36e5;
146
+ const blockEntries = entries.filter((e) => e.ts >= fiveHoursAgo);
147
+ let block = null;
148
+ if (blockEntries.length > 0) {
149
+ const spent = blockEntries.reduce((s, e) => s + e.cost, 0);
150
+ const oldest = Math.min(...blockEntries.map((e) => e.ts));
151
+ const elapsedHrs = (now - oldest) / 36e5;
152
+ const burnRate = elapsedHrs > 0 ? spent / elapsedHrs : 0;
153
+ const remainMs = Math.max(0, oldest + 5 * 36e5 - now);
154
+ const percent = Math.min(100, (now - oldest) / (5 * 36e5) * 100);
155
+ block = { spent, projected: burnRate * 5, burnRate, percent, remaining: minutes(remainMs / 6e4) };
156
+ }
157
+ return {
158
+ today: sum(entries.filter((e) => e.ts >= todayStart)),
159
+ week: sum(entries.filter((e) => e.ts >= weekStart)),
160
+ month: sum(entries),
161
+ block
162
+ };
163
+ }
164
+
165
+ // src/app.tsx
166
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
167
+ var INTERVAL = 2e3;
168
+ function App() {
169
+ const [data, setData] = useState(null);
170
+ const [error, setError] = useState(null);
171
+ const [updated, setUpdated] = useState(/* @__PURE__ */ new Date());
172
+ useEffect(() => {
173
+ let active = true;
174
+ const load = async () => {
175
+ try {
176
+ const result = await fetchUsage();
177
+ if (active) {
178
+ setData(result);
179
+ setError(null);
180
+ setUpdated(/* @__PURE__ */ new Date());
181
+ }
182
+ } catch (e) {
183
+ if (active) setError(e instanceof Error ? e.message : String(e));
184
+ }
185
+ };
186
+ load();
187
+ const id = setInterval(load, INTERVAL);
188
+ return () => {
189
+ active = false;
190
+ clearInterval(id);
191
+ };
192
+ }, []);
193
+ if (error) return /* @__PURE__ */ jsx(Box, { padding: 1, children: /* @__PURE__ */ jsx(Text, { color: "red", children: error }) });
194
+ if (!data) return /* @__PURE__ */ jsx(Box, { padding: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Loading..." }) });
195
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 2, paddingY: 1, children: [
196
+ /* @__PURE__ */ jsx(Header, {}),
197
+ /* @__PURE__ */ jsx(Box, { height: 1 }),
198
+ /* @__PURE__ */ jsx(UsageSection, { color: "green", title: "Claude", data }),
199
+ data.block && /* @__PURE__ */ jsxs(Fragment, { children: [
200
+ /* @__PURE__ */ jsx(Box, { height: 1 }),
201
+ /* @__PURE__ */ jsx(BlockSection, { block: data.block })
202
+ ] }),
203
+ /* @__PURE__ */ jsx(Box, { height: 1 }),
204
+ /* @__PURE__ */ jsx(Divider, {}),
205
+ /* @__PURE__ */ jsx(Footer, { cost: data.month.cost, updated })
206
+ ] });
207
+ }
208
+ function Header() {
209
+ return /* @__PURE__ */ jsxs(Box, { children: [
210
+ /* @__PURE__ */ jsxs(Text, { bold: true, color: "greenBright", children: [
211
+ "\u25C9",
212
+ " tokmon"
213
+ ] }),
214
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
215
+ " \xB7 refreshing every ",
216
+ INTERVAL / 1e3,
217
+ "s"
218
+ ] })
219
+ ] });
220
+ }
221
+ function UsageSection({ color, title, data }) {
222
+ return /* @__PURE__ */ jsxs(
223
+ Box,
224
+ {
225
+ flexDirection: "column",
226
+ paddingLeft: 1,
227
+ borderStyle: "bold",
228
+ borderColor: color,
229
+ borderRight: false,
230
+ borderTop: false,
231
+ borderBottom: false,
232
+ children: [
233
+ /* @__PURE__ */ jsx(Text, { bold: true, children: title }),
234
+ /* @__PURE__ */ jsx(Box, { height: 1 }),
235
+ /* @__PURE__ */ jsx(Row, { label: "Today", summary: data.today }),
236
+ /* @__PURE__ */ jsx(Row, { label: "This Week", summary: data.week }),
237
+ /* @__PURE__ */ jsx(Row, { label: "This Month", summary: data.month })
238
+ ]
239
+ }
240
+ );
241
+ }
242
+ function BlockSection({ block }) {
243
+ return /* @__PURE__ */ jsxs(
244
+ Box,
245
+ {
246
+ flexDirection: "column",
247
+ paddingLeft: 1,
248
+ borderStyle: "bold",
249
+ borderColor: "yellow",
250
+ borderRight: false,
251
+ borderTop: false,
252
+ borderBottom: false,
253
+ children: [
254
+ /* @__PURE__ */ jsxs(Box, { children: [
255
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Active Block" }),
256
+ /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
257
+ " ",
258
+ block.remaining,
259
+ " remaining"
260
+ ] })
261
+ ] }),
262
+ /* @__PURE__ */ jsx(Box, { height: 1 }),
263
+ /* @__PURE__ */ jsxs(Box, { children: [
264
+ /* @__PURE__ */ jsx(Bar, { percent: block.percent, width: 36 }),
265
+ /* @__PURE__ */ jsx(Text, { children: " " }),
266
+ /* @__PURE__ */ jsxs(Text, { bold: true, children: [
267
+ Math.round(block.percent),
268
+ "%"
269
+ ] })
270
+ ] }),
271
+ /* @__PURE__ */ jsxs(Box, { marginTop: 1, children: [
272
+ /* @__PURE__ */ jsx(Text, { color: "yellow", children: currency(block.spent) }),
273
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: " spent" }),
274
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: " \xB7 " }),
275
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "~" }),
276
+ /* @__PURE__ */ jsx(Text, { children: currency(block.projected) }),
277
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: " proj" }),
278
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: " \xB7 " }),
279
+ /* @__PURE__ */ jsx(Text, { color: "red", children: currency(block.burnRate) }),
280
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "/hr" })
281
+ ] })
282
+ ]
283
+ }
284
+ );
285
+ }
286
+ function Row({ label, summary }) {
287
+ return /* @__PURE__ */ jsxs(Box, { children: [
288
+ /* @__PURE__ */ jsx(Box, { width: 14, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: label }) }),
289
+ /* @__PURE__ */ jsx(Box, { width: 12, justifyContent: "flex-end", children: /* @__PURE__ */ jsx(Text, { bold: true, color: "yellow", children: currency(summary.cost) }) }),
290
+ /* @__PURE__ */ jsx(Box, { width: 18, justifyContent: "flex-end", children: /* @__PURE__ */ jsxs(Text, { dimColor: true, children: [
291
+ tokens(summary.tokens),
292
+ " tokens"
293
+ ] }) })
294
+ ] });
295
+ }
296
+ function Bar({ percent, width = 36 }) {
297
+ const filled = Math.round(percent / 100 * width);
298
+ return /* @__PURE__ */ jsxs(Text, { children: [
299
+ /* @__PURE__ */ jsx(Text, { color: "greenBright", children: "\u2501".repeat(filled) }),
300
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\u2500".repeat(width - filled) })
301
+ ] });
302
+ }
303
+ function Divider() {
304
+ return /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\u2500".repeat(50) });
305
+ }
306
+ function Footer({ cost, updated }) {
307
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
308
+ /* @__PURE__ */ jsxs(Box, { justifyContent: "space-between", width: 50, children: [
309
+ /* @__PURE__ */ jsxs(Box, { children: [
310
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Total " }),
311
+ /* @__PURE__ */ jsx(Text, { bold: true, color: "yellowBright", children: currency(cost) })
312
+ ] }),
313
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: time(updated) })
314
+ ] }),
315
+ /* @__PURE__ */ jsxs(Box, { marginTop: 1, children: [
316
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "by " }),
317
+ /* @__PURE__ */ jsx(Text, { children: "David Ilie" }),
318
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: " (" }),
319
+ /* @__PURE__ */ jsx(Text, { color: "cyan", children: "davidilie.com" }),
320
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: ")" })
321
+ ] })
322
+ ] });
323
+ }
324
+
325
+ // src/cli.tsx
326
+ import { jsx as jsx2 } from "react/jsx-runtime";
327
+ var { waitUntilExit } = render(/* @__PURE__ */ jsx2(App, {}));
328
+ await waitUntilExit();
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "tokmon",
3
+ "version": "0.1.0",
4
+ "description": "Terminal dashboard for Claude Code usage and costs",
5
+ "type": "module",
6
+ "bin": {
7
+ "tokmon": "dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "build": "tsup",
14
+ "dev": "tsx src/cli.tsx"
15
+ },
16
+ "dependencies": {
17
+ "ink": "^5.0.0",
18
+ "react": "^18.0.0"
19
+ },
20
+ "devDependencies": {
21
+ "@types/react": "^18.0.0",
22
+ "tsup": "^8.0.0",
23
+ "tsx": "^4.0.0",
24
+ "typescript": "^5.7.0"
25
+ },
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "author": "David Ilie <david@davidilie.com> (https://davidilie.com)",
30
+ "homepage": "https://github.com/DavidIlie/tokmon",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/DavidIlie/tokmon.git"
34
+ },
35
+ "keywords": [
36
+ "claude",
37
+ "claude-code",
38
+ "usage",
39
+ "tokens",
40
+ "cost",
41
+ "terminal",
42
+ "dashboard",
43
+ "cli"
44
+ ],
45
+ "license": "MIT"
46
+ }