ccusage 15.9.1 → 15.9.3

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,162 +0,0 @@
1
- import { CLAUDE_PROJECTS_DIR_NAME, DEBUG_MATCH_THRESHOLD_PERCENT, PricingFetcher, USAGE_DATA_GLOB_PATTERN, __toESM, isFailure, require_usingCtx, try_ } from "./pricing-fetcher-DtGb7sbF.js";
2
- import { getClaudePaths, glob, unwrap, usageDataSchema } from "./data-loader-D3wQxjrt.js";
3
- import { logger } from "./logger-BODy31tA.js";
4
- import { readFile } from "node:fs/promises";
5
- import path from "node:path";
6
- var import_usingCtx = __toESM(require_usingCtx(), 1);
7
- /**
8
- * Analyzes usage data to detect pricing mismatches between stored and calculated costs
9
- * Compares pre-calculated costUSD values with costs calculated from token usage
10
- * @param claudePath - Optional path to Claude data directory
11
- * @returns Statistics about pricing mismatches found
12
- */
13
- async function detectMismatches(claudePath) {
14
- try {
15
- var _usingCtx = (0, import_usingCtx.default)();
16
- let claudeDir;
17
- if (claudePath != null && claudePath !== "") claudeDir = claudePath;
18
- else {
19
- const paths = getClaudePaths();
20
- if (paths.length === 0) throw new Error("No valid Claude data directory found");
21
- claudeDir = path.join(paths[0], CLAUDE_PROJECTS_DIR_NAME);
22
- }
23
- const files = await glob([USAGE_DATA_GLOB_PATTERN], {
24
- cwd: claudeDir,
25
- absolute: true
26
- });
27
- const fetcher = _usingCtx.u(new PricingFetcher());
28
- const stats = {
29
- totalEntries: 0,
30
- entriesWithBoth: 0,
31
- matches: 0,
32
- mismatches: 0,
33
- discrepancies: [],
34
- modelStats: new Map(),
35
- versionStats: new Map()
36
- };
37
- for (const file of files) {
38
- const content = await readFile(file, "utf-8");
39
- const lines = content.trim().split("\n").filter((line) => line.length > 0);
40
- for (const line of lines) {
41
- const parseParser = try_({
42
- try: () => JSON.parse(line),
43
- catch: () => new Error("Invalid JSON")
44
- });
45
- const parseResult = parseParser();
46
- if (isFailure(parseResult)) continue;
47
- const schemaResult = usageDataSchema.safeParse(parseResult.value);
48
- if (!schemaResult.success) continue;
49
- const data = schemaResult.data;
50
- stats.totalEntries++;
51
- if (data.costUSD !== void 0 && data.message.model != null && data.message.model !== "<synthetic>") {
52
- stats.entriesWithBoth++;
53
- const model = data.message.model;
54
- const calculatedCost = await unwrap(fetcher.calculateCostFromTokens(data.message.usage, model));
55
- const difference = Math.abs(data.costUSD - calculatedCost);
56
- const percentDiff = data.costUSD > 0 ? difference / data.costUSD * 100 : 0;
57
- const modelStat = stats.modelStats.get(model) ?? {
58
- total: 0,
59
- matches: 0,
60
- mismatches: 0,
61
- avgPercentDiff: 0
62
- };
63
- modelStat.total++;
64
- if (data.version != null) {
65
- const versionStat = stats.versionStats.get(data.version) ?? {
66
- total: 0,
67
- matches: 0,
68
- mismatches: 0,
69
- avgPercentDiff: 0
70
- };
71
- versionStat.total++;
72
- if (percentDiff < DEBUG_MATCH_THRESHOLD_PERCENT) versionStat.matches++;
73
- else versionStat.mismatches++;
74
- versionStat.avgPercentDiff = (versionStat.avgPercentDiff * (versionStat.total - 1) + percentDiff) / versionStat.total;
75
- stats.versionStats.set(data.version, versionStat);
76
- }
77
- if (percentDiff < .1) {
78
- stats.matches++;
79
- modelStat.matches++;
80
- } else {
81
- stats.mismatches++;
82
- modelStat.mismatches++;
83
- stats.discrepancies.push({
84
- file: path.basename(file),
85
- timestamp: data.timestamp,
86
- model,
87
- originalCost: data.costUSD,
88
- calculatedCost,
89
- difference,
90
- percentDiff,
91
- usage: data.message.usage
92
- });
93
- }
94
- modelStat.avgPercentDiff = (modelStat.avgPercentDiff * (modelStat.total - 1) + percentDiff) / modelStat.total;
95
- stats.modelStats.set(model, modelStat);
96
- }
97
- }
98
- }
99
- return stats;
100
- } catch (_) {
101
- _usingCtx.e = _;
102
- } finally {
103
- _usingCtx.d();
104
- }
105
- }
106
- /**
107
- * Prints a detailed report of pricing mismatches to the console
108
- * @param stats - Mismatch statistics to report
109
- * @param sampleCount - Number of sample discrepancies to show (default: 5)
110
- */
111
- function printMismatchReport(stats, sampleCount = 5) {
112
- if (stats.entriesWithBoth === 0) {
113
- logger.info("No pricing data found to analyze.");
114
- return;
115
- }
116
- const matchRate = stats.matches / stats.entriesWithBoth * 100;
117
- logger.info("\n=== Pricing Mismatch Debug Report ===");
118
- logger.info(`Total entries processed: ${stats.totalEntries.toLocaleString()}`);
119
- logger.info(`Entries with both costUSD and model: ${stats.entriesWithBoth.toLocaleString()}`);
120
- logger.info(`Matches (within 0.1%): ${stats.matches.toLocaleString()}`);
121
- logger.info(`Mismatches: ${stats.mismatches.toLocaleString()}`);
122
- logger.info(`Match rate: ${matchRate.toFixed(2)}%`);
123
- if (stats.mismatches > 0 && stats.modelStats.size > 0) {
124
- logger.info("\n=== Model Statistics ===");
125
- const sortedModels = Array.from(stats.modelStats.entries()).sort((a$1, b) => b[1].mismatches - a$1[1].mismatches);
126
- for (const [model, modelStat] of sortedModels) if (modelStat.mismatches > 0) {
127
- const modelMatchRate = modelStat.matches / modelStat.total * 100;
128
- logger.info(`${model}:`);
129
- logger.info(` Total entries: ${modelStat.total.toLocaleString()}`);
130
- logger.info(` Matches: ${modelStat.matches.toLocaleString()} (${modelMatchRate.toFixed(1)}%)`);
131
- logger.info(` Mismatches: ${modelStat.mismatches.toLocaleString()}`);
132
- logger.info(` Avg % difference: ${modelStat.avgPercentDiff.toFixed(1)}%`);
133
- }
134
- }
135
- if (stats.mismatches > 0 && stats.versionStats.size > 0) {
136
- logger.info("\n=== Version Statistics ===");
137
- const sortedVersions = Array.from(stats.versionStats.entries()).filter(([_, versionStat]) => versionStat.mismatches > 0).sort((a$1, b) => b[1].mismatches - a$1[1].mismatches);
138
- for (const [version, versionStat] of sortedVersions) {
139
- const versionMatchRate = versionStat.matches / versionStat.total * 100;
140
- logger.info(`${version}:`);
141
- logger.info(` Total entries: ${versionStat.total.toLocaleString()}`);
142
- logger.info(` Matches: ${versionStat.matches.toLocaleString()} (${versionMatchRate.toFixed(1)}%)`);
143
- logger.info(` Mismatches: ${versionStat.mismatches.toLocaleString()}`);
144
- logger.info(` Avg % difference: ${versionStat.avgPercentDiff.toFixed(1)}%`);
145
- }
146
- }
147
- if (stats.discrepancies.length > 0 && sampleCount > 0) {
148
- logger.info(`\n=== Sample Discrepancies (first ${sampleCount}) ===`);
149
- const samples = stats.discrepancies.slice(0, sampleCount);
150
- for (const disc of samples) {
151
- logger.info(`File: ${disc.file}`);
152
- logger.info(`Timestamp: ${disc.timestamp}`);
153
- logger.info(`Model: ${disc.model}`);
154
- logger.info(`Original cost: $${disc.originalCost.toFixed(6)}`);
155
- logger.info(`Calculated cost: $${disc.calculatedCost.toFixed(6)}`);
156
- logger.info(`Difference: $${disc.difference.toFixed(6)} (${disc.percentDiff.toFixed(2)}%)`);
157
- logger.info(`Tokens: ${JSON.stringify(disc.usage)}`);
158
- logger.info("---");
159
- }
160
- }
161
- }
162
- export { detectMismatches, printMismatchReport };