import {
  CompactClient
} from "./chunk-SCVWDNQP.js";

// tools/compact/utils.ts
async function compactFileContexts(files, query, apiKey, apiUrl, maxTokens = 1e4, maxConcurrency = 3) {
  const totalLength = files.reduce((sum, file) => sum + file.content.length, 0);
  const estimatedTokens = totalLength / 3;
  if (estimatedTokens <= maxTokens) {
    return files;
  }
  let compressionRatio = maxTokens / estimatedTokens;
  compressionRatio = Math.max(0.3, Math.min(0.99, compressionRatio));
  const client = new CompactClient({
    morphApiKey: apiKey,
    morphApiUrl: apiUrl
  });
  const results = [];
  const inProgress = /* @__PURE__ */ new Set();
  for (const file of files) {
    if (file.content.length < 500) {
      results.push({ path: file.path, content: file.content });
      continue;
    }
    const task = async () => {
      try {
        const result = await client.compact({
          input: file.content,
          query,
          compressionRatio,
          preserveRecent: 0
        });
        results.push({ path: file.path, content: result.output });
      } catch (error) {
        console.error(`[compactFileContexts] Failed to compact file ${file.path}:`, error);
        results.push({ path: file.path, content: file.content });
      }
    };
    const promise = task().finally(() => inProgress.delete(promise));
    inProgress.add(promise);
    if (inProgress.size >= maxConcurrency) {
      await Promise.race(inProgress);
    }
  }
  await Promise.all(inProgress);
  const orderMap = new Map(files.map((f, i) => [f.path, i]));
  return results.sort((a, b) => (orderMap.get(a.path) ?? 0) - (orderMap.get(b.path) ?? 0));
}

export {
  compactFileContexts
};
//# sourceMappingURL=chunk-GLQWEINZ.js.map