@@ -17,7 +17,6 @@ import type {
1717 CostMode ,
1818 ModelName ,
1919 SortOrder ,
20- TranscriptMessage ,
2120 Version ,
2221 WeeklyDate ,
2322} from './_types.ts' ;
@@ -33,7 +32,7 @@ import { createFixture } from 'fs-fixture';
3332import { isDirectorySync } from 'path-type' ;
3433import { glob } from 'tinyglobby' ;
3534import { z } from 'zod' ;
36- import { CLAUDE_CONFIG_DIR_ENV , CLAUDE_PROJECTS_DIR_NAME , CONTEXT_LIMIT , DEFAULT_CLAUDE_CODE_PATH , DEFAULT_CLAUDE_CONFIG_PATH , USAGE_DATA_GLOB_PATTERN , USER_HOME_DIR } from './_consts.ts' ;
35+ 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 , USAGE_DATA_GLOB_PATTERN , USER_HOME_DIR } from './_consts.ts' ;
3736import {
3837 identifySessionBlocks ,
3938} from './_session-blocks.ts' ;
@@ -136,6 +135,22 @@ export function getClaudePaths(): string[] {
136135 return paths ;
137136}
138137
138+ /**
139+ * Get context usage percentage thresholds for color coding
140+ * Can be configured via environment variables or uses defaults
141+ * @returns Context usage thresholds with LOW and MEDIUM percentages
142+ */
143+ export function getContextUsageThresholds ( ) : { readonly LOW : number ; readonly MEDIUM : number } {
144+ // Check environment variables with fallback to defaults
145+ const lowThreshold = process . env [ CONTEXT_LOW_THRESHOLD_ENV ] ;
146+ const mediumThreshold = process . env [ CONTEXT_MEDIUM_THRESHOLD_ENV ] ;
147+
148+ return {
149+ LOW : lowThreshold != null ? Number . parseInt ( lowThreshold , 10 ) : DEFAULT_CONTEXT_USAGE_THRESHOLDS . LOW ,
150+ MEDIUM : mediumThreshold != null ? Number . parseInt ( mediumThreshold , 10 ) : DEFAULT_CONTEXT_USAGE_THRESHOLDS . MEDIUM ,
151+ } as const ;
152+ }
153+
139154/**
140155 * Extract project name from Claude JSONL file path
141156 * @param jsonlPath - Absolute path to JSONL file
@@ -181,6 +196,26 @@ export const usageDataSchema = z.object({
181196 isApiErrorMessage : z . boolean ( ) . optional ( ) ,
182197} ) ;
183198
199+ /**
200+ * Zod schema for transcript usage data from Claude messages
201+ */
202+ export const transcriptUsageSchema = z . object ( {
203+ input_tokens : z . number ( ) . optional ( ) ,
204+ cache_creation_input_tokens : z . number ( ) . optional ( ) ,
205+ cache_read_input_tokens : z . number ( ) . optional ( ) ,
206+ output_tokens : z . number ( ) . optional ( ) ,
207+ } ) ;
208+
209+ /**
210+ * Zod schema for transcript message data
211+ */
212+ export const transcriptMessageSchema = z . object ( {
213+ type : z . string ( ) . optional ( ) ,
214+ message : z . object ( {
215+ usage : transcriptUsageSchema . optional ( ) ,
216+ } ) . optional ( ) ,
217+ } ) ;
218+
184219/**
185220 * Type definition for Claude usage data entries from JSONL files
186221 */
@@ -1365,7 +1400,12 @@ export async function calculateContextTokens(transcriptPath: string): Promise<{
13651400 }
13661401
13671402 try {
1368- const obj = JSON . parse ( trimmedLine ) as TranscriptMessage ;
1403+ const parsed = JSON . parse ( trimmedLine ) as unknown ;
1404+ const result = transcriptMessageSchema . safeParse ( parsed ) ;
1405+ if ( ! result . success ) {
1406+ continue ; // Skip malformed JSON lines
1407+ }
1408+ const obj = result . data ;
13691409
13701410 // Check if this line contains the required token usage fields
13711411 if ( obj . type === 'assistant'
@@ -1397,54 +1437,6 @@ export async function calculateContextTokens(transcriptPath: string): Promise<{
13971437 return null ;
13981438}
13991439
1400- // Test for calculateContextTokens
1401- if ( import . meta. vitest != null ) {
1402- describe ( 'calculateContextTokens' , async ( ) => {
1403- it ( 'returns null when transcript cannot be read' , async ( ) => {
1404- const result = await calculateContextTokens ( '/nonexistent/path.jsonl' ) ;
1405- expect ( result ) . toBeNull ( ) ;
1406- } ) ;
1407- const { createFixture } = await import ( 'fs-fixture' ) ;
1408- it ( 'parses latest assistant line and excludes output tokens' , async ( ) => {
1409- await using fixture = await createFixture ( {
1410- 'transcript.jsonl' : [
1411- JSON . stringify ( { type : 'user' , message : { } } ) ,
1412- JSON . stringify ( { type : 'assistant' , message : { usage : { input_tokens : 1000 , output_tokens : 999 } } } ) ,
1413- JSON . stringify ( { type : 'assistant' , message : { usage : { input_tokens : 2000 , cache_creation_input_tokens : 100 , cache_read_input_tokens : 50 } } } ) ,
1414- ] . join ( '\n' ) ,
1415- } ) ;
1416- const res = await calculateContextTokens ( fixture . getPath ( 'transcript.jsonl' ) ) ;
1417- expect ( res ) . not . toBeNull ( ) ;
1418- // Should pick the last assistant line and exclude output tokens
1419- expect ( res ?. inputTokens ) . toBe ( 2000 + 100 + 50 ) ;
1420- expect ( res ?. percentage ) . toBeGreaterThan ( 0 ) ;
1421- } ) ;
1422-
1423- it ( 'handles missing cache fields gracefully' , async ( ) => {
1424- await using fixture = await createFixture ( {
1425- 'transcript.jsonl' : [
1426- JSON . stringify ( { type : 'assistant' , message : { usage : { input_tokens : 1000 } } } ) ,
1427- ] . join ( '\n' ) ,
1428- } ) ;
1429- const res = await calculateContextTokens ( fixture . getPath ( 'transcript.jsonl' ) ) ;
1430- expect ( res ) . not . toBeNull ( ) ;
1431- expect ( res ?. inputTokens ) . toBe ( 1000 ) ;
1432- expect ( res ?. percentage ) . toBeGreaterThan ( 0 ) ;
1433- } ) ;
1434-
1435- it ( 'clamps percentage to 0-100 range' , async ( ) => {
1436- await using fixture = await createFixture ( {
1437- 'transcript.jsonl' : [
1438- JSON . stringify ( { type : 'assistant' , message : { usage : { input_tokens : 300_000 } } } ) ,
1439- ] . join ( '\n' ) ,
1440- } ) ;
1441- const res = await calculateContextTokens ( fixture . getPath ( 'transcript.jsonl' ) ) ;
1442- expect ( res ) . not . toBeNull ( ) ;
1443- expect ( res ?. percentage ) . toBe ( 100 ) ; // Should be clamped to 100
1444- } ) ;
1445- } ) ;
1446- }
1447-
14481440/**
14491441 * Loads usage data and organizes it into session blocks (typically 5-hour billing periods)
14501442 * Processes all usage data and groups it into time-based blocks for billing analysis
@@ -4681,4 +4673,50 @@ if (import.meta.vitest != null) {
46814673 expect ( results . every ( r => r . baseDir . includes ( 'path1/projects' ) ) ) . toBe ( true ) ;
46824674 } ) ;
46834675 } ) ;
4676+
4677+ // Test for calculateContextTokens
4678+ describe ( 'calculateContextTokens' , async ( ) => {
4679+ it ( 'returns null when transcript cannot be read' , async ( ) => {
4680+ const result = await calculateContextTokens ( '/nonexistent/path.jsonl' ) ;
4681+ expect ( result ) . toBeNull ( ) ;
4682+ } ) ;
4683+ const { createFixture } = await import ( 'fs-fixture' ) ;
4684+ it ( 'parses latest assistant line and excludes output tokens' , async ( ) => {
4685+ await using fixture = await createFixture ( {
4686+ 'transcript.jsonl' : [
4687+ JSON . stringify ( { type : 'user' , message : { } } ) ,
4688+ JSON . stringify ( { type : 'assistant' , message : { usage : { input_tokens : 1000 , output_tokens : 999 } } } ) ,
4689+ JSON . stringify ( { type : 'assistant' , message : { usage : { input_tokens : 2000 , cache_creation_input_tokens : 100 , cache_read_input_tokens : 50 } } } ) ,
4690+ ] . join ( '\n' ) ,
4691+ } ) ;
4692+ const res = await calculateContextTokens ( fixture . getPath ( 'transcript.jsonl' ) ) ;
4693+ expect ( res ) . not . toBeNull ( ) ;
4694+ // Should pick the last assistant line and exclude output tokens
4695+ expect ( res ?. inputTokens ) . toBe ( 2000 + 100 + 50 ) ;
4696+ expect ( res ?. percentage ) . toBeGreaterThan ( 0 ) ;
4697+ } ) ;
4698+
4699+ it ( 'handles missing cache fields gracefully' , async ( ) => {
4700+ await using fixture = await createFixture ( {
4701+ 'transcript.jsonl' : [
4702+ JSON . stringify ( { type : 'assistant' , message : { usage : { input_tokens : 1000 } } } ) ,
4703+ ] . join ( '\n' ) ,
4704+ } ) ;
4705+ const res = await calculateContextTokens ( fixture . getPath ( 'transcript.jsonl' ) ) ;
4706+ expect ( res ) . not . toBeNull ( ) ;
4707+ expect ( res ?. inputTokens ) . toBe ( 1000 ) ;
4708+ expect ( res ?. percentage ) . toBeGreaterThan ( 0 ) ;
4709+ } ) ;
4710+
4711+ it ( 'clamps percentage to 0-100 range' , async ( ) => {
4712+ await using fixture = await createFixture ( {
4713+ 'transcript.jsonl' : [
4714+ JSON . stringify ( { type : 'assistant' , message : { usage : { input_tokens : 300_000 } } } ) ,
4715+ ] . join ( '\n' ) ,
4716+ } ) ;
4717+ const res = await calculateContextTokens ( fixture . getPath ( 'transcript.jsonl' ) ) ;
4718+ expect ( res ) . not . toBeNull ( ) ;
4719+ expect ( res ?. percentage ) . toBe ( 100 ) ; // Should be clamped to 100
4720+ } ) ;
4721+ } ) ;
46844722}
0 commit comments