tokens-metric 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.
- package/LICENSE +21 -0
- package/README.md +93 -0
- package/dist/core/detect.js +129 -0
- package/dist/core/format.js +48 -0
- package/dist/core/parser.js +141 -0
- package/dist/core/tailer.js +82 -0
- package/dist/core/types.js +20 -0
- package/dist/statusline/index.js +61 -0
- package/dist/tui/bars.js +41 -0
- package/dist/tui/index.js +158 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Annibal48
|
|
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,93 @@
|
|
|
1
|
+
# tokens-metric
|
|
2
|
+
|
|
3
|
+
Real-time token usage meter for [Claude Code](https://claude.com/claude-code) โ a terminal UI plus a one-line statusline you can wire into Claude Code itself.
|
|
4
|
+
|
|
5
|
+
It tails the transcripts Claude Code writes under `~/.claude/projects/**/*.jsonl`, aggregates the `usage` field of each message in-memory, and renders it live. No API calls, no telemetry.
|
|
6
|
+
|
|
7
|
+
## What it shows
|
|
8
|
+
|
|
9
|
+
- **Active session**: model, message count, time since last event, total tokens, equivalent API cost, tokens-per-minute rate, and an activity sparkline.
|
|
10
|
+
- **Breakdown**: input / output / cache-write / cache-read tokens with proportional bars, plus per-model totals.
|
|
11
|
+
- **Plan detection** (best-effort, local-only): API key vs. OAuth subscription, and a hint between Free, Pro/Max, or Team/Enterprise, inferred from flags in `~/.claude.json`.
|
|
12
|
+
- **Recent transcripts**: last five sessions across all your projects.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install -g tokens-metric
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Or run without installing:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npx tokens-metric
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Requires Node 18+ and an existing Claude Code installation.
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
### TUI
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
tokens-metric
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Press `q` (or `Esc`, or `Ctrl-C`) to quit.
|
|
37
|
+
|
|
38
|
+
### Statusline inside Claude Code
|
|
39
|
+
|
|
40
|
+
Add to `~/.claude/settings.json`:
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{
|
|
44
|
+
"statusLine": {
|
|
45
|
+
"type": "command",
|
|
46
|
+
"command": "tokens-metric-statusline"
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Output looks like:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
๐ข team opus-4-7 โ in 117 ยท out 43.5k ยท cache 3.21M โ ฮฃ 3.25M ยท ~$12.29 API-eq
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Honest limitations
|
|
58
|
+
|
|
59
|
+
1. **Plan tier is heuristic.** We read flags Claude Code writes locally (e.g. `opusProMigrationComplete`, `cachedExtraUsageDisabledReason`). Anthropic can rename these at any release; if they change, the detector falls back to `unknown` instead of breaking.
|
|
60
|
+
2. **Pro vs. Max are not distinguishable locally.** Both look identical from the config file.
|
|
61
|
+
3. **The USD figure is API-equivalent pricing, not what you actually pay.** On Pro/Max/Team you pay a flat subscription โ the dollar number is purely a reference for what the same tokens would cost on the API.
|
|
62
|
+
4. **Prices are hardcoded.** See `src/core/format.ts`. If Anthropic updates pricing, the numbers drift until you bump the package.
|
|
63
|
+
5. **The transcript format is not a public API.** It works today; it may shift. The parser is intentionally tolerant of unexpected shapes.
|
|
64
|
+
|
|
65
|
+
## How it works
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
~/.claude/projects/<encoded-cwd>/<session-id>.jsonl
|
|
69
|
+
โ
|
|
70
|
+
โผ
|
|
71
|
+
src/core/parser.ts reads + aggregates usage per message
|
|
72
|
+
src/core/tailer.ts watches the active file with fs.watch
|
|
73
|
+
src/core/detect.ts reads ~/.claude.json for auth + plan hints
|
|
74
|
+
โ
|
|
75
|
+
โโโโโโโโโโดโโโโโโโโโ
|
|
76
|
+
โผ โผ
|
|
77
|
+
src/tui (Ink) src/statusline
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Development
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
git clone https://github.com/Annibal48/Tokens-Metric.git
|
|
84
|
+
cd Tokens-Metric
|
|
85
|
+
npm install
|
|
86
|
+
npm run dev:tui # hot-runs the TUI from sources
|
|
87
|
+
npm run dev:statusline # prints one line
|
|
88
|
+
npm run build # builds dist/
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
MIT โ see [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
export function claudeHome() {
|
|
6
|
+
return join(homedir(), '.claude');
|
|
7
|
+
}
|
|
8
|
+
export function claudeConfigPath() {
|
|
9
|
+
return join(homedir(), '.claude.json');
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Detect whether Claude Code is installed, the user is logged in, and best-
|
|
13
|
+
* effort what plan they're on. All signals are LOCAL and BEST-EFFORT โ we
|
|
14
|
+
* never claim authority over a plan tier Anthropic hasn't told us about.
|
|
15
|
+
*/
|
|
16
|
+
export function detectAuth() {
|
|
17
|
+
const binPath = whichClaude();
|
|
18
|
+
const installed = Boolean(binPath) || existsSync(claudeHome()) || existsSync(claudeConfigPath());
|
|
19
|
+
// 1. API key takes precedence over OAuth (Claude Code itself prefers it).
|
|
20
|
+
if (process.env.ANTHROPIC_API_KEY) {
|
|
21
|
+
return {
|
|
22
|
+
installed,
|
|
23
|
+
binPath,
|
|
24
|
+
loggedIn: true,
|
|
25
|
+
authMethod: 'api-key',
|
|
26
|
+
planHint: 'api',
|
|
27
|
+
hint: 'ANTHROPIC_API_KEY is set โ pay-per-token API billing.',
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
// 2. OAuth / subscription: ~/.claude.json holds a `userID` once logged in.
|
|
31
|
+
// The actual access token lives elsewhere (Keychain on macOS), but we
|
|
32
|
+
// don't need it โ userID is sufficient proof of login.
|
|
33
|
+
const cfg = readClaudeConfig();
|
|
34
|
+
const userId = typeof cfg?.userID === 'string' ? cfg.userID : '';
|
|
35
|
+
if (userId) {
|
|
36
|
+
const planHint = inferPlanHint(cfg);
|
|
37
|
+
return {
|
|
38
|
+
installed,
|
|
39
|
+
binPath,
|
|
40
|
+
loggedIn: true,
|
|
41
|
+
authMethod: 'oauth-subscription',
|
|
42
|
+
planHint,
|
|
43
|
+
userIdShort: userId.slice(0, 8),
|
|
44
|
+
hint: planHintExplanation(planHint, cfg),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// 3. Installed but not logged in.
|
|
48
|
+
if (installed) {
|
|
49
|
+
return {
|
|
50
|
+
installed,
|
|
51
|
+
binPath,
|
|
52
|
+
loggedIn: false,
|
|
53
|
+
authMethod: 'none',
|
|
54
|
+
planHint: 'unknown',
|
|
55
|
+
hint: 'Claude Code is installed but no userID was found in ~/.claude.json. Run `claude` to log in.',
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
installed: false,
|
|
60
|
+
loggedIn: false,
|
|
61
|
+
authMethod: 'none',
|
|
62
|
+
planHint: 'unknown',
|
|
63
|
+
hint: 'Claude Code does not appear to be installed.',
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function whichClaude() {
|
|
67
|
+
try {
|
|
68
|
+
return execSync('command -v claude', { stdio: ['ignore', 'pipe', 'ignore'] })
|
|
69
|
+
.toString()
|
|
70
|
+
.trim() || undefined;
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function readClaudeConfig() {
|
|
77
|
+
const p = claudeConfigPath();
|
|
78
|
+
if (!existsSync(p))
|
|
79
|
+
return null;
|
|
80
|
+
try {
|
|
81
|
+
// The file is ~22KB and JSON โ parse it once.
|
|
82
|
+
return JSON.parse(readFileSync(p, 'utf8'));
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Heuristic plan inference. These signals come from `~/.claude.json` flags
|
|
90
|
+
* that Claude Code itself writes after migrations/feature gates run. They
|
|
91
|
+
* are correlational, not authoritative โ Anthropic could change them at any
|
|
92
|
+
* release.
|
|
93
|
+
*
|
|
94
|
+
* - `opusProMigrationComplete: true` is set for accounts that have been
|
|
95
|
+
* migrated to the Opus-on-Pro rollout โ strong signal of a paid plan
|
|
96
|
+
* (Pro / Max / Team / Enterprise).
|
|
97
|
+
* - `cachedExtraUsageDisabledReason: "org_level_disabled"` is set on
|
|
98
|
+
* Team/Enterprise accounts whose org admin has disabled extra usage. It's
|
|
99
|
+
* a strong hint of an org-managed seat.
|
|
100
|
+
*/
|
|
101
|
+
function inferPlanHint(cfg) {
|
|
102
|
+
if (!cfg)
|
|
103
|
+
return 'unknown';
|
|
104
|
+
if (cfg.cachedExtraUsageDisabledReason === 'org_level_disabled') {
|
|
105
|
+
return 'team-or-enterprise';
|
|
106
|
+
}
|
|
107
|
+
if (cfg.opusProMigrationComplete === true)
|
|
108
|
+
return 'paid';
|
|
109
|
+
// Logged in but no Opus-Pro migration flag โ most likely Free, but not
|
|
110
|
+
// guaranteed (could be a fresh paid account before migration).
|
|
111
|
+
return 'free';
|
|
112
|
+
}
|
|
113
|
+
function planHintExplanation(plan, cfg) {
|
|
114
|
+
switch (plan) {
|
|
115
|
+
case 'team-or-enterprise':
|
|
116
|
+
return 'Org-managed seat detected (cachedExtraUsageDisabledReason=org_level_disabled). Likely Team or Enterprise.';
|
|
117
|
+
case 'paid':
|
|
118
|
+
return 'Paid plan likely (Opus-on-Pro migration flag is set). Pro/Max not distinguishable locally.';
|
|
119
|
+
case 'free':
|
|
120
|
+
return cfg
|
|
121
|
+
? 'Logged in, but no paid-plan migration flag found. Likely Free (or very recently upgraded).'
|
|
122
|
+
: 'Logged in.';
|
|
123
|
+
case 'api':
|
|
124
|
+
return 'API key billing.';
|
|
125
|
+
case 'unknown':
|
|
126
|
+
default:
|
|
127
|
+
return 'Plan tier not determinable from local signals.';
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export function fmtNumber(n) {
|
|
2
|
+
if (n < 1000)
|
|
3
|
+
return `${n}`;
|
|
4
|
+
if (n < 1_000_000)
|
|
5
|
+
return `${(n / 1000).toFixed(1)}k`;
|
|
6
|
+
return `${(n / 1_000_000).toFixed(2)}M`;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Reference-only USD cost using public Anthropic API pricing. NOT a real bill
|
|
10
|
+
* when the user is on a Pro/Max subscription. Numbers here are conservative
|
|
11
|
+
* defaults โ keep them updateable.
|
|
12
|
+
*/
|
|
13
|
+
const PRICES_PER_MTOK = {
|
|
14
|
+
// Claude Sonnet 4.x family
|
|
15
|
+
'claude-sonnet-4': { in: 3, out: 15, cacheWrite: 3.75, cacheRead: 0.3 },
|
|
16
|
+
// Opus 4.x family
|
|
17
|
+
'claude-opus-4': { in: 15, out: 75, cacheWrite: 18.75, cacheRead: 1.5 },
|
|
18
|
+
// Haiku 4.x family
|
|
19
|
+
'claude-haiku-4': { in: 0.8, out: 4, cacheWrite: 1, cacheRead: 0.08 },
|
|
20
|
+
};
|
|
21
|
+
function priceKey(model) {
|
|
22
|
+
const m = model.toLowerCase();
|
|
23
|
+
if (m.includes('opus'))
|
|
24
|
+
return 'claude-opus-4';
|
|
25
|
+
if (m.includes('haiku'))
|
|
26
|
+
return 'claude-haiku-4';
|
|
27
|
+
if (m.includes('sonnet'))
|
|
28
|
+
return 'claude-sonnet-4';
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
export function estimateCostUSD(model, u) {
|
|
32
|
+
const key = priceKey(model);
|
|
33
|
+
if (!key)
|
|
34
|
+
return null;
|
|
35
|
+
const p = PRICES_PER_MTOK[key];
|
|
36
|
+
const perTok = 1 / 1_000_000;
|
|
37
|
+
return (u.input_tokens * p.in * perTok +
|
|
38
|
+
u.output_tokens * p.out * perTok +
|
|
39
|
+
u.cache_creation_input_tokens * p.cacheWrite * perTok +
|
|
40
|
+
u.cache_read_input_tokens * p.cacheRead * perTok);
|
|
41
|
+
}
|
|
42
|
+
export function fmtUSD(n) {
|
|
43
|
+
if (n < 0.01)
|
|
44
|
+
return `$${n.toFixed(4)}`;
|
|
45
|
+
if (n < 1)
|
|
46
|
+
return `$${n.toFixed(3)}`;
|
|
47
|
+
return `$${n.toFixed(2)}`;
|
|
48
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { readdirSync, statSync, createReadStream, existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { claudeHome } from './detect.js';
|
|
5
|
+
import { addUsage, EMPTY_USAGE, } from './types.js';
|
|
6
|
+
const PROJECTS_DIR = () => join(claudeHome(), 'projects');
|
|
7
|
+
/**
|
|
8
|
+
* Walk ~/.claude/projects/<encoded-cwd>/*.jsonl and return all transcript
|
|
9
|
+
* files sorted by mtime descending (most recent first).
|
|
10
|
+
*/
|
|
11
|
+
export function listTranscripts() {
|
|
12
|
+
const root = PROJECTS_DIR();
|
|
13
|
+
if (!existsSync(root))
|
|
14
|
+
return [];
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const projectDir of safeReaddir(root)) {
|
|
17
|
+
const full = join(root, projectDir);
|
|
18
|
+
let stat;
|
|
19
|
+
try {
|
|
20
|
+
stat = statSync(full);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (!stat.isDirectory())
|
|
26
|
+
continue;
|
|
27
|
+
for (const f of safeReaddir(full)) {
|
|
28
|
+
if (!f.endsWith('.jsonl'))
|
|
29
|
+
continue;
|
|
30
|
+
const p = join(full, f);
|
|
31
|
+
try {
|
|
32
|
+
const s = statSync(p);
|
|
33
|
+
out.push({ path: p, mtimeMs: s.mtimeMs, cwd: decodeCwd(projectDir) });
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
// ignore
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return out.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
41
|
+
}
|
|
42
|
+
function safeReaddir(p) {
|
|
43
|
+
try {
|
|
44
|
+
return readdirSync(p);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Claude Code encodes the cwd by replacing path separators with `-`.
|
|
52
|
+
* We can't perfectly recover the original, but we can give a best-effort
|
|
53
|
+
* human-readable hint.
|
|
54
|
+
*/
|
|
55
|
+
function decodeCwd(encoded) {
|
|
56
|
+
return encoded.replace(/^-/, '/').replace(/-/g, '/');
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Pick the most recently active transcript within `withinMs` (default 5 min).
|
|
60
|
+
*/
|
|
61
|
+
export function findActiveTranscript(withinMs = 5 * 60_000) {
|
|
62
|
+
const list = listTranscripts();
|
|
63
|
+
if (list.length === 0)
|
|
64
|
+
return null;
|
|
65
|
+
const top = list[0];
|
|
66
|
+
if (Date.now() - top.mtimeMs > withinMs) {
|
|
67
|
+
// Still return it as "last known", but caller can decide.
|
|
68
|
+
return { path: top.path, cwd: top.cwd };
|
|
69
|
+
}
|
|
70
|
+
return { path: top.path, cwd: top.cwd };
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Read a JSONL transcript fully and aggregate usage stats.
|
|
74
|
+
*/
|
|
75
|
+
export async function aggregateTranscript(path) {
|
|
76
|
+
const stats = {
|
|
77
|
+
sessionId: deriveSessionId(path),
|
|
78
|
+
transcriptPath: path,
|
|
79
|
+
totals: EMPTY_USAGE(),
|
|
80
|
+
byModel: {},
|
|
81
|
+
messageCount: 0,
|
|
82
|
+
};
|
|
83
|
+
const stream = createReadStream(path, { encoding: 'utf8' });
|
|
84
|
+
const rl = createInterface({ input: stream, crlfDelay: Infinity });
|
|
85
|
+
for await (const line of rl) {
|
|
86
|
+
if (!line.trim())
|
|
87
|
+
continue;
|
|
88
|
+
applyLine(stats, line);
|
|
89
|
+
}
|
|
90
|
+
return stats;
|
|
91
|
+
}
|
|
92
|
+
export function deriveSessionId(path) {
|
|
93
|
+
const base = path.split('/').pop() ?? path;
|
|
94
|
+
return base.replace(/\.jsonl$/, '');
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Apply a single JSONL line to a running stats object. Tolerant to
|
|
98
|
+
* unexpected shapes โ Claude Code's transcript format evolves.
|
|
99
|
+
*/
|
|
100
|
+
export function applyLine(stats, line) {
|
|
101
|
+
let evt;
|
|
102
|
+
try {
|
|
103
|
+
evt = JSON.parse(line);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (typeof evt?.cwd === 'string' && !stats.cwd)
|
|
109
|
+
stats.cwd = evt.cwd;
|
|
110
|
+
const ts = parseTimestamp(evt?.timestamp);
|
|
111
|
+
if (ts) {
|
|
112
|
+
stats.startedAt = stats.startedAt ? Math.min(stats.startedAt, ts) : ts;
|
|
113
|
+
stats.lastEventAt = stats.lastEventAt ? Math.max(stats.lastEventAt, ts) : ts;
|
|
114
|
+
}
|
|
115
|
+
const message = evt?.message;
|
|
116
|
+
if (!message || typeof message !== 'object')
|
|
117
|
+
return;
|
|
118
|
+
const usage = message.usage;
|
|
119
|
+
if (!usage)
|
|
120
|
+
return;
|
|
121
|
+
const u = {
|
|
122
|
+
input_tokens: numberOr0(usage.input_tokens),
|
|
123
|
+
output_tokens: numberOr0(usage.output_tokens),
|
|
124
|
+
cache_creation_input_tokens: numberOr0(usage.cache_creation_input_tokens),
|
|
125
|
+
cache_read_input_tokens: numberOr0(usage.cache_read_input_tokens),
|
|
126
|
+
};
|
|
127
|
+
const model = typeof message.model === 'string' ? message.model : 'unknown';
|
|
128
|
+
stats.lastModel = model;
|
|
129
|
+
stats.totals = addUsage(stats.totals, u);
|
|
130
|
+
stats.byModel[model] = addUsage(stats.byModel[model] ?? EMPTY_USAGE(), u);
|
|
131
|
+
stats.messageCount += 1;
|
|
132
|
+
}
|
|
133
|
+
function numberOr0(v) {
|
|
134
|
+
return typeof v === 'number' && Number.isFinite(v) ? v : 0;
|
|
135
|
+
}
|
|
136
|
+
function parseTimestamp(v) {
|
|
137
|
+
if (typeof v !== 'string')
|
|
138
|
+
return undefined;
|
|
139
|
+
const n = Date.parse(v);
|
|
140
|
+
return Number.isFinite(n) ? n : undefined;
|
|
141
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { open, watch } from 'node:fs/promises';
|
|
2
|
+
import { statSync } from 'node:fs';
|
|
3
|
+
import { applyLine } from './parser.js';
|
|
4
|
+
import { EMPTY_USAGE } from './types.js';
|
|
5
|
+
import { deriveSessionId } from './parser.js';
|
|
6
|
+
/**
|
|
7
|
+
* Open a JSONL transcript, read everything currently in it, then watch for
|
|
8
|
+
* appended lines. Calls onUpdate whenever the stats change.
|
|
9
|
+
*/
|
|
10
|
+
export async function tailTranscript(path) {
|
|
11
|
+
const stats = {
|
|
12
|
+
sessionId: deriveSessionId(path),
|
|
13
|
+
transcriptPath: path,
|
|
14
|
+
totals: EMPTY_USAGE(),
|
|
15
|
+
byModel: {},
|
|
16
|
+
messageCount: 0,
|
|
17
|
+
};
|
|
18
|
+
const listeners = [];
|
|
19
|
+
const notify = () => listeners.forEach((l) => l(stats));
|
|
20
|
+
let fh = await open(path, 'r');
|
|
21
|
+
let offset = 0;
|
|
22
|
+
let buf = '';
|
|
23
|
+
let stopped = false;
|
|
24
|
+
async function drain() {
|
|
25
|
+
const size = statSync(path).size;
|
|
26
|
+
if (size < offset) {
|
|
27
|
+
// File was truncated/rotated โ reopen.
|
|
28
|
+
await fh.close();
|
|
29
|
+
fh = await open(path, 'r');
|
|
30
|
+
offset = 0;
|
|
31
|
+
buf = '';
|
|
32
|
+
}
|
|
33
|
+
if (size === offset)
|
|
34
|
+
return;
|
|
35
|
+
const length = size - offset;
|
|
36
|
+
const chunk = Buffer.alloc(length);
|
|
37
|
+
const { bytesRead } = await fh.read(chunk, 0, length, offset);
|
|
38
|
+
offset += bytesRead;
|
|
39
|
+
buf += chunk.subarray(0, bytesRead).toString('utf8');
|
|
40
|
+
let nl;
|
|
41
|
+
let changed = false;
|
|
42
|
+
while ((nl = buf.indexOf('\n')) !== -1) {
|
|
43
|
+
const line = buf.slice(0, nl);
|
|
44
|
+
buf = buf.slice(nl + 1);
|
|
45
|
+
if (line.trim()) {
|
|
46
|
+
applyLine(stats, line);
|
|
47
|
+
changed = true;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (changed)
|
|
51
|
+
notify();
|
|
52
|
+
}
|
|
53
|
+
await drain();
|
|
54
|
+
notify();
|
|
55
|
+
// Native watcher. fs.watch on macOS uses FSEvents and may coalesce; that's
|
|
56
|
+
// fine for our use case โ we re-stat on each tick.
|
|
57
|
+
const ac = new AbortController();
|
|
58
|
+
(async () => {
|
|
59
|
+
try {
|
|
60
|
+
const watcher = watch(path, { signal: ac.signal });
|
|
61
|
+
for await (const _ of watcher) {
|
|
62
|
+
if (stopped)
|
|
63
|
+
break;
|
|
64
|
+
await drain().catch(() => undefined);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// aborted or file gone
|
|
69
|
+
}
|
|
70
|
+
})();
|
|
71
|
+
return {
|
|
72
|
+
stats,
|
|
73
|
+
onUpdate(cb) {
|
|
74
|
+
listeners.push(cb);
|
|
75
|
+
},
|
|
76
|
+
async stop() {
|
|
77
|
+
stopped = true;
|
|
78
|
+
ac.abort();
|
|
79
|
+
await fh.close().catch(() => undefined);
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export const EMPTY_USAGE = () => ({
|
|
2
|
+
input_tokens: 0,
|
|
3
|
+
output_tokens: 0,
|
|
4
|
+
cache_creation_input_tokens: 0,
|
|
5
|
+
cache_read_input_tokens: 0,
|
|
6
|
+
});
|
|
7
|
+
export function addUsage(a, b) {
|
|
8
|
+
return {
|
|
9
|
+
input_tokens: a.input_tokens + (b.input_tokens ?? 0),
|
|
10
|
+
output_tokens: a.output_tokens + (b.output_tokens ?? 0),
|
|
11
|
+
cache_creation_input_tokens: a.cache_creation_input_tokens + (b.cache_creation_input_tokens ?? 0),
|
|
12
|
+
cache_read_input_tokens: a.cache_read_input_tokens + (b.cache_read_input_tokens ?? 0),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export function totalTokens(u) {
|
|
16
|
+
return (u.input_tokens +
|
|
17
|
+
u.output_tokens +
|
|
18
|
+
u.cache_creation_input_tokens +
|
|
19
|
+
u.cache_read_input_tokens);
|
|
20
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { aggregateTranscript, findActiveTranscript } from '../core/parser.js';
|
|
3
|
+
import { detectAuth } from '../core/detect.js';
|
|
4
|
+
import { estimateCostUSD, fmtNumber, fmtUSD } from '../core/format.js';
|
|
5
|
+
import { totalTokens } from '../core/types.js';
|
|
6
|
+
/**
|
|
7
|
+
* One-shot status line. Reads whatever JSONL is currently the most recent
|
|
8
|
+
* transcript, aggregates it, and prints a single line. Exits 0 always so
|
|
9
|
+
* Claude Code's statusLine doesn't blank out on errors.
|
|
10
|
+
*/
|
|
11
|
+
async function main() {
|
|
12
|
+
try {
|
|
13
|
+
const active = findActiveTranscript();
|
|
14
|
+
const auth = detectAuth();
|
|
15
|
+
if (!active) {
|
|
16
|
+
process.stdout.write(authBadge(auth) + ' ยท no active session');
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const s = await aggregateTranscript(active.path);
|
|
20
|
+
const model = s.lastModel ?? 'unknown';
|
|
21
|
+
const tot = totalTokens(s.totals);
|
|
22
|
+
const cost = estimateCostUSD(model, s.totals);
|
|
23
|
+
const costStr = cost !== null ? ` ยท ~${fmtUSD(cost)} API-eq` : '';
|
|
24
|
+
const line = `${authBadge(auth)} ` +
|
|
25
|
+
`${shortModel(model)} โ ` +
|
|
26
|
+
`in ${fmtNumber(s.totals.input_tokens)} ยท ` +
|
|
27
|
+
`out ${fmtNumber(s.totals.output_tokens)} ยท ` +
|
|
28
|
+
`cache ${fmtNumber(s.totals.cache_read_input_tokens + s.totals.cache_creation_input_tokens)} ` +
|
|
29
|
+
`โ ฮฃ ${fmtNumber(tot)}` +
|
|
30
|
+
costStr;
|
|
31
|
+
process.stdout.write(line);
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
process.stdout.write('tokens-metric ยท err');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function shortModel(m) {
|
|
38
|
+
return m
|
|
39
|
+
.replace(/^claude-/, '')
|
|
40
|
+
.replace(/-20\d{6}/, '')
|
|
41
|
+
.replace(/-\d{8}$/, '');
|
|
42
|
+
}
|
|
43
|
+
function authBadge(a) {
|
|
44
|
+
if (!a.installed)
|
|
45
|
+
return 'โ no-cc';
|
|
46
|
+
if (!a.loggedIn)
|
|
47
|
+
return '๐ logged-out';
|
|
48
|
+
switch (a.planHint) {
|
|
49
|
+
case 'api':
|
|
50
|
+
return '๐ api';
|
|
51
|
+
case 'team-or-enterprise':
|
|
52
|
+
return '๐ข team';
|
|
53
|
+
case 'paid':
|
|
54
|
+
return '๐ paid';
|
|
55
|
+
case 'free':
|
|
56
|
+
return '๐ free';
|
|
57
|
+
default:
|
|
58
|
+
return '๐ง sub';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
main();
|
package/dist/tui/bars.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny visual helpers โ no dependencies, just unicode block characters.
|
|
3
|
+
*/
|
|
4
|
+
const BAR_BLOCKS = ['', 'โ', 'โ', 'โ', 'โ', 'โ', 'โ', 'โ', 'โ'];
|
|
5
|
+
/**
|
|
6
|
+
* Render a horizontal bar of `width` cells filled to `ratio` (0..1) using
|
|
7
|
+
* partial-block characters for sub-cell precision.
|
|
8
|
+
*/
|
|
9
|
+
export function bar(ratio, width) {
|
|
10
|
+
if (!Number.isFinite(ratio) || ratio < 0)
|
|
11
|
+
ratio = 0;
|
|
12
|
+
if (ratio > 1)
|
|
13
|
+
ratio = 1;
|
|
14
|
+
const total = ratio * width;
|
|
15
|
+
const full = Math.floor(total);
|
|
16
|
+
const remainder = total - full;
|
|
17
|
+
const partialIdx = Math.round(remainder * 8);
|
|
18
|
+
const partial = partialIdx > 0 ? BAR_BLOCKS[partialIdx] : '';
|
|
19
|
+
const empty = Math.max(0, width - full - (partial ? 1 : 0));
|
|
20
|
+
return 'โ'.repeat(full) + partial + ' '.repeat(empty);
|
|
21
|
+
}
|
|
22
|
+
const SPARK = ['โ', 'โ', 'โ', 'โ', 'โ
', 'โ', 'โ', 'โ'];
|
|
23
|
+
/**
|
|
24
|
+
* Map a numeric series into a fixed-width sparkline. Auto-scales to the
|
|
25
|
+
* series max. Returns empty cells when there's no data yet.
|
|
26
|
+
*/
|
|
27
|
+
export function sparkline(values, width) {
|
|
28
|
+
if (width <= 0)
|
|
29
|
+
return '';
|
|
30
|
+
const tail = values.slice(-width);
|
|
31
|
+
const padded = tail.length < width ? Array(width - tail.length).fill(0).concat(tail) : tail;
|
|
32
|
+
const max = Math.max(1, ...padded);
|
|
33
|
+
return padded
|
|
34
|
+
.map((v) => {
|
|
35
|
+
if (v <= 0)
|
|
36
|
+
return ' ';
|
|
37
|
+
const idx = Math.min(SPARK.length - 1, Math.floor((v / max) * (SPARK.length - 1)));
|
|
38
|
+
return SPARK[idx];
|
|
39
|
+
})
|
|
40
|
+
.join('');
|
|
41
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useRef, useState } from 'react';
|
|
4
|
+
import { render, Box, Text, useApp, useInput } from 'ink';
|
|
5
|
+
import { findActiveTranscript, listTranscripts } from '../core/parser.js';
|
|
6
|
+
import { tailTranscript } from '../core/tailer.js';
|
|
7
|
+
import { detectAuth } from '../core/detect.js';
|
|
8
|
+
import { estimateCostUSD, fmtNumber, fmtUSD } from '../core/format.js';
|
|
9
|
+
import { totalTokens } from '../core/types.js';
|
|
10
|
+
import { bar, sparkline } from './bars.js';
|
|
11
|
+
const RESCAN_MS = 3_000;
|
|
12
|
+
const SPARK_WIDTH = 32;
|
|
13
|
+
const BAR_WIDTH = 20;
|
|
14
|
+
function App() {
|
|
15
|
+
const { exit } = useApp();
|
|
16
|
+
const [auth] = useState(() => detectAuth());
|
|
17
|
+
const [stats, setStats] = useState(null);
|
|
18
|
+
const [transcriptPath, setTranscriptPath] = useState(null);
|
|
19
|
+
const [rate, setRate] = useState(0);
|
|
20
|
+
const [series, setSeries] = useState(() => Array(SPARK_WIDTH).fill(0));
|
|
21
|
+
const [now, setNow] = useState(Date.now());
|
|
22
|
+
const lastTotalRef = useRef(0);
|
|
23
|
+
const lastSampleAtRef = useRef(Date.now());
|
|
24
|
+
// useInput requires raw mode (interactive TTY). Skip it when stdin is piped
|
|
25
|
+
// or otherwise non-interactive, so `node dist/tui/index.js | cat` still
|
|
26
|
+
// renders instead of crashing.
|
|
27
|
+
const interactive = Boolean(process.stdin.isTTY);
|
|
28
|
+
if (interactive) {
|
|
29
|
+
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
30
|
+
useInput((input, key) => {
|
|
31
|
+
if (input === 'q' || key.escape || (key.ctrl && input === 'c'))
|
|
32
|
+
exit();
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
// Wall-clock tick + sparkline slot rotation (1 Hz).
|
|
36
|
+
useEffect(() => {
|
|
37
|
+
const t = setInterval(() => {
|
|
38
|
+
setNow(Date.now());
|
|
39
|
+
setSeries((s) => [...s.slice(1), 0]);
|
|
40
|
+
}, 1000);
|
|
41
|
+
return () => clearInterval(t);
|
|
42
|
+
}, []);
|
|
43
|
+
useEffect(() => {
|
|
44
|
+
let handle = null;
|
|
45
|
+
let cancelled = false;
|
|
46
|
+
async function attach(path) {
|
|
47
|
+
handle?.stop().catch(() => undefined);
|
|
48
|
+
setTranscriptPath(path);
|
|
49
|
+
handle = await tailTranscript(path);
|
|
50
|
+
if (cancelled) {
|
|
51
|
+
handle.stop();
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
handle.onUpdate((s) => {
|
|
55
|
+
const tot = totalTokens(s.totals);
|
|
56
|
+
const delta = Math.max(0, tot - lastTotalRef.current);
|
|
57
|
+
const dt = (Date.now() - lastSampleAtRef.current) / 60_000;
|
|
58
|
+
if (dt > 0 && delta > 0)
|
|
59
|
+
setRate(delta / dt);
|
|
60
|
+
if (delta > 0) {
|
|
61
|
+
setSeries((arr) => {
|
|
62
|
+
const next = arr.slice();
|
|
63
|
+
next[next.length - 1] = (next[next.length - 1] ?? 0) + delta;
|
|
64
|
+
return next;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
lastTotalRef.current = tot;
|
|
68
|
+
lastSampleAtRef.current = Date.now();
|
|
69
|
+
setStats({ ...s });
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
async function rescan() {
|
|
73
|
+
const active = findActiveTranscript();
|
|
74
|
+
if (active && active.path !== transcriptPath)
|
|
75
|
+
await attach(active.path);
|
|
76
|
+
}
|
|
77
|
+
rescan();
|
|
78
|
+
const interval = setInterval(rescan, RESCAN_MS);
|
|
79
|
+
return () => {
|
|
80
|
+
cancelled = true;
|
|
81
|
+
clearInterval(interval);
|
|
82
|
+
handle?.stop().catch(() => undefined);
|
|
83
|
+
};
|
|
84
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
85
|
+
}, []);
|
|
86
|
+
const transcripts = listTranscripts().slice(0, 5);
|
|
87
|
+
return (_jsxs(Box, { flexDirection: "column", padding: 1, children: [_jsx(Header, { auth: auth }), _jsxs(Box, { marginTop: 1, flexDirection: "row", gap: 1, children: [_jsx(SessionPanel, { stats: stats, rate: rate, now: now, series: series }), _jsx(BreakdownPanel, { stats: stats })] }), _jsx(Box, { marginTop: 1, children: _jsx(TranscriptsPanel, { transcripts: transcripts, activePath: transcriptPath, now: now }) }), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { dimColor: true, children: [_jsx(Text, { color: "magenta", children: "q" }), " quit \u00B7", ' ', _jsx(Text, { color: "magenta", children: "live" }), " tail of ~/.claude/projects \u00B7 pricing is", ' ', _jsx(Text, { italic: true, children: "API-equivalent" }), ", not your real bill on a subscription"] }) })] }));
|
|
88
|
+
}
|
|
89
|
+
// โโ Header โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
90
|
+
function Header({ auth }) {
|
|
91
|
+
const ok = auth.installed && auth.loggedIn;
|
|
92
|
+
const dot = ok ? 'green' : auth.installed ? 'yellow' : 'red';
|
|
93
|
+
const planChip = planChipFor(auth);
|
|
94
|
+
return (_jsxs(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, flexDirection: "column", children: [_jsxs(Box, { children: [_jsx(Text, { bold: true, color: "cyan", children: "\u258C tokens-metric " }), _jsx(Text, { dimColor: true, children: "v0.1.0 \u2014 real-time Claude Code usage" })] }), _jsx(Box, { marginTop: 0, children: _jsxs(Text, { children: [_jsx(Text, { color: dot, children: "\u25CF" }), ' ', auth.installed ? 'Claude Code detected' : 'Claude Code NOT detected', ' ', _jsx(Text, { ...planChip.style, children: planChip.label }), auth.userIdShort && _jsx(Text, { dimColor: true, children: ` user ${auth.userIdShort}` })] }) }), auth.hint && (_jsx(Box, { children: _jsxs(Text, { dimColor: true, children: ["\u21B3 ", auth.hint] }) }))] }));
|
|
95
|
+
}
|
|
96
|
+
function planChipFor(auth) {
|
|
97
|
+
if (!auth.loggedIn)
|
|
98
|
+
return { label: ' LOGGED-OUT ', style: { color: 'red', bold: true } };
|
|
99
|
+
switch (auth.planHint) {
|
|
100
|
+
case 'api':
|
|
101
|
+
return { label: ' API ', style: { color: 'yellow', bold: true } };
|
|
102
|
+
case 'team-or-enterprise':
|
|
103
|
+
return { label: ' TEAM / ENTERPRISE ', style: { color: 'magenta', bold: true } };
|
|
104
|
+
case 'paid':
|
|
105
|
+
return { label: ' PRO / MAX ', style: { color: 'green', bold: true } };
|
|
106
|
+
case 'free':
|
|
107
|
+
return { label: ' FREE ', style: { color: 'blue', bold: true } };
|
|
108
|
+
default:
|
|
109
|
+
return { label: ' SUBSCRIPTION ', style: { color: 'cyan', bold: true } };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
// โโ Session panel โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
113
|
+
function SessionPanel({ stats, rate, now, series, }) {
|
|
114
|
+
return (_jsxs(Box, { borderStyle: "round", borderColor: "green", paddingX: 1, flexDirection: "column", flexGrow: 1, minWidth: 42, children: [_jsx(Text, { bold: true, color: "green", children: "Active session" }), !stats ? (_jsx(Text, { dimColor: true, children: "Waiting for a Claude Code session\u2026" })) : (_jsxs(_Fragment, { children: [_jsx(KV, { k: "Model", v: _jsx(Text, { color: "cyan", children: stats.lastModel ?? 'โ' }) }), _jsx(KV, { k: "Msgs ", v: _jsx(Text, { children: stats.messageCount }) }), _jsx(KV, { k: "Last ", v: stats.lastEventAt ? (_jsxs(Text, { children: [timeAgo(now - stats.lastEventAt), " ago"] })) : (_jsx(Text, { dimColor: true, children: "\u2014" })) }), _jsx(KV, { k: "cwd ", v: _jsx(Text, { dimColor: true, wrap: "truncate-middle", children: stats.cwd ?? 'โ' }) }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { bold: true, children: "\u03A3 " }), _jsx(Text, { color: "cyan", bold: true, children: fmtNumber(totalTokens(stats.totals)) }), _jsx(Text, { dimColor: true, children: " tokens" })] }), (() => {
|
|
115
|
+
const cost = estimateCostUSD(stats.lastModel ?? '', stats.totals);
|
|
116
|
+
return cost !== null ? (_jsxs(Text, { dimColor: true, children: ["~", fmtUSD(cost), " API-equivalent"] })) : null;
|
|
117
|
+
})(), _jsxs(Text, { children: [_jsx(Text, { bold: true, children: "~ " }), _jsx(Text, { color: "yellow", children: fmtNumber(Math.round(rate)) }), _jsx(Text, { dimColor: true, children: " tok/min" })] })] }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { dimColor: true, children: ["activity (last ", SPARK_WIDTH, "s)"] }), _jsx(Text, { color: "yellow", children: sparkline(series, SPARK_WIDTH) })] })] }))] }));
|
|
118
|
+
}
|
|
119
|
+
// โโ Breakdown panel โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
120
|
+
function BreakdownPanel({ stats }) {
|
|
121
|
+
return (_jsxs(Box, { borderStyle: "round", borderColor: "blue", paddingX: 1, flexDirection: "column", flexGrow: 1, minWidth: 42, children: [_jsx(Text, { bold: true, color: "blue", children: "Token breakdown" }), !stats ? (_jsx(Text, { dimColor: true, children: "No data yet." })) : ((() => {
|
|
122
|
+
const u = stats.totals;
|
|
123
|
+
const max = Math.max(1, u.input_tokens, u.output_tokens, u.cache_creation_input_tokens, u.cache_read_input_tokens);
|
|
124
|
+
return (_jsxs(Box, { flexDirection: "column", children: [_jsx(BarRow, { label: "Input ", value: u.input_tokens, max: max, color: "cyan" }), _jsx(BarRow, { label: "Output ", value: u.output_tokens, max: max, color: "green" }), _jsx(BarRow, { label: "C. write ", value: u.cache_creation_input_tokens, max: max, color: "yellow" }), _jsx(BarRow, { label: "C. read ", value: u.cache_read_input_tokens, max: max, color: "magenta" }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "By model" }), Object.entries(stats.byModel).map(([m, mu]) => (_jsxs(Text, { children: [_jsx(Text, { color: "cyan", children: shortModel(m) }), _jsx(Text, { dimColor: true, children: " \u03A3 " }), _jsx(Text, { children: fmtNumber(totalTokens(mu)) })] }, m)))] })] }));
|
|
125
|
+
})())] }));
|
|
126
|
+
}
|
|
127
|
+
function BarRow({ label, value, max, color, }) {
|
|
128
|
+
return (_jsxs(Text, { children: [_jsx(Text, { bold: true, children: label }), _jsx(Text, { color: color, children: bar(value / max, BAR_WIDTH) }), _jsxs(Text, { children: [" ", fmtNumber(value)] })] }));
|
|
129
|
+
}
|
|
130
|
+
// โโ Transcripts panel โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
131
|
+
function TranscriptsPanel({ transcripts, activePath, now, }) {
|
|
132
|
+
return (_jsxs(Box, { borderStyle: "round", borderColor: "gray", paddingX: 1, flexDirection: "column", width: "100%", children: [_jsx(Text, { bold: true, children: "Recent transcripts" }), transcripts.length === 0 ? (_jsx(Text, { dimColor: true, children: "None found under ~/.claude/projects" })) : (transcripts.map((t) => {
|
|
133
|
+
const isActive = t.path === activePath;
|
|
134
|
+
return (_jsxs(Text, { children: [_jsx(Text, { color: isActive ? 'green' : 'gray', children: isActive ? 'โถ ' : ' ' }), _jsx(Text, { dimColor: !isActive, wrap: "truncate-middle", children: t.cwd }), _jsx(Text, { dimColor: true, children: ` ${timeAgo(now - t.mtimeMs)}` })] }, t.path));
|
|
135
|
+
}))] }));
|
|
136
|
+
}
|
|
137
|
+
// โโ helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
138
|
+
function KV({ k, v }) {
|
|
139
|
+
return (_jsxs(Text, { children: [_jsx(Text, { bold: true, children: k }), _jsx(Text, { dimColor: true, children: " \u00B7 " }), v] }));
|
|
140
|
+
}
|
|
141
|
+
function shortModel(m) {
|
|
142
|
+
return m.replace(/^claude-/, '').replace(/-20\d{6}/, '').replace(/-\d{8}$/, '');
|
|
143
|
+
}
|
|
144
|
+
function timeAgo(ms) {
|
|
145
|
+
if (ms < 0)
|
|
146
|
+
ms = 0;
|
|
147
|
+
const s = Math.floor(ms / 1000);
|
|
148
|
+
if (s < 60)
|
|
149
|
+
return `${s}s`;
|
|
150
|
+
const m = Math.floor(s / 60);
|
|
151
|
+
if (m < 60)
|
|
152
|
+
return `${m}m`;
|
|
153
|
+
const h = Math.floor(m / 60);
|
|
154
|
+
if (h < 24)
|
|
155
|
+
return `${h}h`;
|
|
156
|
+
return `${Math.floor(h / 24)}d`;
|
|
157
|
+
}
|
|
158
|
+
render(_jsx(App, {}));
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "tokens-metric",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Real-time token usage meter for Claude Code โ statusline + Ink TUI.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"tokens-metric": "dist/tui/index.js",
|
|
8
|
+
"tokens-metric-statusline": "dist/statusline/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"build": "tsc",
|
|
17
|
+
"dev:tui": "tsx src/tui/index.tsx",
|
|
18
|
+
"dev:statusline": "tsx src/statusline/index.ts",
|
|
19
|
+
"start": "node dist/tui/index.js",
|
|
20
|
+
"statusline": "node dist/statusline/index.js",
|
|
21
|
+
"prepublishOnly": "npm run build"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"claude",
|
|
25
|
+
"claude-code",
|
|
26
|
+
"tokens",
|
|
27
|
+
"usage",
|
|
28
|
+
"statusline",
|
|
29
|
+
"tui",
|
|
30
|
+
"ink",
|
|
31
|
+
"monitor"
|
|
32
|
+
],
|
|
33
|
+
"author": "Annibal48",
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"homepage": "https://github.com/Annibal48/Tokens-Metric#readme",
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/Annibal48/Tokens-Metric.git"
|
|
39
|
+
},
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/Annibal48/Tokens-Metric/issues"
|
|
42
|
+
},
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public"
|
|
45
|
+
},
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=18"
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"ink": "^5.0.1",
|
|
51
|
+
"react": "^18.3.1"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@types/node": "^20.12.7",
|
|
55
|
+
"@types/react": "^18.3.3",
|
|
56
|
+
"tsx": "^4.16.2",
|
|
57
|
+
"typescript": "^5.5.3"
|
|
58
|
+
}
|
|
59
|
+
}
|