"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 __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/harness.ts
var harness_exports = {};
__export(harness_exports, {
  AGENT_CONFIG: () => AGENT_CONFIG,
  DEFAULT_EXCLUDES: () => DEFAULT_EXCLUDES,
  LLMResponseParser: () => LLMResponseParser,
  LocalRipgrepProvider: () => LocalRipgrepProvider,
  SYSTEM_PROMPT: () => SYSTEM_PROMPT,
  buildInitialState: () => buildInitialState,
  calculateContextBudget: () => calculateContextBudget,
  formatListDirectoryTree: () => formatListDirectoryTree,
  formatToolResult: () => formatAgentToolOutput,
  formatTurnMessage: () => formatTurnMessage,
  getSystemPrompt: () => getSystemPrompt,
  normalizeFinishFiles: () => normalizeFinishFiles,
  parseToolCalls: () => parseToolCalls,
  readFinishFiles: () => readFinishFiles,
  resolveFinishFiles: () => resolveFinishFiles,
  toolGrep: () => toolGrep,
  toolListDirectory: () => toolListDirectory,
  toolRead: () => toolRead
});
module.exports = __toCommonJS(harness_exports);

// 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 path4 = getXmlElementText(content, "path");
      const pattern = getXmlElementText(content, "pattern");
      if (path4) {
        tools.push({ name: "list_directory", arguments: { path: path4, 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 path4 = getXmlElementText(content, "path");
      const linesStr = getXmlElementText(content, "lines");
      if (path4) {
        const args = { path: path4 };
        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(([path4, ranges]) => ({
        path: path4,
        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 path4 = parts[1];
    const pattern = parts[2]?.replace(/^"|"$/g, "") ?? null;
    commands.push({ name: "list_directory", arguments: { path: path4, 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/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/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 path4 = this.asString(args.path) || "...";
    const start = args.start;
    const end = args.end;
    const linesArray = args.lines;
    const attributes = [`path="${path4}"`];
    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 path4 = this.asString(args.path) || ".";
    const pattern = this.asString(args.pattern);
    const attributes = [`path="${path4}"`];
    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);

// 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: 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
};
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/agent/helpers.ts
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 formatListDirectoryTree(entries) {
  if (!entries.length) return "empty";
  return entries.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/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
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/providers/local.ts
var import_promises2 = __toESM(require("fs/promises"), 1);
var import_path3 = __toESM(require("path"), 1);

// tools/warp_grep/utils/ripgrep.ts
var import_child_process = require("child_process");
var import_ripgrep = require("@vscode/ripgrep");
var resolvedRgPath = null;
var rgPathChecked = false;
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
  };
}

// tools/warp_grep/utils/paths.ts
var import_fs = __toESM(require("fs"), 1);
var import_path2 = __toESM(require("path"), 1);
function resolveUnderRepo(repoRoot, targetPath) {
  const absRoot = import_path2.default.resolve(repoRoot);
  const resolved = import_path2.default.resolve(absRoot, targetPath);
  ensureWithinRepo(absRoot, resolved);
  return resolved;
}
function ensureWithinRepo(repoRoot, absTarget) {
  const rel = import_path2.default.relative(import_path2.default.resolve(repoRoot), import_path2.default.resolve(absTarget));
  if (rel.startsWith("..") || import_path2.default.isAbsolute(rel)) {
    throw new Error(`Path outside repository root: ${absTarget}`);
  }
}
function toRepoRelative(repoRoot, absPath) {
  return import_path2.default.relative(import_path2.default.resolve(repoRoot), import_path2.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_path2.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_path2.default.sep + fixed.join(import_path2.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;
  }
}

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

// tools/warp_grep/providers/local.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 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_path3.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 (shouldSkip(entry.name)) continue;
        if (regex && !regex.test(entry.name)) continue;
        const full = import_path3.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/harness.ts
var parser = new LLMResponseParser();
function parseToolCalls(text) {
  return parser.parse(text);
}
async function resolveFinishFiles(provider, files) {
  return readFinishFiles("", files, async (p, s, e) => {
    const r = await provider.read({ path: p, start: s, end: e });
    return r.lines.map((l) => {
      const idx = l.indexOf("|");
      return idx >= 0 ? l.slice(idx + 1) : l;
    });
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AGENT_CONFIG,
  DEFAULT_EXCLUDES,
  LLMResponseParser,
  LocalRipgrepProvider,
  SYSTEM_PROMPT,
  buildInitialState,
  calculateContextBudget,
  formatListDirectoryTree,
  formatToolResult,
  formatTurnMessage,
  getSystemPrompt,
  normalizeFinishFiles,
  parseToolCalls,
  readFinishFiles,
  resolveFinishFiles,
  toolGrep,
  toolListDirectory,
  toolRead
});
//# sourceMappingURL=harness.cjs.map