"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/openai.ts
var openai_exports = {};
__export(openai_exports, {
  codebaseSearchTool: () => codebaseSearchTool,
  createCodebaseSearchTool: () => createCodebaseSearchTool,
  default: () => openai_default,
  execute: () => execute,
  formatResult: () => formatResult,
  getSystemPrompt: () => getSystemPrompt
});
module.exports = __toCommonJS(openai_exports);

// package.json
var package_default = {
  name: "@morphllm/morphsdk",
  version: "0.2.124",
  description: "TypeScript SDK and CLI for Morph Fast Apply integration",
  type: "module",
  main: "./dist/index.cjs",
  module: "./dist/index.js",
  types: "./dist/index.d.ts",
  exports: {
    ".": {
      types: "./dist/index.d.ts",
      import: "./dist/index.js",
      require: "./dist/index.cjs"
    },
    "./edge": {
      types: "./dist/edge.d.ts",
      import: "./dist/edge.js",
      require: "./dist/edge.cjs"
    },
    "./tools/warp-grep": {
      types: "./dist/tools/warp_grep/index.d.ts",
      import: "./dist/tools/warp_grep/index.js",
      require: "./dist/tools/warp_grep/index.cjs"
    },
    "./tools/warp-grep/openai": {
      types: "./dist/tools/warp_grep/openai.d.ts",
      import: "./dist/tools/warp_grep/openai.js",
      require: "./dist/tools/warp_grep/openai.cjs"
    },
    "./tools/warp-grep/anthropic": {
      types: "./dist/tools/warp_grep/anthropic.d.ts",
      import: "./dist/tools/warp_grep/anthropic.js",
      require: "./dist/tools/warp_grep/anthropic.cjs"
    },
    "./tools/warp-grep/vercel": {
      types: "./dist/tools/warp_grep/vercel.d.ts",
      import: "./dist/tools/warp_grep/vercel.js",
      require: "./dist/tools/warp_grep/vercel.cjs"
    },
    "./tools/warp-grep/client": {
      types: "./dist/tools/warp_grep/client.d.ts",
      import: "./dist/tools/warp_grep/client.js",
      require: "./dist/tools/warp_grep/client.cjs"
    },
    "./tools/warp-grep/gemini": {
      types: "./dist/tools/warp_grep/gemini.d.ts",
      import: "./dist/tools/warp_grep/gemini.js",
      require: "./dist/tools/warp_grep/gemini.cjs"
    },
    "./tools/warp-grep/harness": {
      types: "./dist/tools/warp_grep/harness.d.ts",
      import: "./dist/tools/warp_grep/harness.js",
      require: "./dist/tools/warp_grep/harness.cjs"
    },
    "./tools/fastapply": {
      types: "./dist/tools/fastapply/index.d.ts",
      import: "./dist/tools/fastapply/index.js",
      require: "./dist/tools/fastapply/index.cjs"
    },
    "./tools/fastapply/anthropic": {
      types: "./dist/tools/fastapply/anthropic.d.ts",
      import: "./dist/tools/fastapply/anthropic.js",
      require: "./dist/tools/fastapply/anthropic.cjs"
    },
    "./tools/fastapply/openai": {
      types: "./dist/tools/fastapply/openai.d.ts",
      import: "./dist/tools/fastapply/openai.js",
      require: "./dist/tools/fastapply/openai.cjs"
    },
    "./tools/fastapply/vercel": {
      types: "./dist/tools/fastapply/vercel.d.ts",
      import: "./dist/tools/fastapply/vercel.js",
      require: "./dist/tools/fastapply/vercel.cjs"
    },
    "./tools/codebase-search": {
      types: "./dist/tools/codebase_search/index.d.ts",
      import: "./dist/tools/codebase_search/index.js",
      require: "./dist/tools/codebase_search/index.cjs"
    },
    "./tools/codebase-search/anthropic": {
      types: "./dist/tools/codebase_search/anthropic.d.ts",
      import: "./dist/tools/codebase_search/anthropic.js",
      require: "./dist/tools/codebase_search/anthropic.cjs"
    },
    "./tools/codebase-search/openai": {
      types: "./dist/tools/codebase_search/openai.d.ts",
      import: "./dist/tools/codebase_search/openai.js",
      require: "./dist/tools/codebase_search/openai.cjs"
    },
    "./tools/codebase-search/vercel": {
      types: "./dist/tools/codebase_search/vercel.d.ts",
      import: "./dist/tools/codebase_search/vercel.js",
      require: "./dist/tools/codebase_search/vercel.cjs"
    },
    "./tools/git": {
      types: "./dist/git/index.d.ts",
      import: "./dist/git/index.js",
      require: "./dist/git/index.cjs"
    },
    "./tools/browser": {
      types: "./dist/tools/browser/index.d.ts",
      import: "./dist/tools/browser/index.js",
      require: "./dist/tools/browser/index.cjs"
    },
    "./tools/browser/anthropic": {
      types: "./dist/tools/browser/anthropic.d.ts",
      import: "./dist/tools/browser/anthropic.js",
      require: "./dist/tools/browser/anthropic.cjs"
    },
    "./tools/browser/openai": {
      types: "./dist/tools/browser/openai.d.ts",
      import: "./dist/tools/browser/openai.js",
      require: "./dist/tools/browser/openai.cjs"
    },
    "./tools/browser/vercel": {
      types: "./dist/tools/browser/vercel.d.ts",
      import: "./dist/tools/browser/vercel.js",
      require: "./dist/tools/browser/vercel.cjs"
    },
    "./tools/browser/profiles": {
      types: "./dist/tools/browser/profiles/index.d.ts",
      import: "./dist/tools/browser/profiles/index.js",
      require: "./dist/tools/browser/profiles/index.cjs"
    },
    "./modelrouter": {
      types: "./dist/modelrouter/index.d.ts",
      import: "./dist/modelrouter/index.js",
      require: "./dist/modelrouter/index.cjs"
    },
    "./tools/compact": {
      types: "./dist/tools/compact/index.d.ts",
      import: "./dist/tools/compact/index.js",
      require: "./dist/tools/compact/index.cjs"
    }
  },
  files: [
    "dist/**/*.js",
    "dist/**/*.cjs",
    "dist/**/*.d.ts",
    "dist/**/*.map",
    "!dist/**/__tests__/**",
    "!dist/**/*.test.*"
  ],
  scripts: {
    build: "tsup version.ts index.ts edge.ts client.ts tools/index.ts tools/fastapply/index.ts tools/fastapply/core.ts tools/fastapply/apply.ts tools/fastapply/types.ts tools/fastapply/prompts.ts tools/fastapply/anthropic.ts tools/fastapply/openai.ts tools/fastapply/vercel.ts tools/codebase_search/index.ts tools/codebase_search/core.ts tools/codebase_search/types.ts tools/codebase_search/prompts.ts tools/codebase_search/anthropic.ts tools/codebase_search/openai.ts tools/codebase_search/vercel.ts tools/warp_grep/index.ts tools/warp_grep/client.ts tools/warp_grep/openai.ts tools/warp_grep/anthropic.ts tools/warp_grep/vercel.ts tools/warp_grep/gemini.ts tools/warp_grep/harness.ts tools/warp_grep/agent/config.ts tools/warp_grep/agent/prompt.ts tools/warp_grep/agent/parser.ts tools/warp_grep/agent/runner.ts tools/warp_grep/agent/types.ts tools/warp_grep/agent/formatter.ts tools/warp_grep/providers/types.ts tools/warp_grep/providers/local.ts tools/warp_grep/providers/remote.ts tools/warp_grep/providers/code_storage_http.ts tools/warp_grep/tools/grep.ts tools/warp_grep/tools/analyse.ts tools/warp_grep/tools/read.ts tools/warp_grep/tools/finish.ts tools/warp_grep/utils/paths.ts tools/warp_grep/utils/github.ts tools/warp_grep/utils/ripgrep.ts tools/warp_grep/utils/format.ts tools/warp_grep/utils/files.ts git/index.ts git/client.ts git/config.ts git/types.ts tools/browser/index.ts tools/browser/core.ts tools/browser/types.ts tools/browser/prompts.ts tools/browser/anthropic.ts tools/browser/openai.ts tools/browser/vercel.ts tools/browser/live.ts tools/browser/errors.ts tools/browser/profiles/index.ts tools/browser/profiles/core.ts tools/browser/profiles/types.ts modelrouter/index.ts modelrouter/core.ts modelrouter/types.ts tools/compact/index.ts tools/compact/core.ts tools/compact/types.ts tools/utils/resilience.ts --format esm,cjs --sourcemap --clean --dts --dts-resolve",
    prepare: "npm run build",
    typecheck: "tsc --noEmit",
    lint: "eslint .",
    test: "vitest run",
    "test:watch": "vitest watch",
    "test:anthropic": "vitest run anthropic",
    "test:openai": "vitest run openai",
    "test:vercel": "vitest run vercel",
    "test:git": "vitest run git",
    "test:browser": "vitest run browser",
    "test:agent": "npx tsx tests/fullAgentTest.ts",
    "test:integration": "npx tsx tests/fullIntegrationTest.ts",
    "release:patch": "npm version patch && npm publish",
    "release:minor": "npm version minor && npm publish",
    "release:major": "npm version major && npm publish"
  },
  keywords: [
    "morph",
    "fast-apply",
    "cli",
    "sdk",
    "edit-file"
  ],
  engines: {
    node: ">=18"
  },
  license: "MIT",
  dependencies: {
    "@vscode/ripgrep": "^1.17.0",
    ai: "^5.0.0",
    diff: "^7.0.0",
    "isomorphic-git": "^1.25.10",
    openai: "^4.52.7",
    zod: "^3.23.8"
  },
  devDependencies: {
    "@ai-sdk/anthropic": "^1.0.9",
    "@ai-sdk/openai": "^2.0.35",
    "@anthropic-ai/sdk": "^0.30.1",
    "@google/generative-ai": "^0.24.1",
    "@types/diff": "^7.0.2",
    "@types/node": "^20.14.10",
    "@typescript-eslint/eslint-plugin": "^7.18.0",
    "@typescript-eslint/parser": "^7.18.0",
    dotenv: "^16.4.5",
    eslint: "^8.57.0",
    shx: "^0.3.4",
    tsup: "^8.5.0",
    tsx: "^4.16.2",
    typescript: "^5.5.4",
    vitest: "^2.1.6"
  },
  peerDependencies: {
    "@anthropic-ai/sdk": ">=0.25.0",
    "@google/generative-ai": ">=0.21.0",
    ai: ">=5.0.0",
    zod: ">=3.23.0"
  },
  peerDependenciesMeta: {
    "@anthropic-ai/sdk": {
      optional: true
    },
    "@google/generative-ai": {
      optional: true
    },
    ai: {
      optional: true
    },
    zod: {
      optional: true
    }
  },
  publishConfig: {
    access: "public"
  }
};

// version.ts
var SDK_VERSION = package_default.version;

// 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;
  options = { ...options, headers: { "X-Morph-SDK-Version": SDK_VERSION, ...options.headers } };
  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/openai.ts
var codebaseSearchTool = {
  type: "function",
  function: {
    name: "codebase_search",
    description: CODEBASE_SEARCH_DESCRIPTION,
    parameters: {
      type: "object",
      properties: {
        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."
        },
        explanation: {
          type: "string",
          description: "One sentence explanation as to why this tool is being used, and how it contributes to the goal."
        },
        limit: {
          type: "number",
          description: "Maximum results to return (default: 10)"
        }
      },
      required: ["query", "target_directories", "explanation"]
    }
  }
};
function createCodebaseSearchTool(config) {
  const toolDefinition = {
    type: "function",
    function: {
      name: "codebase_search",
      description: CODEBASE_SEARCH_DESCRIPTION,
      parameters: {
        type: "object",
        properties: {
          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."
          },
          explanation: {
            type: "string",
            description: "One sentence explanation as to why this tool is being used, and how it contributes to the goal."
          },
          limit: {
            type: "number",
            description: "Maximum results to return (default: 10)"
          }
        },
        required: ["query", "target_directories", "explanation"]
      }
    }
  };
  return Object.assign(toolDefinition, {
    execute: async (input) => {
      const parsedInput = typeof input === "string" ? JSON.parse(input) : input;
      return executeCodebaseSearch(parsedInput, config);
    },
    formatResult: (result) => {
      return formatResult(result);
    },
    getSystemPrompt: () => {
      return CODEBASE_SEARCH_SYSTEM_PROMPT;
    }
  });
}
async function execute(input, config) {
  return executeCodebaseSearch(input, config);
}
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 removing directory filters.";
  }
  const lines = [];
  lines.push(`Found ${result.results.length} relevant code sections (${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");
}
function getSystemPrompt() {
  return CODEBASE_SEARCH_SYSTEM_PROMPT;
}
var openai_default = { createCodebaseSearchTool, execute, formatResult, getSystemPrompt };
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  codebaseSearchTool,
  createCodebaseSearchTool,
  execute,
  formatResult,
  getSystemPrompt
});
//# sourceMappingURL=openai.cjs.map