-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathtoolUtils.ts
More file actions
360 lines (322 loc) · 14.9 KB
/
toolUtils.ts
File metadata and controls
360 lines (322 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { PromptElement, PromptPiece } from '@vscode/prompt-tsx';
import type * as vscode from 'vscode';
import { IChatDebugFileLoggerService } from '../../../platform/chat/common/chatDebugFileLoggerService';
import { ISessionTranscriptService } from '../../../platform/chat/common/sessionTranscriptService';
import { ConfigKey, IConfigurationService } from '../../../platform/configuration/common/configurationService';
import { ICustomInstructionsService, IInstructionIndexFile } from '../../../platform/customInstructions/common/customInstructionsService';
import { IFileSystemService } from '../../../platform/filesystem/common/fileSystemService';
import { RelativePattern } from '../../../platform/filesystem/common/fileTypes';
import { IIgnoreService } from '../../../platform/ignore/common/ignoreService';
import { IPromptPathRepresentationService } from '../../../platform/prompts/common/promptPathRepresentationService';
import { ITabsAndEditorsService } from '../../../platform/tabs/common/tabsAndEditorsService';
import { IWorkspaceService } from '../../../platform/workspace/common/workspaceService';
import { CancellationToken } from '../../../util/vs/base/common/cancellation';
import { CancellationError } from '../../../util/vs/base/common/errors';
import { Schemas } from '../../../util/vs/base/common/network';
import { isAbsolute } from '../../../util/vs/base/common/path';
import { extUriBiasedIgnorePathCase, isEqual, normalizePath } from '../../../util/vs/base/common/resources';
import { isString } from '../../../util/vs/base/common/types';
import { URI } from '../../../util/vs/base/common/uri';
import { IInstantiationService, ServicesAccessor } from '../../../util/vs/platform/instantiation/common/instantiation';
import { LanguageModelPromptTsxPart, LanguageModelToolResult } from '../../../vscodeTypes';
import { isCustomizationsIndex, isPromptFile } from '../../prompt/common/chatVariablesCollection';
import { IBuildPromptContext } from '../../prompt/common/intents';
import { IChatDiskSessionResources } from '../../prompts/common/chatDiskSessionResources';
import { renderPromptElementJSON } from '../../prompts/node/base/promptRenderer';
export function checkCancellation(token: CancellationToken): void {
if (token.isCancellationRequested) {
throw new CancellationError();
}
}
export async function toolTSX(insta: IInstantiationService, options: vscode.LanguageModelToolInvocationOptions<unknown>, piece: PromptPiece, token: CancellationToken): Promise<vscode.LanguageModelToolResult> {
return new LanguageModelToolResult([
new LanguageModelPromptTsxPart(
await renderPromptElementJSON(insta, class extends PromptElement {
render() {
return piece;
}
}, {}, options.tokenizationOptions, token)
)
]);
}
export interface InputGlobResult {
/** The resolved glob patterns to pass to the search API. */
readonly patterns: vscode.GlobPattern[];
/** The workspace folder name if the pattern was scoped to a specific folder, for display. */
readonly folderName: string | undefined;
/** The glob pattern within the folder (e.g. `src/**`), for display. Only set when folderName is set. */
readonly folderRelativePattern: string | undefined;
}
/**
* Converts a user input glob or file path into VS Code glob patterns.
* Handles:
* - Absolute paths within a workspace folder
* - Patterns prefixed with a workspace folder name (e.g. `folderName/src/**`)
* - Patterns prefixed with `** /folderName/...` in multi-root workspaces
*/
export function inputGlobToPattern(query: string, workspaceService: IWorkspaceService, modelFamily: string | undefined): InputGlobResult {
let pattern: vscode.GlobPattern = query;
let folderName: string | undefined;
let folderRelativePattern: string | undefined;
if (isAbsolute(query)) {
try {
const uri = URI.file(query);
const workspaceFolder = workspaceService.getWorkspaceFolder(uri);
if (workspaceFolder) {
const relative = extUriBiasedIgnorePathCase.relativePath(workspaceFolder, uri) || '';
pattern = new RelativePattern(workspaceFolder, relative);
folderName = workspaceService.getWorkspaceFolderName(workspaceFolder);
folderRelativePattern = relative;
}
} catch (e) {
// ignore
}
}
// In multi-root workspaces, detect patterns like "folderName/src/**" or "**/folderName/src/**"
// and rewrite to a RelativePattern scoped to that folder.
if (typeof pattern === 'string' && workspaceService.getWorkspaceFolders().length > 1) {
let raw = pattern;
if (raw.startsWith('**/')) {
raw = raw.slice(3);
}
const slashIndex = raw.indexOf('/');
const candidateName = slashIndex >= 0 ? raw.slice(0, slashIndex) : raw;
if (candidateName && !candidateName.includes('*')) {
for (const folderUri of workspaceService.getWorkspaceFolders()) {
const name = workspaceService.getWorkspaceFolderName(folderUri);
if (name === candidateName) {
const remainder = slashIndex >= 0 ? raw.slice(slashIndex + 1) : '**';
const resolvedRemainder = remainder || '**';
pattern = new RelativePattern(folderUri, resolvedRemainder);
folderName = name;
folderRelativePattern = resolvedRemainder;
break;
}
}
}
}
const patterns = [pattern];
// For gpt-4.1, it struggles to append /** to the pattern itself, so here we work around it by
// adding a second pattern with /** appended.
// Other models are smart enough to append the /** suffix so they don't need this workaround.
if (modelFamily === 'gpt-4.1') {
if (typeof pattern === 'string' && !pattern.endsWith('/**')) {
patterns.push(pattern + '/**');
} else if (typeof pattern !== 'string' && !pattern.pattern.endsWith('/**')) {
patterns.push(new RelativePattern(pattern.baseUri, pattern.pattern + '/**'));
}
}
return { patterns, folderName, folderRelativePattern };
}
/**
* Checks whether the raw input pattern contains an absolute workspace folder path.
* Used for telemetry to detect patterns we may not be handling yet.
*/
export function patternContainsWorkspaceFolderPath(pattern: string | undefined, workspaceService: IWorkspaceService): boolean {
if (!pattern) {
return false;
}
for (const folderUri of workspaceService.getWorkspaceFolders()) {
if (pattern.includes(folderUri.fsPath) || pattern.includes(folderUri.path)) {
return true;
}
}
return false;
}
export function resolveToolInputPath(path: string, promptPathRepresentationService: IPromptPathRepresentationService): URI {
const uri = promptPathRepresentationService.resolveFilePath(path);
if (!uri) {
throw new Error(`Invalid input path: ${path}. Be sure to use an absolute path.`);
}
return uri;
}
export async function isFileOkForTool(accessor: ServicesAccessor, uri: URI, buildPromptContext?: IBuildPromptContext): Promise<boolean> {
try {
await assertFileOkForTool(accessor, uri, buildPromptContext);
return true;
} catch {
return false;
}
}
export interface AssertFileOkForToolOptions {
readOnly?: boolean;
}
export async function assertFileOkForTool(accessor: ServicesAccessor, uri: URI, buildPromptContext?: IBuildPromptContext, options?: AssertFileOkForToolOptions): Promise<void> {
const workspaceService = accessor.get(IWorkspaceService);
const tabsAndEditorsService = accessor.get(ITabsAndEditorsService);
const promptPathRepresentationService = accessor.get(IPromptPathRepresentationService);
const customInstructionsService = accessor.get(ICustomInstructionsService);
const diskSessionResources = accessor.get(IChatDiskSessionResources);
const configurationService = accessor.get(IConfigurationService);
const chatDebugFileLogger = accessor.get(IChatDebugFileLoggerService);
const sessionTranscriptService = accessor.get(ISessionTranscriptService);
await assertFileNotContentExcluded(accessor, uri);
const normalizedUri = normalizePath(uri);
if (workspaceService.getWorkspaceFolder(normalizedUri)) {
return;
}
if (options?.readOnly && isUriUnderAdditionalReadAccessPaths(normalizedUri, configurationService)) {
return;
}
if (uri.scheme === Schemas.untitled) {
return;
}
const fileOpenInSomeTab = tabsAndEditorsService.tabs.some(tab => isEqual(tab.uri, uri));
if (fileOpenInSomeTab) {
return;
}
if (diskSessionResources.isSessionResourceUri(normalizedUri)) {
return;
}
if (chatDebugFileLogger.isDebugLogUri(normalizedUri)) {
return;
}
if (sessionTranscriptService.isTranscriptUri(normalizedUri)) {
return;
}
if (await isExternalInstructionsFile(normalizedUri, customInstructionsService, buildPromptContext)) {
return;
}
throw new Error(`File ${promptPathRepresentationService.getFilePath(normalizedUri)} is outside of the workspace, and not open in an editor, and can't be read`);
}
async function isExternalInstructionsFile(normalizedUri: URI, customInstructionsService: ICustomInstructionsService, buildPromptContext?: IBuildPromptContext): Promise<boolean> {
if (normalizedUri.scheme === 'vscode-chat-internal') {
return true;
}
if (customInstructionsService.getExtensionSkillInfo(normalizedUri)) {
return true;
}
if (buildPromptContext) {
const instructionIndexFile = getInstructionsIndexFile(buildPromptContext, customInstructionsService);
if (instructionIndexFile) {
if (instructionIndexFile.instructions.has(normalizedUri) || instructionIndexFile.skills.has(normalizedUri)) {
return true;
}
// Check if the URI is under any skill folder (e.g., nested files like primitives/agents.md)
for (const skillFolderUri of instructionIndexFile.skillFolders) {
if (extUriBiasedIgnorePathCase.isEqualOrParent(normalizedUri, skillFolderUri)) {
return true;
}
}
}
const attachedPromptFile = buildPromptContext.chatVariables.find(v => isPromptFile(v) && isEqual(normalizedUri, v.value));
if (attachedPromptFile) {
return true;
}
} else {
// Note: this fallback check does not handle scenario where model passes file:// for userData schemes.
if (await customInstructionsService.isExternalInstructionsFile(normalizedUri)) {
return true;
}
}
return false;
}
let cachedInstructionIndexFile: { requestId: string; file: IInstructionIndexFile } | undefined;
function getInstructionsIndexFile(buildPromptContext: IBuildPromptContext, customInstructionsService: ICustomInstructionsService): IInstructionIndexFile | undefined {
if (!buildPromptContext.requestId) {
return undefined;
}
if (cachedInstructionIndexFile?.requestId === buildPromptContext.requestId) {
return cachedInstructionIndexFile.file;
}
const indexVariable = buildPromptContext.chatVariables.find(isCustomizationsIndex);
if (indexVariable && isString(indexVariable.value)) {
const indexFile = customInstructionsService.parseInstructionIndexFile(indexVariable.value);
cachedInstructionIndexFile = { requestId: buildPromptContext.requestId, file: indexFile };
return indexFile;
}
cachedInstructionIndexFile = undefined;
return undefined;
}
export async function assertFileNotContentExcluded(accessor: ServicesAccessor, uri: URI): Promise<void> {
const ignoreService = accessor.get(IIgnoreService);
const promptPathRepresentationService = accessor.get(IPromptPathRepresentationService);
if (await ignoreService.isCopilotIgnored(uri)) {
throw new Error(`File ${promptPathRepresentationService.getFilePath(uri)} is configured to be ignored by Copilot`);
}
}
export async function isFileExternalAndNeedsConfirmation(accessor: ServicesAccessor, uri: URI, buildPromptContext?: IBuildPromptContext, options?: { readOnly?: boolean }): Promise<boolean> {
const workspaceService = accessor.get(IWorkspaceService);
const tabsAndEditorsService = accessor.get(ITabsAndEditorsService);
const customInstructionsService = accessor.get(ICustomInstructionsService);
const diskSessionResources = accessor.get(IChatDiskSessionResources);
const configurationService = accessor.get(IConfigurationService);
const fileSystemService = accessor.get(IFileSystemService);
const chatDebugFileLogger = accessor.get(IChatDebugFileLoggerService);
const sessionTranscriptService = accessor.get(ISessionTranscriptService);
const normalizedUri = normalizePath(uri);
// Not external if: in workspace, untitled, instructions file, session resource, or open in editor
if (workspaceService.getWorkspaceFolder(normalizedUri)) {
return false;
}
if (options?.readOnly && isUriUnderAdditionalReadAccessPaths(normalizedUri, configurationService)) {
return false;
}
if (uri.scheme === Schemas.untitled || uri.scheme === 'vscode-chat-response-resource') {
return false;
}
if (await isExternalInstructionsFile(normalizedUri, customInstructionsService, buildPromptContext)) {
return false;
}
if (diskSessionResources.isSessionResourceUri(normalizedUri)) {
return false;
}
if (chatDebugFileLogger.isDebugLogUri(normalizedUri)) {
return false;
}
if (sessionTranscriptService.isTranscriptUri(normalizedUri)) {
return false;
}
if (tabsAndEditorsService.tabs.some(tab => isEqual(tab.uri, uri))) {
return false;
}
// If the file doesn't exist, throw immediately rather than showing a confusing "external file"
// confirmation — the tool should fail with a clear "file not found" error instead.
const fileExists = await fileSystemService.stat(normalizedUri).then(() => true).catch(() => false);
if (!fileExists) {
throw new Error(`File ${normalizedUri.fsPath} does not exist`);
}
return true;
}
export function isDirExternalAndNeedsConfirmation(accessor: ServicesAccessor, uri: URI, buildPromptContext?: IBuildPromptContext, options?: { readOnly?: boolean }): boolean {
const workspaceService = accessor.get(IWorkspaceService);
const customInstructionsService = accessor.get(ICustomInstructionsService);
const configurationService = accessor.get(IConfigurationService);
const normalizedUri = normalizePath(uri);
// Not external if: in workspace or external instructions folder
if (workspaceService.getWorkspaceFolder(normalizedUri)) {
return false;
}
if (options?.readOnly && isUriUnderAdditionalReadAccessPaths(normalizedUri, configurationService)) {
return false;
}
if (buildPromptContext) {
const instructionIndexFile = getInstructionsIndexFile(buildPromptContext, customInstructionsService);
if (instructionIndexFile) {
for (const skillFolderUri of instructionIndexFile.skillFolders) {
if (extUriBiasedIgnorePathCase.isEqualOrParent(normalizedUri, skillFolderUri)) {
return false;
}
}
}
} else {
if (customInstructionsService.isExternalInstructionsFolder(normalizedUri)) {
return false;
}
}
return true;
}
function isUriUnderAdditionalReadAccessPaths(uri: URI, configurationService: IConfigurationService): boolean {
const paths = configurationService.getConfig(ConfigKey.AdditionalReadAccessPaths);
for (const p of paths) {
const folderUri = normalizePath(URI.file(p));
if (extUriBiasedIgnorePathCase.isEqualOrParent(uri, folderUri)) {
return true;
}
}
return false;
}