// engine/llm-runtime/token-tracker.ts — SPEC-460: Track real token usage per session
// Estimates tokens from actual text length (measurable). Never invents counts.
// Estimation: ~1 token per 4 characters (widely accepted approximation for English/code).
const CHARS_PER_TOKEN = 4;
/** Session-scoped token accumulator — reset on server restart */
const sessionUsage = {
    inputTokens: 0,
    outputTokens: 0,
    toolCalls: 0,
    byTool: {},
};
/** Estimate token count from text length */
export function estimateTokens(text) {
    return Math.ceil(text.length / CHARS_PER_TOKEN);
}
/** Record a tool call with measured input/output sizes */
export function recordToolTokens(toolName, inputText, outputText) {
    const inputTokens = estimateTokens(inputText);
    const outputTokens = estimateTokens(outputText);
    sessionUsage.inputTokens += inputTokens;
    sessionUsage.outputTokens += outputTokens;
    sessionUsage.toolCalls += 1;
    const existing = sessionUsage.byTool[toolName];
    if (existing) {
        existing.input += inputTokens;
        existing.output += outputTokens;
        existing.calls += 1;
    }
    else {
        sessionUsage.byTool[toolName] = {
            input: inputTokens,
            output: outputTokens,
            calls: 1,
        };
    }
}
/** Get current session token usage — all real measured data */
export function getSessionTokenUsage() {
    return { ...sessionUsage, byTool: { ...sessionUsage.byTool } };
}
/** Get top N tools by token consumption */
export function getTopTokenConsumers(n) {
    return Object.entries(sessionUsage.byTool)
        .map(([tool, usage]) => ({ tool, total: usage.input + usage.output }))
        .sort((a, b) => b.total - a.total)
        .slice(0, n);
}
/** Reset session usage — for testing only */
export function resetSessionUsage() {
    sessionUsage.inputTokens = 0;
    sessionUsage.outputTokens = 0;
    sessionUsage.toolCalls = 0;
    sessionUsage.byTool = {};
}
//# sourceMappingURL=token-tracker.js.map