"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/anthropic.ts
var anthropic_exports = {};
__export(anthropic_exports, {
  createCodebaseSearchTool: () => createCodebaseSearchTool
});
module.exports = __toCommonJS(anthropic_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
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"
    };
  }
}

// tools/codebase_search/prompts.ts
var CODEBASE_SEARCH_DESCRIPTION = `Semantic search that finds code by meaning, not exact text.

Use this to explore unfamiliar codebases or ask "how/where/what" questions:
- "How does X work?" - Find implementation details
- "Where is Y handled?" - Locate specific functionality
- "What happens when Z?" - Understand flow

The tool uses two-stage retrieval (embedding similarity + reranking) to find the most semantically relevant code chunks.

Returns code chunks with file paths, line ranges, and full content ranked by relevance.`;
var CODEBASE_SEARCH_SYSTEM_PROMPT = `You have access to the codebase_search tool that performs semantic code search.

When searching:
- Use natural language queries describing what you're looking for
- Be specific about functionality, not variable names
- Use target_directories to narrow search if you know the area
- Results are ranked by relevance (rerank score is most important)

The tool returns:
- File paths with symbol names (e.g. "src/auth.ts::AuthService@L1-L17")
- Line ranges for precise navigation
- Full code content for each match
- Dual relevance scores: embedding similarity + rerank score

Use results to understand code or answer questions. The content is provided in full - avoid re-reading unless you need more context.`;

// tools/codebase_search/anthropic.ts
function createCodebaseSearchTool(config) {
  const toolDefinition = {
    name: "codebase_search",
    description: CODEBASE_SEARCH_DESCRIPTION,
    input_schema: {
      type: "object",
      properties: {
        explanation: {
          type: "string",
          description: "One sentence explanation as to why this tool is being used, and how it contributes to the goal."
        },
        query: {
          type: "string",
          description: 'A complete question about what you want to understand. Ask as if talking to a colleague: "How does X work?", "What happens when Y?", "Where is Z handled?"'
        },
        target_directories: {
          type: "array",
          items: { type: "string" },
          description: "Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo."
        },
        limit: {
          type: "number",
          description: "Maximum results to return (default: 10)"
        }
      },
      required: ["query", "target_directories", "explanation"]
    },
    cache_control: { type: "ephemeral" }
  };
  return Object.assign(toolDefinition, {
    execute: async (input) => {
      return executeCodebaseSearch(input, config);
    },
    formatResult: (result) => {
      return formatResult(result);
    },
    getSystemPrompt: () => {
      return CODEBASE_SEARCH_SYSTEM_PROMPT;
    }
  });
}
function formatResult(result) {
  if (!result.success) {
    return `Search failed: ${result.error}`;
  }
  if (result.results.length === 0) {
    return "No matching code found. Try rephrasing your query or broadening the search scope.";
  }
  const lines = [];
  lines.push(`Found ${result.results.length} relevant code sections (searched ${result.stats.candidatesRetrieved} candidates in ${result.stats.searchTimeMs}ms):
`);
  result.results.forEach((r, i) => {
    const relevance = (r.rerankScore * 100).toFixed(1);
    lines.push(`${i + 1}. ${r.filepath} (${relevance}% relevant)`);
    lines.push(`   Symbol: ${r.symbolPath}`);
    lines.push(`   Language: ${r.language}`);
    lines.push(`   Lines: ${r.startLine}-${r.endLine}`);
    lines.push(`   Code:`);
    const codeLines = r.content.split("\n");
    codeLines.slice(0, Math.min(codeLines.length, 20)).forEach((line) => {
      lines.push(`     ${line}`);
    });
    if (codeLines.length > 20) {
      lines.push(`     ... (${codeLines.length - 20} more lines)`);
    }
    lines.push("");
  });
  return lines.join("\n");
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createCodebaseSearchTool
});
//# sourceMappingURL=anthropic.cjs.map