"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);

// logger.ts
var MorphLogger, logger;
var init_logger = __esm({
  "logger.ts"() {
    "use strict";
    MorphLogger = class {
      enabled;
      fileStream;
      /** Resolves once the file stream is initialized (or immediately if no file logging). */
      ready;
      constructor() {
        this.enabled = typeof process !== "undefined" && (process.env.MORPH_DEBUG === "1" || !!process.env.MORPH_LOG_FILE);
        this.fileStream = null;
        const f = typeof process !== "undefined" ? process.env.MORPH_LOG_FILE : void 0;
        if (f) {
          this.ready = import("fs").then((fs) => {
            this.fileStream = fs.createWriteStream(f, { flags: "a" });
          }).catch(() => {
          });
        } else {
          this.ready = Promise.resolve();
        }
      }
      debug(component, msg, data) {
        this._log("debug", component, msg, data);
      }
      info(component, msg, data) {
        this._log("info", component, msg, data);
      }
      warn(component, msg, data) {
        this._log("warn", component, msg, data);
      }
      error(component, msg, data) {
        this._log("error", component, msg, data);
      }
      enable() {
        this.enabled = true;
      }
      get isEnabled() {
        return this.enabled;
      }
      _log(level, component, msg, data) {
        if (level !== "error" && !this.enabled) return;
        const ts = (/* @__PURE__ */ new Date()).toISOString();
        const prefix = `[${ts}] [${level.toUpperCase()}] [${component}]`;
        console.error(data ? `${prefix} ${msg} ${JSON.stringify(data)}` : `${prefix} ${msg}`);
        this.fileStream?.write(JSON.stringify({ ts, level, component, msg, ...data && { data } }) + "\n");
      }
    };
    logger = new MorphLogger();
  }
});

// package.json
var package_default;
var init_package = __esm({
  "package.json"() {
    package_default = {
      name: "@morphllm/morphsdk",
      version: "0.2.168",
      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"
        },
        "./logger": {
          types: "./dist/logger.d.ts",
          import: "./dist/logger.js",
          require: "./dist/logger.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"
        },
        "./subagents": {
          types: "./dist/subagents/index.d.ts",
          import: "./dist/subagents/index.js",
          require: "./dist/subagents/index.cjs"
        },
        "./subagents/vercel": {
          types: "./dist/subagents/vercel.d.ts",
          import: "./dist/subagents/vercel.js",
          require: "./dist/subagents/vercel.cjs"
        },
        "./subagents/anthropic": {
          types: "./dist/subagents/anthropic.d.ts",
          import: "./dist/subagents/anthropic.js",
          require: "./dist/subagents/anthropic.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/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 subagents/index.ts subagents/types.ts subagents/prompts.ts subagents/vercel.ts subagents/anthropic.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",
        "test:e2e": "vitest run --config vitest.e2e.config.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.0"
      },
      devDependencies: {
        "@ai-sdk/anthropic": "^2.0.70",
        "@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;
var init_version = __esm({
  "version.ts"() {
    "use strict";
    init_package();
    SDK_VERSION = package_default.version;
  }
});

// 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 useLarge = config.large ?? (typeof process !== "undefined" ? process.env?.MORPH_LARGE_APPLY !== "false" : true);
  const model = useLarge ? "morph-v3-large" : "morph-v3-fast";
  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>`;
  logger.debug("FastApply", "http_request", {
    url: `${apiUrl}/v1/chat/completions`,
    model,
    filepath,
    instruction_len: instructions.length,
    original_len: originalCode.length,
    code_edit_len: codeEdit.length
  });
  const startTime = Date.now();
  const client = new import_openai.default({
    apiKey,
    baseURL: `${apiUrl}/v1`,
    timeout,
    maxRetries: config.retryConfig?.maxRetries ?? 3,
    defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
  });
  try {
    const completion = await client.chat.completions.create({
      model,
      messages: [{ role: "user", content: message }]
    });
    const content = completion.choices[0]?.message?.content;
    if (!content) {
      throw new Error("Morph API returned empty response");
    }
    const elapsed = Date.now() - startTime;
    logger.debug("FastApply", "http_response", { status: 200, completion_id: completion.id, content_len: content.length, latency_ms: elapsed });
    return { content, completionId: completion.id };
  } catch (error) {
    const elapsed = Date.now() - startTime;
    logger.error("FastApply", "http_error", {
      status: error?.status || error?.response?.status,
      error: error?.message,
      latency_ms: elapsed
    });
    throw error;
  }
}
async function applyEdit(input, config = {}) {
  const filepath = input.filepath || "file";
  try {
    logger.debug("FastApply", "apply_edit_start", { original_len: input.originalCode.length, code_edit_len: input.codeEdit.length });
    const instruction = input.instruction ?? input.instructions ?? "";
    const { content: mergedCode, completionId } = await callMorphAPI(
      input.originalCode,
      input.codeEdit,
      instruction,
      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,
      completionId
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
    logger.error("FastApply", "apply_edit_error", { error: errorMessage });
    return {
      success: false,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: errorMessage
    };
  }
}
var import_diff, import_openai, DEFAULT_API_URL, DEFAULT_TIMEOUT;
var init_apply = __esm({
  "tools/fastapply/apply.ts"() {
    "use strict";
    import_diff = require("diff");
    import_openai = __toESM(require("openai"), 1);
    init_version();
    init_logger();
    DEFAULT_API_URL = "https://api.morphllm.com";
    DEFAULT_TIMEOUT = 9e4;
  }
});

// tools/fastapply/vercel.ts
var vercel_exports = {};
__export(vercel_exports, {
  createEditFileTool: () => createEditFileTool,
  default: () => vercel_default,
  editFileTool: () => editFileTool,
  getSystemPrompt: () => getSystemPrompt
});
module.exports = __toCommonJS(vercel_exports);
var import_ai = require("ai");
var import_zod = require("zod");

// tools/fastapply/core.ts
var import_path = require("path");
init_logger();
init_apply();
var DEFAULT_CONFIG = {
  morphApiUrl: "https://api.morphllm.com",
  baseDir: process.cwd(),
  generateUdiff: true,
  autoWrite: true,
  timeout: 9e4,
  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));
  logger.debug("FastApply", "execute_start", { target_filepath: input.target_filepath, baseDir, autoWrite: config.autoWrite !== false });
  const relativePath = (0, import_path.relative)(baseDir, fullPath);
  if (relativePath.startsWith("..") || fullPath === baseDir) {
    logger.warn("FastApply", "security_check_failed", { target_filepath: input.target_filepath, relative: relativePath });
    return {
      success: false,
      filepath: input.target_filepath,
      changes: { linesAdded: 0, linesRemoved: 0, linesModified: 0 },
      error: `Invalid filepath: '${input.target_filepath}' is outside baseDir`
    };
  }
  logger.debug("FastApply", "security_check", { resolved: fullPath, relative: relativePath });
  try {
    const { readFile, writeFile } = await import("fs/promises");
    const { callMorphAPI: callMorphAPI2, generateUdiff: generateUdiff2, countChanges: countChanges2 } = await Promise.resolve().then(() => (init_apply(), apply_exports));
    let originalCode = "";
    let fileExists = true;
    try {
      originalCode = await readFile(fullPath, "utf-8");
      logger.debug("FastApply", "file_read", { path: fullPath, exists: true, size_bytes: originalCode.length });
    } catch (error) {
      if (error.code !== "ENOENT") {
        throw error;
      }
      fileExists = false;
      logger.debug("FastApply", "file_read", { path: fullPath, exists: false });
    }
    const instruction = input.instruction ?? input.instructions ?? "";
    logger.debug("FastApply", "api_call", { instruction_len: instruction.length, code_edit_len: input.code_edit.length, original_len: originalCode.length });
    const { content: mergedCode, completionId } = await callMorphAPI2(originalCode, input.code_edit, instruction, input.target_filepath, config);
    logger.debug("FastApply", "api_response", { completion_id: completionId, merged_len: mergedCode.length });
    const udiff = config.generateUdiff !== false ? generateUdiff2(originalCode, mergedCode, input.target_filepath) : void 0;
    if (config.autoWrite !== false) {
      await writeFile(fullPath, mergedCode, "utf-8");
      logger.debug("FastApply", "file_write", { path: fullPath, size_bytes: mergedCode.length });
    }
    const changes = countChanges2(originalCode, mergedCode);
    logger.debug("FastApply", "changes", { added: changes.linesAdded, removed: changes.linesRemoved, modified: changes.linesModified });
    return {
      success: true,
      filepath: input.target_filepath,
      udiff,
      changes,
      completionId
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
    logger.error("FastApply", "execute_error", { error: errorMessage, target_filepath: input.target_filepath, stack: error instanceof Error ? error.stack : void 0 });
    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/vercel.ts
var editFileSchema = import_zod.z.object({
  target_filepath: import_zod.z.string().describe("The path of the target file to modify"),
  instruction: import_zod.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
  code_edit: import_zod.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
});
var editFileTool = (0, import_ai.tool)({
  description: EDIT_FILE_TOOL_DESCRIPTION,
  inputSchema: editFileSchema,
  execute: async (params) => {
    const result = await executeEditFile({
      target_filepath: params.target_filepath,
      instruction: params.instruction,
      code_edit: params.code_edit
    });
    if (!result.success) {
      throw new Error(`Failed to edit file: ${result.error}`);
    }
    return {
      success: true,
      filepath: result.filepath,
      changes: result.changes,
      udiff: result.udiff
    };
  }
});
function getSystemPrompt() {
  return EDIT_FILE_SYSTEM_PROMPT;
}
function createEditFileTool(config = {}) {
  const schema = import_zod.z.object({
    target_filepath: import_zod.z.string().describe("The path of the target file to modify"),
    instruction: import_zod.z.string().describe("A single sentence written in the first person describing what the agent is changing. Used to help disambiguate uncertainty in the edit."),
    code_edit: import_zod.z.string().describe("Specify ONLY the precise lines of code that you wish to edit. Use `// ... existing code ...` for unchanged sections.")
  });
  return (0, import_ai.tool)({
    description: config.description || EDIT_FILE_TOOL_DESCRIPTION,
    inputSchema: schema,
    execute: async (params) => {
      const result = await executeEditFile(
        {
          target_filepath: params.target_filepath,
          instruction: params.instruction,
          code_edit: params.code_edit
        },
        config
      );
      if (!result.success) {
        throw new Error(`Failed to edit file: ${result.error}`);
      }
      return {
        success: true,
        filepath: result.filepath,
        changes: result.changes,
        udiff: result.udiff
      };
    }
  });
}
var vercel_default = editFileTool;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createEditFileTool,
  editFileTool,
  getSystemPrompt
});
//# sourceMappingURL=vercel.cjs.map