hail-hydra-cc 2.4.0 → 2.4.2

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.
@@ -1,163 +1,179 @@
1
- #!/usr/bin/env node
2
-
3
- // Shared helper: parse Claude Code session JSONL, compute per-tier usage,
4
- // actual cost, and savings vs all-Opus baseline.
5
- //
6
- // Used by:
7
- // - hooks/hydra-statusline.js (cached, every statusline refresh)
8
- // - commands/hydra/stats.md (fresh, on /hydra:stats invocation)
9
-
10
- const fs = require('fs');
11
- const path = require('path');
12
- const os = require('os');
13
-
14
- const PRICING = {
15
- 'claude-haiku-4': { input: 1, output: 5 },
16
- 'claude-sonnet-4': { input: 3, output: 15 },
17
- 'claude-opus-4': { input: 5, output: 25 }
18
- };
19
-
20
- function getPrice(model) {
21
- for (const prefix in PRICING) {
22
- if (model.startsWith(prefix)) return PRICING[prefix];
23
- }
24
- return null;
25
- }
26
-
27
- function getTier(model) {
28
- if (model.startsWith('claude-haiku')) return 'haiku';
29
- if (model.startsWith('claude-sonnet')) return 'sonnet';
30
- if (model.startsWith('claude-opus')) return 'opus';
31
- return null;
32
- }
33
-
34
- function findActiveSessionFile() {
35
- try {
36
- const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
37
- const projectsDir = path.join(configDir, 'projects');
38
- if (!fs.existsSync(projectsDir)) return null;
39
-
40
- const cwd = process.cwd();
41
- const slug = cwd.replace(/[^a-zA-Z0-9-]/g, '-').replace(/^-+/, '');
42
-
43
- let sessionDir = path.join(projectsDir, slug);
44
- if (!fs.existsSync(sessionDir)) {
45
- const all = fs.readdirSync(projectsDir);
46
- const match = all.find(d => d.toLowerCase() === slug.toLowerCase())
47
- || all.find(d => d.toLowerCase().endsWith(path.basename(cwd).toLowerCase()));
48
- if (!match) return null;
49
- sessionDir = path.join(projectsDir, match);
50
- }
51
-
52
- const files = fs.readdirSync(sessionDir)
53
- .filter(f => f.endsWith('.jsonl'))
54
- .map(f => ({ p: path.join(sessionDir, f), m: fs.statSync(path.join(sessionDir, f)).mtimeMs }))
55
- .sort((a, b) => b.m - a.m);
56
-
57
- return files.length > 0 ? files[0].p : null;
58
- } catch (e) {
59
- return null;
60
- }
61
- }
62
-
63
- function parseSession(sessionFile) {
64
- const stats = {
65
- haiku: { input: 0, output: 0, cache_read: 0, cache_create: 0, turns: 0 },
66
- sonnet: { input: 0, output: 0, cache_read: 0, cache_create: 0, turns: 0 },
67
- opus: { input: 0, output: 0, cache_read: 0, cache_create: 0, turns: 0 }
68
- };
69
- const unknownModels = new Set();
70
- let totalTurns = 0;
71
-
72
- try {
73
- const lines = fs.readFileSync(sessionFile, 'utf8').split('\n').filter(Boolean);
74
- for (const line of lines) {
75
- try {
76
- const obj = JSON.parse(line);
77
- if (obj.type !== 'assistant' || !obj.message || !obj.message.usage) continue;
78
- const model = obj.message.model || '';
79
- const tier = getTier(model);
80
- if (!tier) { if (model) unknownModels.add(model); continue; }
81
- const u = obj.message.usage;
82
- stats[tier].input += u.input_tokens || 0;
83
- stats[tier].output += u.output_tokens || 0;
84
- stats[tier].cache_read += u.cache_read_input_tokens || 0;
85
- stats[tier].cache_create += u.cache_creation_input_tokens || 0;
86
- stats[tier].turns += 1;
87
- totalTurns += 1;
88
- } catch (e) { /* skip malformed line */ }
89
- }
90
- } catch (e) { /* file unreadable */ }
91
-
92
- return { stats, totalTurns, unknownModels };
93
- }
94
-
95
- function tierCost(s, p) {
96
- if (!p) return 0;
97
- const inputCost = ((s.input + s.cache_create) * p.input) / 1_000_000;
98
- const cacheReadCost = (s.cache_read * p.input * 0.1) / 1_000_000;
99
- const outputCost = (s.output * p.output) / 1_000_000;
100
- return inputCost + cacheReadCost + outputCost;
101
- }
102
-
103
- function asOpusCost(s) {
104
- return tierCost(s, PRICING['claude-opus-4']);
105
- }
106
-
107
- function computeSummary() {
108
- const sessionFile = findActiveSessionFile();
109
- if (!sessionFile) return { available: false };
110
-
111
- const { stats, totalTurns, unknownModels } = parseSession(sessionFile);
112
- if (totalTurns === 0) return { available: false };
113
-
114
- const haikuCost = tierCost(stats.haiku, PRICING['claude-haiku-4']);
115
- const sonnetCost = tierCost(stats.sonnet, PRICING['claude-sonnet-4']);
116
- const opusCost = tierCost(stats.opus, PRICING['claude-opus-4']);
117
- const actualCost = haikuCost + sonnetCost + opusCost;
118
-
119
- const hypotheticalCost =
120
- asOpusCost(stats.haiku) + asOpusCost(stats.sonnet) + asOpusCost(stats.opus);
121
-
122
- const savedUSD = Math.max(0, hypotheticalCost - actualCost);
123
- const savedPct = hypotheticalCost > 0 ? (savedUSD / hypotheticalCost) * 100 : 0;
124
-
125
- const delegatedTurns = stats.haiku.turns + stats.sonnet.turns;
126
- const delegationRate = totalTurns > 0 ? (delegatedTurns / totalTurns) * 100 : 0;
127
-
128
- return {
129
- available: true,
130
- sessionFile,
131
- totalTurns,
132
- stats,
133
- haikuCost, sonnetCost, opusCost,
134
- actualCost, hypotheticalCost,
135
- savedUSD, savedPct,
136
- delegatedTurns, delegationRate,
137
- unknownModels
138
- };
139
- }
140
-
141
- let _cache = null;
142
- let _cacheExpiry = 0;
143
- const CACHE_TTL_MS = 15000;
144
-
145
- function computeSummaryCached() {
146
- const now = Date.now();
147
- if (_cache && now < _cacheExpiry) return _cache;
148
- _cache = computeSummary();
149
- _cacheExpiry = now + CACHE_TTL_MS;
150
- return _cache;
151
- }
152
-
153
- module.exports = {
154
- computeSummary,
155
- computeSummaryCached,
156
- parseSession,
157
- findActiveSessionFile,
158
- tierCost,
159
- asOpusCost,
160
- getTier,
161
- getPrice,
162
- PRICING
163
- };
1
+ #!/usr/bin/env node
2
+
3
+ // Shared helper: parse Claude Code session JSONL, compute per-tier usage,
4
+ // actual cost, and savings vs all-Opus baseline.
5
+ //
6
+ // Used by:
7
+ // - hooks/hydra-statusline.js (cached, every statusline refresh)
8
+ // - commands/hydra/stats.md (fresh, on /hydra:stats invocation)
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const os = require('os');
13
+
14
+ const PRICING = {
15
+ 'claude-haiku-4': { input: 1, output: 5 },
16
+ 'claude-sonnet-4': { input: 3, output: 15 },
17
+ 'claude-opus-4': { input: 5, output: 25 }
18
+ };
19
+
20
+ function getPrice(model) {
21
+ for (const prefix in PRICING) {
22
+ if (model.startsWith(prefix)) return PRICING[prefix];
23
+ }
24
+ return null;
25
+ }
26
+
27
+ function getTier(model) {
28
+ if (model.startsWith('claude-haiku')) return 'haiku';
29
+ if (model.startsWith('claude-sonnet')) return 'sonnet';
30
+ if (model.startsWith('claude-opus')) return 'opus';
31
+ return null;
32
+ }
33
+
34
+ function findActiveSessionFile() {
35
+ try {
36
+ const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
37
+ const projectsDir = path.join(configDir, 'projects');
38
+ if (!fs.existsSync(projectsDir)) return null;
39
+
40
+ const cwd = process.cwd();
41
+ // Claude Code names project dirs by replacing every non-alphanumeric char
42
+ // (including the leading separator) with '-'. Match that exactly — do NOT
43
+ // strip the leading dash, or exact matches fail for underscore/special paths.
44
+ const slug = cwd.replace(/[^a-zA-Z0-9-]/g, '-');
45
+
46
+ let sessionDir = path.join(projectsDir, slug);
47
+ if (!fs.existsSync(sessionDir)) {
48
+ const all = fs.readdirSync(projectsDir);
49
+ // Normalize basename the same way (underscores/specials → dashes) so the
50
+ // endsWith fallback compares like-for-like.
51
+ const baseSlug = path.basename(cwd).replace(/[^a-zA-Z0-9-]/g, '-').toLowerCase();
52
+ const match = all.find(d => d === slug)
53
+ || all.find(d => d.toLowerCase() === slug.toLowerCase())
54
+ || all.find(d => d.toLowerCase().endsWith(baseSlug));
55
+ if (!match) {
56
+ if (process.env.HYDRA_DEBUG === '1') {
57
+ console.error('[hydra-token-math] No session dir matched.');
58
+ console.error(' cwd:', cwd);
59
+ console.error(' computed slug:', slug);
60
+ console.error(' projects dir contents:',
61
+ fs.existsSync(projectsDir) ? fs.readdirSync(projectsDir).slice(0, 10) : '(none)');
62
+ }
63
+ return null;
64
+ }
65
+ sessionDir = path.join(projectsDir, match);
66
+ }
67
+
68
+ const files = fs.readdirSync(sessionDir)
69
+ .filter(f => f.endsWith('.jsonl'))
70
+ .map(f => ({ p: path.join(sessionDir, f), m: fs.statSync(path.join(sessionDir, f)).mtimeMs }))
71
+ .sort((a, b) => b.m - a.m);
72
+
73
+ return files.length > 0 ? files[0].p : null;
74
+ } catch (e) {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ function parseSession(sessionFile) {
80
+ const stats = {
81
+ haiku: { input: 0, output: 0, cache_read: 0, cache_create: 0, turns: 0 },
82
+ sonnet: { input: 0, output: 0, cache_read: 0, cache_create: 0, turns: 0 },
83
+ opus: { input: 0, output: 0, cache_read: 0, cache_create: 0, turns: 0 }
84
+ };
85
+ const unknownModels = new Set();
86
+ let totalTurns = 0;
87
+
88
+ try {
89
+ const lines = fs.readFileSync(sessionFile, 'utf8').split('\n').filter(Boolean);
90
+ for (const line of lines) {
91
+ try {
92
+ const obj = JSON.parse(line);
93
+ if (obj.type !== 'assistant' || !obj.message || !obj.message.usage) continue;
94
+ const model = obj.message.model || '';
95
+ const tier = getTier(model);
96
+ if (!tier) { if (model) unknownModels.add(model); continue; }
97
+ const u = obj.message.usage;
98
+ stats[tier].input += u.input_tokens || 0;
99
+ stats[tier].output += u.output_tokens || 0;
100
+ stats[tier].cache_read += u.cache_read_input_tokens || 0;
101
+ stats[tier].cache_create += u.cache_creation_input_tokens || 0;
102
+ stats[tier].turns += 1;
103
+ totalTurns += 1;
104
+ } catch (e) { /* skip malformed line */ }
105
+ }
106
+ } catch (e) { /* file unreadable */ }
107
+
108
+ return { stats, totalTurns, unknownModels };
109
+ }
110
+
111
+ function tierCost(s, p) {
112
+ if (!p) return 0;
113
+ const inputCost = ((s.input + s.cache_create) * p.input) / 1_000_000;
114
+ const cacheReadCost = (s.cache_read * p.input * 0.1) / 1_000_000;
115
+ const outputCost = (s.output * p.output) / 1_000_000;
116
+ return inputCost + cacheReadCost + outputCost;
117
+ }
118
+
119
+ function asOpusCost(s) {
120
+ return tierCost(s, PRICING['claude-opus-4']);
121
+ }
122
+
123
+ function computeSummary() {
124
+ const sessionFile = findActiveSessionFile();
125
+ if (!sessionFile) return { available: false };
126
+
127
+ const { stats, totalTurns, unknownModels } = parseSession(sessionFile);
128
+ if (totalTurns === 0) return { available: false };
129
+
130
+ const haikuCost = tierCost(stats.haiku, PRICING['claude-haiku-4']);
131
+ const sonnetCost = tierCost(stats.sonnet, PRICING['claude-sonnet-4']);
132
+ const opusCost = tierCost(stats.opus, PRICING['claude-opus-4']);
133
+ const actualCost = haikuCost + sonnetCost + opusCost;
134
+
135
+ const hypotheticalCost =
136
+ asOpusCost(stats.haiku) + asOpusCost(stats.sonnet) + asOpusCost(stats.opus);
137
+
138
+ const savedUSD = Math.max(0, hypotheticalCost - actualCost);
139
+ const savedPct = hypotheticalCost > 0 ? (savedUSD / hypotheticalCost) * 100 : 0;
140
+
141
+ const delegatedTurns = stats.haiku.turns + stats.sonnet.turns;
142
+ const delegationRate = totalTurns > 0 ? (delegatedTurns / totalTurns) * 100 : 0;
143
+
144
+ return {
145
+ available: true,
146
+ sessionFile,
147
+ totalTurns,
148
+ stats,
149
+ haikuCost, sonnetCost, opusCost,
150
+ actualCost, hypotheticalCost,
151
+ savedUSD, savedPct,
152
+ delegatedTurns, delegationRate,
153
+ unknownModels
154
+ };
155
+ }
156
+
157
+ let _cache = null;
158
+ let _cacheExpiry = 0;
159
+ const CACHE_TTL_MS = 15000;
160
+
161
+ function computeSummaryCached() {
162
+ const now = Date.now();
163
+ if (_cache && now < _cacheExpiry) return _cache;
164
+ _cache = computeSummary();
165
+ _cacheExpiry = now + CACHE_TTL_MS;
166
+ return _cache;
167
+ }
168
+
169
+ module.exports = {
170
+ computeSummary,
171
+ computeSummaryCached,
172
+ parseSession,
173
+ findActiveSessionFile,
174
+ tierCost,
175
+ asOpusCost,
176
+ getTier,
177
+ getPrice,
178
+ PRICING
179
+ };