"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// tools/warp_grep/providers/remote.ts
var remote_exports = {};
__export(remote_exports, {
  RemoteCommandsProvider: () => RemoteCommandsProvider
});
module.exports = __toCommonJS(remote_exports);

// tools/warp_grep/agent/config.ts
var parseEnvTimeout = (envValue, defaultMs) => {
  if (!envValue) return defaultMs;
  const parsed = parseInt(envValue, 10);
  return isNaN(parsed) || parsed <= 0 ? defaultMs : parsed;
};
var AGENT_CONFIG = {
  MAX_TURNS: 6,
  /** 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: 321600,
  MAX_OUTPUT_LINES: 200,
  MAX_LIST_RESULTS: 500,
  MAX_READ_LINES: 800,
  MAX_LIST_DEPTH: 3,
  LIST_TIMEOUT_MS: 2e3
};
var 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
  ".*"
];
var DEFAULT_EXCLUDES = (process.env.MORPH_WARP_GREP_EXCLUDE || "").split(",").map((s) => s.trim()).filter(Boolean).concat(BUILTIN_EXCLUDES);

// tools/warp_grep/providers/remote.ts
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) {
        const truncated = lines.slice(0, AGENT_CONFIG.MAX_OUTPUT_LINES);
        truncated.push(`... (output truncated at ${AGENT_CONFIG.MAX_OUTPUT_LINES} of ${lines.length} lines)`);
        return { lines: truncated };
      }
      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(`... (output truncated at ${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 [];
    }
  }
  /**
   * Glob search - finds files matching a pattern.
   * Falls back to a grep --files approach via the listDir command.
   */
  async glob(params) {
    const searchPath = params.path || this.repoRoot;
    try {
      const stdout = await this.commands.listDir(searchPath, 10);
      const allPaths = (stdout || "").trim().split(/\r?\n/).filter((p) => p.length > 0);
      const globToRegex = (glob) => {
        const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
        return new RegExp(escaped);
      };
      const regex = globToRegex(params.pattern);
      const matched = allPaths.filter((p) => {
        const name = p.split("/").pop() || "";
        return regex.test(name) && !shouldSkip(name);
      });
      const totalFound = matched.length;
      return { files: matched.slice(0, 100), searchDir: searchPath, totalFound };
    } catch (error) {
      return {
        files: [],
        searchDir: searchPath,
        totalFound: 0,
        error: `[GLOB ERROR] ${error instanceof Error ? error.message : String(error)}`
      };
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  RemoteCommandsProvider
});
//# sourceMappingURL=remote.cjs.map