"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/codebase_search/core.ts
var core_exports = {};
__export(core_exports, {
  CodebaseSearchClient: () => CodebaseSearchClient,
  executeCodebaseSearch: () => executeCodebaseSearch
});
module.exports = __toCommonJS(core_exports);

// tools/utils/resilience.ts
var DEFAULT_RETRY_CONFIG = {
  maxRetries: 3,
  initialDelay: 1e3,
  maxDelay: 3e4,
  backoffMultiplier: 2,
  retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
};
async function fetchWithRetry(url, options, retryConfig = {}) {
  const {
    maxRetries = DEFAULT_RETRY_CONFIG.maxRetries,
    initialDelay = DEFAULT_RETRY_CONFIG.initialDelay,
    maxDelay = DEFAULT_RETRY_CONFIG.maxDelay,
    backoffMultiplier = DEFAULT_RETRY_CONFIG.backoffMultiplier,
    retryableErrors = DEFAULT_RETRY_CONFIG.retryableErrors,
    onRetry
  } = retryConfig;
  let lastError = null;
  let delay = initialDelay;
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);
      if (response.status === 429 || response.status === 503) {
        if (attempt < maxRetries) {
          const retryAfter = response.headers.get("Retry-After");
          const waitTime = retryAfter ? parseInt(retryAfter) * 1e3 : Math.min(delay, maxDelay);
          const error = new Error(`HTTP ${response.status}: Retrying after ${waitTime}ms`);
          if (onRetry) {
            onRetry(attempt + 1, error);
          }
          await sleep(waitTime);
          delay *= backoffMultiplier;
          continue;
        }
      }
      return response;
    } catch (error) {
      lastError = error;
      const isRetryable = retryableErrors.some(
        (errType) => lastError?.message?.includes(errType)
      );
      if (!isRetryable || attempt === maxRetries) {
        throw lastError;
      }
      const waitTime = Math.min(delay, maxDelay);
      if (onRetry) {
        onRetry(attempt + 1, lastError);
      }
      await sleep(waitTime);
      delay *= backoffMultiplier;
    }
  }
  throw lastError || new Error("Max retries exceeded");
}
async function withTimeout(promise, timeoutMs, errorMessage) {
  let timeoutId;
  const timeoutPromise = new Promise((_, reject) => {
    timeoutId = setTimeout(() => {
      reject(new Error(errorMessage || `Operation timed out after ${timeoutMs}ms`));
    }, timeoutMs);
  });
  try {
    const result = await Promise.race([promise, timeoutPromise]);
    clearTimeout(timeoutId);
    return result;
  } catch (error) {
    clearTimeout(timeoutId);
    throw error;
  }
}
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// tools/codebase_search/core.ts
var CodebaseSearchClient = class {
  config;
  constructor(config = {}) {
    this.config = {
      apiKey: config.apiKey,
      searchUrl: process.env.MORPH_SEARCH_URL || "https://repos.morphllm.com",
      debug: config.debug,
      timeout: config.timeout || 3e4,
      retryConfig: config.retryConfig
    };
  }
  /**
   * Execute a semantic code search
   * 
   * @param input - Search parameters including query, repoId, and target directories
   * @param overrides - Optional config overrides for this operation
   * @returns Search results with ranked code matches
   */
  async search(input, overrides) {
    return executeCodebaseSearch(
      {
        query: input.query,
        target_directories: input.target_directories,
        explanation: input.explanation,
        limit: input.limit
      },
      { ...this.config, repoId: input.repoId, ...overrides }
    );
  }
};
async function executeCodebaseSearch(input, config) {
  const apiKey = config.apiKey || process.env.MORPH_API_KEY;
  if (!apiKey) {
    throw new Error("MORPH_API_KEY not found. Set environment variable or pass in config");
  }
  const searchUrl = config.searchUrl || process.env.MORPH_SEARCH_URL || "https://repos.morphllm.com";
  const timeout = config.timeout || 3e4;
  const debug = config.debug || false;
  if (debug) {
    console.log(`[CodebaseSearch] Query: "${input.query.slice(0, 60)}..." repo=${config.repoId}`);
    console.log(`[CodebaseSearch] URL: ${searchUrl}/v1/codebase_search`);
  }
  const startTime = Date.now();
  try {
    const fetchPromise = fetchWithRetry(
      `${searchUrl}/v1/codebase_search`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          query: input.query,
          repoId: config.repoId,
          targetDirectories: input.target_directories || [],
          limit: input.limit || 10,
          candidateLimit: 50
        })
      },
      config.retryConfig
    );
    const response = await withTimeout(fetchPromise, timeout, `Codebase search timed out after ${timeout}ms`);
    if (!response.ok) {
      const errorText = await response.text();
      if (debug) console.error(`[CodebaseSearch] Error: ${response.status} - ${errorText}`);
      return {
        success: false,
        results: [],
        stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },
        error: `Search failed (${response.status}): ${errorText}`
      };
    }
    const data = await response.json();
    const elapsed = Date.now() - startTime;
    if (debug) {
      console.log(`[CodebaseSearch] \u2705 ${data.results?.length || 0} results in ${elapsed}ms`);
    }
    return {
      success: true,
      results: data.results || [],
      stats: data.stats || { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: elapsed }
    };
  } catch (error) {
    if (debug) console.error(`[CodebaseSearch] Exception: ${error instanceof Error ? error.message : error}`);
    return {
      success: false,
      results: [],
      stats: { totalResults: 0, candidatesRetrieved: 0, searchTimeMs: 0 },
      error: error instanceof Error ? error.message : "Unknown error"
    };
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CodebaseSearchClient,
  executeCodebaseSearch
});
//# sourceMappingURL=core.cjs.map