diff --git a/.roo/rules-issue-fixer/1_Workflow.xml b/.roo/rules-issue-fixer/1_Workflow.xml index 8aa595cde747..62a3fd7c269b 100644 --- a/.roo/rules-issue-fixer/1_Workflow.xml +++ b/.roo/rules-issue-fixer/1_Workflow.xml @@ -191,7 +191,6 @@ Use appropriate tools: - apply_diff for targeted changes - write_to_file for new files - - search_and_replace for systematic updates After each significant change, run relevant tests: - execute_command to run test suites diff --git a/.roo/rules-merge-resolver/2_best_practices.xml b/.roo/rules-merge-resolver/2_best_practices.xml index 5bf1b393eb28..ea6c7cc6a52a 100644 --- a/.roo/rules-merge-resolver/2_best_practices.xml +++ b/.roo/rules-merge-resolver/2_best_practices.xml @@ -33,7 +33,7 @@ Escape Conflict Markers - When using apply_diff or search_and_replace tools, always escape merge + When using apply_diff, always escape merge conflict markers with backslashes to prevent parsing errors. - apply_diff or search_and_replace + apply_diff To resolve conflicts by replacing conflicted sections Precise editing of specific conflict blocks @@ -127,25 +127,6 @@ function mergedImplementation() { ]]> - - - Use for simple conflict resolutions - Enable regex mode for complex patterns - Always escape special characters - - - -src/config.ts -\<<<<<<< HEAD[\s\S]*?\>>>>>>> \w+ -// Resolved configuration -const config = { - // Merged settings from both branches -} -true - - ]]> - @@ -215,7 +196,7 @@ const config = { Conflict markers are incomplete or nested - Use search_and_replace with careful regex patterns + Use apply_diff with precise search blocks; split into multiple targeted edits if needed Manual inspection may be required @@ -232,7 +213,7 @@ const config = { Code contains literal conflict marker strings Extra careful escaping in diffs - Consider using search_and_replace with precise patterns + Prefer apply_diff with precise search blocks diff --git a/apps/vscode-e2e/src/suite/tools/search-and-replace.test.ts b/apps/vscode-e2e/src/suite/tools/search-and-replace.test.ts deleted file mode 100644 index a371253a8e5a..000000000000 --- a/apps/vscode-e2e/src/suite/tools/search-and-replace.test.ts +++ /dev/null @@ -1,631 +0,0 @@ -import * as assert from "assert" -import * as fs from "fs/promises" -import * as path from "path" -import * as vscode from "vscode" - -import { RooCodeEventName, type ClineMessage } from "@roo-code/types" - -import { waitFor, sleep } from "../utils" -import { setDefaultSuiteTimeout } from "../test-utils" - -suite.skip("Roo Code search_and_replace Tool", function () { - setDefaultSuiteTimeout(this) - - let workspaceDir: string - - // Pre-created test files that will be used across tests - const testFiles = { - simpleReplace: { - name: `test-simple-replace-${Date.now()}.txt`, - content: "Hello World\nThis is a test file\nWith multiple lines\nHello again", - path: "", - }, - regexReplace: { - name: `test-regex-replace-${Date.now()}.js`, - content: `function oldFunction() { - console.log("old implementation") - return "old result" -} - -function anotherOldFunction() { - console.log("another old implementation") - return "another old result" -}`, - path: "", - }, - caseInsensitive: { - name: `test-case-insensitive-${Date.now()}.txt`, - content: `Hello World -HELLO UNIVERSE -hello everyone -HeLLo ThErE`, - path: "", - }, - multipleMatches: { - name: `test-multiple-matches-${Date.now()}.txt`, - content: `TODO: Fix this bug -This is some content -TODO: Add more tests -Some more content -TODO: Update documentation -Final content`, - path: "", - }, - noMatches: { - name: `test-no-matches-${Date.now()}.txt`, - content: "This file has no matching patterns\nJust regular content\nNothing special here", - path: "", - }, - } - - // Get the actual workspace directory that VSCode is using and create all test files - suiteSetup(async function () { - // Get the workspace folder from VSCode - const workspaceFolders = vscode.workspace.workspaceFolders - if (!workspaceFolders || workspaceFolders.length === 0) { - throw new Error("No workspace folder found") - } - workspaceDir = workspaceFolders[0]!.uri.fsPath - console.log("Using workspace directory:", workspaceDir) - - // Create all test files before any tests run - console.log("Creating test files in workspace...") - for (const [key, file] of Object.entries(testFiles)) { - file.path = path.join(workspaceDir, file.name) - await fs.writeFile(file.path, file.content) - console.log(`Created ${key} test file at:`, file.path) - } - - // Verify all files exist - for (const [key, file] of Object.entries(testFiles)) { - const exists = await fs - .access(file.path) - .then(() => true) - .catch(() => false) - if (!exists) { - throw new Error(`Failed to create ${key} test file at ${file.path}`) - } - } - }) - - // Clean up after all tests - suiteTeardown(async () => { - // Cancel any running tasks before cleanup - try { - await globalThis.api.cancelCurrentTask() - } catch { - // Task might not be running - } - - // Clean up all test files - console.log("Cleaning up test files...") - for (const [key, file] of Object.entries(testFiles)) { - try { - await fs.unlink(file.path) - console.log(`Cleaned up ${key} test file`) - } catch (error) { - console.log(`Failed to clean up ${key} test file:`, error) - } - } - }) - - // Clean up before each test - setup(async () => { - // Cancel any previous task - try { - await globalThis.api.cancelCurrentTask() - } catch { - // Task might not be running - } - - // Small delay to ensure clean state - await sleep(100) - }) - - // Clean up after each test - teardown(async () => { - // Cancel the current task - try { - await globalThis.api.cancelCurrentTask() - } catch { - // Task might not be running - } - - // Small delay to ensure clean state - await sleep(100) - }) - - test("Should perform simple text replacement", async function () { - const api = globalThis.api - const messages: ClineMessage[] = [] - const testFile = testFiles.simpleReplace - const expectedContent = "Hello Universe\nThis is a test file\nWith multiple lines\nHello again" - let taskStarted = false - let taskCompleted = false - let errorOccurred: string | null = null - let searchReplaceExecuted = false - - // Listen for messages - const messageHandler = ({ message }: { message: ClineMessage }) => { - messages.push(message) - - // Log important messages for debugging - if (message.type === "say" && message.say === "error") { - errorOccurred = message.text || "Unknown error" - console.error("Error:", message.text) - } - if (message.type === "ask" && message.ask === "tool") { - console.log("Tool request:", message.text?.substring(0, 200)) - } - if (message.type === "say" && (message.say === "completion_result" || message.say === "text")) { - console.log("AI response:", message.text?.substring(0, 200)) - } - - // Check for tool execution - if (message.type === "say" && message.say === "api_req_started" && message.text) { - console.log("API request started:", message.text.substring(0, 200)) - try { - const requestData = JSON.parse(message.text) - if (requestData.request && requestData.request.includes("search_and_replace")) { - searchReplaceExecuted = true - console.log("search_and_replace tool executed!") - } - } catch (e) { - console.log("Failed to parse api_req_started message:", e) - } - } - } - api.on(RooCodeEventName.Message, messageHandler) - - // Listen for task events - const taskStartedHandler = (id: string) => { - if (id === taskId) { - taskStarted = true - console.log("Task started:", id) - } - } - api.on(RooCodeEventName.TaskStarted, taskStartedHandler) - - const taskCompletedHandler = (id: string) => { - if (id === taskId) { - taskCompleted = true - console.log("Task completed:", id) - } - } - api.on(RooCodeEventName.TaskCompleted, taskCompletedHandler) - - let taskId: string - try { - // Start task with search_and_replace instruction - taskId = await api.startNewTask({ - configuration: { - mode: "code", - autoApprovalEnabled: true, - alwaysAllowWrite: true, - alwaysAllowReadOnly: true, - alwaysAllowReadOnlyOutsideWorkspace: true, - }, - text: `Use search_and_replace on the file ${testFile.name} to replace "Hello World" with "Hello Universe". - -The file is located at: ${testFile.path} - -The file already exists with this content: -${testFile.content} - -Assume the file exists and you can modify it directly.`, - }) - - console.log("Task ID:", taskId) - console.log("Test filename:", testFile.name) - - // Wait for task to start - await waitFor(() => taskStarted, { timeout: 45_000 }) - - // Check for early errors - if (errorOccurred) { - console.error("Early error detected:", errorOccurred) - } - - // Wait for task completion - await waitFor(() => taskCompleted, { timeout: 45_000 }) - - // Give extra time for file system operations - await sleep(2000) - - // Check if the file was modified correctly - const actualContent = await fs.readFile(testFile.path, "utf-8") - console.log("File content after modification:", actualContent) - - // Verify tool was executed - assert.strictEqual(searchReplaceExecuted, true, "search_and_replace tool should have been executed") - - // Verify file content - assert.strictEqual( - actualContent.trim(), - expectedContent.trim(), - "File content should be modified correctly", - ) - - console.log("Test passed! search_and_replace tool executed and file modified successfully") - } finally { - // Clean up - api.off(RooCodeEventName.Message, messageHandler) - api.off(RooCodeEventName.TaskStarted, taskStartedHandler) - api.off(RooCodeEventName.TaskCompleted, taskCompletedHandler) - } - }) - - test("Should perform regex pattern replacement", async function () { - const api = globalThis.api - const messages: ClineMessage[] = [] - const testFile = testFiles.regexReplace - const expectedContent = `function newFunction() { - console.log("new implementation") - return "new result" -} - -function anotherNewFunction() { - console.log("another new implementation") - return "another new result" -}` - let taskStarted = false - let taskCompleted = false - let errorOccurred: string | null = null - let searchReplaceExecuted = false - - // Listen for messages - const messageHandler = ({ message }: { message: ClineMessage }) => { - messages.push(message) - - // Log important messages for debugging - if (message.type === "say" && message.say === "error") { - errorOccurred = message.text || "Unknown error" - console.error("Error:", message.text) - } - if (message.type === "ask" && message.ask === "tool") { - console.log("Tool request:", message.text?.substring(0, 200)) - } - if (message.type === "say" && (message.say === "completion_result" || message.say === "text")) { - console.log("AI response:", message.text?.substring(0, 200)) - } - - // Check for tool execution - if (message.type === "say" && message.say === "api_req_started" && message.text) { - console.log("API request started:", message.text.substring(0, 200)) - try { - const requestData = JSON.parse(message.text) - if (requestData.request && requestData.request.includes("search_and_replace")) { - searchReplaceExecuted = true - console.log("search_and_replace tool executed!") - } - } catch (e) { - console.log("Failed to parse api_req_started message:", e) - } - } - } - api.on(RooCodeEventName.Message, messageHandler) - - // Listen for task events - const taskStartedHandler = (id: string) => { - if (id === taskId) { - taskStarted = true - console.log("Task started:", id) - } - } - api.on(RooCodeEventName.TaskStarted, taskStartedHandler) - - const taskCompletedHandler = (id: string) => { - if (id === taskId) { - taskCompleted = true - console.log("Task completed:", id) - } - } - api.on(RooCodeEventName.TaskCompleted, taskCompletedHandler) - - let taskId: string - try { - // Start task with search_and_replace instruction - simpler and more direct - taskId = await api.startNewTask({ - configuration: { - mode: "code", - autoApprovalEnabled: true, - alwaysAllowWrite: true, - alwaysAllowReadOnly: true, - alwaysAllowReadOnlyOutsideWorkspace: true, - }, - text: `Use search_and_replace on the file ${testFile.name} to: -1. First, replace "old" with "new" (use_regex: false) -2. Then, replace "Old" with "New" (use_regex: false) - -The file is located at: ${testFile.path} - -Assume the file exists and you can modify it directly. - -Use the search_and_replace tool twice - once for each replacement.`, - }) - - console.log("Task ID:", taskId) - console.log("Test filename:", testFile.name) - - // Wait for task to start - await waitFor(() => taskStarted, { timeout: 90_000 }) - - // Check for early errors - if (errorOccurred) { - console.error("Early error detected:", errorOccurred) - } - - // Wait for task completion - await waitFor(() => taskCompleted, { timeout: 90_000 }) - - // Give extra time for file system operations - await sleep(2000) - - // Check if the file was modified correctly - const actualContent = await fs.readFile(testFile.path, "utf-8") - console.log("File content after modification:", actualContent) - - // Verify tool was executed - assert.strictEqual(searchReplaceExecuted, true, "search_and_replace tool should have been executed") - - // Verify file content - assert.strictEqual( - actualContent.trim(), - expectedContent.trim(), - "File content should be modified with regex replacement", - ) - - console.log("Test passed! search_and_replace tool executed with regex successfully") - } finally { - // Clean up - api.off(RooCodeEventName.Message, messageHandler) - api.off(RooCodeEventName.TaskStarted, taskStartedHandler) - api.off(RooCodeEventName.TaskCompleted, taskCompletedHandler) - } - }) - - test("Should replace multiple matches in file", async function () { - const api = globalThis.api - const messages: ClineMessage[] = [] - const testFile = testFiles.multipleMatches - const expectedContent = `DONE: Fix this bug -This is some content -DONE: Add more tests -Some more content -DONE: Update documentation -Final content` - let taskStarted = false - let taskCompleted = false - let errorOccurred: string | null = null - let searchReplaceExecuted = false - - // Listen for messages - const messageHandler = ({ message }: { message: ClineMessage }) => { - messages.push(message) - - // Log important messages for debugging - if (message.type === "say" && message.say === "error") { - errorOccurred = message.text || "Unknown error" - console.error("Error:", message.text) - } - if (message.type === "ask" && message.ask === "tool") { - console.log("Tool request:", message.text?.substring(0, 200)) - } - if (message.type === "say" && (message.say === "completion_result" || message.say === "text")) { - console.log("AI response:", message.text?.substring(0, 200)) - } - - // Check for tool execution - if (message.type === "say" && message.say === "api_req_started" && message.text) { - console.log("API request started:", message.text.substring(0, 200)) - try { - const requestData = JSON.parse(message.text) - if (requestData.request && requestData.request.includes("search_and_replace")) { - searchReplaceExecuted = true - console.log("search_and_replace tool executed!") - } - } catch (e) { - console.log("Failed to parse api_req_started message:", e) - } - } - } - api.on(RooCodeEventName.Message, messageHandler) - - // Listen for task events - const taskStartedHandler = (id: string) => { - if (id === taskId) { - taskStarted = true - console.log("Task started:", id) - } - } - api.on(RooCodeEventName.TaskStarted, taskStartedHandler) - - const taskCompletedHandler = (id: string) => { - if (id === taskId) { - taskCompleted = true - console.log("Task completed:", id) - } - } - api.on(RooCodeEventName.TaskCompleted, taskCompletedHandler) - - let taskId: string - try { - // Start task with search_and_replace instruction for multiple matches - taskId = await api.startNewTask({ - configuration: { - mode: "code", - autoApprovalEnabled: true, - alwaysAllowWrite: true, - alwaysAllowReadOnly: true, - alwaysAllowReadOnlyOutsideWorkspace: true, - }, - text: `Use search_and_replace on the file ${testFile.name} to replace all occurrences of "TODO" with "DONE". - -The file is located at: ${testFile.path} - -The file already exists with this content: -${testFile.content} - -Assume the file exists and you can modify it directly.`, - }) - - console.log("Task ID:", taskId) - console.log("Test filename:", testFile.name) - - // Wait for task to start - await waitFor(() => taskStarted, { timeout: 45_000 }) - - // Check for early errors - if (errorOccurred) { - console.error("Early error detected:", errorOccurred) - } - - // Wait for task completion - await waitFor(() => taskCompleted, { timeout: 45_000 }) - - // Give extra time for file system operations - await sleep(2000) - - // Check if the file was modified correctly - const actualContent = await fs.readFile(testFile.path, "utf-8") - console.log("File content after modification:", actualContent) - - // Verify tool was executed - assert.strictEqual(searchReplaceExecuted, true, "search_and_replace tool should have been executed") - - // Verify file content - assert.strictEqual( - actualContent.trim(), - expectedContent.trim(), - "All TODO occurrences should be replaced with DONE", - ) - - console.log("Test passed! search_and_replace tool executed and replaced multiple matches successfully") - } finally { - // Clean up - api.off(RooCodeEventName.Message, messageHandler) - api.off(RooCodeEventName.TaskStarted, taskStartedHandler) - api.off(RooCodeEventName.TaskCompleted, taskCompletedHandler) - } - }) - - test("Should handle case when no matches are found", async function () { - const api = globalThis.api - const messages: ClineMessage[] = [] - const testFile = testFiles.noMatches - const expectedContent = testFile.content // Should remain unchanged - let taskStarted = false - let taskCompleted = false - let errorOccurred: string | null = null - let searchReplaceExecuted = false - - // Listen for messages - const messageHandler = ({ message }: { message: ClineMessage }) => { - messages.push(message) - - // Log important messages for debugging - if (message.type === "say" && message.say === "error") { - errorOccurred = message.text || "Unknown error" - console.error("Error:", message.text) - } - if (message.type === "ask" && message.ask === "tool") { - console.log("Tool request:", message.text?.substring(0, 200)) - } - if (message.type === "say" && (message.say === "completion_result" || message.say === "text")) { - console.log("AI response:", message.text?.substring(0, 200)) - } - - // Check for tool execution - if (message.type === "say" && message.say === "api_req_started" && message.text) { - console.log("API request started:", message.text.substring(0, 200)) - try { - const requestData = JSON.parse(message.text) - if (requestData.request && requestData.request.includes("search_and_replace")) { - searchReplaceExecuted = true - console.log("search_and_replace tool executed!") - } - } catch (e) { - console.log("Failed to parse api_req_started message:", e) - } - } - } - api.on(RooCodeEventName.Message, messageHandler) - - // Listen for task events - const taskStartedHandler = (id: string) => { - if (id === taskId) { - taskStarted = true - console.log("Task started:", id) - } - } - api.on(RooCodeEventName.TaskStarted, taskStartedHandler) - - const taskCompletedHandler = (id: string) => { - if (id === taskId) { - taskCompleted = true - console.log("Task completed:", id) - } - } - api.on(RooCodeEventName.TaskCompleted, taskCompletedHandler) - - let taskId: string - try { - // Start task with search_and_replace instruction for pattern that won't match - taskId = await api.startNewTask({ - configuration: { - mode: "code", - autoApprovalEnabled: true, - alwaysAllowWrite: true, - alwaysAllowReadOnly: true, - alwaysAllowReadOnlyOutsideWorkspace: true, - }, - text: `Use search_and_replace on the file ${testFile.name} to replace "NONEXISTENT_PATTERN" with "REPLACEMENT". This pattern should not be found in the file. - -The file is located at: ${testFile.path} - -The file already exists with this content: -${testFile.content} - -Assume the file exists and you can modify it directly.`, - }) - - console.log("Task ID:", taskId) - console.log("Test filename:", testFile.name) - - // Wait for task to start - await waitFor(() => taskStarted, { timeout: 45_000 }) - - // Check for early errors - if (errorOccurred) { - console.error("Early error detected:", errorOccurred) - } - - // Wait for task completion - await waitFor(() => taskCompleted, { timeout: 45_000 }) - - // Give extra time for file system operations - await sleep(2000) - - // Check if the file remains unchanged - const actualContent = await fs.readFile(testFile.path, "utf-8") - console.log("File content after search (should be unchanged):", actualContent) - - // Verify tool was executed - assert.strictEqual(searchReplaceExecuted, true, "search_and_replace tool should have been executed") - - // Verify file content remains unchanged - assert.strictEqual( - actualContent.trim(), - expectedContent.trim(), - "File content should remain unchanged when no matches are found", - ) - - console.log("Test passed! search_and_replace tool executed and handled no matches correctly") - } finally { - // Clean up - api.off(RooCodeEventName.Message, messageHandler) - api.off(RooCodeEventName.TaskStarted, taskStartedHandler) - api.off(RooCodeEventName.TaskCompleted, taskCompletedHandler) - } - }) -}) diff --git a/packages/types/src/tool.ts b/packages/types/src/tool.ts index 2c7495e5ebef..8c12a2dc0499 100644 --- a/packages/types/src/tool.ts +++ b/packages/types/src/tool.ts @@ -20,7 +20,6 @@ export const toolNames = [ "write_to_file", "apply_diff", "insert_content", - "search_and_replace", "search_files", "list_files", "list_code_definition_names", diff --git a/src/core/assistant-message/presentAssistantMessage.ts b/src/core/assistant-message/presentAssistantMessage.ts index 689675999fd1..2249c008d67e 100644 --- a/src/core/assistant-message/presentAssistantMessage.ts +++ b/src/core/assistant-message/presentAssistantMessage.ts @@ -15,7 +15,6 @@ import { shouldUseSingleFileRead } from "@roo-code/types" import { writeToFileTool } from "../tools/writeToFileTool" import { applyDiffTool } from "../tools/multiApplyDiffTool" import { insertContentTool } from "../tools/insertContentTool" -import { searchAndReplaceTool } from "../tools/searchAndReplaceTool" import { listCodeDefinitionNamesTool } from "../tools/listCodeDefinitionNamesTool" import { searchFilesTool } from "../tools/searchFilesTool" import { browserActionTool } from "../tools/browserActionTool" @@ -195,8 +194,6 @@ export async function presentAssistantMessage(cline: Task) { }]` case "insert_content": return `[${block.name} for '${block.params.path}']` - case "search_and_replace": - return `[${block.name} for '${block.params.path}']` case "list_files": return `[${block.name} for '${block.params.path}']` case "list_code_definition_names": @@ -463,10 +460,6 @@ export async function presentAssistantMessage(cline: Task) { await checkpointSaveAndMark(cline) await insertContentTool(cline, block, askApproval, handleError, pushToolResult, removeClosingTag) break - case "search_and_replace": - await checkpointSaveAndMark(cline) - await searchAndReplaceTool(cline, block, askApproval, handleError, pushToolResult, removeClosingTag) - break case "read_file": // Check if this model should use the simplified single-file read tool const modelId = cline.api.getModel().id diff --git a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/architect-mode-prompt.snap b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/architect-mode-prompt.snap index aa928fd50cf3..f9fc50276493 100644 --- a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/architect-mode-prompt.snap +++ b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/architect-mode-prompt.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -465,9 +429,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/ask-mode-prompt.snap b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/ask-mode-prompt.snap index 07dc1ff9de14..059f98d73b3c 100644 --- a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/ask-mode-prompt.snap +++ b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/ask-mode-prompt.snap @@ -362,9 +362,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/mcp-server-creation-disabled.snap b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/mcp-server-creation-disabled.snap index 300c7a3565ea..e45deefb6a47 100644 --- a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/mcp-server-creation-disabled.snap +++ b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/mcp-server-creation-disabled.snap @@ -225,42 +225,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -464,9 +428,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/mcp-server-creation-enabled.snap b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/mcp-server-creation-enabled.snap index ec5304a2b2ad..a6afbec4065e 100644 --- a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/mcp-server-creation-enabled.snap +++ b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/mcp-server-creation-enabled.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## use_mcp_tool Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters. Parameters: @@ -533,9 +497,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/partial-reads-enabled.snap b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/partial-reads-enabled.snap index bf584f2691cf..0956dcde3826 100644 --- a/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/partial-reads-enabled.snap +++ b/src/core/prompts/__tests__/__snapshots__/add-custom-instructions/partial-reads-enabled.snap @@ -231,42 +231,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -470,9 +434,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/system-prompt/consistent-system-prompt.snap b/src/core/prompts/__tests__/__snapshots__/system-prompt/consistent-system-prompt.snap index aa928fd50cf3..f9fc50276493 100644 --- a/src/core/prompts/__tests__/__snapshots__/system-prompt/consistent-system-prompt.snap +++ b/src/core/prompts/__tests__/__snapshots__/system-prompt/consistent-system-prompt.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -465,9 +429,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-computer-use-support.snap b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-computer-use-support.snap index 641ec16082ef..3420d1d1333c 100644 --- a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-computer-use-support.snap +++ b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-computer-use-support.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## browser_action Description: Request to interact with a Puppeteer-controlled browser. Every action, except `close`, will be responded to with a screenshot of the browser's current state, along with any new console logs. You may only perform one browser action per message, and wait for the user's response including a screenshot and logs to determine the next action. - The sequence of actions **must always start with** launching the browser at a URL, and **must always end with** closing the browser. If you need to visit a new URL that is not possible to navigate to from the current webpage, you must first close the browser, then launch again at the new URL. @@ -520,9 +484,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-false.snap b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-false.snap index aa928fd50cf3..f9fc50276493 100644 --- a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-false.snap +++ b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-false.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -465,9 +429,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-true.snap b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-true.snap index 154e1f08ae8e..530598739c6c 100644 --- a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-true.snap +++ b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-true.snap @@ -314,42 +314,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -553,9 +517,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using apply_diff or write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: apply_diff (for surgical edits - targeted changes to specific lines or functions), write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: apply_diff (for surgical edits - targeted changes to specific lines or functions), write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-undefined.snap b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-undefined.snap index aa928fd50cf3..f9fc50276493 100644 --- a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-undefined.snap +++ b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-diff-enabled-undefined.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -465,9 +429,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-different-viewport-size.snap b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-different-viewport-size.snap index aa928fd50cf3..f9fc50276493 100644 --- a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-different-viewport-size.snap +++ b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-different-viewport-size.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -465,9 +429,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-mcp-hub-provided.snap b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-mcp-hub-provided.snap index ec5304a2b2ad..a6afbec4065e 100644 --- a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-mcp-hub-provided.snap +++ b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-mcp-hub-provided.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## use_mcp_tool Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters. Parameters: @@ -533,9 +497,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-undefined-mcp-hub.snap b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-undefined-mcp-hub.snap index aa928fd50cf3..f9fc50276493 100644 --- a/src/core/prompts/__tests__/__snapshots__/system-prompt/with-undefined-mcp-hub.snap +++ b/src/core/prompts/__tests__/__snapshots__/system-prompt/with-undefined-mcp-hub.snap @@ -226,42 +226,6 @@ Example for appending to the end of file: -## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory /test/path) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -oldw+ -new$& -true -true - - ## ask_followup_question Description: Ask the user a question to gather additional information needed to complete the task. Use when you need clarification or more details to proceed effectively. @@ -465,9 +429,8 @@ RULES - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with `cd`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run `npm install` in a project outside of '/test/path', you would need to prepend with a `cd` i.e. pseudocode for this would be `cd (path to project) && (command, in this case npm install)`. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. -- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files), search_and_replace (for finding and replacing individual pieces of text). +- For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), insert_content (for adding lines to files). - The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line. -- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once. - You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the tool. ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. diff --git a/src/core/prompts/responses.ts b/src/core/prompts/responses.ts index fd51b18feda4..2f3ea87d4c6b 100644 --- a/src/core/prompts/responses.ts +++ b/src/core/prompts/responses.ts @@ -56,8 +56,7 @@ Otherwise, if you have not completed the task and do not need additional informa } existingFileApproaches.push( - `${diffStrategyEnabled ? "3" : "2"}. Or use search_and_replace for specific text replacements`, - `${diffStrategyEnabled ? "4" : "3"}. Or use insert_content to add specific content at particular lines`, + `${diffStrategyEnabled ? "3" : "2"}. Or use insert_content to add specific content at particular lines`, ) const existingFileGuidance = diff --git a/src/core/prompts/sections/rules.ts b/src/core/prompts/sections/rules.ts index a5eaf23ce08f..e8c7534b18a4 100644 --- a/src/core/prompts/sections/rules.ts +++ b/src/core/prompts/sections/rules.ts @@ -16,7 +16,6 @@ function getEditingInstructions(diffStrategy?: DiffStrategy): string { } availableTools.push("insert_content (for adding lines to files)") - availableTools.push("search_and_replace (for finding and replacing individual pieces of text)") // Base editing instruction mentioning all available tools if (availableTools.length > 1) { @@ -28,10 +27,6 @@ function getEditingInstructions(diffStrategy?: DiffStrategy): string { "- The insert_content tool adds lines of text to files at a specific line number, such as adding a new function to a JavaScript file or inserting a new route in a Python file. Use line number 0 to append at the end of the file, or any positive number to insert before that line.", ) - instructions.push( - "- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once.", - ) - if (availableTools.length > 1) { instructions.push( "- You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files.", diff --git a/src/core/prompts/tools/index.ts b/src/core/prompts/tools/index.ts index c212b18a3de4..22588d55d128 100644 --- a/src/core/prompts/tools/index.ts +++ b/src/core/prompts/tools/index.ts @@ -14,7 +14,6 @@ import { getWriteToFileDescription } from "./write-to-file" import { getSearchFilesDescription } from "./search-files" import { getListFilesDescription } from "./list-files" import { getInsertContentDescription } from "./insert-content" -import { getSearchAndReplaceDescription } from "./search-and-replace" import { getListCodeDefinitionNamesDescription } from "./list-code-definition-names" import { getBrowserActionDescription } from "./browser-action" import { getAskFollowupQuestionDescription } from "./ask-followup-question" @@ -54,7 +53,6 @@ const toolDescriptionMap: Record string | undefined> switch_mode: () => getSwitchModeDescription(), new_task: (args) => getNewTaskDescription(args), insert_content: (args) => getInsertContentDescription(args), - search_and_replace: (args) => getSearchAndReplaceDescription(args), apply_diff: (args) => args.diffStrategy ? args.diffStrategy.getToolDescription({ cwd: args.cwd, toolOptions: args.toolOptions }) : "", update_todo_list: (args) => getUpdateTodoListDescription(args), @@ -176,7 +174,6 @@ export { getAccessMcpResourceDescription, getSwitchModeDescription, getInsertContentDescription, - getSearchAndReplaceDescription, getCodebaseSearchDescription, getRunSlashCommandDescription, getGenerateImageDescription, diff --git a/src/core/prompts/tools/search-and-replace.ts b/src/core/prompts/tools/search-and-replace.ts deleted file mode 100644 index 357a7058323b..000000000000 --- a/src/core/prompts/tools/search-and-replace.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { ToolArgs } from "./types" - -export function getSearchAndReplaceDescription(args: ToolArgs): string { - return `## search_and_replace -Description: Use this tool to find and replace specific text strings or patterns (using regex) within a file. It's suitable for targeted replacements across multiple locations within the file. Supports literal text and regex patterns, case sensitivity options, and optional line ranges. Shows a diff preview before applying changes. - -Required Parameters: -- path: The path of the file to modify (relative to the current workspace directory ${args.cwd.toPosix()}) -- search: The text or pattern to search for -- replace: The text to replace matches with - -Optional Parameters: -- start_line: Starting line number for restricted replacement (1-based) -- end_line: Ending line number for restricted replacement (1-based) -- use_regex: Set to "true" to treat search as a regex pattern (default: false) -- ignore_case: Set to "true" to ignore case when matching (default: false) - -Notes: -- When use_regex is true, the search parameter is treated as a regular expression pattern -- When ignore_case is true, the search is case-insensitive regardless of regex mode - -Examples: - -1. Simple text replacement: - -example.ts -oldText -newText - - -2. Case-insensitive regex pattern: - -example.ts -old\w+ -new$& -true -true -` -} diff --git a/src/core/tools/searchAndReplaceTool.ts b/src/core/tools/searchAndReplaceTool.ts deleted file mode 100644 index b0ee3947e1eb..000000000000 --- a/src/core/tools/searchAndReplaceTool.ts +++ /dev/null @@ -1,282 +0,0 @@ -// Core Node.js imports -import path from "path" -import fs from "fs/promises" -import delay from "delay" - -// Internal imports -import { Task } from "../task/Task" -import { AskApproval, HandleError, PushToolResult, RemoveClosingTag, ToolUse } from "../../shared/tools" -import { formatResponse } from "../prompts/responses" -import { ClineSayTool } from "../../shared/ExtensionMessage" -import { getReadablePath } from "../../utils/path" -import { fileExistsAtPath } from "../../utils/fs" -import { RecordSource } from "../context-tracking/FileContextTrackerTypes" -import { DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" -import { EXPERIMENT_IDS, experiments } from "../../shared/experiments" - -/** - * Tool for performing search and replace operations on files - * Supports regex and case-sensitive/insensitive matching - */ - -/** - * Validates required parameters for search and replace operation - */ -async function validateParams( - cline: Task, - relPath: string | undefined, - search: string | undefined, - replace: string | undefined, - pushToolResult: PushToolResult, -): Promise { - if (!relPath) { - cline.consecutiveMistakeCount++ - cline.recordToolError("search_and_replace") - pushToolResult(await cline.sayAndCreateMissingParamError("search_and_replace", "path")) - return false - } - - if (!search) { - cline.consecutiveMistakeCount++ - cline.recordToolError("search_and_replace") - pushToolResult(await cline.sayAndCreateMissingParamError("search_and_replace", "search")) - return false - } - - if (replace === undefined) { - cline.consecutiveMistakeCount++ - cline.recordToolError("search_and_replace") - pushToolResult(await cline.sayAndCreateMissingParamError("search_and_replace", "replace")) - return false - } - - return true -} - -/** - * Performs search and replace operations on a file - * @param cline - Cline instance - * @param block - Tool use parameters - * @param askApproval - Function to request user approval - * @param handleError - Function to handle errors - * @param pushToolResult - Function to push tool results - * @param removeClosingTag - Function to remove closing tags - */ -export async function searchAndReplaceTool( - cline: Task, - block: ToolUse, - askApproval: AskApproval, - handleError: HandleError, - pushToolResult: PushToolResult, - removeClosingTag: RemoveClosingTag, -): Promise { - // Extract and validate parameters - const relPath: string | undefined = block.params.path - const search: string | undefined = block.params.search - const replace: string | undefined = block.params.replace - const useRegex: boolean = block.params.use_regex === "true" - const ignoreCase: boolean = block.params.ignore_case === "true" - const startLine: number | undefined = block.params.start_line ? parseInt(block.params.start_line, 10) : undefined - const endLine: number | undefined = block.params.end_line ? parseInt(block.params.end_line, 10) : undefined - - try { - // Handle partial tool use - if (block.partial) { - const partialMessageProps = { - tool: "searchAndReplace" as const, - path: getReadablePath(cline.cwd, removeClosingTag("path", relPath)), - search: removeClosingTag("search", search), - replace: removeClosingTag("replace", replace), - useRegex: block.params.use_regex === "true", - ignoreCase: block.params.ignore_case === "true", - startLine, - endLine, - } - await cline.ask("tool", JSON.stringify(partialMessageProps), block.partial).catch(() => {}) - return - } - - // Validate required parameters - if (!(await validateParams(cline, relPath, search, replace, pushToolResult))) { - return - } - - // At this point we know relPath, search and replace are defined - const validRelPath = relPath as string - const validSearch = search as string - const validReplace = replace as string - - const sharedMessageProps: ClineSayTool = { - tool: "searchAndReplace", - path: getReadablePath(cline.cwd, validRelPath), - search: validSearch, - replace: validReplace, - useRegex: useRegex, - ignoreCase: ignoreCase, - startLine: startLine, - endLine: endLine, - } - - const accessAllowed = cline.rooIgnoreController?.validateAccess(validRelPath) - - if (!accessAllowed) { - await cline.say("rooignore_error", validRelPath) - pushToolResult(formatResponse.toolError(formatResponse.rooIgnoreError(validRelPath))) - return - } - - // Check if file is write-protected - const isWriteProtected = cline.rooProtectedController?.isWriteProtected(validRelPath) || false - - const absolutePath = path.resolve(cline.cwd, validRelPath) - const fileExists = await fileExistsAtPath(absolutePath) - - if (!fileExists) { - cline.consecutiveMistakeCount++ - cline.recordToolError("search_and_replace") - const formattedError = formatResponse.toolError( - `File does not exist at path: ${absolutePath}\nThe specified file could not be found. Please verify the file path and try again.`, - ) - await cline.say("error", formattedError) - pushToolResult(formattedError) - return - } - - // Reset consecutive mistakes since all validations passed - cline.consecutiveMistakeCount = 0 - - // Read and process file content - let fileContent: string - try { - fileContent = await fs.readFile(absolutePath, "utf-8") - } catch (error) { - cline.consecutiveMistakeCount++ - cline.recordToolError("search_and_replace") - const errorMessage = `Error reading file: ${absolutePath}\nFailed to read the file content: ${ - error instanceof Error ? error.message : String(error) - }\nPlease verify file permissions and try again.` - const formattedError = formatResponse.toolError(errorMessage) - await cline.say("error", formattedError) - pushToolResult(formattedError) - return - } - - // Create search pattern and perform replacement - const flags = ignoreCase ? "gi" : "g" - const searchPattern = useRegex ? new RegExp(validSearch, flags) : new RegExp(escapeRegExp(validSearch), flags) - - let newContent: string - if (startLine !== undefined || endLine !== undefined) { - // Handle line-specific replacement - const lines = fileContent.split("\n") - const start = Math.max((startLine ?? 1) - 1, 0) - const end = Math.min((endLine ?? lines.length) - 1, lines.length - 1) - - // Get content before and after target section - const beforeLines = lines.slice(0, start) - const afterLines = lines.slice(end + 1) - - // Get and modify target section - const targetContent = lines.slice(start, end + 1).join("\n") - const modifiedContent = targetContent.replace(searchPattern, validReplace) - const modifiedLines = modifiedContent.split("\n") - - // Reconstruct full content - newContent = [...beforeLines, ...modifiedLines, ...afterLines].join("\n") - } else { - // Global replacement - newContent = fileContent.replace(searchPattern, validReplace) - } - - // Initialize diff view - cline.diffViewProvider.editType = "modify" - cline.diffViewProvider.originalContent = fileContent - - // Generate and validate diff - const diff = formatResponse.createPrettyPatch(validRelPath, fileContent, newContent) - if (!diff) { - pushToolResult(`No changes needed for '${relPath}'`) - await cline.diffViewProvider.reset() - return - } - - // Check if preventFocusDisruption experiment is enabled - const provider = cline.providerRef.deref() - const state = await provider?.getState() - const diagnosticsEnabled = state?.diagnosticsEnabled ?? true - const writeDelayMs = state?.writeDelayMs ?? DEFAULT_WRITE_DELAY_MS - const isPreventFocusDisruptionEnabled = experiments.isEnabled( - state?.experiments ?? {}, - EXPERIMENT_IDS.PREVENT_FOCUS_DISRUPTION, - ) - - const completeMessage = JSON.stringify({ - ...sharedMessageProps, - diff, - isProtected: isWriteProtected, - } satisfies ClineSayTool) - - // Show diff view if focus disruption prevention is disabled - if (!isPreventFocusDisruptionEnabled) { - await cline.diffViewProvider.open(validRelPath) - await cline.diffViewProvider.update(newContent, true) - cline.diffViewProvider.scrollToFirstDiff() - } - - const didApprove = await askApproval("tool", completeMessage, undefined, isWriteProtected) - - if (!didApprove) { - // Revert changes if diff view was shown - if (!isPreventFocusDisruptionEnabled) { - await cline.diffViewProvider.revertChanges() - } - pushToolResult("Changes were rejected by the user.") - await cline.diffViewProvider.reset() - return - } - - // Save the changes - if (isPreventFocusDisruptionEnabled) { - // Direct file write without diff view or opening the file - await cline.diffViewProvider.saveDirectly(validRelPath, newContent, false, diagnosticsEnabled, writeDelayMs) - } else { - // Call saveChanges to update the DiffViewProvider properties - await cline.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs) - } - - // Track file edit operation - if (relPath) { - await cline.fileContextTracker.trackFileContext(relPath, "roo_edited" as RecordSource) - } - - cline.didEditFile = true - - // Get the formatted response message - const message = await cline.diffViewProvider.pushToolWriteResult( - cline, - cline.cwd, - false, // Always false for search_and_replace - ) - - pushToolResult(message) - - // Record successful tool usage and cleanup - cline.recordToolUsage("search_and_replace") - await cline.diffViewProvider.reset() - - // Process any queued messages after file edit completes - cline.processQueuedMessages() - } catch (error) { - handleError("search and replace", error) - await cline.diffViewProvider.reset() - } -} - -/** - * Escapes special regex characters in a string - * @param input String to escape regex characters in - * @returns Escaped string safe for regex pattern matching - */ -function escapeRegExp(input: string): string { - return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") -} diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index 5929e7a950eb..7d2759c91905 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -379,7 +379,6 @@ export interface ClineSayTool { | "switchMode" | "newTask" | "finishTask" - | "searchAndReplace" | "insertContent" | "generateImage" | "imageGenerated" @@ -394,12 +393,6 @@ export interface ClineSayTool { isOutsideWorkspace?: boolean isProtected?: boolean additionalFileCount?: number // Number of additional files in the same read_file request - search?: string - replace?: string - useRegex?: boolean - ignoreCase?: boolean - startLine?: number - endLine?: number lineNumber?: number query?: string batchFiles?: Array<{ diff --git a/src/shared/__tests__/modes.spec.ts b/src/shared/__tests__/modes.spec.ts index 52e4424d8db4..0ec6554fe2f6 100644 --- a/src/shared/__tests__/modes.spec.ts +++ b/src/shared/__tests__/modes.spec.ts @@ -246,16 +246,7 @@ describe("isToolAllowedForMode", () => { expect(isToolAllowedForMode("use_mcp_tool", "architect", [])).toBe(true) }) - it("applies restrictions to all edit tools including search_and_replace and insert_content", () => { - // Test search_and_replace with matching file - expect( - isToolAllowedForMode("search_and_replace", "architect", [], undefined, { - path: "test.md", - search: "old text", - replace: "new text", - }), - ).toBe(true) - + it("applies restrictions to insert_content edit tool", () => { // Test insert_content with matching file expect( isToolAllowedForMode("insert_content", "architect", [], undefined, { @@ -265,22 +256,6 @@ describe("isToolAllowedForMode", () => { }), ).toBe(true) - // Test search_and_replace with non-matching file - should throw error - expect(() => - isToolAllowedForMode("search_and_replace", "architect", [], undefined, { - path: "test.py", - search: "old text", - replace: "new text", - }), - ).toThrow(FileRestrictionError) - expect(() => - isToolAllowedForMode("search_and_replace", "architect", [], undefined, { - path: "test.py", - search: "old text", - replace: "new text", - }), - ).toThrow(/Markdown files only/) - // Test insert_content with non-matching file - should throw error expect(() => isToolAllowedForMode("insert_content", "architect", [], undefined, { diff --git a/src/shared/tools.ts b/src/shared/tools.ts index 608b50752e7d..61e840272726 100644 --- a/src/shared/tools.ts +++ b/src/shared/tools.ts @@ -55,15 +55,10 @@ export const toolParamNames = [ "follow_up", "task", "size", - "search", - "replace", - "use_regex", - "ignore_case", + "query", "args", "start_line", "end_line", - "query", - "args", "todos", "prompt", "image", @@ -165,12 +160,6 @@ export interface RunSlashCommandToolUse extends ToolUse { params: Partial, "command" | "args">> } -export interface SearchAndReplaceToolUse extends ToolUse { - name: "search_and_replace" - params: Required, "path" | "search" | "replace">> & - Partial, "use_regex" | "ignore_case" | "start_line" | "end_line">> -} - export interface GenerateImageToolUse extends ToolUse { name: "generate_image" params: Partial, "prompt" | "path" | "image">> @@ -199,7 +188,6 @@ export const TOOL_DISPLAY_NAMES: Record = { switch_mode: "switch modes", new_task: "create new task", insert_content: "insert content", - search_and_replace: "search and replace", codebase_search: "codebase search", update_todo_list: "update todo list", run_slash_command: "run slash command", @@ -219,7 +207,7 @@ export const TOOL_GROUPS: Record = { ], }, edit: { - tools: ["apply_diff", "write_to_file", "insert_content", "search_and_replace", "generate_image"], + tools: ["apply_diff", "write_to_file", "insert_content", "generate_image"], }, browser: { tools: ["browser_action"], diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index ed5257528fe1..fd3d480014a6 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -437,39 +437,6 @@ export const ChatRowContent = ({ ) - case "searchAndReplace": - return ( - <> -
- {tool.isProtected ? ( - - ) : ( - toolIcon("replace") - )} - - {tool.isProtected && message.type === "ask" - ? t("chat:fileOperations.wantsToEditProtected") - : message.type === "ask" - ? t("chat:fileOperations.wantsToSearchReplace") - : t("chat:fileOperations.didSearchReplace")} - -
-
- -
- - ) case "codebaseSearch": { return (
diff --git a/webview-ui/src/components/chat/ChatView.tsx b/webview-ui/src/components/chat/ChatView.tsx index b454c97bef96..0683f2ebd03a 100644 --- a/webview-ui/src/components/chat/ChatView.tsx +++ b/webview-ui/src/components/chat/ChatView.tsx @@ -1011,14 +1011,9 @@ const ChatViewComponent: React.ForwardRefRenderFunction