Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/** Whether to include files that would normally be ignored according to .gitignore, other ignore files and `files.exclude` and `search.exclude` settings. */
?
:
boolean
;
}
interface
FileMatch
{
:
string
;
:
.
TextSearchMatch2
[
]
;
?
:
number
;
}
interface
MatchResult
{
:
{
:
number
;
:
number
;
:
number
;
}
;
:
FileMatch
[
]
;
}
export
class
FindTextInFilesTool
implements
ICopilotTool<IFindTextInFilesToolParams>
{
public
static
readonly
=
ToolName
.
FindTextInFiles
;
public
static
readonly
=
true
;
constructor
(
IInstantiationService
private
readonly
:
IInstantiationService
,
ISearchService
private
readonly
:
ISearchService
,
IWorkspaceService
private
readonly
:
IWorkspaceService
,
IEndpointProvider
private
readonly
:
IEndpointProvider
,
IConfigurationService
private
readonly
:
IConfigurationService
,
ITelemetryService
private
readonly
:
ITelemetryService
,
IPromptPathRepresentationService
private
readonly
:
IPromptPathRepresentationService
,
IExperimentationService
private
readonly
:
IExperimentationService
,
)
{
}
async
invoke
(
:
.
LanguageModelToolInvocationOptions
<
IFindTextInFilesToolParams
>
,
:
CancellationToken
)
{
// TODO strict input validation
// Certain models just really want to pass incorrect input
if
(
(
.
input
as
unknown
as
Record
<
string
,
string
>
)
.
pattern
)
{
throw
new
Error
(
'The property "pattern" is not supported, please use "query"'
)
;
}
const
=
.
model
&&
(
await
this
.
endpointProvider
.
getChatEndpoint
(
.
model
)
)
;
const
=
?.
;
// The input _should_ be a pattern matching inside a workspace, folder, but sometimes we get absolute paths, so try to resolve them
const
=
new
WorkingDirectory
(
.
workingDirectory
,
this
.
workspaceService
)
;
const
=
.
input
.
includePattern
?
inputGlobToPattern
(
.
input
.
includePattern
,
,
)
:
undefined
;
let
=
?.
;
// When no include pattern is specified but a working directory is set (agents window),
// scope the search to the session's working directory.
if
(
!
&&
.
hasExplicitWorkingDirectory
)
{
=
[
new
RelativePattern
(
.
uri
!
,
'**'
)
]
;
}
const
=
this
.
getOutputFormat
(
)
;
const
=
===
'grep'
;
const
=
this
.
getDefaultMaxResults
(
)
;
const
=
this
.
getMaxResultsCap
(
)
;
void
this
.
sendSearchToolTelemetry
(
,
,
,
.
input
.
maxResults
,
,
)
;
checkCancellation
(
)
;
const
=
.
input
.
maxResults
&&
.
input
.
maxResults
>
;
const
=
Math
.
min
(
.
input
.
maxResults
??
.
input
.
defaultMaxResults
??
,
)
;
const
=
.
input
.
isRegexp
??
true
;
const
=
this
.
isValidRegex
(
.
input
.
query
)
;
const
=
.
input
.
includeIgnoredFiles
??
false
;
// try find text with a timeout of 20s
const
=
20_000
;
// For the grp output we don't limit the number of matches by cutting files. We instead
// keep files and cut matches for each file. Therefore we need to ask for more results upfront
// to account for the fact that some files will be cut off. For the tag output we cut off files
// instead of matches, so we can just ask for the maxResults number of results.
const
=
?
*
5
:
;
let
=
await
raceTimeoutAndCancellationError
(
(
)
=>
this
.
searchAndCollectResults
(
.
input
.
query
,
,
,
,
,
)
,
,
,
// embed message to give LLM hint about what to do next
`Timeout in searching text in files with ${isRegExp ?'regex':'literal'} search, try a more specific search pattern or change regex/literal mode`
)
;
// If we still have no results, we need to try the opposite regex mode
if
(
!
.
length
&&
)
{
=
await
raceTimeoutAndCancellationError
(
(
)
=>
this
.
searchAndCollectResults
(
.
input
.
query
,
!
,
,
,
,
)
,
,
,
// embed message to give LLM hint about what to do next
`Find ${results.length} results in searching text in files with ${isRegExp ?'regex':'literal'} search, and then another searching hits timeout in with ${!isRegExp ?'regex':'literal'} search, try a more specific search pattern`
)
;
}
let
:
string
|
undefined
=
undefined
;
if
(
!
.
length
&&
!
)
{
// Get the search.exclude configuration
const
=
this
.
configurationService
.
getNonExtensionConfig
<
Record
<
string
,
boolean
>>
(
'search.exclude'
)
;
const
:
string
[
]
=
[
]
;
if
(
)
{
for
(
const
[
,
]
of
Object
.
entries
(
)
)
{
if
(
)
{
.
push
(
)
;
}
}
}
=
`Your search pattern might be excluded completely by either the search.exclude settings or .*ignore files.
If you believe that it should have results, you can check into the .*ignore files and the exclude setting (here are some excluded patterns for reference:[${excludePaths.join(',')}]).
Then if you want to include those files you can call the tool again by setting "includeIgnoredFiles" to true.`
;
}
if
(
)
{
return
this
.
renderGrepStyle
(
,
,
,
,
,
,
)
;
}
else
{
return
this
.
renderTagStyle
(
,
,
,
,
,
,
,
,
)
;
}
}
private
async
renderTagStyle
(
:
.
TextSearchResult2
[
]
,
:
.
LanguageModelToolInvocationOptions
<
IFindTextInFilesToolParams
>
,
:
number
,
:
number
,
:
InputGlobResult
|
undefined
,
:
boolean
|
number
|
undefined
,
:
boolean
,
:
string
|
undefined
,
:
CancellationToken
)
:
Promise
<
.
ExtendedLanguageModelToolResult
>
{
const
=
await
renderPromptElementJSON
(
this
.
instantiationService
,
FindTextInFilesResult
,
{
:
,
,
,
:
Boolean
(
)
,
}
,
.
tokenizationOptions
,
)
;
const
=
new
ExtendedLanguageModelToolResult
(
[
new
LanguageModelPromptTsxPart
(
)
]
)
;
const
=
.
flatMap
(
=>
{
if
(
'ranges'
in
)
{
return
asArray
(
.
ranges
)
.
map
(
=>
new
Location
(
.
uri
,
.
sourceRange
)
)
;
}
return
[
]
;
}
)
.
slice
(
0
,
)
;
const
=
this
.
formatQueryString
(
.
input
,
)
;
.
toolResultMessage
=
this
.
getResultMessage
(
,
,
.
length
)
;
.
toolResultDetails
=
;
return
;
}
private
async
renderGrepStyle
(
:
.
TextSearchResult2
[
]
,
:
.
LanguageModelToolInvocationOptions
<
IFindTextInFilesToolParams
>
,
:
number
,
:
InputGlobResult
|
undefined
,
:
boolean
,
:
string
|
undefined
,
:
CancellationToken
)
:
Promise
<
.
ExtendedLanguageModelToolResult
>
{
const
=
this
.
createGroupedFileMatches
(
,
)
;
if
(
!
)
{
return
this
.
errorResult
(
?
`No matches found. ${noMatchInstructions}`
:
'No matches found.'
)
;
}
const
=
await
renderPromptElementJSON
(
this
.
instantiationService
,
FindTextInFilesGrepResult
,
{
:
,
:
.
input
.
query
}
,
.
tokenizationOptions
,
)
;
const
=
new
ExtendedLanguageModelToolResult
(
[
new
LanguageModelPromptTsxPart
(
)
]
)
;
const
=
this
.
formatQueryString
(
.
input
,
)
;
.
toolResultMessage
=
this
.
getResultMessage
(
,
,
.
stats
.
total
)
;
return
;
}
private
createGroupedFileMatches
(
:
.
TextSearchResult2
[
]
,
:
number
)
:
MatchResult
|
undefined
{
const
=
.
filter
(
)
;
if
(
!
.
length
)
{
return
undefined
;
}
const
:
Map
<
string
,
FileMatch
>
=
new
Map
(
)
;
for
(
const
of
)
{
const
=
this
.
promptPathRepresentationService
.
getFilePath
(
.
uri
,
true
)
;
let
=
.
get
(
)
;
if
(
===
undefined
)
{
=
{
,
:
[
]
}
;
.
set
(
,
)
;
}
.
matches
.
push
(
)
;
}
let
=
Array
.
from
(
.
values
(
)
)
.
sort
(
(
,
)
=>
.
path
.
localeCompare
(
.
path
)
)
;
let
=
0
;
for
(
const
of
)
{
.
matches
=
.
matches
.
sort
(
(
,
)
=>
.
ranges
[
0
]
.
sourceRange
.
start
.
line
-
.
ranges
[
0
]
.
sourceRange
.
start
.
line
)
;
+=
.
matches
.
length
;
}
let
=
0
;
let
=
0
;
if
(
>
)
{
// Every file we keep must show at least one match, so we can show at most
// `maxResults` files. When there are more files than that, drop the extra
// files entirely (keeping the alphabetically-first ones) and count them.
const
=
Math
.
min
(
.
length
,
)
;
for
(
let
=
;
<
.
length
;
++
)
{
+=
[
]
.
matches
.
length
;
}
=
.
length
-
;
=
.
slice
(
0
,
)
;
// Distribute the `maxResults` budget across the kept files proportionally to
// their number of matches, guaranteeing at least one match per file (largest
// remainder method).
const
=
.
reduce
(
(
,
)
=>
+
.
matches
.
length
,
0
)
;
const
=
.
map
(
(
,
)
=>
{
const
=
(
.
matches
.
length
/
)
*
;
const
=
Math
.
floor
(
)
;
return
{
,
:
Math
.
max
(
1
,
)
,
:
-
}
;
}
)
;
let
=
.
reduce
(
(
,
)
=>
+
.
allowed
,
0
)
;
if
(
<
)
{
// Hand out the remaining budget to the files with the largest remainder,
// never allocating more matches than a file actually has.
const
=
.
slice
(
)
.
sort
(
(
,
)
=>
.
remainder
-
.
remainder
)
;
let
=
true
;
while
(
<
&&
)
{
=
false
;
for
(
const
of
)
{
if
(
>=
)
{
break
;
}
if
(
.
allowed
<
[
.
index
]
.
matches
.
length
)
{
.
allowed
++
;
++
;
=
true
;
}
}
}
}
else
if
(
>
)
{
// The minimum-one-per-file rule pushed us over budget; reclaim slots from
// the files with the smallest remainder without dropping below one match.
const
=
.
slice
(
)
.
sort
(
(
,
)
=>
.
remainder
-
.
remainder
)
;
let
=
true
;
while
(
>
&&
)
{
=
false
;
for
(
const
of
)
{
if
(
<=
)
{
break
;
}
if
(
.
allowed
>
1
)
{
.
allowed
--
;
--
;
=
true
;
}
}
}
}
for
(
const
of
)
{
const
=
[
.
index
]
;
if
(
.
matches
.
length
>
.
allowed
)
{
const
=
.
matches
.
length
-
.
allowed
;
.
elidedMatches
=
;
+=
;
.
matches
=
.
matches
.
slice
(
0
,
.
allowed
)
;
}
}
}
return
{
:
{
:
,
:
,
:
,
}
,
:
}
;
}
private
errorResult
(
:
string
)
:
.
ExtendedLanguageModelToolResult
{
const
=
new
ExtendedLanguageModelToolResult
(
[
]
)
;
.
toolResultMessage
=
new
MarkdownString
(
)
;
return
;
}
private
async
sendSearchToolTelemetry
(
:
.
LanguageModelToolInvocationOptions
<
IFindTextInFilesToolParams
>
,
:
InputGlobResult
|
undefined
,
:
string
,
:
number
|
undefined
,
:
number
,
:
number
)
:
Promise
<
void
>
{
const
=
.
model
&&
(
await
this
.
endpointProvider
.
getChatEndpoint
(
.
model
)
)
.
model
;
const
=
this
.
workspaceService
.
getWorkspaceFolders
(
)
.
length
>
1
;
const
=
.
input
.
includePattern
;
/* __GDPR__
"findTextInFilesToolInvoked" : {
"owner": "roblourens",
"comment": "Telemetry for the findTextInFiles tool in multi-root workspaces",
"requestId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The id of the current request turn." },
"model": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The model that invoked the tool" },
"isMultiRoot": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Whether the workspace has multiple root folders" },
"patternScopedToFolder": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Whether the includePattern was resolved to a specific workspace folder" },
"patternStartsWithFolderPath": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Whether the raw includePattern starts with a workspace folder absolute path" },
"patternContainsFolderPath": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Whether the raw includePattern contains a workspace folder absolute path anywhere" },
"outputFormat": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The output format of the search results" },
"requestedMaxResults": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The maximum number of results that was requested by the LLM. Undefined if not provided." },
"defaultMaxResults": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The default maximum number of results used when the LLM doesn't specify a value." },
"maxResultsCap": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The maximum number of results that can be returned." }
}
*/
this
.
telemetryService
.
sendMSFTTelemetryEvent
(
'findTextInFilesToolInvoked'
,
{
:
.
chatRequestId
,
,
:
String
(
)
,
:
String
(
!
!
?.
)
,
:
String
(
!
!
&&
isAbsolute
(
)
&&
!
!
this
.
workspaceService
.
getWorkspaceFolder
(
URI
.
file
(
)
)
)
,
:
String
(
patternContainsWorkspaceFolderPath
(
,
this
.
workspaceService
)
)
,
:
}
,
{
,
,
}
)
;
}
private
getResultMessage
(
:
boolean
,
:
string
,
:
number
)
:
MarkdownString
{
if
(
===
0
)
{
return
?
new
MarkdownString
(
.
t
`Searched for regex ${query}, no results`
)
:
new
MarkdownString
(
.
t
`Searched for text ${query}, no results`
)
;
}
else
if
(
===
1
)
{
return
?
new
MarkdownString
(
.
t
`Searched for regex ${query}, 1 result`
)
:
new
MarkdownString
(
.
t
`Searched for text ${query}, 1 result`
)
;
}
else
{
return
?
new
MarkdownString
(
.
t
`Searched for regex ${query}, ${count} results`
)
:
new
MarkdownString
(
.
t
`Searched for text ${query}, ${count} results`
)
;
}
}
private
isValidRegex
(
:
string
)
:
boolean
{
try
{
new
RegExp
(
)
;
return
true
;
}
catch
{
return
false
;
}
}
private
async
searchAndCollectResults
(
:
string
,
:
boolean
,
:
.
GlobPattern
[
]
|
undefined
,
:
number
,
:
boolean
|
undefined
,
:
CancellationToken
)
:
Promise
<
.
TextSearchResult2
[
]
>
{
const
:
.
FindTextInFilesOptions2
=
{
:
?
:
undefined
,
:
+
1
,
:
?
ExcludeSettingOptions
.
None
:
ExcludeSettingOptions
.
SearchAndFilesExclude
,
:
?
{
:
false
,
:
false
,
:
false
}
:
undefined
,
:
true
,
}
;
const
=
this
.
searchService
.
findTextInFiles2
(
{
:
,
,
}
,
,
)
;
const
:
.
TextSearchResult2
[
]
=
[
]
;
for
await
(
const
of
.
results
)
{
checkCancellation
(
)
;
.
push
(
)
;
}
// Necessary in case it was rejected
await
.
complete
;
return
;
}
prepareInvocation
(
:
.
LanguageModelToolInvocationPrepareOptions
<
IFindTextInFilesToolParams
>
,
:
.
CancellationToken
)
:
.
ProviderResult
<
.
PreparedToolInvocation
>
{
const
=
.
input
.
isRegexp
??
true
;
const
=
.
input
.
includePattern
?
inputGlobToPattern
(
.
input
.
includePattern
,
new
WorkingDirectory
(
undefined
,
this
.
workspaceService
)
,
undefined
)
:
undefined
;
const
=
this
.
formatQueryString
(
.
input
,
)
;
return
{
:
?
new
MarkdownString
(
.
t
`Searching for regex ${query}`
)
:
new
MarkdownString
(
.
t
`Searching for text ${query}`
)
,
}
;
}
/**
* Formats text as a Markdown inline code span that is resilient to backticks within the text.
* It chooses a backtick fence one longer than the longest run of backticks in the content,
* and pads with a space when the content begins or ends with a backtick as per CommonMark.
*/
/**
* 1. Removes excessive extra character data from the match, e.g. avoiding
* giant minified lines
* 2. Wraps the match in a <match> tag
* 3. Prioritizes lines in the middle of the match where the range lies
*/
/**
* Renders grep-style search results as plain text (no XML tags) through prompt-tsx, so the
* output participates in token-budget pruning and carries editor references instead of being
* emitted as a single unprunable text blob.
*
* Each file is rendered as its own {@link TextChunk}, prefixed with a blank line to match the
* grep output format. Earlier files are given a higher priority so that, when the budget is
* exceeded, later files are dropped first.
*/
export
class
FindTextInFilesGrepResult
extends
PromptElement<FindTextInFilesGrepResultProps>
{
/** Grep output: lines at or below this length are emitted verbatim. */
private
static
readonly
MAX_LINE_CHARS
=
600
;
/** Grep output: characters of context kept before the match when a long line is truncated. */
private
static
readonly
CONTEXT_BEFORE_CHARS
=
150
;
/** Grep output: characters of context kept after the match when a long line is truncated. */
private
static
readonly
CONTEXT_AFTER_CHARS
=
105
;
/** Grep output: max characters of the matched span itself before its middle is elided. */
private
static
readonly
MAX_MATCH_CHARS
=
300
;
render
(
)
:
PromptPiece
{
const
{
,
}
=
this
.
props
;
const
=
.
stats
.
total
;
const
=
.
stats
.
filesElided
+
.
files
.
length
;
const
=
===
1
?
`1 match`
:
`${totalMatches} matches`
;
const
=
===
1
?
`1 file`
:
`${totalFiles} files`
;
let
=
''
;
if
(
.
stats
.
elided
>
0
)
{
const
=
-
.
stats
.
elided
;
const
=
===
1
?
`1 match`
:
`${shownMatches} matches`
;
const
=
.
files
.
length
===
1
?
`1 file`
:
`${grouped.files.length} files`
;
=
` (showing ${shownMatchText} in ${shownFilesText})`
;
}
const
=
`Found ${matchText} in ${filesText} for "${query}"${elided}`
/**
* Renders a single search match as one grep-style line, bounded for an LLM consumer.
*
* Lines up to {@link GREP_MAX_LINE_CHARS} characters are returned verbatim. Longer lines (typically
* minified or generated) are reduced to a match-centered window: {@link GREP_CONTEXT_BEFORE_CHARS}
* characters before the match, up to {@link GREP_MAX_MATCH_CHARS} of the match itself (middle-elided
* if larger), and {@link GREP_CONTEXT_AFTER_CHARS} after, followed by a
* `[match at col N, line truncated, M chars]` annotation so the model knows where the match sits in
* the full line and can read the file for the rest. The result is always a single line.
*/