ccusage 15.9.4 → 15.9.6
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/dist/calculate-cost.d.ts +1 -1
- package/dist/{data-loader-B2FL7oh0.d.ts → data-loader-BPepPoPg.d.ts} +99 -1
- package/dist/{data-loader-CY2f8ZBq.js → data-loader-C_o-3Ju1.js} +58 -4
- package/dist/data-loader.d.ts +2 -2
- package/dist/data-loader.js +4 -4
- package/dist/{debug-mIvd8kZa.js → debug-DX6e8anz.js} +3 -3
- package/dist/debug.js +4 -4
- package/dist/index.d.ts +2 -1
- package/dist/index.js +93 -76
- package/dist/{logger-QcakA1fc.js → logger-B42xzUl2.js} +1 -1
- package/dist/logger.js +1 -1
- package/dist/{mcp-COJ_l32e.js → mcp-DsGPnOCJ.js} +3 -3
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +4 -4
- package/dist/{pricing-fetcher-DzkXdtDF.js → pricing-fetcher-BtJtc54j.js} +10 -5
- package/dist/pricing-fetcher.js +2 -2
- package/package.json +1 -1
package/dist/calculate-cost.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./pricing-fetcher-B5m_kEpz.js";
|
|
2
|
-
import { DailyUsage, MonthlyUsage, SessionUsage, WeeklyUsage } from "./data-loader-
|
|
2
|
+
import { DailyUsage, MonthlyUsage, SessionUsage, WeeklyUsage } from "./data-loader-BPepPoPg.js";
|
|
3
3
|
|
|
4
4
|
//#region src/_token-utils.d.ts
|
|
5
5
|
|
|
@@ -62,6 +62,16 @@ type SessionBlock = {
|
|
|
62
62
|
* @returns Array of valid Claude data directory paths
|
|
63
63
|
*/
|
|
64
64
|
declare function getClaudePaths(): string[];
|
|
65
|
+
/**
|
|
66
|
+
* Get context usage percentage thresholds for color coding
|
|
67
|
+
* Can be configured via environment variables or uses defaults
|
|
68
|
+
* Validates and clamps values to 0-100 range and enforces LOW < MEDIUM ordering
|
|
69
|
+
* @returns Context usage thresholds with LOW and MEDIUM percentages
|
|
70
|
+
*/
|
|
71
|
+
declare function getContextUsageThresholds(): {
|
|
72
|
+
readonly LOW: number;
|
|
73
|
+
readonly MEDIUM: number;
|
|
74
|
+
};
|
|
65
75
|
/**
|
|
66
76
|
* Extract project name from Claude JSONL file path
|
|
67
77
|
* @param jsonlPath - Absolute path to JSONL file
|
|
@@ -173,6 +183,83 @@ declare const usageDataSchema: z.ZodObject<{
|
|
|
173
183
|
requestId?: string | undefined;
|
|
174
184
|
isApiErrorMessage?: boolean | undefined;
|
|
175
185
|
}>;
|
|
186
|
+
/**
|
|
187
|
+
* Zod schema for transcript usage data from Claude messages
|
|
188
|
+
*/
|
|
189
|
+
declare const transcriptUsageSchema: z.ZodObject<{
|
|
190
|
+
input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
191
|
+
cache_creation_input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
192
|
+
cache_read_input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
193
|
+
output_tokens: z.ZodOptional<z.ZodNumber>;
|
|
194
|
+
}, "strip", z.ZodTypeAny, {
|
|
195
|
+
input_tokens?: number | undefined;
|
|
196
|
+
cache_creation_input_tokens?: number | undefined;
|
|
197
|
+
cache_read_input_tokens?: number | undefined;
|
|
198
|
+
output_tokens?: number | undefined;
|
|
199
|
+
}, {
|
|
200
|
+
input_tokens?: number | undefined;
|
|
201
|
+
cache_creation_input_tokens?: number | undefined;
|
|
202
|
+
cache_read_input_tokens?: number | undefined;
|
|
203
|
+
output_tokens?: number | undefined;
|
|
204
|
+
}>;
|
|
205
|
+
/**
|
|
206
|
+
* Zod schema for transcript message data
|
|
207
|
+
*/
|
|
208
|
+
declare const transcriptMessageSchema: z.ZodObject<{
|
|
209
|
+
type: z.ZodOptional<z.ZodString>;
|
|
210
|
+
message: z.ZodOptional<z.ZodObject<{
|
|
211
|
+
usage: z.ZodOptional<z.ZodObject<{
|
|
212
|
+
input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
213
|
+
cache_creation_input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
214
|
+
cache_read_input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
215
|
+
output_tokens: z.ZodOptional<z.ZodNumber>;
|
|
216
|
+
}, "strip", z.ZodTypeAny, {
|
|
217
|
+
input_tokens?: number | undefined;
|
|
218
|
+
cache_creation_input_tokens?: number | undefined;
|
|
219
|
+
cache_read_input_tokens?: number | undefined;
|
|
220
|
+
output_tokens?: number | undefined;
|
|
221
|
+
}, {
|
|
222
|
+
input_tokens?: number | undefined;
|
|
223
|
+
cache_creation_input_tokens?: number | undefined;
|
|
224
|
+
cache_read_input_tokens?: number | undefined;
|
|
225
|
+
output_tokens?: number | undefined;
|
|
226
|
+
}>>;
|
|
227
|
+
}, "strip", z.ZodTypeAny, {
|
|
228
|
+
usage?: {
|
|
229
|
+
input_tokens?: number | undefined;
|
|
230
|
+
cache_creation_input_tokens?: number | undefined;
|
|
231
|
+
cache_read_input_tokens?: number | undefined;
|
|
232
|
+
output_tokens?: number | undefined;
|
|
233
|
+
} | undefined;
|
|
234
|
+
}, {
|
|
235
|
+
usage?: {
|
|
236
|
+
input_tokens?: number | undefined;
|
|
237
|
+
cache_creation_input_tokens?: number | undefined;
|
|
238
|
+
cache_read_input_tokens?: number | undefined;
|
|
239
|
+
output_tokens?: number | undefined;
|
|
240
|
+
} | undefined;
|
|
241
|
+
}>>;
|
|
242
|
+
}, "strip", z.ZodTypeAny, {
|
|
243
|
+
type?: string | undefined;
|
|
244
|
+
message?: {
|
|
245
|
+
usage?: {
|
|
246
|
+
input_tokens?: number | undefined;
|
|
247
|
+
cache_creation_input_tokens?: number | undefined;
|
|
248
|
+
cache_read_input_tokens?: number | undefined;
|
|
249
|
+
output_tokens?: number | undefined;
|
|
250
|
+
} | undefined;
|
|
251
|
+
} | undefined;
|
|
252
|
+
}, {
|
|
253
|
+
type?: string | undefined;
|
|
254
|
+
message?: {
|
|
255
|
+
usage?: {
|
|
256
|
+
input_tokens?: number | undefined;
|
|
257
|
+
cache_creation_input_tokens?: number | undefined;
|
|
258
|
+
cache_read_input_tokens?: number | undefined;
|
|
259
|
+
output_tokens?: number | undefined;
|
|
260
|
+
} | undefined;
|
|
261
|
+
} | undefined;
|
|
262
|
+
}>;
|
|
176
263
|
/**
|
|
177
264
|
* Type definition for Claude usage data entries from JSONL files
|
|
178
265
|
*/
|
|
@@ -696,6 +783,17 @@ declare function loadSessionUsageById(sessionId: string, options?: {
|
|
|
696
783
|
entries: UsageData[];
|
|
697
784
|
} | null>;
|
|
698
785
|
declare function loadBucketUsageData(groupingFn: (data: DailyUsage) => Bucket, options?: LoadOptions): Promise<BucketUsage[]>;
|
|
786
|
+
/**
|
|
787
|
+
* Calculate context tokens from transcript file using improved JSONL parsing
|
|
788
|
+
* Based on the Python reference implementation for better accuracy
|
|
789
|
+
* @param transcriptPath - Path to the transcript JSONL file
|
|
790
|
+
* @returns Object with context tokens info or null if unavailable
|
|
791
|
+
*/
|
|
792
|
+
declare function calculateContextTokens(transcriptPath: string): Promise<{
|
|
793
|
+
inputTokens: number;
|
|
794
|
+
percentage: number;
|
|
795
|
+
contextLimit: number;
|
|
796
|
+
} | null>;
|
|
699
797
|
/**
|
|
700
798
|
* Loads usage data and organizes it into session blocks (typically 5-hour billing periods)
|
|
701
799
|
* Processes all usage data and groups it into time-based blocks for billing analysis
|
|
@@ -704,4 +802,4 @@ declare function loadBucketUsageData(groupingFn: (data: DailyUsage) => Bucket, o
|
|
|
704
802
|
*/
|
|
705
803
|
declare function loadSessionBlockData(options?: LoadOptions): Promise<SessionBlock[]>;
|
|
706
804
|
//#endregion
|
|
707
|
-
export { BucketUsage, DailyUsage, DateFilter, GlobResult, LoadOptions, ModelBreakdown, MonthlyUsage, SessionUsage, UsageData, WeeklyUsage, bucketUsageSchema, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, usageDataSchema, weeklyUsageSchema };
|
|
805
|
+
export { BucketUsage, DailyUsage, DateFilter, GlobResult, LoadOptions, ModelBreakdown, MonthlyUsage, SessionUsage, UsageData, WeeklyUsage, bucketUsageSchema, calculateContextTokens, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, transcriptMessageSchema, transcriptUsageSchema, usageDataSchema, weeklyUsageSchema };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_RECENT_DAYS, PricingFetcher, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR, __commonJSMin, __require, __toESM, isFailure, isPromise, require_usingCtx } from "./pricing-fetcher-
|
|
1
|
+
import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, CONTEXT_LIMIT, CONTEXT_LOW_THRESHOLD_ENV, CONTEXT_MEDIUM_THRESHOLD_ENV, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_CONTEXT_USAGE_THRESHOLDS, DEFAULT_RECENT_DAYS, PricingFetcher, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR, __commonJSMin, __require, __toESM, isFailure, isPromise, require_usingCtx } from "./pricing-fetcher-BtJtc54j.js";
|
|
2
2
|
import { getTotalTokens } from "./_token-utils-WjkbrjKv.js";
|
|
3
3
|
import { activityDateSchema, arrayType, booleanType, createBucket, createDailyDate, createMonthlyDate, createProjectPath, createSessionId, createWeeklyDate, dailyDateSchema, isoTimestampSchema, messageIdSchema, modelNameSchema, monthlyDateSchema, numberType, objectType, projectPathSchema, requestIdSchema, sessionIdSchema, stringType, unionType, versionSchema, weeklyDateSchema } from "./_types-C0oFKDO-.js";
|
|
4
|
-
import { logger } from "./logger-
|
|
4
|
+
import { logger } from "./logger-B42xzUl2.js";
|
|
5
5
|
import a, { readFile } from "node:fs/promises";
|
|
6
6
|
import path, { posix } from "node:path";
|
|
7
7
|
import process$1 from "node:process";
|
|
@@ -2201,6 +2201,23 @@ function getClaudePaths() {
|
|
|
2201
2201
|
- Or set ${CLAUDE_CONFIG_DIR_ENV} environment variable to valid directory path(s) containing a '${CLAUDE_PROJECTS_DIR_NAME}' subdirectory`.trim());
|
|
2202
2202
|
return paths;
|
|
2203
2203
|
}
|
|
2204
|
+
function getContextUsageThresholds() {
|
|
2205
|
+
const lowThresholdStr = process$1.env[CONTEXT_LOW_THRESHOLD_ENV], mediumThresholdStr = process$1.env[CONTEXT_MEDIUM_THRESHOLD_ENV];
|
|
2206
|
+
let lowThreshold = DEFAULT_CONTEXT_USAGE_THRESHOLDS.LOW, mediumThreshold = DEFAULT_CONTEXT_USAGE_THRESHOLDS.MEDIUM;
|
|
2207
|
+
if (lowThresholdStr != null) {
|
|
2208
|
+
const parsed = Number.parseInt(lowThresholdStr, 10);
|
|
2209
|
+
if (!Number.isNaN(parsed)) lowThreshold = Math.max(0, Math.min(100, parsed));
|
|
2210
|
+
}
|
|
2211
|
+
if (mediumThresholdStr != null) {
|
|
2212
|
+
const parsed = Number.parseInt(mediumThresholdStr, 10);
|
|
2213
|
+
if (!Number.isNaN(parsed)) mediumThreshold = Math.max(0, Math.min(100, parsed));
|
|
2214
|
+
}
|
|
2215
|
+
if (lowThreshold >= mediumThreshold) lowThreshold = DEFAULT_CONTEXT_USAGE_THRESHOLDS.LOW, mediumThreshold = DEFAULT_CONTEXT_USAGE_THRESHOLDS.MEDIUM;
|
|
2216
|
+
return {
|
|
2217
|
+
LOW: lowThreshold,
|
|
2218
|
+
MEDIUM: mediumThreshold
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2204
2221
|
function extractProjectFromPath(jsonlPath) {
|
|
2205
2222
|
const normalizedPath = jsonlPath.replace(/[/\\]/g, path.sep), segments = normalizedPath.split(path.sep), projectsIndex = segments.findIndex((segment) => segment === CLAUDE_PROJECTS_DIR_NAME);
|
|
2206
2223
|
if (projectsIndex === -1 || projectsIndex + 1 >= segments.length) return "unknown";
|
|
@@ -2226,6 +2243,14 @@ const usageDataSchema = objectType({
|
|
|
2226
2243
|
costUSD: numberType().optional(),
|
|
2227
2244
|
requestId: requestIdSchema.optional(),
|
|
2228
2245
|
isApiErrorMessage: booleanType().optional()
|
|
2246
|
+
}), transcriptUsageSchema = objectType({
|
|
2247
|
+
input_tokens: numberType().optional(),
|
|
2248
|
+
cache_creation_input_tokens: numberType().optional(),
|
|
2249
|
+
cache_read_input_tokens: numberType().optional(),
|
|
2250
|
+
output_tokens: numberType().optional()
|
|
2251
|
+
}), transcriptMessageSchema = objectType({
|
|
2252
|
+
type: stringType().optional(),
|
|
2253
|
+
message: objectType({ usage: transcriptUsageSchema.optional() }).optional()
|
|
2229
2254
|
}), modelBreakdownSchema = objectType({
|
|
2230
2255
|
modelName: modelNameSchema,
|
|
2231
2256
|
inputTokens: numberType(),
|
|
@@ -2599,7 +2624,7 @@ async function loadWeeklyUsageData(options) {
|
|
|
2599
2624
|
async function loadSessionUsageById(sessionId, options) {
|
|
2600
2625
|
try {
|
|
2601
2626
|
var _usingCtx4 = (0, import_usingCtx.default)();
|
|
2602
|
-
const claudePaths = getClaudePaths(), patterns = claudePaths.map((p) => path.join(p, "projects", "**", `${sessionId}.jsonl`)), jsonlFiles = await glob(patterns);
|
|
2627
|
+
const claudePaths = getClaudePaths(), patterns = claudePaths.map((p) => path.join(p, "projects", "**", `${sessionId}.jsonl`).replace(/\\/g, "/")), jsonlFiles = await glob(patterns);
|
|
2603
2628
|
if (jsonlFiles.length === 0) return null;
|
|
2604
2629
|
const file = jsonlFiles[0];
|
|
2605
2630
|
if (file == null) return null;
|
|
@@ -2644,6 +2669,35 @@ async function loadBucketUsageData(groupingFn, options) {
|
|
|
2644
2669
|
}
|
|
2645
2670
|
return sortByDate(buckets, (item) => item.bucket, options?.order);
|
|
2646
2671
|
}
|
|
2672
|
+
async function calculateContextTokens(transcriptPath) {
|
|
2673
|
+
let content;
|
|
2674
|
+
try {
|
|
2675
|
+
content = await readFile(transcriptPath, "utf-8");
|
|
2676
|
+
} catch (error) {
|
|
2677
|
+
return logger.debug(`Failed to read transcript file: ${String(error)}`), null;
|
|
2678
|
+
}
|
|
2679
|
+
const lines = content.split("\n").reverse();
|
|
2680
|
+
for (const line of lines) {
|
|
2681
|
+
const trimmedLine = line.trim();
|
|
2682
|
+
if (trimmedLine === "") continue;
|
|
2683
|
+
try {
|
|
2684
|
+
const parsed = JSON.parse(trimmedLine), result = transcriptMessageSchema.safeParse(parsed);
|
|
2685
|
+
if (!result.success) continue;
|
|
2686
|
+
const obj = result.data;
|
|
2687
|
+
if (obj.type === "assistant" && obj.message != null && obj.message.usage != null && obj.message.usage.input_tokens != null) {
|
|
2688
|
+
const usage = obj.message.usage, inputTokens = usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0), percentage = Math.min(100, Math.max(0, Math.round(inputTokens / CONTEXT_LIMIT * 100)));
|
|
2689
|
+
return {
|
|
2690
|
+
inputTokens,
|
|
2691
|
+
percentage,
|
|
2692
|
+
contextLimit: CONTEXT_LIMIT
|
|
2693
|
+
};
|
|
2694
|
+
}
|
|
2695
|
+
} catch {
|
|
2696
|
+
continue;
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
return logger.debug("No usage information found in transcript"), null;
|
|
2700
|
+
}
|
|
2647
2701
|
async function loadSessionBlockData(options) {
|
|
2648
2702
|
try {
|
|
2649
2703
|
var _usingCtx5 = (0, import_usingCtx.default)();
|
|
@@ -2694,4 +2748,4 @@ async function loadSessionBlockData(options) {
|
|
|
2694
2748
|
_usingCtx5.d();
|
|
2695
2749
|
}
|
|
2696
2750
|
}
|
|
2697
|
-
export { DEFAULT_SESSION_DURATION_HOURS, bucketUsageSchema, calculateBurnRate, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, filterRecentBlocks, formatDate, formatDateCompact, getClaudePaths, getEarliestTimestamp, getUsageLimitResetTime, glob, globUsageFiles, identifySessionBlocks, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, projectBlockUsage, sessionUsageSchema, sortFilesByTimestamp, uniq, unwrap, usageDataSchema, weeklyUsageSchema };
|
|
2751
|
+
export { DEFAULT_SESSION_DURATION_HOURS, bucketUsageSchema, calculateBurnRate, calculateContextTokens, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, filterRecentBlocks, formatDate, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, glob, globUsageFiles, identifySessionBlocks, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, projectBlockUsage, sessionUsageSchema, sortFilesByTimestamp, transcriptMessageSchema, transcriptUsageSchema, uniq, unwrap, usageDataSchema, weeklyUsageSchema };
|
package/dist/data-loader.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import "./pricing-fetcher-B5m_kEpz.js";
|
|
2
|
-
import { BucketUsage, DailyUsage, DateFilter, GlobResult, LoadOptions, ModelBreakdown, MonthlyUsage, SessionUsage, UsageData, WeeklyUsage, bucketUsageSchema, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, usageDataSchema, weeklyUsageSchema } from "./data-loader-
|
|
3
|
-
export { BucketUsage, DailyUsage, DateFilter, GlobResult, LoadOptions, ModelBreakdown, MonthlyUsage, SessionUsage, UsageData, WeeklyUsage, bucketUsageSchema, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, usageDataSchema, weeklyUsageSchema };
|
|
2
|
+
import { BucketUsage, DailyUsage, DateFilter, GlobResult, LoadOptions, ModelBreakdown, MonthlyUsage, SessionUsage, UsageData, WeeklyUsage, bucketUsageSchema, calculateContextTokens, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, transcriptMessageSchema, transcriptUsageSchema, usageDataSchema, weeklyUsageSchema } from "./data-loader-BPepPoPg.js";
|
|
3
|
+
export { BucketUsage, DailyUsage, DateFilter, GlobResult, LoadOptions, ModelBreakdown, MonthlyUsage, SessionUsage, UsageData, WeeklyUsage, bucketUsageSchema, calculateContextTokens, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, transcriptMessageSchema, transcriptUsageSchema, usageDataSchema, weeklyUsageSchema };
|
package/dist/data-loader.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "./pricing-fetcher-
|
|
1
|
+
import "./pricing-fetcher-BtJtc54j.js";
|
|
2
2
|
import "./_token-utils-WjkbrjKv.js";
|
|
3
3
|
import "./_types-C0oFKDO-.js";
|
|
4
|
-
import { bucketUsageSchema, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, usageDataSchema, weeklyUsageSchema } from "./data-loader-
|
|
5
|
-
import "./logger-
|
|
6
|
-
export { bucketUsageSchema, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, usageDataSchema, weeklyUsageSchema };
|
|
4
|
+
import { bucketUsageSchema, calculateContextTokens, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, transcriptMessageSchema, transcriptUsageSchema, usageDataSchema, weeklyUsageSchema } from "./data-loader-C_o-3Ju1.js";
|
|
5
|
+
import "./logger-B42xzUl2.js";
|
|
6
|
+
export { bucketUsageSchema, calculateContextTokens, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, formatDate, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, sessionUsageSchema, sortFilesByTimestamp, transcriptMessageSchema, transcriptUsageSchema, usageDataSchema, weeklyUsageSchema };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { CLAUDE_PROJECTS_DIR_NAME, DEBUG_MATCH_THRESHOLD_PERCENT, PricingFetcher, USAGE_DATA_GLOB_PATTERN, __toESM, isFailure, require_usingCtx, try_ } from "./pricing-fetcher-
|
|
2
|
-
import { getClaudePaths, glob, unwrap, usageDataSchema } from "./data-loader-
|
|
3
|
-
import { logger } from "./logger-
|
|
1
|
+
import { CLAUDE_PROJECTS_DIR_NAME, DEBUG_MATCH_THRESHOLD_PERCENT, PricingFetcher, USAGE_DATA_GLOB_PATTERN, __toESM, isFailure, require_usingCtx, try_ } from "./pricing-fetcher-BtJtc54j.js";
|
|
2
|
+
import { getClaudePaths, glob, unwrap, usageDataSchema } from "./data-loader-C_o-3Ju1.js";
|
|
3
|
+
import { logger } from "./logger-B42xzUl2.js";
|
|
4
4
|
import { readFile } from "node:fs/promises";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
var import_usingCtx = /* @__PURE__ */ __toESM(require_usingCtx(), 1);
|
package/dist/debug.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import "./pricing-fetcher-
|
|
1
|
+
import "./pricing-fetcher-BtJtc54j.js";
|
|
2
2
|
import "./_token-utils-WjkbrjKv.js";
|
|
3
3
|
import "./_types-C0oFKDO-.js";
|
|
4
|
-
import "./data-loader-
|
|
5
|
-
import "./logger-
|
|
6
|
-
import { detectMismatches, printMismatchReport } from "./debug-
|
|
4
|
+
import "./data-loader-C_o-3Ju1.js";
|
|
5
|
+
import "./logger-B42xzUl2.js";
|
|
6
|
+
import { detectMismatches, printMismatchReport } from "./debug-DX6e8anz.js";
|
|
7
7
|
export { detectMismatches, printMismatchReport };
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, BURN_RATE_THRESHOLDS, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, MAX_REFRESH_INTERVAL_SECONDS, MCP_DEFAULT_PORT, MIN_REFRESH_INTERVAL_SECONDS, MIN_RENDER_INTERVAL_MS, PROJECT_ALIASES_ENV, PricingFetcher, WEEK_DAYS, __commonJSMin, __require, __toESM, isFailure, require_usingCtx, try_ } from "./pricing-fetcher-
|
|
2
|
+
import { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, BURN_RATE_THRESHOLDS, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, MAX_REFRESH_INTERVAL_SECONDS, MCP_DEFAULT_PORT, MIN_REFRESH_INTERVAL_SECONDS, MIN_RENDER_INTERVAL_MS, PROJECT_ALIASES_ENV, PricingFetcher, WEEK_DAYS, __commonJSMin, __require, __toESM, inspectError, isFailure, map, pipe, require_usingCtx, try_ } from "./pricing-fetcher-BtJtc54j.js";
|
|
3
3
|
import { getTotalTokens } from "./_token-utils-WjkbrjKv.js";
|
|
4
4
|
import { CostModes, SortOrders, filterDateSchema, statuslineHookJsonSchema } from "./_types-C0oFKDO-.js";
|
|
5
5
|
import { calculateTotals, createTotalsObject } from "./calculate-cost-BDqO4yWA.js";
|
|
6
|
-
import { DEFAULT_SESSION_DURATION_HOURS, calculateBurnRate, calculateCostForEntry, createUniqueHash, filterRecentBlocks, formatDateCompact, getClaudePaths, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, identifySessionBlocks, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, projectBlockUsage, sortFilesByTimestamp, uniq, usageDataSchema } from "./data-loader-
|
|
7
|
-
import { description, log, logger, name, version } from "./logger-
|
|
8
|
-
import { detectMismatches, printMismatchReport } from "./debug-
|
|
9
|
-
import { createMcpHttpApp, createMcpServer, startMcpServerStdio } from "./mcp-
|
|
6
|
+
import { DEFAULT_SESSION_DURATION_HOURS, calculateBurnRate, calculateContextTokens, calculateCostForEntry, createUniqueHash, filterRecentBlocks, formatDateCompact, getClaudePaths, getContextUsageThresholds, getEarliestTimestamp, getUsageLimitResetTime, globUsageFiles, identifySessionBlocks, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, projectBlockUsage, sortFilesByTimestamp, uniq, unwrap, usageDataSchema } from "./data-loader-C_o-3Ju1.js";
|
|
7
|
+
import { description, log, logger, name, version } from "./logger-B42xzUl2.js";
|
|
8
|
+
import { detectMismatches, printMismatchReport } from "./debug-DX6e8anz.js";
|
|
9
|
+
import { createMcpHttpApp, createMcpServer, startMcpServerStdio } from "./mcp-DsGPnOCJ.js";
|
|
10
10
|
import a, { readFile } from "node:fs/promises";
|
|
11
11
|
import path from "node:path";
|
|
12
12
|
import process$1 from "node:process";
|
|
@@ -815,7 +815,7 @@ var require_picocolors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
815
815
|
};
|
|
816
816
|
};
|
|
817
817
|
module.exports = createColors(), module.exports.createColors = createColors;
|
|
818
|
-
}));
|
|
818
|
+
})), import_picocolors$8 = /* @__PURE__ */ __toESM(require_picocolors(), 1);
|
|
819
819
|
const getContext = (raw) => ({
|
|
820
820
|
start: process$1.hrtime.bigint(),
|
|
821
821
|
command: raw.map((part) => getCommandPart(stripVTControlCharacters(part))).join(" "),
|
|
@@ -1893,15 +1893,15 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
1893
1893
|
} };
|
|
1894
1894
|
}), ret;
|
|
1895
1895
|
}
|
|
1896
|
-
var sequencer = function sequencer$1(map$
|
|
1896
|
+
var sequencer = function sequencer$1(map$2, str) {
|
|
1897
1897
|
var exploded = str.split("");
|
|
1898
|
-
return exploded = exploded.map(map$
|
|
1898
|
+
return exploded = exploded.map(map$2), exploded.join("");
|
|
1899
1899
|
};
|
|
1900
|
-
for (var map in colors$1.trap = require_trap(), colors$1.zalgo = require_zalgo(), colors$1.maps = {}, colors$1.maps.america = require_america()(colors$1), colors$1.maps.zebra = require_zebra()(colors$1), colors$1.maps.rainbow = require_rainbow()(colors$1), colors$1.maps.random = require_random()(colors$1), colors$1.maps) (function(map$
|
|
1901
|
-
colors$1[map$
|
|
1902
|
-
return sequencer(colors$1.maps[map$
|
|
1900
|
+
for (var map$1 in colors$1.trap = require_trap(), colors$1.zalgo = require_zalgo(), colors$1.maps = {}, colors$1.maps.america = require_america()(colors$1), colors$1.maps.zebra = require_zebra()(colors$1), colors$1.maps.rainbow = require_rainbow()(colors$1), colors$1.maps.random = require_random()(colors$1), colors$1.maps) (function(map$2) {
|
|
1901
|
+
colors$1[map$2] = function(str) {
|
|
1902
|
+
return sequencer(colors$1.maps[map$2], str);
|
|
1903
1903
|
};
|
|
1904
|
-
})(map);
|
|
1904
|
+
})(map$1);
|
|
1905
1905
|
defineProps(colors$1, init());
|
|
1906
1906
|
})), require_safe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
1907
1907
|
var colors = require_colors();
|
|
@@ -2320,7 +2320,7 @@ var require_debug$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
2320
2320
|
module.exports = Table$1;
|
|
2321
2321
|
})), require_cli_table3 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
2322
2322
|
module.exports = require_table();
|
|
2323
|
-
}));
|
|
2323
|
+
})), import_cli_table3 = /* @__PURE__ */ __toESM(require_cli_table3(), 1);
|
|
2324
2324
|
function ansiRegex({ onlyFirst = false } = {}) {
|
|
2325
2325
|
const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)", pattern = [`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?${ST})`, "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
|
|
2326
2326
|
return new RegExp(pattern, onlyFirst ? void 0 : "g");
|
|
@@ -2369,7 +2369,7 @@ function stringWidth(string, options = {}) {
|
|
|
2369
2369
|
}
|
|
2370
2370
|
return width;
|
|
2371
2371
|
}
|
|
2372
|
-
var
|
|
2372
|
+
var ResponsiveTable = class {
|
|
2373
2373
|
head;
|
|
2374
2374
|
rows = [];
|
|
2375
2375
|
colAligns;
|
|
@@ -2558,10 +2558,10 @@ function delay(ms, options = {}) {
|
|
|
2558
2558
|
const { signal, persistent = true } = options;
|
|
2559
2559
|
return signal?.aborted ? Promise.reject(signal.reason) : new Promise((resolve, reject) => {
|
|
2560
2560
|
const abort = () => {
|
|
2561
|
-
clearTimeout(i), reject(signal?.reason);
|
|
2561
|
+
clearTimeout(+i), reject(signal?.reason);
|
|
2562
2562
|
}, done = () => {
|
|
2563
2563
|
signal?.removeEventListener("abort", abort), resolve();
|
|
2564
|
-
}, i =
|
|
2564
|
+
}, i = setArbitraryLengthTimeout(done, ms);
|
|
2565
2565
|
if (signal?.addEventListener("abort", abort, { once: true }), persistent === false) try {
|
|
2566
2566
|
Deno.unrefTimer(i);
|
|
2567
2567
|
} catch (error) {
|
|
@@ -2570,6 +2570,16 @@ function delay(ms, options = {}) {
|
|
|
2570
2570
|
}
|
|
2571
2571
|
});
|
|
2572
2572
|
}
|
|
2573
|
+
const I32_MAX = 2 ** 31 - 1;
|
|
2574
|
+
function setArbitraryLengthTimeout(callback, delay$1) {
|
|
2575
|
+
let currentDelay = delay$1 = Math.trunc(Math.max(delay$1, 0) || 0);
|
|
2576
|
+
const start = Date.now();
|
|
2577
|
+
let timeoutId;
|
|
2578
|
+
const queueTimeout = () => {
|
|
2579
|
+
currentDelay = delay$1 - (Date.now() - start), timeoutId = currentDelay > I32_MAX ? setTimeout(queueTimeout, I32_MAX) : setTimeout(callback, currentDelay);
|
|
2580
|
+
};
|
|
2581
|
+
return queueTimeout(), { valueOf: () => timeoutId };
|
|
2582
|
+
}
|
|
2573
2583
|
const isBrowser = globalThis.window?.document !== void 0, isNode = globalThis.process?.versions?.node !== void 0, isBun = globalThis.process?.versions?.bun !== void 0, isDeno = globalThis.Deno?.version?.deno !== void 0, isElectron = globalThis.process?.versions?.electron !== void 0, isJsDom = globalThis.navigator?.userAgent?.includes("jsdom") === true, isWebWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope, isDedicatedWorker = typeof DedicatedWorkerGlobalScope !== "undefined" && globalThis instanceof DedicatedWorkerGlobalScope, isSharedWorker = typeof SharedWorkerGlobalScope !== "undefined" && globalThis instanceof SharedWorkerGlobalScope, isServiceWorker = typeof ServiceWorkerGlobalScope !== "undefined" && globalThis instanceof ServiceWorkerGlobalScope, platform = globalThis.navigator?.userAgentData?.platform, isMacOs = platform === "macOS" || globalThis.navigator?.platform === "MacIntel" || globalThis.navigator?.userAgent?.includes(" Mac ") === true || globalThis.process?.platform === "darwin", isWindows$1 = platform === "Windows" || globalThis.navigator?.platform === "Win32" || globalThis.process?.platform === "win32", isLinux = platform === "Linux" || globalThis.navigator?.platform?.startsWith("Linux") === true || globalThis.navigator?.userAgent?.includes(" Linux ") === true || globalThis.process?.platform === "linux", isIos = platform === "iOS" || globalThis.navigator?.platform === "MacIntel" && globalThis.navigator?.maxTouchPoints > 1 || /iPad|iPhone|iPod/.test(globalThis.navigator?.platform), isAndroid = platform === "Android" || globalThis.navigator?.platform === "Android" || globalThis.navigator?.userAgent?.includes(" Android ") === true || globalThis.process?.platform === "android", ESC = "\x1B[", SEP = ";", isTerminalApp = !isBrowser && process$1.env.TERM_PROGRAM === "Apple_Terminal", isWindows = !isBrowser && process$1.platform === "win32", cwdFunction = isBrowser ? () => {
|
|
2574
2584
|
throw new Error("`process.cwd()` only works in Node.js, not the browser.");
|
|
2575
2585
|
} : process$1.cwd, cursorTo = (x, y) => {
|
|
@@ -3702,26 +3712,29 @@ var outgoingEnded = Symbol("outgoingEnded"), handleRequestError = () => new Resp
|
|
|
3702
3712
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
3703
3713
|
if (res.body) {
|
|
3704
3714
|
const reader = res.body.getReader(), values = [];
|
|
3705
|
-
let done = false, currentReadPromise = void 0
|
|
3706
|
-
|
|
3707
|
-
|
|
3708
|
-
|
|
3709
|
-
|
|
3710
|
-
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
|
|
3715
|
+
let done = false, currentReadPromise = void 0;
|
|
3716
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
3717
|
+
let maxReadCount = 2;
|
|
3718
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
3719
|
+
currentReadPromise ||= reader.read();
|
|
3720
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
3721
|
+
console.error(e), done = true;
|
|
3722
|
+
});
|
|
3723
|
+
if (!chunk) {
|
|
3724
|
+
if (i === 1) {
|
|
3725
|
+
await new Promise((resolve) => setTimeout(resolve)), maxReadCount = 3;
|
|
3726
|
+
continue;
|
|
3727
|
+
}
|
|
3728
|
+
break;
|
|
3729
|
+
}
|
|
3730
|
+
if (currentReadPromise = void 0, chunk.value) values.push(chunk.value);
|
|
3731
|
+
if (chunk.done) {
|
|
3732
|
+
done = true;
|
|
3733
|
+
break;
|
|
3715
3734
|
}
|
|
3716
|
-
break;
|
|
3717
|
-
}
|
|
3718
|
-
if (currentReadPromise = void 0, chunk.value) values.push(chunk.value);
|
|
3719
|
-
if (chunk.done) {
|
|
3720
|
-
done = true;
|
|
3721
|
-
break;
|
|
3722
3735
|
}
|
|
3736
|
+
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
3723
3737
|
}
|
|
3724
|
-
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
3725
3738
|
if (outgoing.writeHead(res.status, resHeaderRecord), values.forEach((value) => {
|
|
3726
3739
|
outgoing.write(value);
|
|
3727
3740
|
}), done) outgoing.end();
|
|
@@ -4221,62 +4234,65 @@ const statuslineCommand = define({
|
|
|
4221
4234
|
if (!hookDataParseResult.success) log("❌ Invalid input format:", hookDataParseResult.error.message), process$1.exit(1);
|
|
4222
4235
|
const hookData = hookDataParseResult.data, claudePaths = getClaudePaths();
|
|
4223
4236
|
if (claudePaths.length === 0) log("❌ No Claude data directory found"), process$1.exit(1);
|
|
4224
|
-
const sessionId = hookData.session_id
|
|
4225
|
-
|
|
4226
|
-
try {
|
|
4227
|
-
const sessionData = await loadSessionUsageById(sessionId, {
|
|
4237
|
+
const sessionId = hookData.session_id, sessionCost = await pipe(try_({
|
|
4238
|
+
try: loadSessionUsageById(sessionId, {
|
|
4228
4239
|
mode: "auto",
|
|
4229
4240
|
offline: ctx.values.offline
|
|
4230
|
-
})
|
|
4231
|
-
|
|
4232
|
-
}
|
|
4233
|
-
|
|
4234
|
-
}
|
|
4235
|
-
const today = /* @__PURE__ */ new Date(), todayStr = today.toISOString().split("T")[0]?.replace(/-/g, "") ?? "";
|
|
4236
|
-
let todayCost = 0;
|
|
4237
|
-
try {
|
|
4238
|
-
const dailyData = await loadDailyUsageData({
|
|
4241
|
+
}),
|
|
4242
|
+
catch: (error) => error
|
|
4243
|
+
}), map((sessionCost$1) => sessionCost$1?.totalCost), inspectError((error) => logger.error("Failed to load session data:", error)), unwrap(void 0)), today = /* @__PURE__ */ new Date(), todayStr = today.toISOString().split("T")[0]?.replace(/-/g, "") ?? "", todayCost = await pipe(try_({
|
|
4244
|
+
try: loadDailyUsageData({
|
|
4239
4245
|
since: todayStr,
|
|
4240
4246
|
until: todayStr,
|
|
4241
4247
|
mode: "auto",
|
|
4242
4248
|
offline: ctx.values.offline
|
|
4243
|
-
})
|
|
4249
|
+
}),
|
|
4250
|
+
catch: (error) => error
|
|
4251
|
+
}), map((dailyData) => {
|
|
4244
4252
|
if (dailyData.length > 0) {
|
|
4245
4253
|
const totals = calculateTotals(dailyData);
|
|
4246
|
-
|
|
4254
|
+
return totals.totalCost;
|
|
4247
4255
|
}
|
|
4248
|
-
|
|
4249
|
-
|
|
4250
|
-
|
|
4251
|
-
let blockInfo = "", burnRateInfo = "";
|
|
4252
|
-
try {
|
|
4253
|
-
const blocks = await loadSessionBlockData({
|
|
4256
|
+
return 0;
|
|
4257
|
+
}), inspectError((error) => logger.error("Failed to load daily data:", error)), unwrap(0)), { blockInfo, burnRateInfo } = await pipe(try_({
|
|
4258
|
+
try: loadSessionBlockData({
|
|
4254
4259
|
mode: "auto",
|
|
4255
4260
|
offline: ctx.values.offline
|
|
4261
|
+
}),
|
|
4262
|
+
catch: (error) => error
|
|
4263
|
+
}), map((blocks) => {
|
|
4264
|
+
if (blocks.length === 0) return {
|
|
4265
|
+
blockInfo: "No active block",
|
|
4266
|
+
burnRateInfo: ""
|
|
4267
|
+
};
|
|
4268
|
+
const activeBlock = blocks.find((block) => {
|
|
4269
|
+
return !!block.isActive;
|
|
4256
4270
|
});
|
|
4257
|
-
if (
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
return
|
|
4261
|
-
});
|
|
4262
|
-
|
|
4263
|
-
|
|
4264
|
-
|
|
4265
|
-
|
|
4266
|
-
if (burnRate != null) {
|
|
4267
|
-
const costPerHour = burnRate.costPerHour, costPerHourStr = `${formatCurrency(costPerHour)}/hr`;
|
|
4268
|
-
let coloredBurnRate = costPerHourStr;
|
|
4269
|
-
if (burnRate.tokensPerMinuteForIndicator < 2e3) coloredBurnRate = import_picocolors$1.default.green(costPerHourStr);
|
|
4270
|
-
else if (burnRate.tokensPerMinuteForIndicator < 5e3) coloredBurnRate = import_picocolors$1.default.yellow(costPerHourStr);
|
|
4271
|
-
else coloredBurnRate = import_picocolors$1.default.red(costPerHourStr);
|
|
4272
|
-
burnRateInfo = ` | 🔥 ${coloredBurnRate}`;
|
|
4273
|
-
}
|
|
4274
|
-
} else blockInfo = "No active block";
|
|
4271
|
+
if (activeBlock != null) {
|
|
4272
|
+
const now = /* @__PURE__ */ new Date(), remaining = Math.round((activeBlock.endTime.getTime() - now.getTime()) / (1e3 * 60)), blockCost = activeBlock.costUSD, blockInfo$1 = `${formatCurrency(blockCost)} block (${formatRemainingTime(remaining)})`, burnRate = calculateBurnRate(activeBlock), burnRateInfo$1 = burnRate != null ? (() => {
|
|
4273
|
+
const costPerHour = burnRate.costPerHour, costPerHourStr = `${formatCurrency(costPerHour)}/hr`, coloredBurnRate = burnRate.tokensPerMinuteForIndicator < 2e3 ? import_picocolors$1.default.green(costPerHourStr) : burnRate.tokensPerMinuteForIndicator < 5e3 ? import_picocolors$1.default.yellow(costPerHourStr) : import_picocolors$1.default.red(costPerHourStr);
|
|
4274
|
+
return ` | 🔥 ${coloredBurnRate}`;
|
|
4275
|
+
})() : "";
|
|
4276
|
+
return {
|
|
4277
|
+
blockInfo: blockInfo$1,
|
|
4278
|
+
burnRateInfo: burnRateInfo$1
|
|
4279
|
+
};
|
|
4275
4280
|
}
|
|
4276
|
-
|
|
4277
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4281
|
+
return {
|
|
4282
|
+
blockInfo: "No active block",
|
|
4283
|
+
burnRateInfo: ""
|
|
4284
|
+
};
|
|
4285
|
+
}), inspectError((error) => logger.error("Failed to load block data:", error)), unwrap({
|
|
4286
|
+
blockInfo: "No active block",
|
|
4287
|
+
burnRateInfo: ""
|
|
4288
|
+
})), contextInfo = await pipe(try_({
|
|
4289
|
+
try: calculateContextTokens(hookData.transcript_path),
|
|
4290
|
+
catch: (error) => error
|
|
4291
|
+
}), inspectError((error) => logger.debug(`Failed to calculate context tokens: ${error instanceof Error ? error.message : String(error)}`)), map((ctx$1) => {
|
|
4292
|
+
if (ctx$1 == null) return void 0;
|
|
4293
|
+
const thresholds = getContextUsageThresholds(), color = ctx$1.percentage < thresholds.LOW ? import_picocolors$1.default.green : ctx$1.percentage < thresholds.MEDIUM ? import_picocolors$1.default.yellow : import_picocolors$1.default.red, coloredPercentage = color(`${ctx$1.percentage}%`), tokenDisplay = ctx$1.inputTokens.toLocaleString();
|
|
4294
|
+
return `${tokenDisplay} (${coloredPercentage})`;
|
|
4295
|
+
}), unwrap(void 0)), modelName = hookData.model.display_name, sessionDisplay = sessionCost != null ? formatCurrency(sessionCost) : "N/A", statusLine = `🤖 ${modelName} | 💰 ${sessionDisplay} session / ${formatCurrency(todayCost)} today / ${blockInfo}${burnRateInfo} | 🧠 ${contextInfo ?? "N/A"}`;
|
|
4280
4296
|
log(statusLine);
|
|
4281
4297
|
}
|
|
4282
4298
|
});
|
|
@@ -4432,3 +4448,4 @@ await cli(process$1.argv.slice(2), mainCommand, {
|
|
|
4432
4448
|
subCommands,
|
|
4433
4449
|
renderHeader: null
|
|
4434
4450
|
});
|
|
4451
|
+
export {};
|
|
@@ -761,7 +761,7 @@ function _getDefaultLogLevel() {
|
|
|
761
761
|
return g ? LogLevels.debug : R ? LogLevels.warn : LogLevels.info;
|
|
762
762
|
}
|
|
763
763
|
const consola = createConsola$1();
|
|
764
|
-
var name = "ccusage", version = "15.9.
|
|
764
|
+
var name = "ccusage", version = "15.9.6", description = "Usage analysis tool for Claude Code";
|
|
765
765
|
const logger = consola.withTag(name);
|
|
766
766
|
if (process$1.env.LOG_LEVEL != null) {
|
|
767
767
|
const level = Number.parseInt(process$1.env.LOG_LEVEL, 10);
|
package/dist/logger.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { log, logger } from "./logger-
|
|
1
|
+
import { log, logger } from "./logger-B42xzUl2.js";
|
|
2
2
|
export { log, logger };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { __commonJSMin, __toESM, require_usingCtx } from "./pricing-fetcher-
|
|
1
|
+
import { __commonJSMin, __toESM, require_usingCtx } from "./pricing-fetcher-BtJtc54j.js";
|
|
2
2
|
import { getTotalTokens } from "./_token-utils-WjkbrjKv.js";
|
|
3
3
|
import { ZodFirstPartyTypeKind, ZodOptional, ZodType, arrayType, booleanType, discriminatedUnionType, enumType, filterDateSchema, literalType, numberType, objectType, optionalType, recordType, stringType, unionType, unknownType } from "./_types-C0oFKDO-.js";
|
|
4
4
|
import { calculateTotals, createTotalsObject } from "./calculate-cost-BDqO4yWA.js";
|
|
5
|
-
import { getClaudePaths, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData } from "./data-loader-
|
|
6
|
-
import { name, version } from "./logger-
|
|
5
|
+
import { getClaudePaths, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData } from "./data-loader-C_o-3Ju1.js";
|
|
6
|
+
import { name, version } from "./logger-B42xzUl2.js";
|
|
7
7
|
import process from "node:process";
|
|
8
8
|
const LATEST_PROTOCOL_VERSION = "2025-06-18", SUPPORTED_PROTOCOL_VERSIONS = [
|
|
9
9
|
LATEST_PROTOCOL_VERSION,
|
package/dist/mcp.d.ts
CHANGED
package/dist/mcp.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import "./pricing-fetcher-
|
|
1
|
+
import "./pricing-fetcher-BtJtc54j.js";
|
|
2
2
|
import "./_token-utils-WjkbrjKv.js";
|
|
3
3
|
import "./_types-C0oFKDO-.js";
|
|
4
4
|
import "./calculate-cost-BDqO4yWA.js";
|
|
5
|
-
import "./data-loader-
|
|
6
|
-
import "./logger-
|
|
7
|
-
import { createMcpHttpApp, createMcpServer, startMcpServerStdio } from "./mcp-
|
|
5
|
+
import "./data-loader-C_o-3Ju1.js";
|
|
6
|
+
import "./logger-B42xzUl2.js";
|
|
7
|
+
import { createMcpHttpApp, createMcpServer, startMcpServerStdio } from "./mcp-DsGPnOCJ.js";
|
|
8
8
|
export { createMcpHttpApp, createMcpServer, startMcpServerStdio };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { modelPricingSchema } from "./_types-C0oFKDO-.js";
|
|
2
|
-
import { logger } from "./logger-
|
|
2
|
+
import { logger } from "./logger-B42xzUl2.js";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import F, { homedir } from "node:os";
|
|
@@ -30,8 +30,9 @@ const isFailure = (result) => "Failure" === result.type, isPromise = (value) =>
|
|
|
30
30
|
};
|
|
31
31
|
return isPromise(result) ? result.then(apply) : apply(result);
|
|
32
32
|
}, isSuccess = (result) => "Success" === result.type, succeed = (...args) => {
|
|
33
|
+
if (args.length <= 0) return { type: "Success" };
|
|
33
34
|
const value = args[0];
|
|
34
|
-
return
|
|
35
|
+
return isPromise(value) ? value.then((value$1) => ({
|
|
35
36
|
type: "Success",
|
|
36
37
|
value: value$1
|
|
37
38
|
})) : {
|
|
@@ -39,8 +40,9 @@ const isFailure = (result) => "Failure" === result.type, isPromise = (value) =>
|
|
|
39
40
|
value
|
|
40
41
|
};
|
|
41
42
|
}, fail = (...args) => {
|
|
43
|
+
if (args.length <= 0) return { type: "Failure" };
|
|
42
44
|
const error = args[0];
|
|
43
|
-
return
|
|
45
|
+
return isPromise(error) ? error.then((error$1) => ({
|
|
44
46
|
type: "Failure",
|
|
45
47
|
error: error$1
|
|
46
48
|
})) : {
|
|
@@ -94,7 +96,10 @@ if (xdgConfig) xdgConfigDirectories.unshift(xdgConfig);
|
|
|
94
96
|
const LITELLM_PRICING_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json", DEFAULT_RECENT_DAYS = 3, BLOCKS_WARNING_THRESHOLD = .8, BLOCKS_COMPACT_WIDTH_THRESHOLD = 120, BLOCKS_DEFAULT_TERMINAL_WIDTH = 120, DEBUG_MATCH_THRESHOLD_PERCENT = .1, USER_HOME_DIR = homedir(), XDG_CONFIG_DIR = xdgConfig ?? `${USER_HOME_DIR}/.config`, DEFAULT_CLAUDE_CODE_PATH = ".claude", DEFAULT_CLAUDE_CONFIG_PATH = `${XDG_CONFIG_DIR}/claude`, CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR", PROJECT_ALIASES_ENV = "CCUSAGE_PROJECT_ALIASES", CLAUDE_PROJECTS_DIR_NAME = "projects", USAGE_DATA_GLOB_PATTERN = "**/*.jsonl", MCP_DEFAULT_PORT = 8080, DEFAULT_REFRESH_INTERVAL_SECONDS = 1, MIN_REFRESH_INTERVAL_SECONDS = 1, MAX_REFRESH_INTERVAL_SECONDS = 60, MIN_RENDER_INTERVAL_MS = 16, BURN_RATE_THRESHOLDS = {
|
|
95
97
|
HIGH: 1e3,
|
|
96
98
|
MODERATE: 500
|
|
97
|
-
},
|
|
99
|
+
}, CONTEXT_LIMIT = 2e5, DEFAULT_CONTEXT_USAGE_THRESHOLDS = {
|
|
100
|
+
LOW: 50,
|
|
101
|
+
MEDIUM: 80
|
|
102
|
+
}, CONTEXT_LOW_THRESHOLD_ENV = "CCUSAGE_CONTEXT_LOW_THRESHOLD", CONTEXT_MEDIUM_THRESHOLD_ENV = "CCUSAGE_CONTEXT_MEDIUM_THRESHOLD", WEEK_DAYS = [
|
|
98
103
|
"sunday",
|
|
99
104
|
"monday",
|
|
100
105
|
"tuesday",
|
|
@@ -339,4 +344,4 @@ var require_usingCtx = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
339
344
|
return cost;
|
|
340
345
|
}
|
|
341
346
|
};
|
|
342
|
-
export { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, BURN_RATE_THRESHOLDS, CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, DEBUG_MATCH_THRESHOLD_PERCENT, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, MAX_REFRESH_INTERVAL_SECONDS, MCP_DEFAULT_PORT, MIN_REFRESH_INTERVAL_SECONDS, MIN_RENDER_INTERVAL_MS, PROJECT_ALIASES_ENV, PricingFetcher, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR, WEEK_DAYS, __commonJSMin, __require, __toESM, isFailure, isPromise, require_usingCtx, try_ };
|
|
347
|
+
export { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, BURN_RATE_THRESHOLDS, CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, CONTEXT_LIMIT, CONTEXT_LOW_THRESHOLD_ENV, CONTEXT_MEDIUM_THRESHOLD_ENV, DEBUG_MATCH_THRESHOLD_PERCENT, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_CONTEXT_USAGE_THRESHOLDS, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, MAX_REFRESH_INTERVAL_SECONDS, MCP_DEFAULT_PORT, MIN_REFRESH_INTERVAL_SECONDS, MIN_RENDER_INTERVAL_MS, PROJECT_ALIASES_ENV, PricingFetcher, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR, WEEK_DAYS, __commonJSMin, __require, __toESM, inspectError, isFailure, isPromise, map, pipe, require_usingCtx, try_ };
|
package/dist/pricing-fetcher.js
CHANGED