"use strict";
// src/orchestrator/context/ContextBudget.ts
// v1.14.0 — Token counter + greedy packer.
//
// Uses tiktoken when available (cl100k_base). Falls back to a
// char/4 heuristic if tiktoken cannot be loaded (e.g. unsupported
// platform). Never throws — token counts are advisory.
Object.defineProperty(exports, "__esModule", { value: true });
exports.countTokens = countTokens;
exports.pack = pack;
let cachedEnc;
function loadEncoder() {
    if (cachedEnc !== undefined)
        return cachedEnc;
    try {
        const tiktoken = require('tiktoken');
        cachedEnc = tiktoken.get_encoding('cl100k_base');
    }
    catch {
        cachedEnc = null;
    }
    return cachedEnc;
}
function countTokens(text) {
    const enc = loadEncoder();
    if (!enc)
        return Math.ceil(text.length / 4);
    try {
        const out = enc.encode(text);
        return out.length;
    }
    catch {
        return Math.ceil(text.length / 4);
    }
}
/**
 * Greedy pack `hits` (already sorted desc by score) until `budgetTokens`
 * is exhausted. Returns the kept hits and the actual token usage.
 */
function pack(hits, budgetTokens) {
    let used = 0;
    const kept = [];
    for (const h of hits) {
        if (used + h.tokens > budgetTokens)
            continue;
        kept.push(h);
        used += h.tokens;
    }
    return { kept, usedTokens: used };
}
