/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as crypto from 'node:crypto';
import * as Diff from 'diff';
import { BaseDeclarativeTool, Kind, ToolConfirmationOutcome, } from './tools.js';
import { ToolErrorType } from './tool-error.js';
import { makeRelative, shortenPath } from '../utils/paths.js';
import { isNodeError } from '../utils/errors.js';
import { ApprovalMode } from '../config/config.js';
import { DEFAULT_DIFF_OPTIONS, getDiffStat } from './diffOptions.js';
import {} from './modifiable-tool.js';
import { IdeClient } from '../ide/ide-client.js';
import { FixLLMEditWithInstruction } from '../utils/llm-edit-fixer.js';
import { applyReplacement } from './edit.js';
import { safeLiteralReplace } from '../utils/textUtils.js';
import { SmartEditStrategyEvent } from '../telemetry/types.js';
import { logSmartEditStrategy } from '../telemetry/loggers.js';
import { SmartEditCorrectionEvent } from '../telemetry/types.js';
import { logSmartEditCorrectionEvent } from '../telemetry/loggers.js';
import { correctPath } from '../utils/pathCorrector.js';
import { EDIT_TOOL_NAME, READ_FILE_TOOL_NAME } from './tool-names.js';
import { debugLogger } from '../utils/debugLogger.js';
/**
 * Creates a SHA256 hash of the given content.
 * @param content The string content to hash.
 * @returns A hex-encoded hash string.
 */
function hashContent(content) {
    return crypto.createHash('sha256').update(content).digest('hex');
}
function restoreTrailingNewline(originalContent, modifiedContent) {
    const hadTrailingNewline = originalContent.endsWith('\n');
    if (hadTrailingNewline && !modifiedContent.endsWith('\n')) {
        return modifiedContent + '\n';
    }
    else if (!hadTrailingNewline && modifiedContent.endsWith('\n')) {
        return modifiedContent.replace(/\n$/, '');
    }
    return modifiedContent;
}
/**
 * Escapes characters with special meaning in regular expressions.
 * @param str The string to escape.
 * @returns The escaped string.
 */
function escapeRegex(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
async function calculateExactReplacement(context) {
    const { currentContent, params } = context;
    const { old_string, new_string } = params;
    const normalizedCode = currentContent;
    const normalizedSearch = old_string.replace(/\r\n/g, '\n');
    const normalizedReplace = new_string.replace(/\r\n/g, '\n');
    const exactOccurrences = normalizedCode.split(normalizedSearch).length - 1;
    if (exactOccurrences > 0) {
        let modifiedCode = safeLiteralReplace(normalizedCode, normalizedSearch, normalizedReplace);
        modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
        return {
            newContent: modifiedCode,
            occurrences: exactOccurrences,
            finalOldString: normalizedSearch,
            finalNewString: normalizedReplace,
        };
    }
    return null;
}
async function calculateFlexibleReplacement(context) {
    const { currentContent, params } = context;
    const { old_string, new_string } = params;
    const normalizedCode = currentContent;
    const normalizedSearch = old_string.replace(/\r\n/g, '\n');
    const normalizedReplace = new_string.replace(/\r\n/g, '\n');
    const sourceLines = normalizedCode.match(/.*(?:\n|$)/g)?.slice(0, -1) ?? [];
    const searchLinesStripped = normalizedSearch
        .split('\n')
        .map((line) => line.trim());
    const replaceLines = normalizedReplace.split('\n');
    let flexibleOccurrences = 0;
    let i = 0;
    while (i <= sourceLines.length - searchLinesStripped.length) {
        const window = sourceLines.slice(i, i + searchLinesStripped.length);
        const windowStripped = window.map((line) => line.trim());
        const isMatch = windowStripped.every((line, index) => line === searchLinesStripped[index]);
        if (isMatch) {
            flexibleOccurrences++;
            const firstLineInMatch = window[0];
            const indentationMatch = firstLineInMatch.match(/^(\s*)/);
            const indentation = indentationMatch ? indentationMatch[1] : '';
            const newBlockWithIndent = replaceLines.map((line) => `${indentation}${line}`);
            sourceLines.splice(i, searchLinesStripped.length, newBlockWithIndent.join('\n'));
            i += replaceLines.length;
        }
        else {
            i++;
        }
    }
    if (flexibleOccurrences > 0) {
        let modifiedCode = sourceLines.join('');
        modifiedCode = restoreTrailingNewline(currentContent, modifiedCode);
        return {
            newContent: modifiedCode,
            occurrences: flexibleOccurrences,
            finalOldString: normalizedSearch,
            finalNewString: normalizedReplace,
        };
    }
    return null;
}
async function calculateRegexReplacement(context) {
    const { currentContent, params } = context;
    const { old_string, new_string } = params;
    // Normalize line endings for consistent processing.
    const normalizedSearch = old_string.replace(/\r\n/g, '\n');
    const normalizedReplace = new_string.replace(/\r\n/g, '\n');
    // This logic is ported from your Python implementation.
    // It builds a flexible, multi-line regex from a search string.
    const delimiters = ['(', ')', ':', '[', ']', '{', '}', '>', '<', '='];
    let processedString = normalizedSearch;
    for (const delim of delimiters) {
        processedString = processedString.split(delim).join(` ${delim} `);
    }
    // Split by any whitespace and remove empty strings.
    const tokens = processedString.split(/\s+/).filter(Boolean);
    if (tokens.length === 0) {
        return null;
    }
    const escapedTokens = tokens.map(escapeRegex);
    // Join tokens with `\s*` to allow for flexible whitespace between them.
    const pattern = escapedTokens.join('\\s*');
    // The final pattern captures leading whitespace (indentation) and then matches the token pattern.
    // 'm' flag enables multi-line mode, so '^' matches the start of any line.
    const finalPattern = `^(\\s*)${pattern}`;
    const flexibleRegex = new RegExp(finalPattern, 'm');
    const match = flexibleRegex.exec(currentContent);
    if (!match) {
        return null;
    }
    const indentation = match[1] || '';
    const newLines = normalizedReplace.split('\n');
    const newBlockWithIndent = newLines
        .map((line) => `${indentation}${line}`)
        .join('\n');
    // Use replace with the regex to substitute the matched content.
    // Since the regex doesn't have the 'g' flag, it will only replace the first occurrence.
    const modifiedCode = currentContent.replace(flexibleRegex, newBlockWithIndent);
    return {
        newContent: restoreTrailingNewline(currentContent, modifiedCode),
        occurrences: 1, // This method is designed to find and replace only the first occurrence.
        finalOldString: normalizedSearch,
        finalNewString: normalizedReplace,
    };
}
/**
 * Detects the line ending style of a string.
 * @param content The string content to analyze.
 * @returns '\r\n' for Windows-style, '\n' for Unix-style.
 */
function detectLineEnding(content) {
    // If a Carriage Return is found, assume Windows-style endings.
    // This is a simple but effective heuristic.
    return content.includes('\r\n') ? '\r\n' : '\n';
}
export async function calculateReplacement(config, context) {
    const { currentContent, params } = context;
    const { old_string, new_string } = params;
    const normalizedSearch = old_string.replace(/\r\n/g, '\n');
    const normalizedReplace = new_string.replace(/\r\n/g, '\n');
    if (normalizedSearch === '') {
        return {
            newContent: currentContent,
            occurrences: 0,
            finalOldString: normalizedSearch,
            finalNewString: normalizedReplace,
        };
    }
    const exactResult = await calculateExactReplacement(context);
    if (exactResult) {
        const event = new SmartEditStrategyEvent('exact');
        logSmartEditStrategy(config, event);
        return exactResult;
    }
    const flexibleResult = await calculateFlexibleReplacement(context);
    if (flexibleResult) {
        const event = new SmartEditStrategyEvent('flexible');
        logSmartEditStrategy(config, event);
        return flexibleResult;
    }
    const regexResult = await calculateRegexReplacement(context);
    if (regexResult) {
        const event = new SmartEditStrategyEvent('regex');
        logSmartEditStrategy(config, event);
        return regexResult;
    }
    return {
        newContent: currentContent,
        occurrences: 0,
        finalOldString: normalizedSearch,
        finalNewString: normalizedReplace,
    };
}
export function getErrorReplaceResult(params, occurrences, expectedReplacements, finalOldString, finalNewString) {
    let error = undefined;
    if (occurrences === 0) {
        error = {
            display: `Failed to edit, could not find the string to replace.`,
            raw: `Failed to edit, 0 occurrences found for old_string (${finalOldString}). Original old_string was (${params.old_string}) in ${params.file_path}. No edits made. The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${READ_FILE_TOOL_NAME} tool to verify.`,
            type: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND,
        };
    }
    else if (occurrences !== expectedReplacements) {
        const occurrenceTerm = expectedReplacements === 1 ? 'occurrence' : 'occurrences';
        error = {
            display: `Failed to edit, expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences}.`,
            raw: `Failed to edit, Expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences} for old_string in file: ${params.file_path}`,
            type: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
        };
    }
    else if (finalOldString === finalNewString) {
        error = {
            display: `No changes to apply. The old_string and new_string are identical.`,
            raw: `No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,
            type: ToolErrorType.EDIT_NO_CHANGE,
        };
    }
    return error;
}
class EditToolInvocation {
    config;
    params;
    constructor(config, params) {
        this.config = config;
        this.params = params;
    }
    toolLocations() {
        return [{ path: this.params.file_path }];
    }
    async attemptSelfCorrection(params, currentContent, initialError, abortSignal, originalLineEnding) {
        // In order to keep from clobbering edits made outside our system,
        // check if the file has been modified since we first read it.
        let errorForLlmEditFixer = initialError.raw;
        let contentForLlmEditFixer = currentContent;
        const initialContentHash = hashContent(currentContent);
        const onDiskContent = await this.config
            .getFileSystemService()
            .readTextFile(params.file_path);
        const onDiskContentHash = hashContent(onDiskContent.replace(/\r\n/g, '\n'));
        if (initialContentHash !== onDiskContentHash) {
            // The file has changed on disk since we first read it.
            // Use the latest content for the correction attempt.
            contentForLlmEditFixer = onDiskContent.replace(/\r\n/g, '\n');
            errorForLlmEditFixer = `The initial edit attempt failed with the following error: "${initialError.raw}". However, the file has been modified by either the user or an external process since that edit attempt. The file content provided to you is the latest version. Please base your correction on this new content.`;
        }
        const fixedEdit = await FixLLMEditWithInstruction(params.instruction, params.old_string, params.new_string, errorForLlmEditFixer, contentForLlmEditFixer, this.config.getBaseLlmClient(), abortSignal);
        if (fixedEdit.noChangesRequired) {
            return {
                currentContent,
                newContent: currentContent,
                occurrences: 0,
                isNewFile: false,
                error: {
                    display: `No changes required. The file already meets the specified conditions.`,
                    raw: `A secondary check by an LLM determined that no changes were necessary to fulfill the instruction. Explanation: ${fixedEdit.explanation}. Original error with the parameters given: ${initialError.raw}`,
                    type: ToolErrorType.EDIT_NO_CHANGE_LLM_JUDGEMENT,
                },
                originalLineEnding,
            };
        }
        const secondAttemptResult = await calculateReplacement(this.config, {
            params: {
                ...params,
                old_string: fixedEdit.search,
                new_string: fixedEdit.replace,
            },
            currentContent: contentForLlmEditFixer,
            abortSignal,
        });
        const secondError = getErrorReplaceResult(params, secondAttemptResult.occurrences, 1, // expectedReplacements is always 1 for smart_edit
        secondAttemptResult.finalOldString, secondAttemptResult.finalNewString);
        if (secondError) {
            // The fix failed, log failure and return the original error
            const event = new SmartEditCorrectionEvent('failure');
            logSmartEditCorrectionEvent(this.config, event);
            return {
                currentContent: contentForLlmEditFixer,
                newContent: currentContent,
                occurrences: 0,
                isNewFile: false,
                error: initialError,
                originalLineEnding,
            };
        }
        const event = new SmartEditCorrectionEvent('success');
        logSmartEditCorrectionEvent(this.config, event);
        return {
            currentContent: contentForLlmEditFixer,
            newContent: secondAttemptResult.newContent,
            occurrences: secondAttemptResult.occurrences,
            isNewFile: false,
            error: undefined,
            originalLineEnding,
        };
    }
    /**
     * Calculates the potential outcome of an edit operation.
     * @param params Parameters for the edit operation
     * @returns An object describing the potential edit outcome
     * @throws File system errors if reading the file fails unexpectedly (e.g., permissions)
     */
    async calculateEdit(params, abortSignal) {
        const expectedReplacements = 1;
        let currentContent = null;
        let fileExists = false;
        let originalLineEnding = '\n'; // Default for new files
        try {
            currentContent = await this.config
                .getFileSystemService()
                .readTextFile(params.file_path);
            originalLineEnding = detectLineEnding(currentContent);
            currentContent = currentContent.replace(/\r\n/g, '\n');
            fileExists = true;
        }
        catch (err) {
            if (!isNodeError(err) || err.code !== 'ENOENT') {
                throw err;
            }
            fileExists = false;
        }
        const isNewFile = params.old_string === '' && !fileExists;
        if (isNewFile) {
            return {
                currentContent,
                newContent: params.new_string,
                occurrences: 1,
                isNewFile: true,
                error: undefined,
                originalLineEnding,
            };
        }
        // after this point, it's not a new file/edit
        if (!fileExists) {
            return {
                currentContent,
                newContent: '',
                occurrences: 0,
                isNewFile: false,
                error: {
                    display: `File not found. Cannot apply edit. Use an empty old_string to create a new file.`,
                    raw: `File not found: ${params.file_path}`,
                    type: ToolErrorType.FILE_NOT_FOUND,
                },
                originalLineEnding,
            };
        }
        if (currentContent === null) {
            return {
                currentContent,
                newContent: '',
                occurrences: 0,
                isNewFile: false,
                error: {
                    display: `Failed to read content of file.`,
                    raw: `Failed to read content of existing file: ${params.file_path}`,
                    type: ToolErrorType.READ_CONTENT_FAILURE,
                },
                originalLineEnding,
            };
        }
        if (params.old_string === '') {
            return {
                currentContent,
                newContent: currentContent,
                occurrences: 0,
                isNewFile: false,
                error: {
                    display: `Failed to edit. Attempted to create a file that already exists.`,
                    raw: `File already exists, cannot create: ${params.file_path}`,
                    type: ToolErrorType.ATTEMPT_TO_CREATE_EXISTING_FILE,
                },
                originalLineEnding,
            };
        }
        const replacementResult = await calculateReplacement(this.config, {
            params,
            currentContent,
            abortSignal,
        });
        const initialError = getErrorReplaceResult(params, replacementResult.occurrences, expectedReplacements, replacementResult.finalOldString, replacementResult.finalNewString);
        if (!initialError) {
            return {
                currentContent,
                newContent: replacementResult.newContent,
                occurrences: replacementResult.occurrences,
                isNewFile: false,
                error: undefined,
                originalLineEnding,
            };
        }
        // If there was an error, try to self-correct.
        return this.attemptSelfCorrection(params, currentContent, initialError, abortSignal, originalLineEnding);
    }
    /**
     * Handles the confirmation prompt for the Edit tool in the CLI.
     * It needs to calculate the diff to show the user.
     */
    async shouldConfirmExecute(abortSignal) {
        if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
            return false;
        }
        let editData;
        try {
            editData = await this.calculateEdit(this.params, abortSignal);
        }
        catch (error) {
            if (abortSignal.aborted) {
                throw error;
            }
            const errorMsg = error instanceof Error ? error.message : String(error);
            debugLogger.log(`Error preparing edit: ${errorMsg}`);
            return false;
        }
        if (editData.error) {
            debugLogger.log(`Error: ${editData.error.display}`);
            return false;
        }
        const fileName = path.basename(this.params.file_path);
        const fileDiff = Diff.createPatch(fileName, editData.currentContent ?? '', editData.newContent, 'Current', 'Proposed', DEFAULT_DIFF_OPTIONS);
        const ideClient = await IdeClient.getInstance();
        const ideConfirmation = this.config.getIdeMode() && ideClient.isDiffingEnabled()
            ? ideClient.openDiff(this.params.file_path, editData.newContent)
            : undefined;
        const confirmationDetails = {
            type: 'edit',
            title: `Confirm Edit: ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`,
            fileName,
            filePath: this.params.file_path,
            fileDiff,
            originalContent: editData.currentContent,
            newContent: editData.newContent,
            onConfirm: async (outcome) => {
                if (outcome === ToolConfirmationOutcome.ProceedAlways) {
                    this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
                }
                if (ideConfirmation) {
                    const result = await ideConfirmation;
                    if (result.status === 'accepted' && result.content) {
                        // TODO(chrstn): See https://github.com/google-gemini/gemini-cli/pull/5618#discussion_r2255413084
                        // for info on a possible race condition where the file is modified on disk while being edited.
                        this.params.old_string = editData.currentContent ?? '';
                        this.params.new_string = result.content;
                    }
                }
            },
            ideConfirmation,
        };
        return confirmationDetails;
    }
    getDescription() {
        const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
        if (this.params.old_string === '') {
            return `Create ${shortenPath(relativePath)}`;
        }
        const oldStringSnippet = this.params.old_string.split('\n')[0].substring(0, 30) +
            (this.params.old_string.length > 30 ? '...' : '');
        const newStringSnippet = this.params.new_string.split('\n')[0].substring(0, 30) +
            (this.params.new_string.length > 30 ? '...' : '');
        if (this.params.old_string === this.params.new_string) {
            return `No file changes to ${shortenPath(relativePath)}`;
        }
        return `${shortenPath(relativePath)}: ${oldStringSnippet} => ${newStringSnippet}`;
    }
    /**
     * Executes the edit operation with the given parameters.
     * @param params Parameters for the edit operation
     * @returns Result of the edit operation
     */
    async execute(signal) {
        let editData;
        try {
            editData = await this.calculateEdit(this.params, signal);
        }
        catch (error) {
            if (signal.aborted) {
                throw error;
            }
            const errorMsg = error instanceof Error ? error.message : String(error);
            return {
                llmContent: `Error preparing edit: ${errorMsg}`,
                returnDisplay: `Error preparing edit: ${errorMsg}`,
                error: {
                    message: errorMsg,
                    type: ToolErrorType.EDIT_PREPARATION_FAILURE,
                },
            };
        }
        if (editData.error) {
            return {
                llmContent: editData.error.raw,
                returnDisplay: `Error: ${editData.error.display}`,
                error: {
                    message: editData.error.raw,
                    type: editData.error.type,
                },
            };
        }
        try {
            this.ensureParentDirectoriesExist(this.params.file_path);
            let finalContent = editData.newContent;
            // Restore original line endings if they were CRLF
            if (!editData.isNewFile && editData.originalLineEnding === '\r\n') {
                finalContent = finalContent.replace(/\n/g, '\r\n');
            }
            await this.config
                .getFileSystemService()
                .writeTextFile(this.params.file_path, finalContent);
            let displayResult;
            if (editData.isNewFile) {
                displayResult = `Created ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`;
            }
            else {
                // Generate diff for display, even though core logic doesn't technically need it
                // The CLI wrapper will use this part of the ToolResult
                const fileName = path.basename(this.params.file_path);
                const fileDiff = Diff.createPatch(fileName, editData.currentContent ?? '', // Should not be null here if not isNewFile
                editData.newContent, 'Current', 'Proposed', DEFAULT_DIFF_OPTIONS);
                const originallyProposedContent = this.params.ai_proposed_string || this.params.new_string;
                const diffStat = getDiffStat(fileName, editData.currentContent ?? '', originallyProposedContent, this.params.new_string);
                displayResult = {
                    fileDiff,
                    fileName,
                    originalContent: editData.currentContent,
                    newContent: editData.newContent,
                    diffStat,
                };
            }
            const llmSuccessMessageParts = [
                editData.isNewFile
                    ? `Created new file: ${this.params.file_path} with provided content.`
                    : `Successfully modified file: ${this.params.file_path} (${editData.occurrences} replacements).`,
            ];
            if (this.params.modified_by_user) {
                llmSuccessMessageParts.push(`User modified the \`new_string\` content to be: ${this.params.new_string}.`);
            }
            return {
                llmContent: llmSuccessMessageParts.join(' '),
                returnDisplay: displayResult,
            };
        }
        catch (error) {
            const errorMsg = error instanceof Error ? error.message : String(error);
            return {
                llmContent: `Error executing edit: ${errorMsg}`,
                returnDisplay: `Error writing file: ${errorMsg}`,
                error: {
                    message: errorMsg,
                    type: ToolErrorType.FILE_WRITE_FAILURE,
                },
            };
        }
    }
    /**
     * Creates parent directories if they don't exist
     */
    ensureParentDirectoriesExist(filePath) {
        const dirName = path.dirname(filePath);
        if (!fs.existsSync(dirName)) {
            fs.mkdirSync(dirName, { recursive: true });
        }
    }
}
/**
 * Implementation of the Edit tool logic
 */
export class SmartEditTool extends BaseDeclarativeTool {
    config;
    static Name = EDIT_TOOL_NAME;
    constructor(config) {
        super(SmartEditTool.Name, 'Edit', `Replaces text within a file. Replaces a single occurrence. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${READ_FILE_TOOL_NAME} tool to examine the file's current content before attempting a text replacement.
      
      The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
      
      Expectation for required parameters:
      1. \`file_path\` MUST be an absolute path; otherwise an error will be thrown.
      2. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.).
      3. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic and that \`old_string\` and \`new_string\` are different.
      4. \`instruction\` is the detailed instruction of what needs to be changed. It is important to Make it specific and detailed so developers or large language models can understand what needs to be changed and perform the changes on their own if necessary. 
      5. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
      **Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
      6. Prefer to break down complex and long changes into multiple smaller atomic calls to this tool. Always check the content of the file after changes or not finding a string to match.
      **Multiple replacements:** If there are multiple and ambiguous occurences of the \`old_string\` in the file, the tool will also fail.`, Kind.Edit, {
            properties: {
                file_path: {
                    description: "The absolute path to the file to modify. Must start with '/'.",
                    type: 'string',
                },
                instruction: {
                    description: `A clear, semantic instruction for the code change, acting as a high-quality prompt for an expert LLM assistant. It must be self-contained and explain the goal of the change.

A good instruction should concisely answer:
1.  WHY is the change needed? (e.g., "To fix a bug where users can be null...")
2.  WHERE should the change happen? (e.g., "...in the 'renderUserProfile' function...")
3.  WHAT is the high-level change? (e.g., "...add a null check for the 'user' object...")
4.  WHAT is the desired outcome? (e.g., "...so that it displays a loading spinner instead of crashing.")

**GOOD Example:** "In the 'calculateTotal' function, correct the sales tax calculation by updating the 'taxRate' constant from 0.05 to 0.075 to reflect the new regional tax laws."

**BAD Examples:**
- "Change the text." (Too vague)
- "Fix the bug." (Doesn't explain the bug or the fix)
- "Replace the line with this new line." (Brittle, just repeats the other parameters)
`,
                    type: 'string',
                },
                old_string: {
                    description: 'The exact literal text to replace, preferably unescaped. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.',
                    type: 'string',
                },
                new_string: {
                    description: 'The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.',
                    type: 'string',
                },
            },
            required: ['file_path', 'instruction', 'old_string', 'new_string'],
            type: 'object',
        });
        this.config = config;
    }
    /**
     * Validates the parameters for the Edit tool
     * @param params Parameters to validate
     * @returns Error message string or null if valid
     */
    validateToolParamValues(params) {
        if (!params.file_path) {
            return "The 'file_path' parameter must be non-empty.";
        }
        let filePath = params.file_path;
        if (!path.isAbsolute(filePath)) {
            // Attempt to auto-correct to an absolute path
            const result = correctPath(filePath, this.config);
            if (result.success) {
                filePath = result.correctedPath;
            }
            else {
                return result.error;
            }
        }
        params.file_path = filePath;
        const workspaceContext = this.config.getWorkspaceContext();
        if (!workspaceContext.isPathWithinWorkspace(params.file_path)) {
            const directories = workspaceContext.getDirectories();
            return `File path must be within one of the workspace directories: ${directories.join(', ')}`;
        }
        return null;
    }
    createInvocation(params) {
        return new EditToolInvocation(this.config, params);
    }
    getModifyContext(_) {
        return {
            getFilePath: (params) => params.file_path,
            getCurrentContent: async (params) => {
                try {
                    return this.config
                        .getFileSystemService()
                        .readTextFile(params.file_path);
                }
                catch (err) {
                    if (!isNodeError(err) || err.code !== 'ENOENT')
                        throw err;
                    return '';
                }
            },
            getProposedContent: async (params) => {
                try {
                    const currentContent = await this.config
                        .getFileSystemService()
                        .readTextFile(params.file_path);
                    return applyReplacement(currentContent, params.old_string, params.new_string, params.old_string === '' && currentContent === '');
                }
                catch (err) {
                    if (!isNodeError(err) || err.code !== 'ENOENT')
                        throw err;
                    return '';
                }
            },
            createUpdatedParams: (oldContent, modifiedProposedContent, originalParams) => {
                const content = originalParams.new_string;
                return {
                    ...originalParams,
                    ai_proposed_string: content,
                    old_string: oldContent,
                    new_string: modifiedProposedContent,
                    modified_by_user: true,
                };
            },
        };
    }
}
//# sourceMappingURL=smart-edit.js.map