claude-monitor
Version:
Real-time terminal monitoring tool for Claude AI token usage
59 lines • 2.02 kB
JavaScript
import { getTotalTokens } from '../types/index.js';
export const DEFAULT_P90_CONFIG = {
commonLimits: [19_000, 88_000, 220_000, 880_000],
limitThreshold: 0.95,
defaultMinLimit: 44_000,
cacheTTLSeconds: 300,
};
function didHitLimit(tokens, config) {
return config.commonLimits.some(limit => tokens >= limit * config.limitThreshold);
}
function calculateP90(values) {
if (values.length === 0)
return 0;
const sorted = [...values].sort((a, b) => a - b);
const index = Math.floor(sorted.length * 0.9);
return sorted[Math.min(index, sorted.length - 1)];
}
export function calculateP90Limit(blocks, config = DEFAULT_P90_CONFIG) {
const limitHits = blocks
.filter(block => !block.isGap &&
!block.isActive &&
block.entries.length > 0)
.map(block => getTotalTokens(block.tokenCounts))
.filter(tokens => didHitLimit(tokens, config));
if (limitHits.length > 0) {
const p90 = calculateP90(limitHits);
return Math.max(Math.round(p90), config.defaultMinLimit);
}
const allSessions = blocks
.filter(block => !block.isGap &&
!block.isActive &&
block.entries.length > 0)
.map(block => getTotalTokens(block.tokenCounts));
if (allSessions.length === 0) {
return config.defaultMinLimit;
}
const p90 = calculateP90(allSessions);
return Math.max(Math.round(p90), config.defaultMinLimit);
}
export class P90Calculator {
config;
cache = null;
constructor(config = DEFAULT_P90_CONFIG) {
this.config = config;
}
getLimit(blocks) {
const now = Date.now();
if (this.cache && now - this.cache.timestamp < this.config.cacheTTLSeconds * 1000) {
return this.cache.value;
}
const limit = calculateP90Limit(blocks, this.config);
this.cache = { value: limit, timestamp: now };
return limit;
}
clearCache() {
this.cache = null;
}
}
//# sourceMappingURL=p90-calculator.js.map