claude-instance-manager 0.0.0-stage → 1.0.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/usage.js ADDED
@@ -0,0 +1,46 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { getCachedResets } = require('./usage-cache');
4
+
5
+ async function readUsageHistory(directory) {
6
+ const file = path.join(directory, 'plan-usage-history.json');
7
+ let contents;
8
+ try {
9
+ contents = await fs.promises.readFile(file, 'utf8');
10
+ } catch (error) {
11
+ if (error.code === 'ENOENT') return null;
12
+ throw error;
13
+ }
14
+
15
+ const history = JSON.parse(contents);
16
+ if (!history || ![1, 2].includes(history.version) || !Array.isArray(history.samples)) {
17
+ throw new Error('Unsupported local usage history format.');
18
+ }
19
+
20
+ let latest = null;
21
+ for (const sample of history.samples) {
22
+ if (!sample || !Number.isFinite(sample.t) || sample.t < 0 || sample.t > 8640000000000000 ||
23
+ (latest && sample.t <= latest.t)) continue;
24
+ const values = history.version === 1 ? sample : sample.u;
25
+ if (!values || typeof values !== 'object' || Array.isArray(values)) continue;
26
+ const metrics = {};
27
+ for (const [field, label] of [['fh', 'Five-hour'], ['sd', 'Weekly all models'], ['sn', 'Weekly Sonnet'], ['so', 'Weekly Opus']]) {
28
+ if (Number.isFinite(values[field]) && values[field] >= 0) metrics[label] = values[field];
29
+ }
30
+ if (Object.keys(metrics).length) latest = { t: sample.t, org: sample.org, metrics };
31
+ }
32
+ if (!latest) return null;
33
+ const result = { recordedAt: latest.t, metrics: latest.metrics };
34
+ if (history.version === 2 && typeof latest.org === 'string' && latest.org) {
35
+ try {
36
+ const resets = await getCachedResets(directory, latest, latest.metrics);
37
+ if (Object.keys(resets).length) result.resets = resets;
38
+ } catch (error) {
39
+ console.error('Could not read cached usage reset times:', error.code || error.name);
40
+ result.resetError = true;
41
+ }
42
+ }
43
+ return result;
44
+ }
45
+
46
+ module.exports = { readUsageHistory };