@@ -1343,16 +1343,16 @@ export async function loadBucketUsageData(
13431343 * @returns Object with context tokens info or null if unavailable
13441344 */
13451345export async function calculateContextTokens ( transcriptPath : string ) : Promise < {
1346- maxInputTokens : number ;
1346+ inputTokens : number ;
13471347 percentage : number ;
13481348 contextLimit : number ;
13491349} | null > {
13501350 let content : string ;
13511351 try {
13521352 content = await readFile ( transcriptPath , 'utf-8' ) ;
13531353 }
1354- catch ( error ) {
1355- logger . debug ( ' Failed to read transcript file:' , error ) ;
1354+ catch ( error : unknown ) {
1355+ logger . debug ( ` Failed to read transcript file: ${ String ( error ) } ` ) ;
13561356 return null ;
13571357 }
13581358
@@ -1364,39 +1364,31 @@ export async function calculateContextTokens(transcriptPath: string): Promise<{
13641364 continue ;
13651365 }
13661366
1367- const parseParser = Result . try ( {
1368- try : ( ) => JSON . parse ( trimmedLine ) as TranscriptMessage ,
1369- catch : ( ) => new Error ( 'Invalid JSON' ) ,
1370- } ) ;
1371- const parseResult = parseParser ( ) ;
1372- if ( Result . isFailure ( parseResult ) ) {
1373- continue ; // Skip malformed JSON lines
1367+ try {
1368+ const obj = JSON . parse ( trimmedLine ) as TranscriptMessage ;
1369+
1370+ // Check if this line contains the required token usage fields
1371+ if ( obj . type === 'assistant'
1372+ && obj . message != null
1373+ && obj . message . usage != null
1374+ && obj . message . usage . input_tokens != null ) {
1375+ const usage = obj . message . usage ;
1376+ const inputTokens
1377+ = usage . input_tokens !
1378+ + ( usage . cache_creation_input_tokens ?? 0 )
1379+ + ( usage . cache_read_input_tokens ?? 0 ) ;
1380+
1381+ const percentage = Math . min ( 100 , Math . max ( 0 , Math . round ( ( inputTokens / CONTEXT_LIMIT ) * 100 ) ) ) ;
1382+
1383+ return {
1384+ inputTokens,
1385+ percentage,
1386+ contextLimit : CONTEXT_LIMIT ,
1387+ } ;
1388+ }
13741389 }
1375-
1376- const obj = parseResult . value ;
1377-
1378- // Check if this line contains the required token usage fields
1379- if ( obj . type === 'assistant'
1380- && obj . message != null
1381- && obj . message . usage != null
1382- && obj . message . usage . input_tokens != null
1383- && obj . message . usage . cache_creation_input_tokens != null
1384- && obj . message . usage . cache_read_input_tokens != null
1385- && obj . message . usage . output_tokens != null ) {
1386- const usage = obj . message . usage ;
1387- const maxInputTokens
1388- = usage . input_tokens !
1389- + usage . cache_creation_input_tokens !
1390- + usage . cache_read_input_tokens !
1391- + usage . output_tokens ! ;
1392-
1393- const percentage = Math . round ( ( maxInputTokens / CONTEXT_LIMIT ) * 100 ) ;
1394-
1395- return {
1396- maxInputTokens,
1397- percentage,
1398- contextLimit : CONTEXT_LIMIT ,
1399- } ;
1390+ catch {
1391+ continue ; // Skip malformed JSON lines
14001392 }
14011393 }
14021394
@@ -1405,6 +1397,54 @@ export async function calculateContextTokens(transcriptPath: string): Promise<{
14051397 return null ;
14061398}
14071399
1400+ // Test for calculateContextTokens
1401+ if ( import . meta. vitest != null ) {
1402+ describe ( 'calculateContextTokens' , ( ) => {
1403+ it ( 'returns null when transcript cannot be read' , async ( ) => {
1404+ const result = await calculateContextTokens ( '/nonexistent/path.jsonl' ) ;
1405+ expect ( result ) . toBeNull ( ) ;
1406+ } ) ;
1407+
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+
14081448/**
14091449 * Loads usage data and organizes it into session blocks (typically 5-hour billing periods)
14101450 * Processes all usage data and groups it into time-based blocks for billing analysis
0 commit comments