"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/vercel.ts
var vercel_exports = {};
__export(vercel_exports, {
  createCodebaseSearchTool: () => createCodebaseSearchTool,
  default: () => vercel_default,
  getSystemPrompt: () => getSystemPrompt
});
module.exports = __toCommonJS(vercel_exports);
var import_ai = require("ai");
var import_zod = require("zod");

// 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.`;

// tools/codebase_search/vercel.ts
function createCodebaseSearchTool(config) {
  const schema = import_zod.z.object({
    query: import_zod.z.string().describe('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: import_zod.z.array(import_zod.z.string()).describe("Prefix directory paths to limit search scope (single directory only, no glob patterns). Use [] to search entire repo."),
    explanation: import_zod.z.string().describe("One sentence explanation as to why this tool is being used, and how it contributes to the goal."),
    limit: import_zod.z.number().optional().describe("Max results to return (default: 10)")
  });
  return (0, import_ai.tool)({
    description: CODEBASE_SEARCH_DESCRIPTION,
    inputSchema: schema,
    execute: async (params) => {
      const { query, target_directories, explanation, limit } = params;
      const result = await executeCodebaseSearch(
        { query, target_directories, explanation, limit },
        config
      );
      if (!result.success) {
        return {
          error: result.error,
          results: []
        };
      }
      return {
        found: result.results.length,
        searchTime: `${result.stats.searchTimeMs}ms`,
        results: result.results.map((r) => ({
          file: r.filepath,
          symbol: r.symbolPath,
          lines: `${r.startLine}-${r.endLine}`,
          language: r.language,
          relevance: `${(r.rerankScore * 100).toFixed(1)}%`,
          code: r.content
        }))
      };
    }
  });
}
function getSystemPrompt() {
  return CODEBASE_SEARCH_DESCRIPTION;
}
var vercel_default = { createCodebaseSearchTool, getSystemPrompt };
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createCodebaseSearchTool,
  getSystemPrompt
});
//# sourceMappingURL=vercel.cjs.map