import { estimateTokensForOperation } from '../token-tracker.js';
// ---------------------------------------------------------------------------
// Default configuration
// ---------------------------------------------------------------------------
export const DEFAULT_CONFIG = {
    contextWindowSize: 200_000,
    warningThreshold: 0.75,
    criticalThreshold: 0.9,
    autoCompressAbove: 0.75,
    autoCheckpointAbove: 0.9,
};
// ---------------------------------------------------------------------------
// In-memory session state (resets each server restart)
// ---------------------------------------------------------------------------
let sessionOps = [];
let activeConfig = { ...DEFAULT_CONFIG };
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/** Record a tool invocation with estimated token consumption. */
export function recordToolCall(tool, responseLength) {
    const estimated = responseLength
        ? estimateTokensFromText(responseLength)
        : estimateTokensForOperation(tool);
    sessionOps.push({ tool, tokens: estimated, timestamp: new Date().toISOString() });
}
/** Get the current context budget status. */
export function getStatus(config) {
    const cfg = config ?? activeConfig;
    const totalUsed = sessionOps.reduce((sum, op) => sum + op.tokens, 0);
    const available = Math.max(0, cfg.contextWindowSize - totalUsed);
    const percent = cfg.contextWindowSize > 0 ? totalUsed / cfg.contextWindowSize : 0;
    return {
        tokensEstimatedUsed: totalUsed,
        tokensEstimatedAvailable: available,
        percentUsed: Math.round(percent * 100),
        alertLevel: getAlertLevel(percent, cfg),
        operationCount: sessionOps.length,
        topConsumers: getTopConsumers(5),
    };
}
/** Build a context warning if usage exceeds the warning threshold. */
export function getWarning(config) {
    const cfg = config ?? activeConfig;
    const status = getStatus(cfg);
    const percent = status.percentUsed / 100;
    if (percent < cfg.warningThreshold) {
        return null;
    }
    const recommendation = getRecommendation(percent, cfg);
    return {
        percentUsed: status.percentUsed,
        tokensRemaining: status.tokensEstimatedAvailable,
        recommendation,
    };
}
/** Update the active configuration. */
export function setConfig(config) {
    activeConfig = { ...activeConfig, ...config };
    return activeConfig;
}
/** Get the active configuration. */
export function getConfig() {
    return { ...activeConfig };
}
/** Get the raw session operations list. */
export function getSessionOps() {
    return [...sessionOps];
}
/** Reset all session state (for testing or new sessions). */
export function resetSession() {
    sessionOps = [];
    activeConfig = { ...DEFAULT_CONFIG };
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
/** Estimate tokens from text character length (chars × 0.25). */
export function estimateTokensFromText(charCount) {
    return Math.ceil(charCount * 0.25);
}
function getAlertLevel(percent, cfg) {
    if (percent >= cfg.criticalThreshold) {
        return 'red';
    }
    if (percent >= cfg.warningThreshold) {
        return 'orange';
    }
    if (percent >= 0.5) {
        return 'yellow';
    }
    return 'green';
}
function getTopConsumers(limit) {
    const byTool = {};
    for (const op of sessionOps) {
        byTool[op.tool] = (byTool[op.tool] ?? 0) + op.tokens;
    }
    return Object.entries(byTool)
        .map(([tool, tokens]) => ({ tool, tokens }))
        .sort((a, b) => b.tokens - a.tokens)
        .slice(0, limit);
}
function getRecommendation(percent, cfg) {
    if (percent >= cfg.criticalThreshold) {
        return 'Context nearly exhausted. Generate a checkpoint immediately and start a new session.';
    }
    if (percent >= cfg.warningThreshold) {
        return 'Context pressure high. Delegate remaining work to subagents or reduce response verbosity.';
    }
    return 'Context usage moderate. Consider delegating large reads to subagents.';
}
//# sourceMappingURL=tracker.js.map