Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/import{ t }from'@vscode/l10n';import{ homedir }from'os';importtype{LanguageModelChat,PreparedToolInvocation}from'vscode';import{ToolName}from'../common/toolNames';import{IConfigurationService}from'../../../platform/configuration/common/configurationService';import{ICustomInstructionsService}from'../../../platform/customInstructions/common/customInstructionsService'
oldStart
oldLines
newStart
newLines
lines
message kindForTelemetry
message
message file
message
message file
message
message file
message
message file
message
str
str
accessor uri oldContent newContent
oldContent newContent
diffService accessor
diff diffServiceoldContent newContent
ignoreTrimWhitespace
maxComputationTimeMs
computeMoves
result
uri
oldLines oldContent
newLines newContent
oldLineIdx
newLineIdx
change diff
originalStart change
originalEnd change
modifiedStart change
modifiedEnd change
oldLineIdx originalStart
result
oldLineIdx
newLineIdx
i originalStart i originalEnd i
result
oldLineIdx
i modifiedStart i modifiedEnd i
result
newLineIdx
oldLineIdx oldLines
result
oldLineIdx
result
result
str1 str2
str1 str2
str1
str2
matrix
i i str1 i
matrixi i
j j str2 j
matrixj j
i i str1 i
j
start idx identical
end idx oldStr identical
text newStridentical newStr identical
matchPositions
text
type
editPosition
strategy
matchPositions
suggestion
firstExactIdx matchPositions
replaced text firstExactIdx newStr textfirstExactIdx oldStr
text replaced
type
editPosition
text oldStr newStr eol
haystack texteolline line
oldLines oldStreol
needle oldLinesline line
needle
convert text
matchedLines
i i haystack needle i
haystacki i needle needle
matchedLinesi
i needle
matchedLines
text
editPosition
type
suggestion
newLines newStreol
identical oldLines newLines
positions matchedLinesmatch
start match identical
end startoldLines identical
start end
matchedLines
text
type
editPosition
matchPositions positionsp convertp
suggestion
strategy
start end positions
startIdx convertstart
endIdx convertend
minimizedNewStr newLinesidentical newLines identicaleol
replaced text startIdx minimizedNewStr textendIdx
text replaced
editPosition start startIdx end endIdx text minimizedNewStr
type
text oldStr newStr eol
hasTrailingLF oldStreol
hasTrailingLF
oldStr oldStr eol
oldLines oldStreol
pattern oldLines
line i
escaped line
i oldLines hasTrailingLF
regex pattern
matches textregex
matches
text
editPosition
type
suggestion
matches
text
type
editPosition
suggestion
strategy
matchPositions matchesmatch match
match matches
startIdx match
endIdx startIdx match
replaced text startIdx newStr textendIdx
text replaced
type
editPosition start startIdx end endIdx text newStr
defaultSimilaryMatchThreshold
threshold
old defaultSimilaryMatchThreshold
defaultSimilaryMatchThreshold threshold
old
text oldStr newStr eol threshold defaultSimilaryMatchThreshold
oldStr oldStreol
text editPosition type
lines texteol
oldLines oldStreol
lines
text editPosition type
newLines newStreol
identical oldLines newLines
bestMatch startLine startOffset oldLength similarity
startOffset
i i lines oldLines i
totalSimilarity
oldLength
startOffsetIdenticalIncr
endOffsetIdenticalIncr
j j oldLines j
similarity oldLinesj linesi j
totalSimilarity similarity
oldLength linesi j
j identical
startOffsetIdenticalIncr linesi j eol
j oldLines identical
endOffsetIdenticalIncr linesi j eol
avgSimilarity totalSimilarity oldLines
avgSimilarity threshold avgSimilarity bestMatch
bestMatch
startLine i identical
startOffset startOffset startOffsetIdenticalIncr
similarity avgSimilarity
oldLength oldLength oldLines eol startOffsetIdenticalIncr endOffsetIdenticalIncr
startOffset linesi eol
bestMatch
text editPosition type
newStrMinimized newLinesidentical newLines identicaleol
matchStart bestMatch identical
afterIdx matchStart oldLines identical
newText
lines bestMatch
newLinesidentical newLines identical
linesafterIdx
eol
text newText
type
editPosition
start bestMatch
end bestMatch bestMatch
text newStrMinimized
similarity bestMatch
suggestion
fileContents oldStr newStr fileContents oldStr newStr
oldStart
oldLines oldStr
newStart
newLines newStr
lines
a b
leading
trailing
leading a
leading b
aleading bleading
leading
trailing leading a
trailing leading b
aa trailing bb trailing
trailing
leading trailing
oldString newString
leading
trailing
leading oldString leading newString oldStringleading newStringleading
leading
trailing leading oldString trailing leading newString
oldStringoldString trailing newStringnewString trailing
trailing
leading trailing
uri
old_string
new_string
workspaceService
notebookService
alternativeNotebookContent
languageModel
opts replaceAll
patch updatedFile edits
originalFile
updatedFile
edits
filePath uri
notebookServiceuri
workspaceServiceuri alternativeNotebookContentlanguageModel
workspaceServiceuri
originalFile
eol
old_string old_string eol
new_string new_string eol
originalFile old_string
updatedFile new_string
edits new_string
old_string
originalFile
filePath
updatedFile new_string
edits new_string
new_string
result originalFile old_string new_string eol
result
old_stringeol originalFileold_string eol
updatedFile originalFileold_string eol new_string
result
start end result
range start end
editsrange
suggestion resultsuggestion
filePath
result optsreplaceAll
suggestion resultsuggestion
filePath
updatedFile result
start end result
range start end
editsrange
result originalFile old_string new_string eol
result
suggestion resultsuggestion
filePath
result optsreplaceAll
suggestion resultsuggestion
filePath
updatedFile result
start end text result
range start end
editsrange text
result resultsimilarity
updatedFile originalFile
filePath
patch
fileContents originalFile
oldStr originalFile
newStr updatedFile
patch updatedFile edits
error
old_string error
originalFile
updatedFile new_string
patch
fileContents originalFile
oldStr originalFile
newStr updatedFile
edits new_string
patch updatedFile edits
error
error
allPlatformPatterns glob
glob
glob
specializedPatterns glob
isWindows
process process
isMacintosh
platformConfirmationRequiredPaths specializedPatternsisDefinedallPlatformPatterns
fsPath _isWindows isWindows
fsPath
_isWindows
colonIndex fsPath
colonIndex
invalidChars
pathAfterDrive fsPath fsPath fsPath
invalidCharspathAfterDrive
fsPath fsPath
reserved
parts fsPath
part parts
part
reservedpart
part part
tildeIndex part
tildeIndex
afterTilde parttildeIndex
afterTilde afterTilde
configuration resource customInstructionsService
patterns configuration
hookFilesLocations configuration
hookFilesPatterns
hookFilesLocations
pattern hookFilesLocations
pattern
normalizedPattern pattern pattern pattern pattern
hookFilesPatternsnormalizedPattern
lastSegment normalizedPattern
lastSegment
folderJsonPattern normalizedPattern normalizedPattern normalizedPattern
hookFilesPatternsfolderJsonPattern
checks
wf
arr checkswf
arr
arr
ignoreCasing extUriBiasedIgnorePathCasewf
arr patterns ignoreCasing
obj patterns hookFilesPatterns
obj
pattern isApproved obj
arr pattern glob base wf pattern ignoreCasing pattern pattern isApproved
checkswf arr
arr
uri
normalizedUri uri
workspaceFolder normalizedUri
workspaceFolder uri
ok
fsPath uri
fsPath
platformCheckFailed platformConfirmationRequiredPathsp
p
fsPath
parentURI p
extUriBiasedIgnorePathCaseuri parentURI
workspaceFolder extUriBiasedIgnorePathCaseworkspaceFolder parentURI
platformCheckFailed
patterns ignoreCasing workspaceFolder
ignoreCasing
fsPath fsPath
pattern isApproved patterns
isApproved ok fsPath
ok isApproved
ok
uri
toCheck uri
uri
linked uri
linked
extUriBiasedIgnorePathCaselinked uri
toChecklinked
e
e
toCheckcheckUri
accessor uris allowedUris detailMessage urisNeedingConfirmation forceConfirmationReason getWorkspaceFolder resource workingDirectory
forceConfirmationReason
details detailMessage uris
confirmationMessages
title
message forceConfirmationReason t details details
presentation
workspaceService accessor
getWorkspaceFolder
wd workingDirectory workspaceService
resource wdresource
checker accessor getWorkspaceFolder accessor
needsConfirmation uris
uri uri reason uri
r r allowedUrisr
needsConfirmation
presentation
fileParts needsConfirmation uri uri
message
needsConfirmationr r
message t
needsConfirmationr r
message t
needsConfirmationr r
message t
message t
urisNeedingConfirmation needsConfirmationc c
details detailMessage urisNeedingConfirmation
confirmationMessages
title
message message t details details
presentation
accessor uri
workspace accessor
workspaced extUriBiasedIgnorePathCased uri
workspaced extUriBiasedIgnorePathCased uri
fileSystemService accessor
fileSystemServiceuri
logService requestId opts
input
success
healed
logService
uri allowedUris promptPathRepresentationService
allowedUris allowedUrisuri
accessor promptContext uri
notebookService accessor
workspaceService accessor
alternativeNotebookContent accessor
previouslyEdited promptContextturnEditedDocumentsuri
previouslyEdited
previouslyEdited
isNotebook notebookServiceuri
isNotebook
uri uri workspaceServiceuri uri
isNotebook
workspaceServiceuri alternativeNotebookContentpromptContextrequestmodel
workspaceServiceuri
/**
* Error thrown when no match is found for a string replacement
*/
export
class
NoMatchError
extends
EditError
{
constructor
(
:
string
,
public
readonly
:
string
)
{
super
(
,
'noMatchFound'
)
;
}
}
/**
* Error thrown when multiple matches are found for a string replacement
*/
export
class
MultipleMatchesError
extends
EditError
{
constructor
(
:
string
,
public
readonly
:
string
)
{
super
(
,
'multipleMatchesFound'
)
;
}
}
/**
* Error thrown when the edit would result in no changes
*/
export
class
NoChangeError
extends
EditError
{
constructor
(
:
string
,
public
readonly
:
string
)
{
super
(
,
'noChange'
)
;
}
}
/**
* Error thrown when there are issues with the content format
*/
export
class
ContentFormatError
extends
EditError
{
constructor
(
:
string
,
public
readonly
:
string
)
{
super
(
,
'contentFormatError'
)
;
}
}
/**
* Escapes special regex characters in a string.
*/
function
escapeRegex
(
:
string
)
:
string
{
return
.
replace
(
/[.*+?^${}()|[\]\\]/g
,
'\\$&'
)
;
}
/**
* Formats a diff computed by IDiffService as a unified diff string.
* Lines starting with '-' are removed, lines starting with '+' are added.
* Context lines (unchanged) are prefixed with a space.
* This outputs the entire file with all changes marked.
*/
// Add any remaining unchanged lines after all changes
while
(
<
.
length
)
{
.
push
(
`${oldLines[oldLineIdx]}`
)
;
++
;
}
.
push
(
'```'
)
;
return
.
join
(
'\n'
)
;
}
/**
* Calculates the similarity ratio between two strings using Levenshtein distance.
* Returns a value between 0 (completely different) and 1 (identical).
*/
function
calculateSimilarity
(
:
string
,
:
string
)
:
number
{
if
(
===
)
{
return
1.0
;
}
if
(
.
length
===
0
)
{
return
0.0
;
}
if
(
.
length
===
0
)
{
return
0.0
;
}
// Calculate Levenshtein distance
const
:
number
[
]
[
]
=
[
]
;
for
(
let
=
0
;
<=
.
length
;
++
)
{
[
]
=
[
]
;
}
for
(
let
=
0
;
<=
.
length
;
++
)
{
[
0
]
[
]
=
;
}
for
(
let
=
1
;
<=
.
length
;
++
)
{
for
(
let
=
1
;
j<= str2.length; j++){const cost = str1[i -1]=== str2[j -1]?0:1;
matrix[i][j]= Math.min(
matrix[i -1][j]+1,// deletion
matrix[i][j -1]+1,// insertion
matrix[i -1][j -1]+ cost // substitution);}}const distance = matrix[str1.length][str2.length];const maxLength = Math.max(str1.length, str2.length);// Return similarity ratio (1 - normalized distance)return1- distance / maxLength;}interface MatchResultCommon {
type:string;/** Resulting document text */
text:string;/** Array of [startIndex, endIndex] to replace in the file content */
editPosition:{ start:number; end:number; text:string}[];/** Model suggestion to correct a fialing match */
suggestion?:string;}/**
* Type-safe union type for match results with discriminated unions
*/type MatchResult = MatchResultCommon &(|{ text:string; type:'none'; suggestion?:string}|{ text:string; type:'exact'}|{ text:string; type:'fuzzy'}|{ text:string; type:'whitespace'}|{ text:string; type:'similarity'; suggestion:string; similarity:number}|{ text:string; type:'multiple'; suggestion:string; matchPositions:number[]; strategy:'exact'|'fuzzy'|'whitespace'});/**
* Enhanced version of findAndReplaceOne with more robust matching strategies
* and better error information.
*
* @paramtext The source text to search in
* @paramoldStr The string to find and replace
* @paramnewStr The replacement string
* @returns An object with the new text, match type, and additional match information
*/exportfunctionfindAndReplaceOne(
text:string,
oldStr:string,
newStr:string,
eol:string,): MatchResult {// Strategy 1: Try exact match first (fastest)const exactResult =tryExactMatch(text, oldStr, newStr);if(exactResult.type !=='none'){return exactResult;}// Strategy 2: Try whitespace-flexible matchingconst whitespaceResult =tryWhitespaceFlexibleMatch(text, oldStr, newStr, eol);if(whitespaceResult.type !=='none'){return whitespaceResult;}// Strategy 3: Try line-by-line fuzzy matchingconst fuzzyResult =tryFuzzyMatch(text, oldStr, newStr, eol);if(fuzzyResult.type !=='none'){return fuzzyResult;}// Strategy 4: Try similarity-based matching as last resortconst similarityResult =trySimilarityMatch(text, oldStr, newStr, eol);if(similarityResult.type !=='none'){return similarityResult;}// No matches found with any strategyreturn{
text,
type:'none',
editPosition:[],
suggestion:`Try making your search string more specific or checking for whitespace/formatting differences.`};}/**
* Tries to find an exact match of oldStr in text.
*/functiontryExactMatch(text:string, oldStr:string, newStr:string): MatchResult {const matchPositions:number[]=[];for(let searchIdx =0;;){const idx = text.indexOf(oldStr, searchIdx);if(idx ===-1){break;}
matchPositions.push(idx);
searchIdx = idx + oldStr.length;}if(matchPositions.length ===0){return{ text, editPosition:[], type:'none'};}const identical =getIdenticalChars(oldStr, newStr);const editPosition = matchPositions.map(idx =>
(
{
:
+
.
leading
,
:
+
.
length
-
.
trailing
,
:
.
slice
(
.
leading
,
.
length
-
.
trailing
)
}
)
)
;
// Check for multiple exact occurrences.
if
(
.
length
>
1
)
{
return
{
,
:
'multiple'
,
,
:
'exact'
,
,
:
'Multiple exact matches found. Make your search string more specific.'
}
;
}
// Exactly one exact match found.
const
=
[
0
]
;
const
=
.
slice
(
0
,
)
+
+
.
slice
(
+
.
length
)
;
return
{
:
,
:
'exact'
,
,
}
;
}
/**
* Tries to match using flexible whitespace handling.
*/
function
tryWhitespaceFlexibleMatch
(
:
string
,
:
string
,
:
string
,
:
string
)
:
MatchResult
{
const
=
.
split
(
)
.
map
(
=>
.
trim
(
)
)
;
const
=
.
trim
(
)
.
split
(
)
;
const
=
.
map
(
=>
.
trim
(
)
)
;
.
push
(
''
)
;
// trailing newline to match until the end of a line
const
=
new
OffsetLineColumnConverter
(
)
;
const
:
number
[
]
=
[
]
;
for
(
let
=
0
;
<=
.
length
-
.
length
;
++
)
{
if
(
.
slice
(
,
+
.
length
)
.
join
(
'\n'
)
===
.
join
(
'\n'
)
)
{
.
push
(
)
;
+=
.
length
-
1
;
}
}
if
(
.
length
===
0
)
{
return
{
,
:
[
]
,
:
'none'
,
:
'No whitespace-flexible match found.'
}
;
}
const
=
.
trim
(
)
.
split
(
)
;
const
=
getIndenticalLines
(
,
)
;
const
=
.
map
(
=>
{
const
=
new
EditorPosition
(
+
.
leading
+
1
,
1
)
;
const
=
.
delta
(
.
length
-
.
trailing
)
;
return
{
,
}
;
}
)
;
if
(
.
length
>
1
)
{
return
{
,
:
'multiple'
,
:
[
]
,
:
.
map
(
=>
.
positionToOffset
(
.
start
)
)
,
:
'Multiple matches found with flexible whitespace. Make your search string more unique.'
,
:
'whitespace'
,
}
;
}
const
{
,
}
=
[
0
]
;
const
=
.
positionToOffset
(
)
;
const
=
.
positionToOffset
(
)
-
1
;
// -1 to include the last EOL
const
=
.
slice
(
.
leading
,
.
length
-
.
trailing
)
.
join
(
)
;
const
=
.
slice
(
0
,
)
+
+
.
slice
(
)
;
return
{
:
,
:
[
{
:
,
:
,
:
}
]
,
:
'whitespace'
,
}
;
}
/**
* Tries to match using the traditional fuzzy approach with line-by-line matching.
*/
function
tryFuzzyMatch
(
:
string
,
:
string
,
:
string
,
:
string
)
:
MatchResult
{
// Handle trailing newlines
const
=
.
endsWith
(
)
;
if
(
)
{
=
.
slice
(
0
,
-
.
length
)
;
}
// Build a regex pattern where each line is matched exactly
// but allows for trailing spaces/tabs and flexible newline formats
const
=
.
split
(
)
;
const
=
.
map
(
(
,
)
=>
{
const
=
escapeRegex
(
)
;
return
<
.
length
-
1
||
?
`${escaped}[ \\t]*\\r?\\n`
:
`${escaped}[ \\t]*`
;
}
)
.
join
(
''
)
;
const
=
new
RegExp
(
,
'g'
)
;
const
=
Array
.
from
(
.
matchAll
(
)
)
;
if
(
.
length
===
0
)
{
return
{
,
:
[
]
,
:
'none'
,
:
'No fuzzy match found.'
}
;
}
if
(
.
length
>
1
)
{
return
{
,
:
'multiple'
,
:
[
]
,
:
'Multiple fuzzy matches found. Try including more context in your search string.'
,
:
'fuzzy'
,
:
.
map
(
=>
.
index
||
0
)
,
}
;
}
// Exactly one fuzzy match found
const
=
[
0
]
;
const
=
.
index
||
0
;
const
=
+
[
0
]
.
length
;
const
=
.
slice
(
0
,
)
+
+
.
slice
(
)
;
return
{
:
,
:
'fuzzy'
,
:
[
{
:
,
:
,
:
}
]
,
}
;
}
let
=
0.95
;
export
function
setSimilarityMatchThresholdForTests
(
:
number
)
{
const
=
;
=
;
return
;
}
/**
* Tries to match based on overall string similarity as a last resort.
* Only works for relatively small strings to avoid performance issues.
*/
function
trySimilarityMatch
(
:
string
,
:
string
,
:
string
,
:
string
,
:
number
=
)
:
MatchResult
{
// Skip similarity matching for very large strings or too many lines
if
(
.
length
>
1000
||
.
split
(
)
.
length
>
20
)
{
return
{
,
:
[
]
,
:
'none'
}
;
}
const
=
.
split
(
)
;
const
=
.
split
(
)
;
// Don't try similarity matching for very large files
if
(
.
length
>
1000
)
{
return
{
,
:
[
]
,
:
'none'
}
;
}
const
=
.
split
(
)
;
const
=
getIndenticalLines
(
,
)
;
let
=
{
:
-
1
,
:
0
,
:
0
,
:
0
}
;
let
=
0
;
// Sliding window approach to find the best matching section
for
(
let
=
0
;
<=
.
length
-
.
length
;
++
)
{
let
=
0
;
let
=
0
;
// Calculate similarity for each line in the window
let
=
0
;
let
=
0
;
for
(
let
=
0
;
<
.
length
;
++
)
{
const
=
calculateSimilarity
(
[
]
,
[
+
]
)
;
+=
;
+=
[
+
]
.
length
;
if
(
<
.
leading
)
{
+=
[
+
]
.
length
+
.
length
;
}
if
(
>=
.
length
-
.
trailing
)
{
+=
[
+
]
.
length
+
.
length
;
}
}
const
=
/
.
length
;
if
(
>
&&
>
.
similarity
)
{
=
{
:
+
.
leading
,
:
+
,
:
,
:
+
(
.
length
-
1
)
*
.
length
-
-
,
}
;
}
+=
[
]
.
length
+
.
length
;
}
if
(
.
startLine
===
-
1
)
{
return
{
,
:
[
]
,
:
'none'
}
;
}
// Replace the matched section
const
=
.
slice
(
.
leading
,
.
length
-
.
trailing
)
.
join
(
)
;
const
=
.
startLine
-
.
leading
;
const
=
+
.
length
-
.
trailing
;
const
=
[
...
.
slice
(
0
,
.
startLine
)
,
...
.
slice
(
.
leading
,
.
length
-
.
trailing
)
,
...
.
slice
(
)
,
]
.
join
(
)
;
return
{
:
,
:
'similarity'
,
:
[
{
:
.
startOffset
,
:
.
startOffset
+
.
oldLength
,
:
,
}
]
,
:
.
similarity
,
:
`Used similarity matching (${(bestMatch.similarity *100).toFixed(1)}% similar). Verify the replacement.`
}
;
}
// Function to generate a simple patch
function
getPatch
(
{
,
,
}
:
{
:
string
;
:
string
;
:
string
}
)
:
Hunk
[
]
{
// Simplified patch generation - in a real implementation this would generate proper diff hunks
return
[
{
:
1
,
:
(
.
match
(
/\n/g
)
||
[
]
)
.
length
+
1
,
:
1
,
:
(
.
match
(
/\n/g
)
||
[
]
)
.
length
+
1
,
:
[
]
}
]
;
}
/** Gets the number of identical leading and trailing lines between two arrays of strings */
function
getIndenticalLines
(
:
string
[
]
,
:
string
[
]
)
{
let
=
0
;
let
=
0
;
while
(
<
.
length
&&
<
.
length
&&
[
]
===
[
]
)
{
++
;
}
while
(
+
<
.
length
&&
+
<
.
length
&&
[
.
length
-
1
-
]
===
[
.
length
-
1
-
]
)
{
++
;
}
return
{
,
}
;
}
/** Gets the number of identical leading and trailing characters between two strings */
function
getIdenticalChars
(
:
string
,
:
string
)
{
let
=
0
;
let
=
0
;
while
(
<
.
length
&&
<
.
length
&&
[
]
===
[
]
)
{
++
;
}
while
(
+
<
.
length
&&
+
<
.
length
&&
[
.
length
-
-
1
]
===
[
.
length
-
-
1
]
)
{
++
;
}
return
{
,
}
;
}
// Apply string edit function
export
async
function
applyEdit
(
:
URI
,
:
string
,
:
string
,
:
IWorkspaceService
,
:
INotebookService
,
:
IAlternativeNotebookContentService
,
:
LanguageModelChat
|
undefined
,
?
:
{
?
:
boolean
}
,
)
:
Promise
<
{
:
Hunk
[
]
;
:
string
;
:
TextEdit
[
]
}
>
{
let
:
string
;
let
:
string
;
const
:
TextEdit
[
]
=
[
]
;
const
=
.
toString
(
)
;
try
{
// Use VS Code workspace API to get the document content
const
document
=
.
hasSupportedNotebooks
(
)
?
await
.
openNotebookDocumentAndSnapshot
(
,
.
getFormat
(
)
)
:
await
.
openTextDocumentAndSnapshot
(
)
;
=
document
.
getText
(
)
;
const
=
document
instanceof
TextDocumentSnapshot
&&
document
.
eol
===
EndOfLine
.
CRLF
?
'\r\n'
:
'\n'
;
=
.
replace
(
/\r?\n/g
,
)
;
=
.
replace
(
/\r?\n/g
,
)
;
if
(
isFalsyOrWhitespace
(
)
&&
isFalsyOrWhitespace
(
)
)
{
=
;
.
push
(
TextEdit
.
insert
(
new
Position
(
0
,
0
)
,
)
)
;
}
else
if
(
===
''
)
{
if
(
!==
''
)
{
// If the file already exists and we're creating a new file with empty old_string
throw
new
ContentFormatError
(
'File already exists. Please provide a non-empty old_string for replacement.'
,
)
;
}
// Create new file case
=
;
.
push
(
TextEdit
.
insert
(
new
Position
(
0
,
0
)
,
)
)
;
}
else
{
// Edit existing file case
if
(
===
''
)
{
// For empty new string, handle special deletion case
const
=
findAndReplaceOne
(
,
,
,
)
;
if
(
.
type
===
'none'
)
{
// Try with newline appended if the original doesn't end with newline
if
(
!
.
endsWith
(
)
&&
.
includes
(
+
)
)
{
=
.
replace
(
+
,
)
;
if
(
.
editPosition
.
length
)
{
const
{
,
}
=
.
editPosition
[
0
]
;
const
=
new
Range
(
document
.
positionAt
(
)
,
document
.
positionAt
(
)
)
;
.
push
(
TextEdit
.
delete
(
)
)
;
}
}
else
{
const
=
?.
||
'The string to replace must match exactly.'
;
throw
new
NoMatchError
(
`Could not find matching text to replace. ${suggestion}`
,
)
;
}
}
else
if
(
.
type
===
'multiple'
&&
!
?.
)
{
const
=
?.
||
'Please provide a more specific string.'
;
throw
new
MultipleMatchesError
(
`Multiple matches found for the text to replace. ${suggestion}`
,
)
;
}
else
{
=
.
text
;
for
(
const
{
,
}
of
.
editPosition
)
{
const
=
new
Range
(
document
.
positionAt
(
)
,
document
.
positionAt
(
)
)
;
.
push
(
TextEdit
.
delete
(
)
)
;
}
}
}
else
{
// Normal replacement case using the enhanced matcher
const
=
findAndReplaceOne
(
,
,
,
)
;
if
(
.
type
===
'none'
)
{
const
=
?.
||
'The string to replace must match exactly or be a valid fuzzy match.'
;
throw
new
NoMatchError
(
`Could not find matching text to replace. ${suggestion}`
,
)
;
}
else
if
(
.
type
===
'multiple'
&&
!
?.
)
{
const
=
?.
||
'Please provide a more specific string.'
;
throw
new
MultipleMatchesError
(
`Multiple matches found for the text to replace. ${suggestion}`
,
)
;
}
else
{
=
.
text
;
for
(
const
{
,
,
}
of
.
editPosition
)
{
const
=
new
Range
(
document
.
positionAt
(
)
,
document
.
positionAt
(
)
)
;
.
push
(
TextEdit
.
replace
(
,
)
)
;
}
// If we used similarity matching, add a warning
if
(
.
type
===
'similarity'
&&
?.
)
{
console
.
warn
(
`Used similarity matching with ${(result.similarity *100).toFixed(1)}% confidence. Verify the result is correct.`
)
;
}
}
}
if
(
===
)
{
throw
new
NoChangeError
(
`Original and edited file match exactly. Failed to apply edit. Use the ${ToolName.ReadFile} tool to re-read the file and determine the correct edit.`
,
)
;
}
}
// Generate a simple patch
const
=
getPatch
(
{
:
,
:
,
:
,
}
)
;
return
{
,
,
}
;
}
catch
(
)
{
// If the file doesn't exist and we're creating a new file with empty oldString
if
(
===
''
&&
.
code
===
'ENOENT'
)
{
=
''
;
=
;
const
=
getPatch
(
{
:
,
:
,
:
,
}
)
;
.
push
(
TextEdit
.
insert
(
new
Position
(
0
,
0
)
,
)
)
;
return
{
,
,
}
;
}
if
(
instanceof
EditError
)
{
throw
;
}
else
{
throw
new
EditError
(
`Failed to edit file: ${error.stack || error.message}`
,
'unknownError'
)
;
}
}
}
const
ALWAYS_CHECKED_EDIT_PATTERNS
:
Readonly
<
Record
<
string
,
boolean
>>
=
{
'**/.mcp.json'
:
false
,
'**/.npmrc'
:
false
,
'**/.vscode/*.json'
:
false
,
// Markdown files in these folders are loaded as custom agents; their
// frontmatter can declare a `hooks:` block that runs shell commands during
// the agent lifecycle, so writing them must always be confirmed.
'**/.github/agents/**'
:
false
,
'**/.claude/agents/**'
:
false
,
}
;
const
:
(
.
ParsedPattern
|
string
)
[
]
=
[
.
parse
(
homedir
(
)
+
'/.*'
)
,
.
parse
(
homedir
(
)
+
'/.*/**'
)
,
]
;
const
:
(
.
ParsedPattern
|
string
|
undefined
)
[
]
=
?
[
.
env
.
APPDATA
,
.
env
.
LOCALAPPDATA
]
:
?
[
homedir
(
)
+
'/Library'
]
:
[
]
;
// Path prefixes under which confirmation is unconditionally required
const
=
.
filter
(
)
.
concat
(
)
;
/**
* Validates that a path doesn't contain suspicious characters that could be used
* to bypass security checks on Windows (e.g., NTFS Alternate Data Streams, invalid chars).
* Throws an error if the path is suspicious.
*/
export
function
assertPathIsSafe
(
:
string
,
=
)
:
void
{
if
(
.
includes
(
'\0'
)
)
{
throw
new
Error
(
`Path contains null bytes: ${fsPath}`
)
;
}
if
(
!
)
{
return
;
}
// Check for NTFS Alternate Data Streams (ADS)
const
=
.
indexOf
(
':'
,
2
)
;
if
(
!==
-
1
)
{
throw
new
Error
(
`Path contains invalid characters (alternate data stream): ${fsPath}`
)
;
}
// Check for invalid Windows filename characters
const
=
/[<>"|?*]/
;
const
=
.
length
>
2
?
.
substring
(
2
)
:
;
if
(
.
test
(
)
)
{
throw
new
Error
(
`Path contains invalid characters: ${fsPath}`
)
;
}
// Check for named pipes or device paths
if
(
.
startsWith
(
'\\\\.'
)
||
.
startsWith
(
'\\\\?'
)
)
{
throw
new
Error
(
`Path is a reserved device path: ${fsPath}`
)
;
}
const
=
/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i
;
// Check for trailing dots and spaces on path components (Windows quirk)
const
=
.
split
(
'\\'
)
;
for
(
const
of
)
{
if
(
.
length
===
0
)
{
continue
;
}
// Reserved device names. Would error on edit, but fail explicitly