From 660de97f2e70929f23c7911d2bcd39282ed84c77 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 25 Jul 2025 20:06:37 +0700 Subject: [PATCH] feat: cli search and replace tool --- package-lock.json | 4 +- src/tools/searchAndReplace/findSearchMatch.ts | 317 ++++++++++++++++++ src/tools/searchAndReplace/index.ts | 178 ++++++++++ src/tools/searchAndReplace/parseBlock.ts | 147 ++++++++ src/tools/types.ts | 5 +- src/tools/writeFile.ts | 2 +- 6 files changed, 649 insertions(+), 4 deletions(-) create mode 100644 src/tools/searchAndReplace/findSearchMatch.ts create mode 100644 src/tools/searchAndReplace/index.ts create mode 100644 src/tools/searchAndReplace/parseBlock.ts diff --git a/package-lock.json b/package-lock.json index 39059bba9..0e65af766 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/cli", - "version": "1.4.2", + "version": "0.0.0-dev", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/cli", - "version": "1.4.2", + "version": "0.0.0-dev", "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "^1.0.96", diff --git a/src/tools/searchAndReplace/findSearchMatch.ts b/src/tools/searchAndReplace/findSearchMatch.ts new file mode 100644 index 000000000..bb731e6a5 --- /dev/null +++ b/src/tools/searchAndReplace/findSearchMatch.ts @@ -0,0 +1,317 @@ +/** + * Represents a basic match result with start and end character positions + */ +interface BasicMatchResult { + /** The starting character index of the match in the file content */ + startIndex: number; + /** The ending character index of the match in the file content */ + endIndex: number; +} + +/** + * Represents a match result with start and end character positions + */ +export interface SearchMatchResult extends BasicMatchResult { + /** The name of the strategy that successfully matched */ + strategyName: string; +} + +/** + * Strategy function type for finding matches + */ +type MatchStrategy = ( + fileContent: string, + searchContent: string +) => BasicMatchResult | null; + +/** + * Exact string matching strategy + */ +function exactMatch( + fileContent: string, + searchContent: string +): BasicMatchResult | null { + const exactIndex = fileContent.indexOf(searchContent); + if (exactIndex !== -1) { + return { + startIndex: exactIndex, + endIndex: exactIndex + searchContent.length, + }; + } + return null; +} + +/** + * Trimmed content matching strategy + */ +function trimmedMatch( + fileContent: string, + searchContent: string +): BasicMatchResult | null { + const trimmedSearchContent = searchContent.trim(); + const trimmedIndex = fileContent.indexOf(trimmedSearchContent); + if (trimmedIndex !== -1) { + return { + startIndex: trimmedIndex, + endIndex: trimmedIndex + trimmedSearchContent.length, + }; + } + return null; +} + +/** + * Whitespace-ignored matching strategy + * Removes all whitespace from both content and search, then finds the match + */ +function whitespaceIgnoredMatch( + fileContent: string, + searchContent: string +): BasicMatchResult | null { + // Remove all whitespace (spaces, tabs, newlines, etc.) + const strippedFileContent = fileContent.replace(/\s/g, ""); + const strippedSearchContent = searchContent.replace(/\s/g, ""); + + if (strippedSearchContent === "") { + return null; // Empty search after stripping whitespace + } + + const strippedIndex = strippedFileContent.indexOf(strippedSearchContent); + if (strippedIndex === -1) { + return null; + } + + // Map the stripped position back to the original file content + let originalStartIndex = 0; + let strippedCharCount = 0; + + // Find the original position by counting non-whitespace characters + for (let i = 0; i < fileContent.length; i++) { + if (strippedCharCount === strippedIndex) { + originalStartIndex = i; + break; + } + if (!/\s/.test(fileContent[i])) { + strippedCharCount++; + } + } + + // Find the end position by counting the length of the search content + let originalEndIndex = originalStartIndex; + let matchedChars = 0; + + for ( + let i = originalStartIndex; + i < fileContent.length && matchedChars < strippedSearchContent.length; + i++ + ) { + if (!/\s/.test(fileContent[i])) { + matchedChars++; + } + originalEndIndex = i + 1; + } + + return { + startIndex: originalStartIndex, + endIndex: originalEndIndex, + }; +} + +/** + * Calculate the Jaro similarity between two strings + */ +function jaroSimilarity(s1: string, s2: string): number { + if (s1 === s2) return 1.0; + if (s1.length === 0 || s2.length === 0) return 0.0; + + const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1; + if (matchDistance < 0) return 0.0; + + const s1Matches = new Array(s1.length).fill(false); + const s2Matches = new Array(s2.length).fill(false); + + let matches = 0; + let transpositions = 0; + + // Find matches + for (let i = 0; i < s1.length; i++) { + const start = Math.max(0, i - matchDistance); + const end = Math.min(i + matchDistance + 1, s2.length); + + for (let j = start; j < end; j++) { + if (s2Matches[j] || s1[i] !== s2[j]) continue; + s1Matches[i] = true; + s2Matches[j] = true; + matches++; + break; + } + } + + if (matches === 0) return 0.0; + + // Count transpositions + let k = 0; + for (let i = 0; i < s1.length; i++) { + if (!s1Matches[i]) continue; + while (!s2Matches[k]) k++; + if (s1[i] !== s2[k]) transpositions++; + k++; + } + + return ( + (matches / s1.length + + matches / s2.length + + (matches - transpositions / 2) / matches) / + 3.0 + ); +} + +/** + * Calculate the Jaro-Winkler similarity between two strings + */ +function jaroWinklerSimilarity( + s1: string, + s2: string, + prefixScale = 0.1 +): number { + const jaroSim = jaroSimilarity(s1, s2); + + if (jaroSim < 0.7) return jaroSim; + + // Calculate common prefix length (up to 4 characters) + let prefixLength = 0; + const maxPrefix = Math.min(4, Math.min(s1.length, s2.length)); + + for (let i = 0; i < maxPrefix; i++) { + if (s1[i] === s2[i]) { + prefixLength++; + } else { + break; + } + } + + return jaroSim + prefixLength * prefixScale * (1 - jaroSim); +} + +/** + * Find the best fuzzy match for search content in file content using Jaro-Winkler + */ +function findFuzzyMatch( + fileContent: string, + searchContent: string, + threshold: number = 0.9 +): BasicMatchResult | null { + const searchLines = searchContent.split("\n"); + const fileLines = fileContent.split("\n"); + + let bestMatch: BasicMatchResult | null = null; + let bestSimilarity = 0; + + // Try matching the search content as a whole block + const searchBlock = searchContent.trim(); + if (searchBlock.length > 5) { + // Require minimum length for meaningful matches + // Use sliding window approach for multi-line search + for (let i = 0; i <= fileLines.length - searchLines.length; i++) { + const candidateLines = fileLines.slice(i, i + searchLines.length); + const candidateBlock = candidateLines.join("\n").trim(); + + if (candidateBlock.length < 5) continue; // Skip very short blocks + + const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock); + + if (similarity >= threshold && similarity > bestSimilarity) { + // Calculate character positions + const linesBeforeMatch = fileLines.slice(0, i); + const startIndex = + linesBeforeMatch.join("\n").length + + (linesBeforeMatch.length > 0 ? 1 : 0); + const endIndex = startIndex + candidateBlock.length; + + bestMatch = { + startIndex, + endIndex, + }; + bestSimilarity = similarity; + } + } + } + + // Also try line-by-line matching for better granularity + for ( + let searchLineIdx = 0; + searchLineIdx < searchLines.length; + searchLineIdx++ + ) { + const searchLine = searchLines[searchLineIdx].trim(); + if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines + + for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) { + const fileLine = fileLines[fileLineIdx].trim(); + if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines + + const similarity = jaroWinklerSimilarity(searchLine, fileLine); + + if (similarity >= threshold && similarity > bestSimilarity) { + // Calculate character positions for the line + const linesBeforeMatch = fileLines.slice(0, fileLineIdx); + const startIndex = + linesBeforeMatch.join("\n").length + + (linesBeforeMatch.length > 0 ? 1 : 0); + const endIndex = startIndex + fileLines[fileLineIdx].length; + + bestMatch = { + startIndex, + endIndex, + }; + bestSimilarity = similarity; + } + } + } + + return bestMatch; +} + +/** + * Ordered list of matching strategies to try with their names + */ +const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [ + { strategy: exactMatch, name: "exactMatch" }, + { strategy: trimmedMatch, name: "trimmedMatch" }, + { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" }, + { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" }, +]; + +/** + * Find the exact match position for search content in file content. + * Uses multiple matching strategies in order of preference. + * + * Matching Strategy: + * 1. If search content is empty, matches at the beginning of file (position 0) + * 2. Try each matching strategy in order until one succeeds + * + * @param fileContent - The complete content of the file to search in + * @param searchContent - The content to search for + * @param config - Configuration options for matching behavior + * @returns Match result with character positions, or null if no match found + */ +export function findSearchMatch( + fileContent: string, + searchContent: string +): SearchMatchResult | null { + const trimmedSearchContent = searchContent.trim(); + + if (trimmedSearchContent === "") { + // Empty search content matches the beginning of the file + return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" }; + } + + // Try each matching strategy in order + for (const { strategy, name } of matchingStrategies) { + const result = strategy(fileContent, searchContent); + if (result !== null) { + return { ...result, strategyName: name }; + } + } + + return null; +} diff --git a/src/tools/searchAndReplace/index.ts b/src/tools/searchAndReplace/index.ts new file mode 100644 index 000000000..65b155732 --- /dev/null +++ b/src/tools/searchAndReplace/index.ts @@ -0,0 +1,178 @@ +import { findSearchMatch } from "./findSearchMatch.js"; +import { parseAllSearchReplaceBlocks } from "./parseBlock.js"; +import { Tool } from "../types.js"; +import { generateDiff } from "../writeFile.js"; +import * as fs from "fs"; +import * as path from "path"; +import telemetryService from "../../telemetry/telemetryService.js"; +import { + calculateLinesOfCodeDiff, + getLanguageFromFilePath, +} from "../../telemetry/utils.js"; + +export interface SearchAndReplaceInFileArgs { + filepath: string; + diffs: string[]; +} + +// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts` +export const NO_PARALLEL_TOOL_CALLING_INSRUCTION = + "Note this tool CANNOT be called in parallel."; + +/** + * This tool is in an experimental state. + * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 + */ +export const searchAndReplaceInFileTool: Tool = { + name: "search_and_replace_in_file", + displayName: "Search and Replace", + readonly: false, + description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, + parameters: { + filepath: { + type: "string", + description: "The path to the file to edit", + required: true, + }, + diffs: { + type: "array", + items: { + type: "string", + }, + description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: +\`\`\` +------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE +\`\`\` + +Critical rules: +1. SEARCH content must match the associated file section to find EXACTLY: + * Match character-for-character including whitespace, indentation, line endings + * Include all comments, docstrings, etc. +2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. + * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. + * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. + * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. +3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application. +4. Keep SEARCH/REPLACE blocks concise: + * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. + * Include just the changing lines, and a few surrounding lines if needed for uniqueness. + * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. + * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. +5. Splitting up tool calls: + * When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls + * If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls + * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] +6. Special operations: + * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) + * To delete code: Use empty REPLACE section + +Usage: +\`\`\` +------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE + +------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE + \`\`\` + +Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`, + required: true, + }, + }, + run: async (args) => { + try { + // Get and validate args + const { filepath, diffs } = args; + + if (!filepath || !diffs) { + throw new Error("filepath and diffs args are required"); + } + + if (typeof filepath !== "string") { + throw new Error("filepath must be a string"); + } + + if ( + !Array.isArray(diffs) || + diffs.some((diff) => typeof diff !== "string") + ) { + throw new Error( + "diffs must be an array of string search/replace blocks" + ); + } + + // Get current file contents + const fixedPath = filepath.replace(/\/|\\/g, path.sep); + + if (!fs.existsSync(fixedPath)) { + throw new Error(`file ${filepath} does not exist`); + } + const oldContent = fs.readFileSync(fixedPath, "utf-8"); + let newContent = oldContent; + + // Parse blocks + const blocks = diffs.map(parseAllSearchReplaceBlocks).flat(); + if (blocks.length === 0) { + throw new Error("No complete search/replace blocks found in any diffs"); + } + + // Apply all replacements sequentially to build the final content + for (let i = 0; i < blocks.length; i++) { + const block = blocks[i]; + const { searchContent, replaceContent } = block; + + const match = findSearchMatch(newContent, searchContent || ""); + + if (!match) { + throw new Error( + `Search content not found in block ${i + 1}:\n${searchContent}` + ); + } + + newContent = + newContent.substring(0, match.startIndex) + + (replaceContent || "") + + newContent.substring(match.endIndex); + } + + // Get lines for telemetry + const { added, removed } = calculateLinesOfCodeDiff( + oldContent, + args.content + ); + const language = getLanguageFromFilePath(args.filepath); + + if (added > 0) { + telemetryService.recordLinesOfCodeModified("added", added, language); + } + if (removed > 0) { + telemetryService.recordLinesOfCodeModified( + "removed", + removed, + language + ); + } + + const diff = generateDiff(oldContent, args.content, args.filepath); + + // Record file operation + return `Successfully wrote to file: ${args.filepath}\n\nDiff:\n${diff}`; + } catch (error) { + throw new Error( + `Failed to apply search and replace: ${ + error instanceof Error ? error.message : String(error) + }` + ); + } + }, +}; diff --git a/src/tools/searchAndReplace/parseBlock.ts b/src/tools/searchAndReplace/parseBlock.ts new file mode 100644 index 000000000..8bc4088c0 --- /dev/null +++ b/src/tools/searchAndReplace/parseBlock.ts @@ -0,0 +1,147 @@ +// Search and replace block markers using flexible regex patterns +const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/; +const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/; +const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/; + +export interface SearchReplaceBlockResult { + /** Whether a complete search/replace block has been parsed */ + isComplete: boolean; + /** The content to search for in the file */ + searchContent?: string; + /** The content to replace the search content with */ + replaceContent?: string; + /** Error message if parsing failed */ + error?: string; +} + +/** + * Parses a search and replace block from content. + * + * Expected format: + * ------- SEARCH + * [content to find] + * ======= + * [content to replace with] + * +++++++ REPLACE + * + * @param content - The content to parse + * @returns ParseResult with completion status and extracted content + */ +export function parseSearchReplaceBlock( + content: string +): SearchReplaceBlockResult { + const lines = content.split("\n"); + + let currentSearchContent = ""; + let currentReplaceContent = ""; + let inSearch = false; + let inReplace = false; + + for (const line of lines) { + if (SEARCH_BLOCK_START_REGEX.test(line)) { + inSearch = true; + inReplace = false; + currentSearchContent = ""; + currentReplaceContent = ""; + continue; + } + + if (SEARCH_BLOCK_END_REGEX.test(line)) { + if (!inSearch) { + return { + isComplete: false, + error: "Found search block end marker without matching start marker", + }; + } + inSearch = false; + inReplace = true; + continue; + } + + if (REPLACE_BLOCK_END_REGEX.test(line)) { + if (!inReplace) { + return { + isComplete: false, + error: + "Found replace block end marker without matching replace start marker", + }; + } + + // Complete block found + return { + isComplete: true, + searchContent: currentSearchContent.trim(), + replaceContent: currentReplaceContent.trim(), + }; + } + + // Accumulate content + if (inSearch) { + currentSearchContent += line + "\n"; + } else if (inReplace) { + currentReplaceContent += line + "\n"; + } + } + + // Block is not yet complete + return { + isComplete: false, + searchContent: currentSearchContent.trim(), + replaceContent: currentReplaceContent.trim(), + }; +} + +/** + * Parses all complete search and replace blocks from content. + * + * @param content - The content containing multiple search/replace blocks + * @returns Array of complete search/replace blocks found + * @throws Error if any malformed blocks are encountered + */ +export function parseAllSearchReplaceBlocks( + content: string +): SearchReplaceBlockResult[] { + const blocks: SearchReplaceBlockResult[] = []; + const lines = content.split("\n"); + + let currentBlockLines: string[] = []; + let inBlock = false; + + for (const line of lines) { + if (SEARCH_BLOCK_START_REGEX.test(line)) { + // Start of new block + if (inBlock && currentBlockLines.length > 0) { + // Process previous incomplete block if any + const blockContent = currentBlockLines.join("\n"); + const result = parseSearchReplaceBlock(blockContent); + if (result.isComplete) { + blocks.push(result); + } else if (result.error) { + // Fail fast on any parsing error + throw new Error(result.error); + } + // If incomplete but no error, it's just a partial block - continue processing + } + currentBlockLines = [line]; + inBlock = true; + } else if (inBlock) { + currentBlockLines.push(line); + + // Check if this line completes the current block + if (REPLACE_BLOCK_END_REGEX.test(line)) { + const blockContent = currentBlockLines.join("\n"); + const result = parseSearchReplaceBlock(blockContent); + if (result.isComplete) { + blocks.push(result); + } else if (result.error) { + // Fail fast on any parsing error + throw new Error(result.error); + } + currentBlockLines = []; + inBlock = false; + } + } + } + + return blocks; +} diff --git a/src/tools/types.ts b/src/tools/types.ts index 65b2a0981..231186707 100644 --- a/src/tools/types.ts +++ b/src/tools/types.ts @@ -4,6 +4,9 @@ export type ToolParameters = Record< type: string; description: string; required: boolean; + items?: { + type: string; + }; } >; @@ -14,4 +17,4 @@ export interface Tool { parameters: ToolParameters; run: (args: any) => Promise; readonly?: boolean; // Indicates if the tool is readonly -} \ No newline at end of file +} diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index b23387b88..4b4cdd56f 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -8,7 +8,7 @@ import { } from "../telemetry/utils.js"; import { Tool } from "./types.js"; -function generateDiff( +export function generateDiff( oldContent: string, newContent: string, filePath: string