"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/warp_grep/agent/config.ts
var parseEnvTimeout, AGENT_CONFIG, BUILTIN_EXCLUDES, DEFAULT_EXCLUDES, DEFAULT_MODEL;
var init_config = __esm({
  "tools/warp_grep/agent/config.ts"() {
    "use strict";
    parseEnvTimeout = (envValue, defaultMs) => {
      if (!envValue) return defaultMs;
      const parsed = parseInt(envValue, 10);
      return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;
    };
    AGENT_CONFIG = {
      MAX_TURNS: 4,
      /** Default timeout for model calls. Can be overridden via MORPH_WARP_GREP_TIMEOUT env var (in ms) */
      TIMEOUT_MS: parseEnvTimeout(process.env.MORPH_WARP_GREP_TIMEOUT, 3e4),
      MAX_CONTEXT_CHARS: 54e4,
      MAX_OUTPUT_LINES: 200,
      MAX_READ_LINES: 800,
      MAX_LIST_DEPTH: 3,
      LIST_TIMEOUT_MS: 2e3
    };
    BUILTIN_EXCLUDES = [
      // Version control
      ".git",
      ".svn",
      ".hg",
      ".bzr",
      // Dependencies
      "node_modules",
      "bower_components",
      ".pnpm",
      ".yarn",
      "vendor",
      "packages",
      "Pods",
      ".bundle",
      // Python
      "__pycache__",
      ".pytest_cache",
      ".mypy_cache",
      ".ruff_cache",
      ".venv",
      "venv",
      ".tox",
      ".nox",
      ".eggs",
      "*.egg-info",
      // Build outputs
      "dist",
      "build",
      "out",
      "output",
      "target",
      "_build",
      ".next",
      ".nuxt",
      ".output",
      ".vercel",
      ".netlify",
      // Cache directories
      ".cache",
      ".parcel-cache",
      ".turbo",
      ".nx",
      ".gradle",
      // IDE/Editor
      ".idea",
      ".vscode",
      ".vs",
      // Coverage
      "coverage",
      ".coverage",
      "htmlcov",
      ".nyc_output",
      // Temporary
      "tmp",
      "temp",
      ".tmp",
      ".temp",
      // Lock files
      "package-lock.json",
      "yarn.lock",
      "pnpm-lock.yaml",
      "bun.lockb",
      "Cargo.lock",
      "Gemfile.lock",
      "poetry.lock",
      // Binary/minified
      "*.min.js",
      "*.min.css",
      "*.bundle.js",
      "*.wasm",
      "*.so",
      "*.dll",
      "*.pyc",
      "*.map",
      "*.js.map",
      // Hidden directories catch-all
      ".*"
    ];
    DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || "").split(",").map((s) => s.trim()).filter(Boolean).concat(BUILTIN_EXCLUDES);
    DEFAULT_MODEL = "morph-warp-grep-v1";
  }
});

// tools/warp_grep/utils/ripgrep.ts
function spawnRg(rgBinary, args, opts) {
  return new Promise((resolve) => {
    const child = (0, import_child_process.spawn)(rgBinary, args, {
      cwd: opts?.cwd,
      env: { ...process.env, ...opts?.env || {} },
      stdio: ["ignore", "pipe", "pipe"]
    });
    let stdout = "";
    let stderr = "";
    child.stdout.on("data", (d) => stdout += d.toString());
    child.stderr.on("data", (d) => stderr += d.toString());
    child.on("close", (code) => {
      resolve({ stdout, stderr, exitCode: typeof code === "number" ? code : -1 });
    });
    child.on("error", () => {
      resolve({ stdout: "", stderr: "Failed to spawn ripgrep.", exitCode: -1 });
    });
  });
}
function isBinaryFailure(result) {
  if (result.exitCode === -1) return true;
  if (result.stderr.includes("jemalloc") || result.stderr.includes("Unsupported system page size")) return true;
  if (result.exitCode === 134) return true;
  return false;
}
async function runRipgrep(args, opts) {
  if (rgPathChecked && resolvedRgPath) {
    return spawnRg(resolvedRgPath, args, opts);
  }
  if (!rgPathChecked) {
    const result = await spawnRg(import_ripgrep.rgPath, args, opts);
    if (!isBinaryFailure(result)) {
      resolvedRgPath = import_ripgrep.rgPath;
      rgPathChecked = true;
      return result;
    }
    const fallbackResult = await spawnRg("rg", args, opts);
    if (!isBinaryFailure(fallbackResult)) {
      resolvedRgPath = "rg";
      rgPathChecked = true;
      return fallbackResult;
    }
    rgPathChecked = true;
    return {
      stdout: "",
      stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
      exitCode: -1
    };
  }
  return {
    stdout: "",
    stderr: "Failed to spawn ripgrep. Neither bundled nor system rg is available.",
    exitCode: -1
  };
}
var import_child_process, import_ripgrep, resolvedRgPath, rgPathChecked;
var init_ripgrep = __esm({
  "tools/warp_grep/utils/ripgrep.ts"() {
    "use strict";
    import_child_process = require("child_process");
    import_ripgrep = require("@vscode/ripgrep");
    resolvedRgPath = null;
    rgPathChecked = false;
  }
});

// tools/warp_grep/utils/paths.ts
function resolveUnderRepo(repoRoot, targetPath) {
  const absRoot = import_path3.default.resolve(repoRoot);
  const resolved = import_path3.default.resolve(absRoot, targetPath);
  ensureWithinRepo(absRoot, resolved);
  return resolved;
}
function ensureWithinRepo(repoRoot, absTarget) {
  const rel = import_path3.default.relative(import_path3.default.resolve(repoRoot), import_path3.default.resolve(absTarget));
  if (rel.startsWith("..") || import_path3.default.isAbsolute(rel)) {
    throw new Error(`Path outside repository root: ${absTarget}`);
  }
}
function toRepoRelative(repoRoot, absPath) {
  return import_path3.default.relative(import_path3.default.resolve(repoRoot), import_path3.default.resolve(absPath));
}
function isSymlink(p) {
  try {
    const st = import_fs.default.lstatSync(p);
    return st.isSymbolicLink();
  } catch {
    return false;
  }
}
function fixPathRepetition(fullPath) {
  const segments = fullPath.split(import_path3.default.sep).filter(Boolean);
  if (segments.length < 2) return null;
  for (let len = Math.floor(segments.length / 2); len >= 1; len--) {
    for (let i = 0; i <= segments.length - 2 * len; i++) {
      const first = segments.slice(i, i + len);
      const second = segments.slice(i + len, i + 2 * len);
      if (first.every((seg, idx) => seg === second[idx])) {
        const fixed = [...segments.slice(0, i), ...segments.slice(i + len)];
        return import_path3.default.sep + fixed.join(import_path3.default.sep);
      }
    }
  }
  return null;
}
function isTextualFile(filePath, maxBytes = 2e6) {
  try {
    const st = import_fs.default.statSync(filePath);
    if (!st.isFile()) return false;
    if (st.size > maxBytes) return false;
    const fd = import_fs.default.openSync(filePath, "r");
    const buf = Buffer.alloc(512);
    const read = import_fs.default.readSync(fd, buf, 0, buf.length, 0);
    import_fs.default.closeSync(fd);
    for (let i = 0; i < read; i++) {
      const c = buf[i];
      if (c === 0) return false;
    }
    return true;
  } catch {
    return false;
  }
}
var import_fs, import_path3;
var init_paths = __esm({
  "tools/warp_grep/utils/paths.ts"() {
    "use strict";
    import_fs = __toESM(require("fs"), 1);
    import_path3 = __toESM(require("path"), 1);
  }
});

// tools/warp_grep/utils/files.ts
async function readAllLines(filePath) {
  const content = await import_promises.default.readFile(filePath, "utf8");
  return content.split(/\r?\n/);
}
var import_promises;
var init_files = __esm({
  "tools/warp_grep/utils/files.ts"() {
    "use strict";
    import_promises = __toESM(require("fs/promises"), 1);
  }
});

// tools/warp_grep/providers/local.ts
var local_exports = {};
__export(local_exports, {
  LocalRipgrepProvider: () => LocalRipgrepProvider
});
function shouldSkip2(name) {
  if (SKIP_NAMES2.has(name)) return true;
  if (name.startsWith(".")) return true;
  for (const ext of SKIP_EXTENSIONS2) {
    if (name.endsWith(ext)) return true;
  }
  return false;
}
var import_promises2, import_path4, SKIP_NAMES2, SKIP_EXTENSIONS2, LocalRipgrepProvider;
var init_local = __esm({
  "tools/warp_grep/providers/local.ts"() {
    "use strict";
    import_promises2 = __toESM(require("fs/promises"), 1);
    import_path4 = __toESM(require("path"), 1);
    init_ripgrep();
    init_paths();
    init_files();
    init_config();
    SKIP_NAMES2 = /* @__PURE__ */ new Set([
      // Version control
      ".git",
      ".svn",
      ".hg",
      ".bzr",
      // Dependencies
      "node_modules",
      "bower_components",
      ".pnpm",
      ".yarn",
      "vendor",
      "Pods",
      ".bundle",
      // Python
      "__pycache__",
      ".pytest_cache",
      ".mypy_cache",
      ".ruff_cache",
      ".venv",
      "venv",
      ".tox",
      ".nox",
      ".eggs",
      // Build outputs
      "dist",
      "build",
      "out",
      "output",
      "target",
      "_build",
      ".next",
      ".nuxt",
      ".output",
      ".vercel",
      ".netlify",
      // Cache
      ".cache",
      ".parcel-cache",
      ".turbo",
      ".nx",
      ".gradle",
      // IDE
      ".idea",
      ".vscode",
      ".vs",
      // Coverage
      "coverage",
      ".coverage",
      "htmlcov",
      ".nyc_output",
      // Temp
      "tmp",
      "temp",
      ".tmp",
      ".temp",
      // Lock files
      "package-lock.json",
      "yarn.lock",
      "pnpm-lock.yaml",
      "bun.lockb",
      "Cargo.lock",
      "Gemfile.lock",
      "poetry.lock"
    ]);
    SKIP_EXTENSIONS2 = /* @__PURE__ */ new Set([
      ".min.js",
      ".min.css",
      ".bundle.js",
      ".wasm",
      ".so",
      ".dll",
      ".pyc",
      ".map",
      ".js.map"
    ]);
    LocalRipgrepProvider = class {
      constructor(repoRoot, excludes = DEFAULT_EXCLUDES) {
        this.repoRoot = repoRoot;
        this.excludes = excludes;
      }
      async grep(params) {
        let abs;
        try {
          abs = resolveUnderRepo(this.repoRoot, params.path);
        } catch (err) {
          return {
            lines: [],
            error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
          };
        }
        const stat = await import_promises2.default.stat(abs).catch(() => null);
        if (!stat) return { lines: [] };
        const targetArg = abs === import_path4.default.resolve(this.repoRoot) ? "." : toRepoRelative(this.repoRoot, abs);
        const args = [
          "--no-config",
          "--no-heading",
          "--with-filename",
          "--line-number",
          "--color=never",
          "--trim",
          "--max-columns=400",
          "-C",
          "1",
          ...params.glob ? ["--glob", params.glob] : [],
          ...this.excludes.flatMap((e) => ["-g", `!${e}`]),
          params.pattern,
          targetArg || "."
        ];
        const res = await runRipgrep(args, { cwd: this.repoRoot });
        if (res.exitCode === -1) {
          return {
            lines: [],
            error: `[RIPGREP NOT AVAILABLE] ripgrep (rg) is required but failed to execute. Please install it:
  \u2022 macOS: brew install ripgrep
  \u2022 Ubuntu/Debian: apt install ripgrep
  \u2022 Windows: choco install ripgrep
  \u2022 Or visit: https://github.com/BurntSushi/ripgrep#installation
Exit code: ${res.exitCode}${res.stderr ? `
Details: ${res.stderr}` : ""}`
          };
        }
        if (res.exitCode !== 0 && res.exitCode !== 1) {
          return {
            lines: [],
            error: `[RIPGREP ERROR] grep failed with exit code ${res.exitCode}${res.stderr ? `: ${res.stderr}` : ""}`
          };
        }
        const lines = (res.stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
        if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
          return {
            lines: [],
            error: "query not specific enough, tool tried to return too much context and failed"
          };
        }
        return { lines };
      }
      async read(params) {
        let abs;
        try {
          abs = resolveUnderRepo(this.repoRoot, params.path);
        } catch (err) {
          return {
            lines: [],
            error: `[PATH ERROR] ${err instanceof Error ? err.message : String(err)}`
          };
        }
        let stat = await import_promises2.default.stat(abs).catch(() => null);
        if (!stat || !stat.isFile()) {
          const fixedPath = fixPathRepetition(abs);
          if (fixedPath) {
            const fixedStat = await import_promises2.default.stat(fixedPath).catch(() => null);
            if (fixedStat?.isFile()) {
              abs = fixedPath;
              stat = fixedStat;
            }
          }
        }
        if (!stat || !stat.isFile()) {
          return {
            lines: [],
            error: `[FILE NOT FOUND] You tried to read "${params.path}" but there is no file at this path. Double-check the path exists and is spelled correctly.`
          };
        }
        if (isSymlink(abs)) {
          return {
            lines: [],
            error: `[SYMLINK] You tried to read "${params.path}" but this is a symlink. Try reading the actual file it points to instead.`
          };
        }
        if (!isTextualFile(abs)) {
          return {
            lines: [],
            error: `[UNREADABLE FILE] You tried to read "${params.path}" but this file is either too large or not a text file, so it cannot be read. Try a different file.`
          };
        }
        let lines;
        try {
          lines = await readAllLines(abs);
        } catch (err) {
          return {
            lines: [],
            error: `[READ ERROR] Failed to read "${params.path}": ${err instanceof Error ? err.message : String(err)}`
          };
        }
        const total = lines.length;
        const rawStart = params.start;
        const rawEnd = params.end;
        let s = 1;
        let e = total;
        const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
        const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
        if (startValid && endValid) {
          s = rawStart ?? 1;
          e = Math.min(rawEnd ?? total, total);
          if (s > total && total > 0 || s > e) {
            s = 1;
            e = total;
          }
        }
        const out = [];
        for (let i = s; i <= e; i += 1) {
          const content = lines[i - 1] ?? "";
          out.push(`${i}|${content}`);
        }
        if (out.length > AGENT_CONFIG.MAX_READ_LINES) {
          const truncated = out.slice(0, AGENT_CONFIG.MAX_READ_LINES);
          truncated.push(`... [truncated: showing ${AGENT_CONFIG.MAX_READ_LINES} of ${out.length} lines]`);
          return { lines: truncated };
        }
        return { lines: out };
      }
      async listDirectory(params) {
        let abs;
        try {
          abs = resolveUnderRepo(this.repoRoot, params.path);
        } catch {
          return [];
        }
        const stat = await import_promises2.default.stat(abs).catch(() => null);
        if (!stat || !stat.isDirectory()) {
          return [];
        }
        const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
        const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
        const regex = params.pattern ? new RegExp(params.pattern) : null;
        const repoRoot = this.repoRoot;
        const results = [];
        let timedOut = false;
        const startTime = Date.now();
        async function walk(dir, depth) {
          if (Date.now() - startTime > AGENT_CONFIG.LIST_TIMEOUT_MS) {
            timedOut = true;
            return;
          }
          if (depth > maxDepth || results.length >= maxResults) return;
          let entries;
          try {
            entries = await import_promises2.default.readdir(dir, { withFileTypes: true });
          } catch {
            return;
          }
          for (const entry of entries) {
            if (timedOut || results.length >= maxResults) break;
            if (shouldSkip2(entry.name)) continue;
            if (regex && !regex.test(entry.name)) continue;
            const full = import_path4.default.join(dir, entry.name);
            const isDir = entry.isDirectory();
            results.push({
              name: entry.name,
              path: toRepoRelative(repoRoot, full),
              type: isDir ? "dir" : "file",
              depth
            });
            if (isDir) {
              await walk(full, depth + 1);
            }
          }
        }
        await walk(abs, 0);
        return results;
      }
    };
  }
});

// tools/warp_grep/index.ts
var warp_grep_exports = {};
__export(warp_grep_exports, {
  GITHUB_SEARCH_DESCRIPTION: () => GITHUB_SEARCH_DESCRIPTION,
  GITHUB_SEARCH_INPUT_SCHEMA: () => GITHUB_SEARCH_INPUT_SCHEMA,
  GITHUB_SEARCH_TOOL_NAME: () => GITHUB_SEARCH_TOOL_NAME,
  LocalRipgrepProvider: () => LocalRipgrepProvider,
  RemoteCommandsProvider: () => RemoteCommandsProvider,
  WARP_GREP_DESCRIPTION: () => WARP_GREP_DESCRIPTION,
  WARP_GREP_SYSTEM_PROMPT: () => SYSTEM_PROMPT,
  WARP_GREP_TOOL_NAME: () => WARP_GREP_TOOL_NAME,
  WarpGrepClient: () => WarpGrepClient,
  createCodeStorageHttpCommands: () => createCodeStorageHttpCommands,
  executeToolCall: () => executeToolCall,
  executeWarpGrep: () => executeWarpGrep,
  fixPathRepetition: () => fixPathRepetition,
  formatResult: () => formatResult,
  getSystemPrompt: () => getSystemPrompt,
  normalizeFinishFiles: () => normalizeFinishFiles,
  readFinishFiles: () => readFinishFiles,
  runWarpGrep: () => runWarpGrep,
  runWarpGrepStreaming: () => runWarpGrepStreaming,
  toolGrep: () => toolGrep,
  toolListDirectory: () => toolListDirectory,
  toolRead: () => toolRead,
  warpGrepInputSchema: () => warpGrepInputSchema
});
module.exports = __toCommonJS(warp_grep_exports);
var import_zod = require("zod");

// tools/warp_grep/agent/runner.ts
init_config();

// tools/warp_grep/agent/prompt.ts
var SYSTEM_PROMPT = `You are a code search agent. Your task is to find all relevant code for a given search_string.

### workflow
You have exactly 4 turns. The 4th turn MUST be a \`finish\` call. Each turn allows up to 8 parallel tool calls.

- Turn 1: Map the territory OR dive deep (based on search_string specificity)
- Turn 2-3: Refine based on findings
- Turn 4: MUST call \`finish\` with all relevant code locations
- You MAY call \`finish\` early if confident\u2014but never before at least 1 search turn.
- The user strongly prefers if you can call the finish tool early, but you must be correct

Remember, if the task feels easy to you, it is strongly desirable to call 'finish' early using fewer turns, but quality over speed

### tools
Tool calls use nested XML elements:
\`\`\`xml
<tool_name>
  <parameter>value</parameter>
</tool_name>
\`\`\`

### \`list_directory\`
Directory tree view. Shows structure of a path, optionally filtered by regex pattern.

Elements:
- \`<path>\` (required): Directory path to list (use \`.\` for repo root)
- \`<pattern>\` (optional): Regex to filter results

Examples:
\`\`\`
<list_directory>
  <path>src/services</path>
</list_directory>

<list_directory>
  <path>lib/utils</path>
  <pattern>.*\\.(ts|js)$</pattern>
</list_directory>
\`\`\`

### \`read\`
Read file contents. Supports multiple line ranges.
- Returns numbered lines for easy reference
- ALWAYS include import statements (usually lines 1-20). Better to over-include than miss context.

Elements:
- \`<path>\` (required): File path to read
- \`<lines>\` (optional): Line ranges like "1-50,75-80,100-120" (omit to read entire file)

Examples:
\`\`\`
<read>
  <path>src/main.py</path>
</read>

<read>
  <path>src/auth.py</path>
  <lines>1-20,45-80,150-200</lines>
</read>
\`\`\`

### \`grep\`
Search for pattern matches across files. Returns matches with 1 line of context above and below.
- Match lines use \`:\` separator \u2192 \`filepath:linenum:content\`
- Context lines use \`-\` separator \u2192 \`filepath-linenum-content\`

Elements:
- \`<pattern>\` (required): Search pattern (regex). Use \`(a|b)\` for OR patterns.
- \`<sub_dir>\` (optional): Subdirectory to search in (defaults to \`.\`)
- \`<glob>\` (optional): File pattern filter like \`*.py\` or \`*.{ts,tsx}\`

Examples:
\`\`\`
<grep>
  <pattern>(authenticate|authorize|login)</pattern>
  <sub_dir>src/auth/</sub_dir>
</grep>

<grep>
  <pattern>class.*(Service|Controller)</pattern>
  <glob>*.{ts,js}</glob>
</grep>

<grep>
  <pattern>(DB_HOST|DATABASE_URL|connection)</pattern>
  <glob>*.{py,yaml,env}</glob>
  <sub_dir>lib/</sub_dir>
</grep>
\`\`\`

### \`finish\`
Submit final answer with all relevant code locations. Uses nested \`<file>\` elements.

File elements:
- \`<path>\` (required): File path
- \`<lines>\` (optional): Line ranges like "1-50,75-80" (\`*\` for entire file)

ALWAYS include import statements (usually lines 1-20). Better to over-include than miss context.

Examples:
\`\`\`
<finish>
  <file>
    <path>src/auth.py</path>
    <lines>1-15,25-50,75-80</lines>
  </file>
  <file>
    <path>src/models/user.py</path>
    <lines>*</lines>
  </file>
</finish>
\`\`\`
</tools>

<strategy>
**Before your first tool call, classify the search_string:**

| Search_string Type | Round 1 Strategy | Early Finish? |
|------------|------------------|---------------|
| **Specific** (function name, error string, unique identifier) | 8 parallel greps on likely paths | Often by round 2 |
| **Conceptual** (how does X work, where is Y handled) | list_directory + 2-3 broad greps | Rarely early |
| **Exploratory** (find all tests, list API endpoints) | list_directory at multiple depths | Usually needs 3 rounds |

**Parallel call patterns:**
- **Shotgun grep**: Same pattern, 8 different directories\u2014fast coverage
- **Variant grep**: 8 pattern variations (synonyms, naming conventions)\u2014catches inconsistent codebases
- **Funnel**: 1 list_directory + 7 greps\u2014orient and search simultaneously
- **Deep read**: 8 reads on files you already identified\u2014gather full context fast

**Tool call expectations:**
- Low quality tool calls are ones that give back sparse information. This either means they are not well thought out and are not educated guesses OR, they are too broad and give back too many results.
- High quality tool calls strike a balance between complexity in the tool call to exclude results we know we don't want, and how wide the search space is so that we don't miss anything. It is ok to start off with wider search spaces, but is imperative that you use your intuition from there on out and seek high quality tool calls only.
- You are not starting blind, you have some information about root level repo structure going in, so use that to prevent making trivial repo wide queries.
- The grep tool shows you which file path and line numbers the pattern was found in, use this information smartly when trying to read the file.
</strategy>

<output_format>
EVERY response MUST follow this exact format:

1. First, wrap your reasoning in \`<think>...</think>\` tags containing:
   - Search_string classification (specific/conceptual/exploratory)
   - Confidence estimate (can I finish in 1-2 rounds?)
   - This round's parallel strategy
   - What signals would let me finish early?

2. Then, output up to 8 tool calls using nested XML elements.

Example:
\`\`\`
<think>
This is a specific search_string about authentication. I'll grep for auth-related patterns.
High confidence I can finish in 2 rounds if I find the auth module. I have already been shown the repo's structure at root
Strategy: Shotgun grep across likely directories.
</think>
<grep>
  <pattern>(authenticate|login|session)</pattern>
  <sub_dir>src/auth/</sub_dir>
</grep>
<grep>
  <pattern>(middleware|interceptor)</pattern>
  <glob>*.{ts,js}</glob>
</grep>
<list_directory>
  <path>src/auth</path>
</list_directory>
\`\`\`

Finishing example:
\`\`\`
<think>
I think I have a rough idea, but this is my last turn so I must call the finish tool regardless.
</think>
<finish>
  <file>
    <path>src/auth/login.py</path>
    <lines>1-50</lines>
  </file>
  <file>
    <path>src/middleware/session.py</path>
    <lines>10-80</lines>
  </file>
</finish>
\`\`\`

No commentary outside \`<think>\`. No explanations after tool calls.
</output_format>

use as all 8 tool calls to be optimal

<finishing_requirements>
When calling \`finish\`:
- Include the import section (typically lines 1-20) of each file
- Include all function/class definitions that are relevant
- Include any type definitions, interfaces, or constants used
- Better to over-include than leave the user missing context
- If unsure about boundaries, include more rather than less
</finishing_requirements>`;
function getSystemPrompt() {
  return SYSTEM_PROMPT;
}

// tools/warp_grep/agent/parser.ts
var VALID_COMMANDS = ["list_directory", "grep", "read", "finish"];
function isValidCommand(name) {
  return VALID_COMMANDS.includes(name);
}
function getXmlElementText(xml, tagName) {
  const regex = new RegExp(`<${tagName}>([\\s\\S]*?)</${tagName}>`, "i");
  const match = xml.match(regex);
  return match ? match[1].trim() : null;
}
function parseNestedXmlTools(text) {
  const tools = [];
  const toolRegex = /<([a-z_][a-z0-9_]*)>([\s\S]*?)<\/\1>/gi;
  let match;
  while ((match = toolRegex.exec(text)) !== null) {
    const rawToolName = match[1].toLowerCase();
    const content = match[2];
    if (!isValidCommand(rawToolName)) continue;
    const toolName = rawToolName;
    if (toolName === "list_directory") {
      const path5 = getXmlElementText(content, "path");
      const pattern = getXmlElementText(content, "pattern");
      if (path5) {
        tools.push({ name: "list_directory", arguments: { path: path5, pattern } });
      }
    } else if (toolName === "grep") {
      const pattern = getXmlElementText(content, "pattern");
      const subDir = getXmlElementText(content, "sub_dir");
      const glob = getXmlElementText(content, "glob");
      if (pattern) {
        tools.push({
          name: "grep",
          arguments: {
            pattern,
            path: subDir || ".",
            ...glob && { glob }
          }
        });
      }
    } else if (toolName === "read") {
      const path5 = getXmlElementText(content, "path");
      const linesStr = getXmlElementText(content, "lines");
      if (path5) {
        const args = { path: path5 };
        if (linesStr) {
          const ranges = [];
          for (const rangeStr of linesStr.split(",")) {
            const trimmed = rangeStr.trim();
            if (!trimmed) continue;
            const [s, e] = trimmed.split("-").map((v) => parseInt(v.trim(), 10));
            if (Number.isFinite(s) && Number.isFinite(e)) {
              ranges.push([s, e]);
            } else if (Number.isFinite(s)) {
              ranges.push([s, s]);
            }
          }
          if (ranges.length === 1) {
            args.start = ranges[0][0];
            args.end = ranges[0][1];
          } else if (ranges.length > 1) {
            args.lines = ranges;
          }
        }
        tools.push({ name: "read", arguments: args });
      }
    } else if (toolName === "finish") {
      const fileRegex = /<file>([\s\S]*?)<\/file>/gi;
      const files = [];
      let fileMatch;
      while ((fileMatch = fileRegex.exec(content)) !== null) {
        const fileContent = fileMatch[1];
        const filePath = getXmlElementText(fileContent, "path");
        const linesStr = getXmlElementText(fileContent, "lines");
        if (filePath) {
          if (!linesStr || linesStr.trim() === "*") {
            files.push({ path: filePath, lines: "*" });
          } else {
            const ranges = [];
            for (const rangeStr of linesStr.split(",")) {
              const [s, e] = rangeStr.split("-").map((v) => parseInt(v.trim(), 10));
              if (Number.isFinite(s) && Number.isFinite(e)) {
                ranges.push([s, e]);
              }
            }
            if (ranges.length > 0) {
              files.push({ path: filePath, lines: ranges });
            } else {
              files.push({ path: filePath, lines: "*" });
            }
          }
        }
      }
      if (files.length > 0) {
        tools.push({ name: "finish", arguments: { files } });
      } else {
        const raw = content.replace(/<[^>]*>/g, "").trim();
        const textResult = !raw || raw === "*" ? "No relevant code found." : raw;
        tools.push({ name: "finish", arguments: { files: [], textResult } });
      }
    }
  }
  if (tools.length === 0) {
    const fnFinishMatch = text.match(/<function=finish>([\s\S]*?)<\/function>/i);
    if (fnFinishMatch) {
      const inner = fnFinishMatch[1];
      const paramMatch = inner.match(/<parameter=result>([\s\S]*?)<\/parameter>/i);
      const raw = (paramMatch ? paramMatch[1] : inner).trim();
      const textResult = !raw || raw === "*" ? "No relevant code found." : raw;
      tools.push({ name: "finish", arguments: { files: [], textResult } });
    }
  }
  return tools;
}
function preprocessText(text) {
  const processed = text.replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/<\/?tool_call>/gi, "");
  const nestedTools = parseNestedXmlTools(processed);
  const toolCallLines = [];
  const allLines = processed.split(/\r?\n/).map((l) => l.trim());
  for (const line of allLines) {
    if (!line) continue;
    if (line.startsWith("<")) continue;
    const firstWord = line.split(/\s/)[0];
    if (VALID_COMMANDS.includes(firstWord)) {
      if (!toolCallLines.includes(line)) {
        toolCallLines.push(line);
      }
    }
  }
  return { lines: toolCallLines, nestedTools };
}
var LLMResponseParser = class {
  finishSpecSplitRe = /,(?=[^,\s]+:)/;
  parse(text) {
    if (typeof text !== "string") {
      throw new TypeError("Command text must be a string.");
    }
    const { lines, nestedTools } = preprocessText(text);
    const commands = [...nestedTools];
    let finishAccumulator = null;
    lines.forEach((line) => {
      if (!line || line.startsWith("#")) return;
      const parts = this.splitLine(line);
      if (parts.length === 0) return;
      const cmd = parts[0];
      switch (cmd) {
        case "list_directory":
          this.handleListDirectory(parts, line, commands);
          break;
        case "grep":
          this.handleGrep(parts, line, commands);
          break;
        case "read":
          this.handleRead(parts, line, commands);
          break;
        case "finish":
          finishAccumulator = this.handleFinish(parts, line, commands, finishAccumulator);
          break;
        default:
          break;
      }
    });
    if (finishAccumulator) {
      const map = finishAccumulator;
      const entries = [...map.entries()];
      const filesPayload = entries.map(([path5, ranges]) => ({
        path: path5,
        lines: [...ranges].sort((a, b) => a[0] - b[0])
      }));
      commands.push({ name: "finish", arguments: { files: filesPayload } });
    }
    return commands;
  }
  splitLine(line) {
    const parts = [];
    let current = "";
    let inSingle = false;
    for (let i = 0; i < line.length; i++) {
      const ch = line[i];
      if (ch === "'" && line[i - 1] !== "\\") {
        inSingle = !inSingle;
        current += ch;
      } else if (!inSingle && /\s/.test(ch)) {
        if (current) {
          parts.push(current);
          current = "";
        }
      } else {
        current += ch;
      }
    }
    if (current) parts.push(current);
    return parts;
  }
  /** Helper to create a _skip tool call with an error message */
  skip(message) {
    return { name: "_skip", arguments: { message } };
  }
  handleListDirectory(parts, rawLine, commands) {
    if (parts.length < 2) {
      commands.push(this.skip(
        `[SKIPPED] Your command "${rawLine}" is missing a path. Correct format: list_directory <path> [pattern]. Example: list_directory src/`
      ));
      return;
    }
    const path5 = parts[1];
    const pattern = parts[2]?.replace(/^"|"$/g, "") ?? null;
    commands.push({ name: "list_directory", arguments: { path: path5, pattern } });
  }
  handleGrep(parts, rawLine, commands) {
    if (parts.length < 3) {
      commands.push(this.skip(
        `[SKIPPED] Your command "${rawLine}" is missing arguments. Correct format: grep '<pattern>' <path>. Example: grep 'TODO' src/`
      ));
      return;
    }
    let pat = parts[1];
    if (pat.startsWith("'") && pat.endsWith("'")) {
      pat = pat.slice(1, -1);
    }
    if (!pat) {
      commands.push(this.skip(
        `[SKIPPED] Your command "${rawLine}" has an empty pattern. Provide a non-empty search pattern. Example: grep 'function' src/`
      ));
      return;
    }
    commands.push({ name: "grep", arguments: { pattern: pat, path: parts[2] } });
  }
  handleRead(parts, rawLine, commands) {
    if (parts.length < 2) {
      commands.push(this.skip(
        `[SKIPPED] Your command "${rawLine}" is missing a path. Correct format: read <path> or read <path>:<start>-<end>. Example: read src/index.ts:1-50`
      ));
      return;
    }
    const spec = parts[1];
    const rangeIdx = spec.indexOf(":");
    if (rangeIdx === -1) {
      commands.push({ name: "read", arguments: { path: spec } });
      return;
    }
    const filePath = spec.slice(0, rangeIdx);
    const range = spec.slice(rangeIdx + 1);
    const [s, e] = range.split("-").map((v) => parseInt(v, 10));
    if (!Number.isFinite(s) || !Number.isFinite(e)) {
      commands.push({ name: "read", arguments: { path: filePath } });
      return;
    }
    commands.push({ name: "read", arguments: { path: filePath, start: s, end: e } });
  }
  handleFinish(parts, rawLine, commands, acc) {
    const map = acc ?? /* @__PURE__ */ new Map();
    const args = parts.slice(1);
    for (const token of args) {
      const [filePath, rangesText] = token.split(":", 2);
      if (!filePath || !rangesText) {
        commands.push(this.skip(
          `[SKIPPED] Invalid finish token "${token}". Correct format: finish <path>:<start>-<end>. Example: finish src/index.ts:1-50`
        ));
        continue;
      }
      const rangeSpecs = rangesText.split(",").filter(Boolean);
      for (const spec of rangeSpecs) {
        const [s, e] = spec.split("-").map((v) => parseInt(v, 10));
        if (!Number.isFinite(s) || !Number.isFinite(e) || e < s) {
          commands.push(this.skip(
            `[SKIPPED] Invalid range "${spec}" in "${token}". Ranges must be <start>-<end> where start <= end. Example: 1-50`
          ));
          continue;
        }
        const arr = map.get(filePath) ?? [];
        arr.push([s, e]);
        map.set(filePath, arr);
      }
    }
    return map;
  }
};

// tools/warp_grep/agent/tools/grep.ts
async function toolGrep(provider, args) {
  const res = await provider.grep(args);
  if (res.error) {
    return { output: res.error };
  }
  if (!res.lines.length) {
    return { output: "no matches" };
  }
  return { output: res.lines.join("\n") };
}

// tools/warp_grep/agent/tools/read.ts
function isValidRange(start, end) {
  return typeof start === "number" && typeof end === "number" && Number.isFinite(start) && Number.isFinite(end) && start > 0 && end >= start;
}
async function toolRead(provider, args) {
  if (args.lines && Array.isArray(args.lines) && args.lines.length > 0) {
    const validRanges = [];
    for (const range of args.lines) {
      if (Array.isArray(range) && range.length >= 2 && isValidRange(range[0], range[1])) {
        validRanges.push([range[0], range[1]]);
      }
    }
    if (validRanges.length === 0) {
      const res2 = await provider.read({ path: args.path });
      if (res2.error) return res2.error;
      if (!res2.lines.length) return "(empty file)";
      return res2.lines.join("\n");
    }
    const chunks = [];
    for (const [start, end] of validRanges) {
      const res2 = await provider.read({ path: args.path, start, end });
      if (res2.error) return res2.error;
      chunks.push(res2.lines.join("\n"));
    }
    if (chunks.every((c) => c === "")) return "(empty file)";
    return chunks.join("\n...\n");
  }
  const res = await provider.read({ path: args.path, start: args.start, end: args.end });
  if (res.error) {
    return res.error;
  }
  if (!res.lines.length) return "(empty file)";
  return res.lines.join("\n");
}

// tools/warp_grep/agent/tools/list_directory.ts
init_config();
async function toolListDirectory(provider, args) {
  const maxResults = args.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
  const initialDepth = args.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
  async function getListRecursive(currentDepth) {
    const entries = await provider.listDirectory({
      path: args.path,
      pattern: args.pattern ?? null,
      maxResults,
      maxDepth: currentDepth
    });
    if (entries.length >= maxResults && currentDepth > 0) {
      return getListRecursive(currentDepth - 1);
    }
    return { entries };
  }
  const { entries: list } = await getListRecursive(initialDepth);
  if (!list.length) return "empty";
  if (list.length >= maxResults) {
    return "query not specific enough, tool called tried to return too much context and failed";
  }
  return list.map((e) => {
    const indent = "  ".repeat(e.depth);
    const name = e.type === "dir" ? `${e.name}/` : e.name;
    return `${indent}${name}`;
  }).join("\n");
}

// tools/warp_grep/agent/tools/finish.ts
function isValidRange2(range) {
  return Array.isArray(range) && range.length >= 2 && typeof range[0] === "number" && typeof range[1] === "number" && Number.isFinite(range[0]) && Number.isFinite(range[1]) && range[0] > 0 && range[1] >= range[0];
}
function extractValidRanges(lines) {
  if (!Array.isArray(lines)) return null;
  const valid = [];
  for (const range of lines) {
    if (isValidRange2(range)) {
      valid.push([range[0], range[1]]);
    }
  }
  return valid.length > 0 ? valid : null;
}
function normalizeFinishFiles(files) {
  return files.map((f) => {
    if (f.lines === "*") return { path: f.path, lines: "*" };
    const validRanges = extractValidRanges(f.lines);
    if (!validRanges) return { path: f.path, lines: "*" };
    return { path: f.path, lines: mergeRanges(validRanges) };
  });
}
async function readFinishFiles(repoRoot, files, reader) {
  const out = [];
  for (const f of files) {
    const validRanges = f.lines === "*" ? null : extractValidRanges(f.lines);
    if (f.lines === "*" || !validRanges) {
      const lines = await reader(f.path);
      out.push({ path: f.path, ranges: "*", content: lines.join("\n") });
    } else {
      const ranges = mergeRanges(validRanges);
      const chunks = [];
      for (let i = 0; i < ranges.length; i++) {
        const [s, e] = ranges[i];
        if (i === 0 && s > 1) {
          chunks.push(`// ... existing code, block starting at line ${s} ...`);
        } else if (i > 0) {
          chunks.push(`// ... existing code, block starting at line ${s} ...`);
        }
        const lines = await reader(f.path, s, e);
        chunks.push(lines.join("\n"));
      }
      out.push({ path: f.path, ranges, content: chunks.join("\n") });
    }
  }
  return out;
}
function mergeRanges(ranges) {
  if (!ranges.length) return [];
  const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
  const merged = [];
  let [cs, ce] = sorted[0];
  for (let i = 1; i < sorted.length; i++) {
    const [s, e] = sorted[i];
    if (s <= ce + 1) {
      ce = Math.max(ce, e);
    } else {
      merged.push([cs, ce]);
      cs = s;
      ce = e;
    }
  }
  merged.push([cs, ce]);
  return merged;
}

// tools/warp_grep/agent/formatter.ts
var ToolOutputFormatter = class {
  format(toolName, args, output, options = {}) {
    const name = (toolName ?? "").trim();
    if (!name) {
      return "";
    }
    const payload = output?.toString?.()?.trim?.() ?? "";
    const isError = Boolean(options.isError);
    const safeArgs = args ?? {};
    if (!payload && !isError) {
      return "";
    }
    switch (name) {
      case "read":
        return this.formatRead(safeArgs, payload, isError);
      case "list_directory":
        return this.formatListDirectory(safeArgs, payload, isError);
      case "grep":
        return this.formatGrep(safeArgs, payload, isError);
      default:
        return payload ? `<tool_output>
${payload}
</tool_output>` : "";
    }
  }
  formatRead(args, payload, isError) {
    if (isError) {
      return payload;
    }
    const path5 = this.asString(args.path) || "...";
    const start = args.start;
    const end = args.end;
    const linesArray = args.lines;
    const attributes = [`path="${path5}"`];
    if (linesArray && linesArray.length > 0) {
      const rangeStr = linesArray.map(([s, e]) => `${s}-${e}`).join(",");
      attributes.push(`lines="${rangeStr}"`);
    } else if (start !== void 0 && end !== void 0) {
      attributes.push(`lines="${start}-${end}"`);
    }
    return `<read ${attributes.join(" ")}>
${payload}
</read>`;
  }
  formatListDirectory(args, payload, isError) {
    const path5 = this.asString(args.path) || ".";
    const pattern = this.asString(args.pattern);
    const attributes = [`path="${path5}"`];
    if (pattern) {
      attributes.push(`pattern="${pattern}"`);
    }
    if (isError) {
      attributes.push('status="error"');
    }
    return `<list_directory ${attributes.join(" ")}>
${payload}
</list_directory>`;
  }
  formatGrep(args, payload, isError) {
    const pattern = this.asString(args.pattern);
    const subDir = this.asString(args.path);
    const glob = this.asString(args.glob);
    const attributes = [];
    if (pattern !== void 0) {
      attributes.push(`pattern="${pattern}"`);
    }
    if (subDir !== void 0) {
      attributes.push(`sub_dir="${subDir}"`);
    }
    if (glob !== void 0) {
      attributes.push(`glob="${glob}"`);
    }
    if (isError) {
      attributes.push('status="error"');
    }
    const attrText = attributes.length ? ` ${attributes.join(" ")}` : "";
    return `<grep${attrText}>
${payload}
</grep>`;
  }
  asString(value) {
    if (value === null || value === void 0) {
      return void 0;
    }
    return String(value);
  }
};
var sharedFormatter = new ToolOutputFormatter();
function formatAgentToolOutput(toolName, args, output, options = {}) {
  return sharedFormatter.format(toolName, args, output, options);
}

// tools/warp_grep/agent/helpers.ts
var import_path = __toESM(require("path"), 1);
init_config();
var TRUNCATED_MARKER = "[truncated for context limit]";
function formatTurnMessage(turnsUsed, maxTurns) {
  const turnsRemaining = maxTurns - turnsUsed;
  if (turnsRemaining === 1) {
    return `
You have used ${turnsUsed} turns, you only have 1 turn remaining. You have run out of turns to explore the code base and MUST call the finish tool now`;
  }
  return `
You have used ${turnsUsed} turn${turnsUsed === 1 ? "" : "s"} and have ${turnsRemaining} remaining`;
}
function calculateContextBudget(messages) {
  const totalChars = messages.reduce((sum, m) => sum + m.content.length, 0);
  const maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS;
  const percent = Math.round(totalChars / maxChars * 100);
  const usedK = Math.round(totalChars / 1e3);
  const maxK = Math.round(maxChars / 1e3);
  return `<context_budget>${percent}% (${usedK}K/${maxK}K chars)</context_budget>`;
}
async function buildInitialState(repoRoot, query, provider) {
  try {
    const entries = await provider.listDirectory({
      path: ".",
      maxResults: AGENT_CONFIG.MAX_OUTPUT_LINES,
      maxDepth: 2
    });
    const treeLines = entries.map((e) => {
      const indent = "  ".repeat(e.depth);
      const name = e.type === "dir" ? `${e.name}/` : e.name;
      return `${indent}${name}`;
    });
    const repoName = import_path.default.basename(repoRoot);
    const treeOutput = treeLines.length > 0 ? `${repoName}/
${treeLines.join("\n")}` : `${repoName}/`;
    return `<repo_structure>
${treeOutput}
</repo_structure>

<search_string>
${query}
</search_string>`;
  } catch {
    const repoName = import_path.default.basename(repoRoot);
    return `<repo_structure>
${repoName}/
</repo_structure>

<search_string>
${query}
</search_string>`;
  }
}
function enforceContextLimit(messages, maxChars = AGENT_CONFIG.MAX_CONTEXT_CHARS) {
  const getTotalChars = () => messages.reduce((sum, m) => sum + m.content.length, 0);
  if (getTotalChars() <= maxChars) {
    return messages;
  }
  const userIndices = [];
  let firstUserSkipped = false;
  for (let i = 0; i < messages.length; i++) {
    if (messages[i].role === "user") {
      if (!firstUserSkipped) {
        firstUserSkipped = true;
        continue;
      }
      userIndices.push(i);
    }
  }
  for (const idx of userIndices) {
    if (getTotalChars() <= maxChars) {
      break;
    }
    if (messages[idx].content !== TRUNCATED_MARKER) {
      messages[idx] = { role: "user", content: TRUNCATED_MARKER };
    }
  }
  return messages;
}

// tools/warp_grep/agent/runner.ts
var import_openai = __toESM(require("openai"), 1);

// package.json
var package_default = {
  name: "@morphllm/morphsdk",
  version: "0.2.122",
  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/warp_grep/agent/runner.ts
var import_path2 = __toESM(require("path"), 1);
var parser = new LLMResponseParser();
var DEFAULT_API_URL = "https://api.morphllm.com";
async function callModel(messages, model, options = {}) {
  const baseUrl = options.morphApiUrl || DEFAULT_API_URL;
  const apiKey = options.morphApiKey || process.env.MORPH_API_KEY || "";
  const timeoutMs = options.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
  const client = new import_openai.default({
    apiKey,
    baseURL: `${baseUrl}/v1`,
    maxRetries: options.retryConfig?.maxRetries,
    timeout: timeoutMs,
    defaultHeaders: { "X-Morph-SDK-Version": SDK_VERSION }
  });
  const MAX_EMPTY_RETRIES = 1;
  for (let attempt = 0; attempt <= MAX_EMPTY_RETRIES; attempt++) {
    let data;
    try {
      data = await client.chat.completions.create({
        model,
        temperature: 0,
        max_tokens: 1024,
        messages
      });
    } catch (error) {
      if (error instanceof import_openai.default.APIError && error.status === 404) {
        throw new Error(
          "The endpoint you are trying to call is likely deprecated. Please update with: npm cache clean --force && npx -y @morphllm/morphmcp@latest or visit: https://morphllm.com/mcp"
        );
      }
      throw error;
    }
    const choice = data?.choices?.[0];
    const content = choice?.message?.content;
    if (content && typeof content === "string") {
      return content;
    }
    if (attempt === MAX_EMPTY_RETRIES) {
      const finishReason = choice?.finish_reason ?? "unknown";
      const hasToolCalls = Array.isArray(choice?.message?.tool_calls) && choice.message.tool_calls.length > 0;
      const choicesLen = data?.choices?.length ?? 0;
      const contentType = content === null ? "null" : content === void 0 ? "undefined" : typeof content;
      throw new Error(
        `Invalid response from model: content=${contentType}, finish_reason=${finishReason}, has_tool_calls=${hasToolCalls}, choices_length=${choicesLen}`
      );
    }
    await new Promise((resolve) => setTimeout(resolve, 200));
  }
  throw new Error("Invalid response from model");
}
async function runWarpGrep(config) {
  const totalStart = Date.now();
  const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
  const timings = { turns: [], timeout_ms: timeoutMs };
  const repoRoot = import_path2.default.resolve(config.repoRoot || process.cwd());
  const messages = [];
  messages.push({ role: "system", content: getSystemPrompt() });
  const initialStateStart = Date.now();
  const initialState = await buildInitialState(repoRoot, config.query, config.provider);
  timings.initial_state_ms = Date.now() - initialStateStart;
  messages.push({ role: "user", content: initialState });
  const maxTurns = AGENT_CONFIG.MAX_TURNS;
  const model = config.model || DEFAULT_MODEL;
  const provider = config.provider;
  const errors = [];
  let finishMeta;
  let terminationReason = "terminated";
  for (let turn = 1; turn <= maxTurns; turn += 1) {
    const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
    enforceContextLimit(messages);
    const modelCallStart = Date.now();
    const assistantContent = await callModel(messages, model, {
      morphApiKey: config.morphApiKey,
      morphApiUrl: config.morphApiUrl,
      retryConfig: config.retryConfig,
      timeout: timeoutMs
    }).catch((e) => {
      const errMsg = e instanceof Error ? e.message : String(e);
      console.error(`[warp_grep] Morph API call failed on turn ${turn}:`, errMsg);
      errors.push({ message: errMsg });
      return "";
    });
    turnMetrics.morph_api_ms = Date.now() - modelCallStart;
    if (!assistantContent) {
      console.error(`[warp_grep] Empty response from Morph API on turn ${turn}. Errors so far:`, errors);
      timings.turns.push(turnMetrics);
      break;
    }
    messages.push({ role: "assistant", content: assistantContent });
    const toolCalls = parser.parse(assistantContent);
    if (toolCalls.length === 0) {
      console.error(`[warp_grep] No tool calls parsed on turn ${turn}. Assistant content (first 500 chars):`, assistantContent.slice(0, 500));
      errors.push({ message: "No tool calls produced by the model. Your MCP is likely out of date! Update it by running: rm -rf ~/.npm/_npx && npm cache clean --force && npx -y @morphllm/morphmcp@latest" });
      terminationReason = "terminated";
      timings.turns.push(turnMetrics);
      break;
    }
    const finishCalls = toolCalls.filter((c) => c.name === "finish");
    const grepCalls = toolCalls.filter((c) => c.name === "grep");
    const listDirCalls = toolCalls.filter((c) => c.name === "list_directory");
    const readCalls = toolCalls.filter((c) => c.name === "read");
    const skipCalls = toolCalls.filter((c) => c.name === "_skip");
    const formatted = [];
    for (const c of skipCalls) {
      const msg = c.arguments?.message || "Command skipped due to parsing error";
      formatted.push(msg);
    }
    const allPromises = [];
    for (const c of grepCalls) {
      const args = c.arguments ?? {};
      allPromises.push(
        toolGrep(provider, args).then(
          ({ output }) => formatAgentToolOutput("grep", args, output, { isError: false }),
          (err) => formatAgentToolOutput("grep", args, String(err), { isError: true })
        )
      );
    }
    for (const c of listDirCalls) {
      const args = c.arguments ?? {};
      allPromises.push(
        toolListDirectory(provider, args).then(
          (p) => formatAgentToolOutput("list_directory", args, p, { isError: false }),
          (err) => formatAgentToolOutput("list_directory", args, String(err), { isError: true })
        )
      );
    }
    for (const c of readCalls) {
      const args = c.arguments ?? {};
      allPromises.push(
        toolRead(provider, args).then(
          (p) => formatAgentToolOutput("read", args, p, { isError: false }),
          (err) => formatAgentToolOutput("read", args, String(err), { isError: true })
        )
      );
    }
    const toolExecStart = Date.now();
    const allResults = await Promise.all(allPromises);
    turnMetrics.local_tools_ms = Date.now() - toolExecStart;
    for (const result of allResults) {
      formatted.push(result);
    }
    if (formatted.length > 0) {
      const turnMessage = formatTurnMessage(turn, maxTurns);
      const contextBudget = calculateContextBudget(messages);
      messages.push({ role: "user", content: formatted.join("\n") + turnMessage + "\n" + contextBudget });
    }
    timings.turns.push(turnMetrics);
    if (finishCalls.length) {
      const fc = finishCalls[0];
      const files = fc.arguments?.files ?? [];
      const textResult = fc.arguments?.textResult;
      finishMeta = { files };
      terminationReason = "completed";
      if (files.length === 0) {
        const payload2 = textResult || "No relevant code found.";
        timings.turns.push(turnMetrics);
        timings.total_ms = Date.now() - totalStart;
        return {
          terminationReason: "completed",
          messages,
          finish: { payload: payload2, metadata: finishMeta },
          timings
        };
      }
      break;
    }
  }
  if (terminationReason !== "completed" || !finishMeta) {
    timings.total_ms = Date.now() - totalStart;
    return { terminationReason, messages, errors, timings };
  }
  const parts = ["Relevant context found:"];
  for (const f of finishMeta.files) {
    const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
    parts.push(`- ${f.path}: ${ranges}`);
  }
  const payload = parts.join("\n");
  const finishResolutionStart = Date.now();
  const fileReadErrors = [];
  const resolved = await readFinishFiles(
    repoRoot,
    finishMeta.files,
    async (p, s, e) => {
      try {
        const rr = await provider.read({ path: p, start: s, end: e });
        return rr.lines.map((l) => {
          const idx = l.indexOf("|");
          return idx >= 0 ? l.slice(idx + 1) : l;
        });
      } catch (err) {
        const errorMsg = err instanceof Error ? err.message : String(err);
        fileReadErrors.push({ path: p, error: errorMsg });
        console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);
        return [`[couldn't find: ${p}]`];
      }
    }
  );
  timings.finish_resolution_ms = Date.now() - finishResolutionStart;
  if (fileReadErrors.length > 0) {
    errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
  }
  timings.total_ms = Date.now() - totalStart;
  return {
    terminationReason: "completed",
    messages,
    finish: { payload, metadata: finishMeta, resolved },
    timings
  };
}
async function* runWarpGrepStreaming(config) {
  const totalStart = Date.now();
  const timeoutMs = config.timeout ?? AGENT_CONFIG.TIMEOUT_MS;
  const timings = { turns: [], timeout_ms: timeoutMs };
  const repoRoot = import_path2.default.resolve(config.repoRoot || process.cwd());
  const messages = [];
  messages.push({ role: "system", content: getSystemPrompt() });
  const initialStateStart = Date.now();
  const initialState = await buildInitialState(repoRoot, config.query, config.provider);
  timings.initial_state_ms = Date.now() - initialStateStart;
  messages.push({ role: "user", content: initialState });
  const maxTurns = AGENT_CONFIG.MAX_TURNS;
  const model = config.model || DEFAULT_MODEL;
  const provider = config.provider;
  const errors = [];
  let finishMeta;
  let terminationReason = "terminated";
  for (let turn = 1; turn <= maxTurns; turn += 1) {
    const turnMetrics = { turn, morph_api_ms: 0, local_tools_ms: 0 };
    enforceContextLimit(messages);
    const modelCallStart = Date.now();
    const assistantContent = await callModel(messages, model, {
      morphApiKey: config.morphApiKey,
      morphApiUrl: config.morphApiUrl,
      retryConfig: config.retryConfig,
      timeout: timeoutMs
    }).catch((e) => {
      const errMsg = e instanceof Error ? e.message : String(e);
      console.error(`[warp_grep:stream] Morph API call failed on turn ${turn}:`, errMsg);
      errors.push({ message: errMsg });
      return "";
    });
    turnMetrics.morph_api_ms = Date.now() - modelCallStart;
    if (!assistantContent) {
      console.error(`[warp_grep:stream] Empty response from Morph API on turn ${turn}. Errors so far:`, errors);
      timings.turns.push(turnMetrics);
      break;
    }
    messages.push({ role: "assistant", content: assistantContent });
    const toolCalls = parser.parse(assistantContent);
    if (toolCalls.length === 0) {
      console.error(`[warp_grep:stream] No tool calls parsed on turn ${turn}. Assistant content (first 500 chars):`, assistantContent.slice(0, 500));
      errors.push({ message: "No tool calls produced by the model. Your MCP is likely out of date! Update it by running: rm -rf ~/.npm/_npx && npm cache clean --force && npx -y @morphllm/morphmcp@latest" });
      terminationReason = "terminated";
      timings.turns.push(turnMetrics);
      break;
    }
    yield {
      turn,
      toolCalls: toolCalls.map((c) => ({
        name: c.name,
        arguments: c.arguments ?? {}
      }))
    };
    const finishCalls = toolCalls.filter((c) => c.name === "finish");
    const grepCalls = toolCalls.filter((c) => c.name === "grep");
    const listDirCalls = toolCalls.filter((c) => c.name === "list_directory");
    const readCalls = toolCalls.filter((c) => c.name === "read");
    const skipCalls = toolCalls.filter((c) => c.name === "_skip");
    const formatted = [];
    for (const c of skipCalls) {
      const msg = c.arguments?.message || "Command skipped due to parsing error";
      formatted.push(msg);
    }
    const allPromises = [];
    for (const c of grepCalls) {
      const args = c.arguments ?? {};
      allPromises.push(
        toolGrep(provider, args).then(
          ({ output }) => formatAgentToolOutput("grep", args, output, { isError: false }),
          (err) => formatAgentToolOutput("grep", args, String(err), { isError: true })
        )
      );
    }
    for (const c of listDirCalls) {
      const args = c.arguments ?? {};
      allPromises.push(
        toolListDirectory(provider, args).then(
          (p) => formatAgentToolOutput("list_directory", args, p, { isError: false }),
          (err) => formatAgentToolOutput("list_directory", args, String(err), { isError: true })
        )
      );
    }
    for (const c of readCalls) {
      const args = c.arguments ?? {};
      allPromises.push(
        toolRead(provider, args).then(
          (p) => formatAgentToolOutput("read", args, p, { isError: false }),
          (err) => formatAgentToolOutput("read", args, String(err), { isError: true })
        )
      );
    }
    const toolExecStart = Date.now();
    const allResults = await Promise.all(allPromises);
    turnMetrics.local_tools_ms = Date.now() - toolExecStart;
    for (const result of allResults) {
      formatted.push(result);
    }
    if (formatted.length > 0) {
      const turnMessage = formatTurnMessage(turn, maxTurns);
      const contextBudget = calculateContextBudget(messages);
      messages.push({ role: "user", content: formatted.join("\n") + turnMessage + "\n" + contextBudget });
    }
    timings.turns.push(turnMetrics);
    if (finishCalls.length) {
      const fc = finishCalls[0];
      const files = fc.arguments?.files ?? [];
      const textResult = fc.arguments?.textResult;
      finishMeta = { files };
      terminationReason = "completed";
      if (files.length === 0) {
        const payload2 = textResult || "No relevant code found.";
        timings.total_ms = Date.now() - totalStart;
        return {
          terminationReason: "completed",
          messages,
          finish: { payload: payload2, metadata: finishMeta },
          timings
        };
      }
      break;
    }
  }
  if (terminationReason !== "completed" || !finishMeta) {
    timings.total_ms = Date.now() - totalStart;
    return { terminationReason, messages, errors, timings };
  }
  const parts = ["Relevant context found:"];
  for (const f of finishMeta.files) {
    const ranges = f.lines === "*" ? "*" : Array.isArray(f.lines) ? f.lines.map(([s, e]) => `${s}-${e}`).join(", ") : "*";
    parts.push(`- ${f.path}: ${ranges}`);
  }
  const payload = parts.join("\n");
  const finishResolutionStart = Date.now();
  const fileReadErrors = [];
  const resolved = await readFinishFiles(
    repoRoot,
    finishMeta.files,
    async (p, s, e) => {
      try {
        const rr = await provider.read({ path: p, start: s, end: e });
        return rr.lines.map((l) => {
          const idx = l.indexOf("|");
          return idx >= 0 ? l.slice(idx + 1) : l;
        });
      } catch (err) {
        const errorMsg = err instanceof Error ? err.message : String(err);
        fileReadErrors.push({ path: p, error: errorMsg });
        console.error(`[warp_grep] Failed to read file: ${p} - ${errorMsg}`);
        return [`[couldn't find: ${p}]`];
      }
    }
  );
  timings.finish_resolution_ms = Date.now() - finishResolutionStart;
  if (fileReadErrors.length > 0) {
    errors.push(...fileReadErrors.map((e) => ({ message: `File read error: ${e.path} - ${e.error}` })));
  }
  timings.total_ms = Date.now() - totalStart;
  return {
    terminationReason: "completed",
    messages,
    finish: { payload, metadata: finishMeta, resolved },
    timings
  };
}

// tools/warp_grep/providers/remote.ts
init_config();
var SKIP_NAMES = /* @__PURE__ */ new Set([
  // Version control
  ".git",
  ".svn",
  ".hg",
  ".bzr",
  // Dependencies
  "node_modules",
  "bower_components",
  ".pnpm",
  ".yarn",
  "vendor",
  "Pods",
  ".bundle",
  // Python
  "__pycache__",
  ".pytest_cache",
  ".mypy_cache",
  ".ruff_cache",
  ".venv",
  "venv",
  ".tox",
  ".nox",
  ".eggs",
  // Build outputs
  "dist",
  "build",
  "out",
  "output",
  "target",
  "_build",
  ".next",
  ".nuxt",
  ".output",
  ".vercel",
  ".netlify",
  // Cache
  ".cache",
  ".parcel-cache",
  ".turbo",
  ".nx",
  ".gradle",
  // IDE
  ".idea",
  ".vscode",
  ".vs",
  // Coverage
  "coverage",
  ".coverage",
  "htmlcov",
  ".nyc_output",
  // Temp
  "tmp",
  "temp",
  ".tmp",
  ".temp",
  // Lock files
  "package-lock.json",
  "yarn.lock",
  "pnpm-lock.yaml",
  "bun.lockb",
  "Cargo.lock",
  "Gemfile.lock",
  "poetry.lock"
]);
var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
  ".min.js",
  ".min.css",
  ".bundle.js",
  ".wasm",
  ".so",
  ".dll",
  ".pyc",
  ".map",
  ".js.map"
]);
function shouldSkip(name) {
  if (SKIP_NAMES.has(name)) return true;
  if (name.startsWith(".")) return true;
  for (const ext of SKIP_EXTENSIONS) {
    if (name.endsWith(ext)) return true;
  }
  return false;
}
var RemoteCommandsProvider = class {
  constructor(repoRoot, commands) {
    this.repoRoot = repoRoot;
    this.commands = commands;
  }
  /**
   * Run grep command and parse ripgrep output
   */
  async grep(params) {
    try {
      const stdout = await this.commands.grep(params.pattern, params.path, params.glob);
      const lines = (stdout || "").trim().split(/\r?\n/).filter((l) => l.length > 0);
      if (lines.length > AGENT_CONFIG.MAX_OUTPUT_LINES) {
        return {
          lines: [],
          error: "Query not specific enough - too many results returned. Try a more specific pattern."
        };
      }
      return { lines };
    } catch (error) {
      return {
        lines: [],
        error: `[GREP ERROR] ${error instanceof Error ? error.message : String(error)}`
      };
    }
  }
  /**
   * Read file and add line numbers
   */
  async read(params) {
    const rawStart = params.start;
    const rawEnd = params.end;
    const startValid = rawStart === void 0 || Number.isFinite(rawStart) && rawStart > 0;
    const endValid = rawEnd === void 0 || Number.isFinite(rawEnd) && rawEnd > 0;
    const rangeValid = startValid && endValid && (rawStart === void 0 || rawEnd === void 0 || rawStart <= rawEnd);
    const start = rangeValid && rawStart !== void 0 ? rawStart : 1;
    const end = rangeValid && rawEnd !== void 0 ? rawEnd : 1e6;
    try {
      const stdout = await this.commands.read(params.path, start, end);
      const contentLines = (stdout || "").split("\n");
      if (contentLines.length > 0 && contentLines[contentLines.length - 1] === "") {
        contentLines.pop();
      }
      const lines = contentLines.map((content, idx) => `${start + idx}|${content}`);
      if (lines.length > AGENT_CONFIG.MAX_READ_LINES) {
        const truncated = lines.slice(0, AGENT_CONFIG.MAX_READ_LINES);
        truncated.push(`... [truncated: showing ${AGENT_CONFIG.MAX_READ_LINES} of ${lines.length} lines]`);
        return { lines: truncated };
      }
      return { lines };
    } catch (error) {
      return {
        lines: [],
        error: `[READ ERROR] ${error instanceof Error ? error.message : String(error)}`
      };
    }
  }
  /**
   * List directory and parse find output
   */
  async listDirectory(params) {
    const maxDepth = params.maxDepth ?? AGENT_CONFIG.MAX_LIST_DEPTH;
    const maxResults = params.maxResults ?? AGENT_CONFIG.MAX_OUTPUT_LINES;
    try {
      const stdout = await this.commands.listDir(params.path, maxDepth);
      const paths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
      const regex = params.pattern ? new RegExp(params.pattern) : null;
      const entries = [];
      for (const fullPath of paths) {
        if (fullPath === params.path || fullPath === this.repoRoot) continue;
        const name = fullPath.split("/").pop() || "";
        if (shouldSkip(name)) continue;
        if (regex && !regex.test(name)) continue;
        let relativePath = fullPath;
        if (fullPath.startsWith(this.repoRoot)) {
          relativePath = fullPath.slice(this.repoRoot.length).replace(/^\//, "");
        }
        const depth = relativePath.split("/").filter(Boolean).length - 1;
        const hasExtension = name.includes(".") && !name.startsWith(".");
        const type = hasExtension ? "file" : "dir";
        entries.push({
          name,
          path: relativePath,
          type,
          depth: Math.max(0, depth)
        });
        if (entries.length >= maxResults) break;
      }
      return entries;
    } catch (error) {
      return [];
    }
  }
};

// tools/warp_grep/providers/code_storage_http.ts
async function post(url, body, op) {
  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  });
  if (!res.ok) {
    const text = await res.text().catch(() => res.statusText);
    throw new Error(`${op} failed (${res.status}): ${text}`);
  }
  const data = await res.json();
  if (data.error) throw new Error(data.error);
  return data.stdout;
}
function createCodeStorageHttpCommands(config) {
  const { baseUrl, repoId, branch } = config;
  const encodedRepoId = encodeURIComponent(repoId);
  return {
    grep: (pattern, path5, glob) => post(`${baseUrl}/api/code-search/${encodedRepoId}/grep`, { pattern, path: path5, glob, branch }, "grep"),
    read: (path5, start, end) => post(`${baseUrl}/api/code-search/${encodedRepoId}/read`, { path: path5, start, end, branch }, "read"),
    listDir: (path5, maxDepth) => post(`${baseUrl}/api/code-search/${encodedRepoId}/list`, { path: path5, maxDepth, branch }, "list")
  };
}

// tools/warp_grep/utils/github.ts
function parseGitHubUrl(input) {
  input = input.trim();
  const urlPattern = /^(?:https?:\/\/)?github\.com\/([^\/]+)\/([^\/\?\#]+)/;
  const match = input.match(urlPattern);
  if (match) {
    return { owner: match[1], repo: match[2].replace(/\.git$/, "") };
  }
  const shortPattern = /^([^\/]+)\/([^\/]+)$/;
  const shortMatch = input.match(shortPattern);
  if (shortMatch && !shortMatch[1].includes(".")) {
    return { owner: shortMatch[1], repo: shortMatch[2].replace(/\.git$/, "") };
  }
  throw new Error(
    `Invalid GitHub URL or shorthand: "${input}". Expected "owner/repo" or "https://github.com/owner/repo"`
  );
}

// tools/warp_grep/client.ts
var DEFAULT_CODE_SEARCH_URL = "https://morphllm.com";
async function getLocalProvider(repoRoot, excludes) {
  const { LocalRipgrepProvider: LocalRipgrepProvider2 } = await Promise.resolve().then(() => (init_local(), local_exports));
  return new LocalRipgrepProvider2(repoRoot, excludes);
}
var WarpGrepClient = class {
  config;
  constructor(config = {}) {
    this.config = { ...config };
  }
  execute(input) {
    const toolConfig = {
      repoRoot: input.repoRoot,
      remoteCommands: input.remoteCommands,
      provider: input.provider,
      excludes: input.excludes,
      includes: input.includes,
      debug: input.debug ?? this.config.debug,
      morphApiKey: this.config.morphApiKey,
      morphApiUrl: this.config.morphApiUrl,
      retryConfig: this.config.retryConfig,
      timeout: this.config.timeout
    };
    if (input.streamSteps) {
      return executeToolCallStreaming({ query: input.query }, toolConfig);
    }
    return executeToolCall({ query: input.query }, toolConfig);
  }
  searchGitHub(input) {
    if (input.streamSteps) {
      return this._searchGitHubStreaming(input);
    }
    return this._searchGitHubAsync(input);
  }
  async _resolveGitHubRepo(input) {
    const { owner, repo } = parseGitHubUrl(input.github);
    const baseUrl = this.config.codeSearchUrl || DEFAULT_CODE_SEARCH_URL;
    const importRes = await fetch(`${baseUrl}/api/code-search/get-or-create?url=${encodeURIComponent(`${owner}/${repo}`)}`);
    if (!importRes.ok) {
      const text = await importRes.text().catch(() => importRes.statusText);
      throw new Error(`Failed to import repo ${owner}/${repo}: ${text}`);
    }
    const { repoId, defaultBranch } = await importRes.json();
    return {
      repo,
      remoteCommands: createCodeStorageHttpCommands({ baseUrl, repoId, branch: input.branch || defaultBranch })
    };
  }
  async _searchGitHubAsync(input) {
    try {
      const { repo, remoteCommands } = await this._resolveGitHubRepo(input);
      return this.execute({
        query: input.query,
        repoRoot: repo,
        remoteCommands
      });
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : String(error) };
    }
  }
  async *_searchGitHubStreaming(input) {
    let repo;
    let remoteCommands;
    try {
      ({ repo, remoteCommands } = await this._resolveGitHubRepo(input));
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : String(error) };
    }
    const generator = this.execute({
      query: input.query,
      repoRoot: repo,
      remoteCommands,
      streamSteps: true
    });
    let result;
    for (; ; ) {
      const { value, done } = await generator.next();
      if (done) {
        result = value;
        break;
      }
      yield value;
    }
    return result;
  }
};
function executeWarpGrep(input, config) {
  const client = new WarpGrepClient(config);
  if (input.streamSteps) {
    return client.execute({ ...input, streamSteps: true });
  }
  return client.execute({ ...input, streamSteps: false });
}
async function executeToolCall(input, config) {
  const parsed = typeof input === "string" ? JSON.parse(input) : input;
  const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes);
  const result = await runWarpGrep({
    query: parsed.query,
    repoRoot: config.repoRoot,
    provider,
    excludes: config.excludes,
    includes: config.includes,
    debug: config.debug ?? false,
    morphApiKey: config.morphApiKey,
    morphApiUrl: config.morphApiUrl,
    retryConfig: config.retryConfig,
    timeout: config.timeout
  });
  const finish = result.finish;
  if (result.terminationReason !== "completed" || !finish?.metadata) {
    const errorDetails = result.errors?.map((e) => e.message).join("; ") || "unknown reason";
    console.error(`[warp_grep] executeToolCall failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);
    return { success: false, error: `Search did not complete: ${errorDetails}` };
  }
  const contexts = (finish.resolved ?? []).map((r) => ({
    file: r.path,
    content: r.content,
    lines: r.ranges
  }));
  return { success: true, contexts, summary: finish.payload };
}
function processAgentResult(result) {
  const finish = result.finish;
  if (result.terminationReason !== "completed" || !finish?.metadata) {
    const errorDetails = result.errors?.map((e) => e.message).join("; ") || "unknown reason";
    console.error(`[warp_grep] processAgentResult failed. Reason: ${result.terminationReason}. Errors: ${errorDetails}. Turns: ${result.timings?.turns?.length ?? 0}`);
    return { success: false, error: `Search did not complete: ${errorDetails}` };
  }
  const contexts = (finish.resolved ?? []).map((r) => ({
    file: r.path,
    content: r.content,
    lines: r.ranges
  }));
  return { success: true, contexts, summary: finish.payload };
}
async function* executeToolCallStreaming(input, config) {
  const parsed = typeof input === "string" ? JSON.parse(input) : input;
  const provider = config.remoteCommands ? new RemoteCommandsProvider(config.repoRoot, config.remoteCommands) : config.provider ?? await getLocalProvider(config.repoRoot, config.excludes);
  const generator = runWarpGrepStreaming({
    query: parsed.query,
    repoRoot: config.repoRoot,
    provider,
    excludes: config.excludes,
    includes: config.includes,
    debug: config.debug ?? false,
    morphApiKey: config.morphApiKey,
    morphApiUrl: config.morphApiUrl,
    retryConfig: config.retryConfig,
    timeout: config.timeout
  });
  let agentResult;
  for (; ; ) {
    const { value, done } = await generator.next();
    if (done) {
      agentResult = value;
      break;
    }
    yield value;
  }
  return processAgentResult(agentResult);
}
function formatResult(result) {
  if (!result.success) {
    return `Search failed: ${result.error}`;
  }
  if (!result.contexts || result.contexts.length === 0) {
    return "No relevant code found. Try rephrasing your query.";
  }
  const parts = [];
  parts.push(`Morph Fast Context subagent performed search on repository:
`);
  parts.push("Relevant context found:");
  for (const ctx of result.contexts) {
    const rangeStr = !ctx.lines || ctx.lines === "*" ? "*" : ctx.lines.map(([s, e]) => `${s}-${e}`).join(",");
    parts.push(`- ${ctx.file}:${rangeStr}`);
  }
  parts.push("\nHere is the content of files:\n");
  for (const ctx of result.contexts) {
    const rangeStr = !ctx.lines || ctx.lines === "*" ? "" : ` lines="${ctx.lines.map(([s, e]) => `${s}-${e}`).join(",")}"`;
    parts.push(`<file path="${ctx.file}"${rangeStr}>`);
    parts.push(ctx.content);
    parts.push("</file>\n");
  }
  return parts.join("\n");
}

// tools/warp_grep/prompts.ts
var WARP_GREP_TOOL_NAME = "warpgrep_codebase_search";
var WARP_GREP_DESCRIPTION = 'IMPORTANT: If you need to explore the codebase to gather context, and the task does not involve a single file or function which is provided by name, you should ALWAYS use the warpgrep codebase search tool first instead of running search commands. When the task requires exploration beyond a single known file, invoke warpgrep first with a natural-language query describing the target functionality, bug, or architectural concern. Warp Grep is a fast and accurate tool that can search for all relevant context in a codebase. Keep queries action-oriented (e.g., "Find where billing invoices are generated and emailed"), and after reviewing the summarized results, you may verify important findings with other search tools or direct file reads to ensure completeness. Warp Grep can be used for query types like: find function responsible for <small feature>; find code that does <description>; find code path for <big feature>; Where does <minimal error message> come from?; or any query of that type. When a task requires exploration beyond a single known file, ALWAYS default to warpgrep codebase search before other search mechanisms.';
var GITHUB_SEARCH_TOOL_NAME = "warpgrep_github_search";
var GITHUB_SEARCH_DESCRIPTION = "Search a public GitHub repository using WarpGrep. Provide a GitHub URL or owner/repo shorthand and a natural language query.";
var GITHUB_SEARCH_INPUT_SCHEMA = {
  type: "object",
  properties: {
    query: { type: "string", description: "Natural language search query describing what to find in the repository" },
    github: { type: "string", description: 'GitHub repository URL or owner/repo shorthand (e.g., "vercel/next.js" or "https://github.com/vercel/next.js")' },
    branch: { type: "string", description: "Branch to search (defaults to the repository default branch)" }
  },
  required: ["query", "github"]
};

// tools/warp_grep/providers/index.ts
init_local();

// tools/warp_grep/index.ts
init_paths();

// tools/warp_grep/agent/index.ts
init_config();

// tools/warp_grep/index.ts
var warpGrepInputSchema = import_zod.z.object({
  query: import_zod.z.string().describe("Free-form repository question")
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  GITHUB_SEARCH_DESCRIPTION,
  GITHUB_SEARCH_INPUT_SCHEMA,
  GITHUB_SEARCH_TOOL_NAME,
  LocalRipgrepProvider,
  RemoteCommandsProvider,
  WARP_GREP_DESCRIPTION,
  WARP_GREP_SYSTEM_PROMPT,
  WARP_GREP_TOOL_NAME,
  WarpGrepClient,
  createCodeStorageHttpCommands,
  executeToolCall,
  executeWarpGrep,
  fixPathRepetition,
  formatResult,
  getSystemPrompt,
  normalizeFinishFiles,
  readFinishFiles,
  runWarpGrep,
  runWarpGrepStreaming,
  toolGrep,
  toolListDirectory,
  toolRead,
  warpGrepInputSchema
});
//# sourceMappingURL=index.cjs.map