"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// tools/compact/index.ts
var compact_exports = {};
__export(compact_exports, {
  CompactClient: () => CompactClient,
  compactFileContexts: () => compactFileContexts
});
module.exports = __toCommonJS(compact_exports);

// tools/compact/core.ts
var DEFAULT_API_URL = "https://api.morphllm.com";
var DEFAULT_TIMEOUT = 12e4;
var CompactClient = class {
  config;
  constructor(config = {}) {
    this.config = {
      ...config,
      morphApiUrl: config.morphApiUrl ?? DEFAULT_API_URL,
      timeout: config.timeout ?? DEFAULT_TIMEOUT
    };
  }
  /**
   * Compact messages or text via /v1/compact.
   * Returns per-message `compacted_line_ranges` showing which lines were removed.
   *
   * @example
   * ```typescript
   * const client = new CompactClient({ morphApiKey: 'sk-...' });
   * const result = await client.compact({
   *   input: codeFile,
   *   query: "authentication",
   *   compressionRatio: 0.5,
   * });
   * console.log(result.output);
   * ```
   */
  async compact(input) {
    const apiKey = this.config.morphApiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
    const debug = this.config.debug || false;
    if (!apiKey) {
      throw new Error(
        "Morph API key not found. Set MORPH_API_KEY environment variable or pass morphApiKey in config."
      );
    }
    const url = `${this.config.morphApiUrl}/v1/compact`;
    if (debug) {
      console.log(`[Compact] Calling ${url}`);
    }
    const body = {
      compression_ratio: input.compressionRatio ?? 0.5,
      preserve_recent: input.preserveRecent ?? 2,
      model: input.model ?? "morph-compactor",
      include_line_ranges: input.includeLineRanges ?? true,
      include_markers: input.includeMarkers ?? true
    };
    if (input.query !== void 0) {
      body.query = input.query;
    }
    if (input.messages) {
      body.messages = input.messages;
    } else if (typeof input.input === "string") {
      body.input = input.input;
    } else if (Array.isArray(input.input)) {
      body.messages = input.input;
    } else {
      throw new Error("Either 'input' or 'messages' must be provided");
    }
    const startTime = Date.now();
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${apiKey}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(this.config.timeout)
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(`Compact API error ${response.status}: ${text}`);
    }
    const data = await response.json();
    if (debug) {
      console.log(`[Compact] compact() done in ${Date.now() - startTime}ms`);
    }
    return data;
  }
};

// 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));
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CompactClient,
  compactFileContexts
});
//# sourceMappingURL=index.cjs.map