"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// tools/utils/resilience.ts
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((resolve2) => setTimeout(resolve2, ms));
}
var DEFAULT_RETRY_CONFIG;
var init_resilience = __esm({
  "tools/utils/resilience.ts"() {
    "use strict";
    DEFAULT_RETRY_CONFIG = {
      maxRetries: 3,
      initialDelay: 1e3,
      maxDelay: 3e4,
      backoffMultiplier: 2,
      retryableErrors: ["ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND"]
    };
  }
});

// tools/fastapply/apply.ts
var apply_exports = {};
__export(apply_exports, {
  applyEdit: () => applyEdit,
  callMorphAPI: () => callMorphAPI,
  countChanges: () => countChanges,
  generateUdiff: () => generateUdiff
});
function generateUdiff(original, modified, filepath) {
  return (0, import_diff.createTwoFilesPatch)(
    filepath,
    filepath,
    original,
    modified,
    "Original",
    "Modified"
  );
}
function countChanges(original, modified) {
  const diff = generateUdiff(original, modified, "file");
  const lines = diff.split("\n");
  let linesAdded = 0;
  let linesRemoved = 0;
  for (const line of lines) {
    if (line.startsWith("+") && !line.startsWith("+++")) {
      linesAdded++;
    } else if (line.startsWith("-") && !line.startsWith("---")) {
      linesRemoved++;
    }
  }
  const linesModified = Math.min(linesAdded, linesRemoved);
  return {
    linesAdded: linesAdded - linesModified,
    linesRemoved: linesRemoved - linesModified,
    linesModified
  };
}
async function callMorphAPI(originalCode, codeEdit, instructions, filepath, config) {
  const apiKey = config.morphApiKey || (typeof process !== "undefined" ? process.env?.MORPH_API_KEY : void 0);
  const apiUrl = config.morphApiUrl || DEFAULT_API_URL;
  const timeout = config.timeout || DEFAULT_TIMEOUT;
  const debug = 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 message = `<instruction>${instructions}</instruction>
<code>${originalCode}</code>
<update>${codeEdit}</update>`;
  if (debug) {
    console.log(`[FastApply] Calling ${apiUrl}/v1/chat/completions`);
    console.log(`[FastApply] File: ${filepath}, Instructions: ${instructions.slice(0, 60)}...`);
    console.log(`[FastApply] Original: ${originalCode.length} chars, Edit: ${codeEdit.length} chars`);
  }
  const startTime = Date.now();
  const fetchPromise = fetchWithRetry(
    `${apiUrl}/v1/chat/completions`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${apiKey}`
      },
      body: JSON.stringify({
        model: "morph-v3-fast",
        messages: [{ role: "user", content: message }]
      })
    },
    config.retryConfig
  );
  const response = await withTimeout(
    fetchPromise,
    timeout,
    `Morph API request timed out after ${timeout}ms`
  );
  if (!response.ok) {
    const error = await response.text();
    if (debug) console.error(`[FastApply] API error: ${response.status} - ${error}`);
    throw new Error(`Morph API error (${response.status}): ${error}`);
  }
  const data = await response.json();
  const elapsed = Date.now() - startTime;
  if (debug) {
    console.log(`[FastApply] \u2705 Success in ${elapsed}ms, merged: ${data.choices[0].message.content.length} chars`);
  }
  return data.choices[0].message.content;
}
async function applyEdit(input, config = {}) {
  const debug = config.debug || false;
  const filepath = input.filepath || "file";
  try {
    if (debug) {
      console.log(`[FastApply] Applying edit to code (${input.originalCode.length} chars)`);
    }
    const mergedCode = await callMorphAPI(
      input.originalCode,
      input.codeEdit,
      input.instructions,
      filepath,
      config
    );
    const udiff = config.generateUdiff !== false ? generateUdiff(input.originalCode, mergedCode, filepath) : void 0;
    const changes = countChanges(input.originalCode, mergedCode);
    return {
      success: true,
      mergedCode,
      udiff,
      changes
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
    if (debug) console.error(`[FastApply] Error: ${errorMessage}`);
    return {
      success: false,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: errorMessage
    };
  }
}
var import_diff, DEFAULT_API_URL, DEFAULT_TIMEOUT;
var init_apply = __esm({
  "tools/fastapply/apply.ts"() {
    "use strict";
    import_diff = require("diff");
    init_resilience();
    DEFAULT_API_URL = "https://api.morphllm.com";
    DEFAULT_TIMEOUT = 3e4;
  }
});

// tools/fastapply/anthropic.ts
var anthropic_exports = {};
__export(anthropic_exports, {
  createEditFileTool: () => createEditFileTool,
  editFileTool: () => editFileTool,
  execute: () => execute,
  formatResult: () => formatResult,
  getSystemPrompt: () => getSystemPrompt
});
module.exports = __toCommonJS(anthropic_exports);

// tools/fastapply/core.ts
var import_path = require("path");
init_apply();
var DEFAULT_CONFIG = {
  morphApiUrl: "https://api.morphllm.com",
  baseDir: process.cwd(),
  generateUdiff: true,
  autoWrite: true,
  timeout: 3e4,
  debug: false
};
async function executeEditFile(input, config = {}) {
  const baseDir = config.baseDir || DEFAULT_CONFIG.baseDir;
  const fullPath = (0, import_path.resolve)((0, import_path.join)(baseDir, input.target_filepath));
  const debug = config.debug || false;
  const relativePath = (0, import_path.relative)(baseDir, fullPath);
  if (relativePath.startsWith("..") || fullPath === baseDir) {
    return {
      success: false,
      filepath: input.target_filepath,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`
    };
  }
  try {
    if (debug) console.log(`[FastApply] Reading file: ${input.target_filepath}`);
    const { readFile, writeFile } = await import("fs/promises");
    const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await Promise.resolve().then(() => (init_apply(), apply_exports));
    let originalCode = "";
    try {
      originalCode = await readFile(fullPath, "utf-8");
    } catch (error) {
      if (error.code !== "ENOENT") {
        throw error;
      }
      if (debug) console.log(`[FastApply] File doesn't exist, will create new file`);
    }
    const mergedCode = await callMorphAPI2(originalCode, input.code_edit, input.instructions, input.target_filepath, config);
    const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
    if (config.autoWrite !== false) {
      await writeFile(fullPath, mergedCode, "utf-8");
      if (debug) console.log(`[FastApply] Wrote ${mergedCode.length} chars to ${input.target_filepath}`);
    }
    const changes = countChanges2(originalCode, mergedCode);
    return {
      success: true,
      filepath: input.target_filepath,
      udiff,
      changes
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
    if (debug) console.error(`[FastApply] Error: ${errorMessage}`);
    return {
      success: false,
      filepath: input.target_filepath,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: errorMessage
    };
  }
}

// tools/fastapply/prompts.ts
var EDIT_FILE_TOOL_DESCRIPTION = `Use this tool to make an edit to an existing file.

This will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.

When writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.

For example:

// ... existing code ...
FIRST_EDIT
// ... existing code ...
SECOND_EDIT
// ... existing code ...
THIRD_EDIT
// ... existing code ...

You should still bias towards repeating as few lines of the original file as possible to convey the change.
But, each edit should contain minimally sufficient context of unchanged lines around the code you're editing to resolve ambiguity.

DO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.

If you plan on deleting a section, you must provide context before and after to delete it.

Make sure it is clear what the edit should be, and where it should be applied.
Make edits to a file in a single edit_file call instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once.`;
var EDIT_FILE_SYSTEM_PROMPT = `When the user is asking for edits to their code, use the edit_file tool to highlight the changes necessary and add comments to indicate where unchanged code has been skipped. For example:

// ... existing code ...
{{ edit_1 }}
// ... existing code ...
{{ edit_2 }}
// ... existing code ...

Often this will mean that the start/end of the file will be skipped, but that's okay! Rewrite the entire file ONLY if specifically requested. Always provide a brief explanation of the updates, unless the user specifically requests only the code.

These edit codeblocks are also read by a less intelligent language model, colloquially called the apply model, to update the file. To help specify the edit to the apply model, you will be very careful when generating the codeblock to not introduce ambiguity. You will specify all unchanged regions (code and comments) of the file with "// ... existing code ..." comment markers. This will ensure the apply model will not delete existing unchanged code or comments when editing the file.`;

// tools/fastapply/anthropic.ts
var editFileTool = {
  name: "edit_file",
  description: EDIT_FILE_TOOL_DESCRIPTION,
  input_schema: {
    type: "object",
    properties: {
      target_filepath: {
        type: "string",
        description: "The path of the target file to modify"
      },
      instructions: {
        type: "string",
        description: "A single sentence describing what you are changing (first person)"
      },
      code_edit: {
        type: "string",
        description: "The lazy edit with // ... existing code ... markers"
      }
    },
    required: ["target_filepath", "instructions", "code_edit"]
  }
};
function formatResult(result) {
  if (!result.success) {
    return `Error editing file: ${result.error}`;
  }
  const { changes } = result;
  return `Successfully applied changes to ${result.filepath}. Added ${changes.linesAdded}, removed ${changes.linesRemoved}, modified ${changes.linesModified}.`;
}
function createEditFileTool(config = {}) {
  const toolDef = {
    ...editFileTool,
    ...config.description && { description: config.description }
  };
  return Object.assign({}, toolDef, {
    execute: async (input) => {
      return executeEditFile(input, config);
    },
    formatResult: (result) => {
      return formatResult(result);
    },
    getSystemPrompt: () => {
      return EDIT_FILE_SYSTEM_PROMPT;
    }
  });
}
async function execute(input, config) {
  return executeEditFile(input, config);
}
function getSystemPrompt() {
  return EDIT_FILE_SYSTEM_PROMPT;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createEditFileTool,
  editFileTool,
  execute,
  formatResult,
  getSystemPrompt
});
//# sourceMappingURL=anthropic.cjs.map