Add files using upload-large-folder tool
Browse files- projects/ui/qwen-code/packages/core/src/tools/glob.ts +331 -0
- projects/ui/qwen-code/packages/core/src/tools/grep.test.ts +522 -0
- projects/ui/qwen-code/packages/core/src/tools/grep.ts +711 -0
- projects/ui/qwen-code/packages/core/src/tools/ls.test.ts +484 -0
- projects/ui/qwen-code/packages/core/src/tools/ls.ts +338 -0
- projects/ui/qwen-code/packages/core/src/tools/mcp-client-manager.test.ts +54 -0
- projects/ui/qwen-code/packages/core/src/tools/mcp-client-manager.ts +115 -0
- projects/ui/qwen-code/packages/core/src/tools/mcp-client.test.ts +569 -0
- projects/ui/qwen-code/packages/core/src/tools/mcp-client.ts +1375 -0
- projects/ui/qwen-code/packages/core/src/tools/mcp-tool.test.ts +746 -0
- projects/ui/qwen-code/packages/core/src/tools/mcp-tool.ts +356 -0
- projects/ui/qwen-code/packages/core/src/tools/memoryTool.test.ts +595 -0
- projects/ui/qwen-code/packages/core/src/tools/memoryTool.ts +568 -0
- projects/ui/qwen-code/packages/core/src/tools/modifiable-tool.test.ts +353 -0
- projects/ui/qwen-code/packages/core/src/tools/modifiable-tool.ts +170 -0
- projects/ui/qwen-code/packages/core/src/tools/read-file.test.ts +448 -0
- projects/ui/qwen-code/packages/core/src/tools/read-file.ts +238 -0
- projects/ui/qwen-code/packages/core/src/tools/read-many-files.test.ts +696 -0
- projects/ui/qwen-code/packages/core/src/tools/read-many-files.ts +644 -0
- projects/ui/qwen-code/packages/core/src/tools/shell.test.ts +878 -0
projects/ui/qwen-code/packages/core/src/tools/glob.ts
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import fs from 'fs';
|
| 8 |
+
import path from 'path';
|
| 9 |
+
import { glob, escape } from 'glob';
|
| 10 |
+
import {
|
| 11 |
+
BaseDeclarativeTool,
|
| 12 |
+
BaseToolInvocation,
|
| 13 |
+
Kind,
|
| 14 |
+
ToolInvocation,
|
| 15 |
+
ToolResult,
|
| 16 |
+
} from './tools.js';
|
| 17 |
+
import { shortenPath, makeRelative } from '../utils/paths.js';
|
| 18 |
+
import { Config } from '../config/config.js';
|
| 19 |
+
|
| 20 |
+
// Subset of 'Path' interface provided by 'glob' that we can implement for testing
|
| 21 |
+
export interface GlobPath {
|
| 22 |
+
fullpath(): string;
|
| 23 |
+
mtimeMs?: number;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
/**
|
| 27 |
+
* Sorts file entries based on recency and then alphabetically.
|
| 28 |
+
* Recent files (modified within recencyThresholdMs) are listed first, newest to oldest.
|
| 29 |
+
* Older files are listed after recent ones, sorted alphabetically by path.
|
| 30 |
+
*/
|
| 31 |
+
export function sortFileEntries(
|
| 32 |
+
entries: GlobPath[],
|
| 33 |
+
nowTimestamp: number,
|
| 34 |
+
recencyThresholdMs: number,
|
| 35 |
+
): GlobPath[] {
|
| 36 |
+
const sortedEntries = [...entries];
|
| 37 |
+
sortedEntries.sort((a, b) => {
|
| 38 |
+
const mtimeA = a.mtimeMs ?? 0;
|
| 39 |
+
const mtimeB = b.mtimeMs ?? 0;
|
| 40 |
+
const aIsRecent = nowTimestamp - mtimeA < recencyThresholdMs;
|
| 41 |
+
const bIsRecent = nowTimestamp - mtimeB < recencyThresholdMs;
|
| 42 |
+
|
| 43 |
+
if (aIsRecent && bIsRecent) {
|
| 44 |
+
return mtimeB - mtimeA;
|
| 45 |
+
} else if (aIsRecent) {
|
| 46 |
+
return -1;
|
| 47 |
+
} else if (bIsRecent) {
|
| 48 |
+
return 1;
|
| 49 |
+
} else {
|
| 50 |
+
return a.fullpath().localeCompare(b.fullpath());
|
| 51 |
+
}
|
| 52 |
+
});
|
| 53 |
+
return sortedEntries;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/**
|
| 57 |
+
* Parameters for the GlobTool
|
| 58 |
+
*/
|
| 59 |
+
export interface GlobToolParams {
|
| 60 |
+
/**
|
| 61 |
+
* The glob pattern to match files against
|
| 62 |
+
*/
|
| 63 |
+
pattern: string;
|
| 64 |
+
|
| 65 |
+
/**
|
| 66 |
+
* The directory to search in (optional, defaults to current directory)
|
| 67 |
+
*/
|
| 68 |
+
path?: string;
|
| 69 |
+
|
| 70 |
+
/**
|
| 71 |
+
* Whether the search should be case-sensitive (optional, defaults to false)
|
| 72 |
+
*/
|
| 73 |
+
case_sensitive?: boolean;
|
| 74 |
+
|
| 75 |
+
/**
|
| 76 |
+
* Whether to respect .gitignore patterns (optional, defaults to true)
|
| 77 |
+
*/
|
| 78 |
+
respect_git_ignore?: boolean;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
class GlobToolInvocation extends BaseToolInvocation<
|
| 82 |
+
GlobToolParams,
|
| 83 |
+
ToolResult
|
| 84 |
+
> {
|
| 85 |
+
constructor(
|
| 86 |
+
private config: Config,
|
| 87 |
+
params: GlobToolParams,
|
| 88 |
+
) {
|
| 89 |
+
super(params);
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
getDescription(): string {
|
| 93 |
+
let description = `'${this.params.pattern}'`;
|
| 94 |
+
if (this.params.path) {
|
| 95 |
+
const searchDir = path.resolve(
|
| 96 |
+
this.config.getTargetDir(),
|
| 97 |
+
this.params.path || '.',
|
| 98 |
+
);
|
| 99 |
+
const relativePath = makeRelative(searchDir, this.config.getTargetDir());
|
| 100 |
+
description += ` within ${shortenPath(relativePath)}`;
|
| 101 |
+
}
|
| 102 |
+
return description;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
async execute(signal: AbortSignal): Promise<ToolResult> {
|
| 106 |
+
try {
|
| 107 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 108 |
+
const workspaceDirectories = workspaceContext.getDirectories();
|
| 109 |
+
|
| 110 |
+
// If a specific path is provided, resolve it and check if it's within workspace
|
| 111 |
+
let searchDirectories: readonly string[];
|
| 112 |
+
if (this.params.path) {
|
| 113 |
+
const searchDirAbsolute = path.resolve(
|
| 114 |
+
this.config.getTargetDir(),
|
| 115 |
+
this.params.path,
|
| 116 |
+
);
|
| 117 |
+
if (!workspaceContext.isPathWithinWorkspace(searchDirAbsolute)) {
|
| 118 |
+
return {
|
| 119 |
+
llmContent: `Error: Path "${this.params.path}" is not within any workspace directory`,
|
| 120 |
+
returnDisplay: `Path is not within workspace`,
|
| 121 |
+
};
|
| 122 |
+
}
|
| 123 |
+
searchDirectories = [searchDirAbsolute];
|
| 124 |
+
} else {
|
| 125 |
+
// Search across all workspace directories
|
| 126 |
+
searchDirectories = workspaceDirectories;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
// Get centralized file discovery service
|
| 130 |
+
const respectGitIgnore =
|
| 131 |
+
this.params.respect_git_ignore ??
|
| 132 |
+
this.config.getFileFilteringRespectGitIgnore();
|
| 133 |
+
const fileDiscovery = this.config.getFileService();
|
| 134 |
+
|
| 135 |
+
// Collect entries from all search directories
|
| 136 |
+
let allEntries: GlobPath[] = [];
|
| 137 |
+
|
| 138 |
+
for (const searchDir of searchDirectories) {
|
| 139 |
+
let pattern = this.params.pattern;
|
| 140 |
+
const fullPath = path.join(searchDir, pattern);
|
| 141 |
+
if (fs.existsSync(fullPath)) {
|
| 142 |
+
pattern = escape(pattern);
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
const entries = (await glob(pattern, {
|
| 146 |
+
cwd: searchDir,
|
| 147 |
+
withFileTypes: true,
|
| 148 |
+
nodir: true,
|
| 149 |
+
stat: true,
|
| 150 |
+
nocase: !this.params.case_sensitive,
|
| 151 |
+
dot: true,
|
| 152 |
+
ignore: ['**/node_modules/**', '**/.git/**'],
|
| 153 |
+
follow: false,
|
| 154 |
+
signal,
|
| 155 |
+
})) as GlobPath[];
|
| 156 |
+
|
| 157 |
+
allEntries = allEntries.concat(entries);
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
const entries = allEntries;
|
| 161 |
+
|
| 162 |
+
// Apply git-aware filtering if enabled and in git repository
|
| 163 |
+
let filteredEntries = entries;
|
| 164 |
+
let gitIgnoredCount = 0;
|
| 165 |
+
|
| 166 |
+
if (respectGitIgnore) {
|
| 167 |
+
const relativePaths = entries.map((p) =>
|
| 168 |
+
path.relative(this.config.getTargetDir(), p.fullpath()),
|
| 169 |
+
);
|
| 170 |
+
const filteredRelativePaths = fileDiscovery.filterFiles(relativePaths, {
|
| 171 |
+
respectGitIgnore,
|
| 172 |
+
});
|
| 173 |
+
const filteredAbsolutePaths = new Set(
|
| 174 |
+
filteredRelativePaths.map((p) =>
|
| 175 |
+
path.resolve(this.config.getTargetDir(), p),
|
| 176 |
+
),
|
| 177 |
+
);
|
| 178 |
+
|
| 179 |
+
filteredEntries = entries.filter((entry) =>
|
| 180 |
+
filteredAbsolutePaths.has(entry.fullpath()),
|
| 181 |
+
);
|
| 182 |
+
gitIgnoredCount = entries.length - filteredEntries.length;
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
if (!filteredEntries || filteredEntries.length === 0) {
|
| 186 |
+
let message = `No files found matching pattern "${this.params.pattern}"`;
|
| 187 |
+
if (searchDirectories.length === 1) {
|
| 188 |
+
message += ` within ${searchDirectories[0]}`;
|
| 189 |
+
} else {
|
| 190 |
+
message += ` within ${searchDirectories.length} workspace directories`;
|
| 191 |
+
}
|
| 192 |
+
if (gitIgnoredCount > 0) {
|
| 193 |
+
message += ` (${gitIgnoredCount} files were git-ignored)`;
|
| 194 |
+
}
|
| 195 |
+
return {
|
| 196 |
+
llmContent: message,
|
| 197 |
+
returnDisplay: `No files found`,
|
| 198 |
+
};
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
// Set filtering such that we first show the most recent files
|
| 202 |
+
const oneDayInMs = 24 * 60 * 60 * 1000;
|
| 203 |
+
const nowTimestamp = new Date().getTime();
|
| 204 |
+
|
| 205 |
+
// Sort the filtered entries using the new helper function
|
| 206 |
+
const sortedEntries = sortFileEntries(
|
| 207 |
+
filteredEntries,
|
| 208 |
+
nowTimestamp,
|
| 209 |
+
oneDayInMs,
|
| 210 |
+
);
|
| 211 |
+
|
| 212 |
+
const sortedAbsolutePaths = sortedEntries.map((entry) =>
|
| 213 |
+
entry.fullpath(),
|
| 214 |
+
);
|
| 215 |
+
const fileListDescription = sortedAbsolutePaths.join('\n');
|
| 216 |
+
const fileCount = sortedAbsolutePaths.length;
|
| 217 |
+
|
| 218 |
+
let resultMessage = `Found ${fileCount} file(s) matching "${this.params.pattern}"`;
|
| 219 |
+
if (searchDirectories.length === 1) {
|
| 220 |
+
resultMessage += ` within ${searchDirectories[0]}`;
|
| 221 |
+
} else {
|
| 222 |
+
resultMessage += ` across ${searchDirectories.length} workspace directories`;
|
| 223 |
+
}
|
| 224 |
+
if (gitIgnoredCount > 0) {
|
| 225 |
+
resultMessage += ` (${gitIgnoredCount} additional files were git-ignored)`;
|
| 226 |
+
}
|
| 227 |
+
resultMessage += `, sorted by modification time (newest first):\n${fileListDescription}`;
|
| 228 |
+
|
| 229 |
+
return {
|
| 230 |
+
llmContent: resultMessage,
|
| 231 |
+
returnDisplay: `Found ${fileCount} matching file(s)`,
|
| 232 |
+
};
|
| 233 |
+
} catch (error) {
|
| 234 |
+
const errorMessage =
|
| 235 |
+
error instanceof Error ? error.message : String(error);
|
| 236 |
+
console.error(`GlobLogic execute Error: ${errorMessage}`, error);
|
| 237 |
+
return {
|
| 238 |
+
llmContent: `Error during glob search operation: ${errorMessage}`,
|
| 239 |
+
returnDisplay: `Error: An unexpected error occurred.`,
|
| 240 |
+
};
|
| 241 |
+
}
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/**
|
| 246 |
+
* Implementation of the Glob tool logic
|
| 247 |
+
*/
|
| 248 |
+
export class GlobTool extends BaseDeclarativeTool<GlobToolParams, ToolResult> {
|
| 249 |
+
static readonly Name = 'glob';
|
| 250 |
+
|
| 251 |
+
constructor(private config: Config) {
|
| 252 |
+
super(
|
| 253 |
+
GlobTool.Name,
|
| 254 |
+
'FindFiles',
|
| 255 |
+
'Efficiently finds files matching specific glob patterns (e.g., `src/**/*.ts`, `**/*.md`), returning absolute paths sorted by modification time (newest first). Ideal for quickly locating files based on their name or path structure, especially in large codebases.',
|
| 256 |
+
Kind.Search,
|
| 257 |
+
{
|
| 258 |
+
properties: {
|
| 259 |
+
pattern: {
|
| 260 |
+
description:
|
| 261 |
+
"The glob pattern to match against (e.g., '**/*.py', 'docs/*.md').",
|
| 262 |
+
type: 'string',
|
| 263 |
+
},
|
| 264 |
+
path: {
|
| 265 |
+
description:
|
| 266 |
+
'Optional: The absolute path to the directory to search within. If omitted, searches the root directory.',
|
| 267 |
+
type: 'string',
|
| 268 |
+
},
|
| 269 |
+
case_sensitive: {
|
| 270 |
+
description:
|
| 271 |
+
'Optional: Whether the search should be case-sensitive. Defaults to false.',
|
| 272 |
+
type: 'boolean',
|
| 273 |
+
},
|
| 274 |
+
respect_git_ignore: {
|
| 275 |
+
description:
|
| 276 |
+
'Optional: Whether to respect .gitignore patterns when finding files. Only available in git repositories. Defaults to true.',
|
| 277 |
+
type: 'boolean',
|
| 278 |
+
},
|
| 279 |
+
},
|
| 280 |
+
required: ['pattern'],
|
| 281 |
+
type: 'object',
|
| 282 |
+
},
|
| 283 |
+
);
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
/**
|
| 287 |
+
* Validates the parameters for the tool.
|
| 288 |
+
*/
|
| 289 |
+
protected override validateToolParamValues(
|
| 290 |
+
params: GlobToolParams,
|
| 291 |
+
): string | null {
|
| 292 |
+
const searchDirAbsolute = path.resolve(
|
| 293 |
+
this.config.getTargetDir(),
|
| 294 |
+
params.path || '.',
|
| 295 |
+
);
|
| 296 |
+
|
| 297 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 298 |
+
if (!workspaceContext.isPathWithinWorkspace(searchDirAbsolute)) {
|
| 299 |
+
const directories = workspaceContext.getDirectories();
|
| 300 |
+
return `Search path ("${searchDirAbsolute}") resolves outside the allowed workspace directories: ${directories.join(', ')}`;
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
const targetDir = searchDirAbsolute || this.config.getTargetDir();
|
| 304 |
+
try {
|
| 305 |
+
if (!fs.existsSync(targetDir)) {
|
| 306 |
+
return `Search path does not exist ${targetDir}`;
|
| 307 |
+
}
|
| 308 |
+
if (!fs.statSync(targetDir).isDirectory()) {
|
| 309 |
+
return `Search path is not a directory: ${targetDir}`;
|
| 310 |
+
}
|
| 311 |
+
} catch (e: unknown) {
|
| 312 |
+
return `Error accessing search path: ${e}`;
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
if (
|
| 316 |
+
!params.pattern ||
|
| 317 |
+
typeof params.pattern !== 'string' ||
|
| 318 |
+
params.pattern.trim() === ''
|
| 319 |
+
) {
|
| 320 |
+
return "The 'pattern' parameter cannot be empty.";
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
return null;
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
protected createInvocation(
|
| 327 |
+
params: GlobToolParams,
|
| 328 |
+
): ToolInvocation<GlobToolParams, ToolResult> {
|
| 329 |
+
return new GlobToolInvocation(this.config, params);
|
| 330 |
+
}
|
| 331 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/grep.test.ts
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
| 8 |
+
import { GrepTool, GrepToolParams } from './grep.js';
|
| 9 |
+
import path from 'path';
|
| 10 |
+
import fs from 'fs/promises';
|
| 11 |
+
import os from 'os';
|
| 12 |
+
import { Config } from '../config/config.js';
|
| 13 |
+
import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js';
|
| 14 |
+
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
|
| 15 |
+
|
| 16 |
+
// Mock the child_process module to control grep/git grep behavior
|
| 17 |
+
vi.mock('child_process', () => ({
|
| 18 |
+
spawn: vi.fn(() => ({
|
| 19 |
+
on: (event: string, cb: (...args: unknown[]) => void) => {
|
| 20 |
+
if (event === 'error' || event === 'close') {
|
| 21 |
+
// Simulate command not found or error for git grep and system grep
|
| 22 |
+
// to force it to fall back to JS implementation.
|
| 23 |
+
setTimeout(() => cb(1), 0); // cb(1) for error/close
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
stdout: { on: vi.fn() },
|
| 27 |
+
stderr: { on: vi.fn() },
|
| 28 |
+
})),
|
| 29 |
+
}));
|
| 30 |
+
|
| 31 |
+
describe('GrepTool', () => {
|
| 32 |
+
let tempRootDir: string;
|
| 33 |
+
let grepTool: GrepTool;
|
| 34 |
+
const abortSignal = new AbortController().signal;
|
| 35 |
+
|
| 36 |
+
const mockFileService = {
|
| 37 |
+
getGeminiIgnorePatterns: () => [],
|
| 38 |
+
} as unknown as FileDiscoveryService;
|
| 39 |
+
|
| 40 |
+
const mockConfig = {
|
| 41 |
+
getTargetDir: () => tempRootDir,
|
| 42 |
+
getWorkspaceContext: () => createMockWorkspaceContext(tempRootDir),
|
| 43 |
+
getFileService: () => mockFileService,
|
| 44 |
+
} as unknown as Config;
|
| 45 |
+
|
| 46 |
+
beforeEach(async () => {
|
| 47 |
+
tempRootDir = await fs.mkdtemp(path.join(os.tmpdir(), 'grep-tool-root-'));
|
| 48 |
+
grepTool = new GrepTool(mockConfig);
|
| 49 |
+
|
| 50 |
+
// Create some test files and directories
|
| 51 |
+
await fs.writeFile(
|
| 52 |
+
path.join(tempRootDir, 'fileA.txt'),
|
| 53 |
+
'hello world\nsecond line with world',
|
| 54 |
+
);
|
| 55 |
+
await fs.writeFile(
|
| 56 |
+
path.join(tempRootDir, 'fileB.js'),
|
| 57 |
+
'const foo = "bar";\nfunction baz() { return "hello"; }',
|
| 58 |
+
);
|
| 59 |
+
await fs.mkdir(path.join(tempRootDir, 'sub'));
|
| 60 |
+
await fs.writeFile(
|
| 61 |
+
path.join(tempRootDir, 'sub', 'fileC.txt'),
|
| 62 |
+
'another world in sub dir',
|
| 63 |
+
);
|
| 64 |
+
await fs.writeFile(
|
| 65 |
+
path.join(tempRootDir, 'sub', 'fileD.md'),
|
| 66 |
+
'# Markdown file\nThis is a test.',
|
| 67 |
+
);
|
| 68 |
+
});
|
| 69 |
+
|
| 70 |
+
afterEach(async () => {
|
| 71 |
+
await fs.rm(tempRootDir, { recursive: true, force: true });
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
describe('validateToolParams', () => {
|
| 75 |
+
it('should return null for valid params (pattern only)', () => {
|
| 76 |
+
const params: GrepToolParams = { pattern: 'hello' };
|
| 77 |
+
expect(grepTool.validateToolParams(params)).toBeNull();
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
it('should return null for valid params (pattern and path)', () => {
|
| 81 |
+
const params: GrepToolParams = { pattern: 'hello', path: '.' };
|
| 82 |
+
expect(grepTool.validateToolParams(params)).toBeNull();
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
it('should return null for valid params (pattern, path, and include)', () => {
|
| 86 |
+
const params: GrepToolParams = {
|
| 87 |
+
pattern: 'hello',
|
| 88 |
+
path: '.',
|
| 89 |
+
include: '*.txt',
|
| 90 |
+
};
|
| 91 |
+
expect(grepTool.validateToolParams(params)).toBeNull();
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it('should return error if pattern is missing', () => {
|
| 95 |
+
const params = { path: '.' } as unknown as GrepToolParams;
|
| 96 |
+
expect(grepTool.validateToolParams(params)).toBe(
|
| 97 |
+
`params must have required property 'pattern'`,
|
| 98 |
+
);
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
it('should return error for invalid regex pattern', () => {
|
| 102 |
+
const params: GrepToolParams = { pattern: '[[' };
|
| 103 |
+
expect(grepTool.validateToolParams(params)).toContain(
|
| 104 |
+
'Invalid regular expression pattern',
|
| 105 |
+
);
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
it('should return error if path does not exist', () => {
|
| 109 |
+
const params: GrepToolParams = { pattern: 'hello', path: 'nonexistent' };
|
| 110 |
+
// Check for the core error message, as the full path might vary
|
| 111 |
+
expect(grepTool.validateToolParams(params)).toContain(
|
| 112 |
+
'Failed to access path stats for',
|
| 113 |
+
);
|
| 114 |
+
expect(grepTool.validateToolParams(params)).toContain('nonexistent');
|
| 115 |
+
});
|
| 116 |
+
|
| 117 |
+
it('should return error if path is a file, not a directory', async () => {
|
| 118 |
+
const filePath = path.join(tempRootDir, 'fileA.txt');
|
| 119 |
+
const params: GrepToolParams = { pattern: 'hello', path: filePath };
|
| 120 |
+
expect(grepTool.validateToolParams(params)).toContain(
|
| 121 |
+
`Path is not a directory: ${filePath}`,
|
| 122 |
+
);
|
| 123 |
+
});
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
describe('execute', () => {
|
| 127 |
+
it('should find matches for a simple pattern in all files', async () => {
|
| 128 |
+
const params: GrepToolParams = { pattern: 'world' };
|
| 129 |
+
const invocation = grepTool.build(params);
|
| 130 |
+
const result = await invocation.execute(abortSignal);
|
| 131 |
+
expect(result.llmContent).toContain(
|
| 132 |
+
'Found 3 matches for pattern "world" in the workspace directory',
|
| 133 |
+
);
|
| 134 |
+
expect(result.llmContent).toContain('File: fileA.txt');
|
| 135 |
+
expect(result.llmContent).toContain('L1: hello world');
|
| 136 |
+
expect(result.llmContent).toContain('L2: second line with world');
|
| 137 |
+
expect(result.llmContent).toContain(
|
| 138 |
+
`File: ${path.join('sub', 'fileC.txt')}`,
|
| 139 |
+
);
|
| 140 |
+
expect(result.llmContent).toContain('L1: another world in sub dir');
|
| 141 |
+
expect(result.returnDisplay).toBe('Found 3 matches');
|
| 142 |
+
});
|
| 143 |
+
|
| 144 |
+
it('should find matches in a specific path', async () => {
|
| 145 |
+
const params: GrepToolParams = { pattern: 'world', path: 'sub' };
|
| 146 |
+
const invocation = grepTool.build(params);
|
| 147 |
+
const result = await invocation.execute(abortSignal);
|
| 148 |
+
expect(result.llmContent).toContain(
|
| 149 |
+
'Found 1 match for pattern "world" in path "sub"',
|
| 150 |
+
);
|
| 151 |
+
expect(result.llmContent).toContain('File: fileC.txt'); // Path relative to 'sub'
|
| 152 |
+
expect(result.llmContent).toContain('L1: another world in sub dir');
|
| 153 |
+
expect(result.returnDisplay).toBe('Found 1 match');
|
| 154 |
+
});
|
| 155 |
+
|
| 156 |
+
it('should find matches with an include glob', async () => {
|
| 157 |
+
const params: GrepToolParams = { pattern: 'hello', include: '*.js' };
|
| 158 |
+
const invocation = grepTool.build(params);
|
| 159 |
+
const result = await invocation.execute(abortSignal);
|
| 160 |
+
expect(result.llmContent).toContain(
|
| 161 |
+
'Found 1 match for pattern "hello" in the workspace directory (filter: "*.js"):',
|
| 162 |
+
);
|
| 163 |
+
expect(result.llmContent).toContain('File: fileB.js');
|
| 164 |
+
expect(result.llmContent).toContain(
|
| 165 |
+
'L2: function baz() { return "hello"; }',
|
| 166 |
+
);
|
| 167 |
+
expect(result.returnDisplay).toBe('Found 1 match');
|
| 168 |
+
});
|
| 169 |
+
|
| 170 |
+
it('should find matches with an include glob and path', async () => {
|
| 171 |
+
await fs.writeFile(
|
| 172 |
+
path.join(tempRootDir, 'sub', 'another.js'),
|
| 173 |
+
'const greeting = "hello";',
|
| 174 |
+
);
|
| 175 |
+
const params: GrepToolParams = {
|
| 176 |
+
pattern: 'hello',
|
| 177 |
+
path: 'sub',
|
| 178 |
+
include: '*.js',
|
| 179 |
+
};
|
| 180 |
+
const invocation = grepTool.build(params);
|
| 181 |
+
const result = await invocation.execute(abortSignal);
|
| 182 |
+
expect(result.llmContent).toContain(
|
| 183 |
+
'Found 1 match for pattern "hello" in path "sub" (filter: "*.js")',
|
| 184 |
+
);
|
| 185 |
+
expect(result.llmContent).toContain('File: another.js');
|
| 186 |
+
expect(result.llmContent).toContain('L1: const greeting = "hello";');
|
| 187 |
+
expect(result.returnDisplay).toBe('Found 1 match');
|
| 188 |
+
});
|
| 189 |
+
|
| 190 |
+
it('should return "No matches found" when pattern does not exist', async () => {
|
| 191 |
+
const params: GrepToolParams = { pattern: 'nonexistentpattern' };
|
| 192 |
+
const invocation = grepTool.build(params);
|
| 193 |
+
const result = await invocation.execute(abortSignal);
|
| 194 |
+
expect(result.llmContent).toContain(
|
| 195 |
+
'No matches found for pattern "nonexistentpattern" in the workspace directory.',
|
| 196 |
+
);
|
| 197 |
+
expect(result.returnDisplay).toBe('No matches found');
|
| 198 |
+
});
|
| 199 |
+
|
| 200 |
+
it('should handle regex special characters correctly', async () => {
|
| 201 |
+
const params: GrepToolParams = { pattern: 'foo.*bar' }; // Matches 'const foo = "bar";'
|
| 202 |
+
const invocation = grepTool.build(params);
|
| 203 |
+
const result = await invocation.execute(abortSignal);
|
| 204 |
+
expect(result.llmContent).toContain(
|
| 205 |
+
'Found 1 match for pattern "foo.*bar" in the workspace directory:',
|
| 206 |
+
);
|
| 207 |
+
expect(result.llmContent).toContain('File: fileB.js');
|
| 208 |
+
expect(result.llmContent).toContain('L1: const foo = "bar";');
|
| 209 |
+
});
|
| 210 |
+
|
| 211 |
+
it('should be case-insensitive by default (JS fallback)', async () => {
|
| 212 |
+
const params: GrepToolParams = { pattern: 'HELLO' };
|
| 213 |
+
const invocation = grepTool.build(params);
|
| 214 |
+
const result = await invocation.execute(abortSignal);
|
| 215 |
+
expect(result.llmContent).toContain(
|
| 216 |
+
'Found 2 matches for pattern "HELLO" in the workspace directory:',
|
| 217 |
+
);
|
| 218 |
+
expect(result.llmContent).toContain('File: fileA.txt');
|
| 219 |
+
expect(result.llmContent).toContain('L1: hello world');
|
| 220 |
+
expect(result.llmContent).toContain('File: fileB.js');
|
| 221 |
+
expect(result.llmContent).toContain(
|
| 222 |
+
'L2: function baz() { return "hello"; }',
|
| 223 |
+
);
|
| 224 |
+
});
|
| 225 |
+
|
| 226 |
+
it('should throw an error if params are invalid', async () => {
|
| 227 |
+
const params = { path: '.' } as unknown as GrepToolParams; // Invalid: pattern missing
|
| 228 |
+
expect(() => grepTool.build(params)).toThrow(
|
| 229 |
+
/params must have required property 'pattern'/,
|
| 230 |
+
);
|
| 231 |
+
});
|
| 232 |
+
|
| 233 |
+
it('should exclude files matching geminiIgnorePatterns', async () => {
|
| 234 |
+
// Create a file that should be ignored
|
| 235 |
+
await fs.writeFile(
|
| 236 |
+
path.join(tempRootDir, 'ignored-file.txt'),
|
| 237 |
+
'this file should be ignored\nit contains the word world',
|
| 238 |
+
);
|
| 239 |
+
|
| 240 |
+
// Update the mock file service to return ignore patterns
|
| 241 |
+
mockFileService.getGeminiIgnorePatterns = () => ['ignored-file.txt'];
|
| 242 |
+
|
| 243 |
+
// Re-create the grep tool with the updated mock
|
| 244 |
+
const grepToolWithIgnore = new GrepTool(mockConfig);
|
| 245 |
+
|
| 246 |
+
// Search for 'world' which exists in both the regular file and the ignored file
|
| 247 |
+
const params: GrepToolParams = { pattern: 'world' };
|
| 248 |
+
const invocation = grepToolWithIgnore.build(params);
|
| 249 |
+
const result = await invocation.execute(abortSignal);
|
| 250 |
+
|
| 251 |
+
// Should only find matches in the non-ignored files (3 matches)
|
| 252 |
+
expect(result.llmContent).toContain(
|
| 253 |
+
'Found 3 matches for pattern "world" in the workspace directory',
|
| 254 |
+
);
|
| 255 |
+
|
| 256 |
+
// Should find matches in the regular files
|
| 257 |
+
expect(result.llmContent).toContain('File: fileA.txt');
|
| 258 |
+
expect(result.llmContent).toContain('L1: hello world');
|
| 259 |
+
expect(result.llmContent).toContain('L2: second line with world');
|
| 260 |
+
expect(result.llmContent).toContain(
|
| 261 |
+
`File: ${path.join('sub', 'fileC.txt')}`,
|
| 262 |
+
);
|
| 263 |
+
expect(result.llmContent).toContain('L1: another world in sub dir');
|
| 264 |
+
|
| 265 |
+
// Should NOT find matches in the ignored file
|
| 266 |
+
expect(result.llmContent).not.toContain('ignored-file.txt');
|
| 267 |
+
|
| 268 |
+
expect(result.returnDisplay).toBe('Found 3 matches');
|
| 269 |
+
});
|
| 270 |
+
});
|
| 271 |
+
|
| 272 |
+
describe('multi-directory workspace', () => {
|
| 273 |
+
it('should search across all workspace directories when no path is specified', async () => {
|
| 274 |
+
// Create additional directory with test files
|
| 275 |
+
const secondDir = await fs.mkdtemp(
|
| 276 |
+
path.join(os.tmpdir(), 'grep-tool-second-'),
|
| 277 |
+
);
|
| 278 |
+
await fs.writeFile(
|
| 279 |
+
path.join(secondDir, 'other.txt'),
|
| 280 |
+
'hello from second directory\nworld in second',
|
| 281 |
+
);
|
| 282 |
+
await fs.writeFile(
|
| 283 |
+
path.join(secondDir, 'another.js'),
|
| 284 |
+
'function world() { return "test"; }',
|
| 285 |
+
);
|
| 286 |
+
|
| 287 |
+
// Create a mock config with multiple directories
|
| 288 |
+
const multiDirFileService = {
|
| 289 |
+
getGeminiIgnorePatterns: () => [],
|
| 290 |
+
};
|
| 291 |
+
|
| 292 |
+
const multiDirConfig = {
|
| 293 |
+
getTargetDir: () => tempRootDir,
|
| 294 |
+
getWorkspaceContext: () =>
|
| 295 |
+
createMockWorkspaceContext(tempRootDir, [secondDir]),
|
| 296 |
+
getFileService: () => multiDirFileService,
|
| 297 |
+
} as unknown as Config;
|
| 298 |
+
|
| 299 |
+
const multiDirGrepTool = new GrepTool(multiDirConfig);
|
| 300 |
+
const params: GrepToolParams = { pattern: 'world' };
|
| 301 |
+
const invocation = multiDirGrepTool.build(params);
|
| 302 |
+
const result = await invocation.execute(abortSignal);
|
| 303 |
+
|
| 304 |
+
// Should find matches in both directories
|
| 305 |
+
expect(result.llmContent).toContain(
|
| 306 |
+
'Found 5 matches for pattern "world"',
|
| 307 |
+
);
|
| 308 |
+
|
| 309 |
+
// Matches from first directory
|
| 310 |
+
expect(result.llmContent).toContain('fileA.txt');
|
| 311 |
+
expect(result.llmContent).toContain('L1: hello world');
|
| 312 |
+
expect(result.llmContent).toContain('L2: second line with world');
|
| 313 |
+
expect(result.llmContent).toContain('fileC.txt');
|
| 314 |
+
expect(result.llmContent).toContain('L1: another world in sub dir');
|
| 315 |
+
|
| 316 |
+
// Matches from second directory (with directory name prefix)
|
| 317 |
+
const secondDirName = path.basename(secondDir);
|
| 318 |
+
expect(result.llmContent).toContain(
|
| 319 |
+
`File: ${path.join(secondDirName, 'other.txt')}`,
|
| 320 |
+
);
|
| 321 |
+
expect(result.llmContent).toContain('L2: world in second');
|
| 322 |
+
expect(result.llmContent).toContain(
|
| 323 |
+
`File: ${path.join(secondDirName, 'another.js')}`,
|
| 324 |
+
);
|
| 325 |
+
expect(result.llmContent).toContain('L1: function world()');
|
| 326 |
+
|
| 327 |
+
// Clean up
|
| 328 |
+
await fs.rm(secondDir, { recursive: true, force: true });
|
| 329 |
+
});
|
| 330 |
+
|
| 331 |
+
it('should search only specified path within workspace directories', async () => {
|
| 332 |
+
// Create additional directory
|
| 333 |
+
const secondDir = await fs.mkdtemp(
|
| 334 |
+
path.join(os.tmpdir(), 'grep-tool-second-'),
|
| 335 |
+
);
|
| 336 |
+
await fs.mkdir(path.join(secondDir, 'sub'));
|
| 337 |
+
await fs.writeFile(
|
| 338 |
+
path.join(secondDir, 'sub', 'test.txt'),
|
| 339 |
+
'hello from second sub directory',
|
| 340 |
+
);
|
| 341 |
+
|
| 342 |
+
// Create a mock config with multiple directories
|
| 343 |
+
const multiDirFileService = {
|
| 344 |
+
getGeminiIgnorePatterns: () => [],
|
| 345 |
+
};
|
| 346 |
+
|
| 347 |
+
const multiDirConfig = {
|
| 348 |
+
getTargetDir: () => tempRootDir,
|
| 349 |
+
getWorkspaceContext: () =>
|
| 350 |
+
createMockWorkspaceContext(tempRootDir, [secondDir]),
|
| 351 |
+
getFileService: () => multiDirFileService,
|
| 352 |
+
} as unknown as Config;
|
| 353 |
+
|
| 354 |
+
const multiDirGrepTool = new GrepTool(multiDirConfig);
|
| 355 |
+
|
| 356 |
+
// Search only in the 'sub' directory of the first workspace
|
| 357 |
+
const params: GrepToolParams = { pattern: 'world', path: 'sub' };
|
| 358 |
+
const invocation = multiDirGrepTool.build(params);
|
| 359 |
+
const result = await invocation.execute(abortSignal);
|
| 360 |
+
|
| 361 |
+
// Should only find matches in the specified sub directory
|
| 362 |
+
expect(result.llmContent).toContain(
|
| 363 |
+
'Found 1 match for pattern "world" in path "sub"',
|
| 364 |
+
);
|
| 365 |
+
expect(result.llmContent).toContain('File: fileC.txt');
|
| 366 |
+
expect(result.llmContent).toContain('L1: another world in sub dir');
|
| 367 |
+
|
| 368 |
+
// Should not contain matches from second directory
|
| 369 |
+
expect(result.llmContent).not.toContain('test.txt');
|
| 370 |
+
|
| 371 |
+
// Clean up
|
| 372 |
+
await fs.rm(secondDir, { recursive: true, force: true });
|
| 373 |
+
});
|
| 374 |
+
});
|
| 375 |
+
|
| 376 |
+
describe('getDescription', () => {
|
| 377 |
+
it('should generate correct description with pattern only', () => {
|
| 378 |
+
const params: GrepToolParams = { pattern: 'testPattern' };
|
| 379 |
+
const invocation = grepTool.build(params);
|
| 380 |
+
expect(invocation.getDescription()).toBe("'testPattern'");
|
| 381 |
+
});
|
| 382 |
+
|
| 383 |
+
it('should generate correct description with pattern and include', () => {
|
| 384 |
+
const params: GrepToolParams = {
|
| 385 |
+
pattern: 'testPattern',
|
| 386 |
+
include: '*.ts',
|
| 387 |
+
};
|
| 388 |
+
const invocation = grepTool.build(params);
|
| 389 |
+
expect(invocation.getDescription()).toBe("'testPattern' in *.ts");
|
| 390 |
+
});
|
| 391 |
+
|
| 392 |
+
it('should generate correct description with pattern and path', async () => {
|
| 393 |
+
const dirPath = path.join(tempRootDir, 'src', 'app');
|
| 394 |
+
await fs.mkdir(dirPath, { recursive: true });
|
| 395 |
+
const params: GrepToolParams = {
|
| 396 |
+
pattern: 'testPattern',
|
| 397 |
+
path: path.join('src', 'app'),
|
| 398 |
+
};
|
| 399 |
+
const invocation = grepTool.build(params);
|
| 400 |
+
// The path will be relative to the tempRootDir, so we check for containment.
|
| 401 |
+
expect(invocation.getDescription()).toContain("'testPattern' within");
|
| 402 |
+
expect(invocation.getDescription()).toContain(path.join('src', 'app'));
|
| 403 |
+
});
|
| 404 |
+
|
| 405 |
+
it('should indicate searching across all workspace directories when no path specified', () => {
|
| 406 |
+
// Create a mock config with multiple directories
|
| 407 |
+
const multiDirConfig = {
|
| 408 |
+
getTargetDir: () => tempRootDir,
|
| 409 |
+
getWorkspaceContext: () =>
|
| 410 |
+
createMockWorkspaceContext(tempRootDir, ['/another/dir']),
|
| 411 |
+
} as unknown as Config;
|
| 412 |
+
|
| 413 |
+
const multiDirGrepTool = new GrepTool(multiDirConfig);
|
| 414 |
+
const params: GrepToolParams = { pattern: 'testPattern' };
|
| 415 |
+
const invocation = multiDirGrepTool.build(params);
|
| 416 |
+
expect(invocation.getDescription()).toBe(
|
| 417 |
+
"'testPattern' across all workspace directories",
|
| 418 |
+
);
|
| 419 |
+
});
|
| 420 |
+
|
| 421 |
+
it('should generate correct description with pattern, include, and path', async () => {
|
| 422 |
+
const dirPath = path.join(tempRootDir, 'src', 'app');
|
| 423 |
+
await fs.mkdir(dirPath, { recursive: true });
|
| 424 |
+
const params: GrepToolParams = {
|
| 425 |
+
pattern: 'testPattern',
|
| 426 |
+
include: '*.ts',
|
| 427 |
+
path: path.join('src', 'app'),
|
| 428 |
+
};
|
| 429 |
+
const invocation = grepTool.build(params);
|
| 430 |
+
expect(invocation.getDescription()).toContain(
|
| 431 |
+
"'testPattern' in *.ts within",
|
| 432 |
+
);
|
| 433 |
+
expect(invocation.getDescription()).toContain(path.join('src', 'app'));
|
| 434 |
+
});
|
| 435 |
+
|
| 436 |
+
it('should use ./ for root path in description', () => {
|
| 437 |
+
const params: GrepToolParams = { pattern: 'testPattern', path: '.' };
|
| 438 |
+
const invocation = grepTool.build(params);
|
| 439 |
+
expect(invocation.getDescription()).toBe("'testPattern' within ./");
|
| 440 |
+
});
|
| 441 |
+
});
|
| 442 |
+
|
| 443 |
+
describe('Result limiting', () => {
|
| 444 |
+
beforeEach(async () => {
|
| 445 |
+
// Create many test files with matches to test limiting
|
| 446 |
+
for (let i = 1; i <= 30; i++) {
|
| 447 |
+
const fileName = `test${i}.txt`;
|
| 448 |
+
const content = `This is test file ${i} with the pattern testword in it.`;
|
| 449 |
+
await fs.writeFile(path.join(tempRootDir, fileName), content);
|
| 450 |
+
}
|
| 451 |
+
});
|
| 452 |
+
|
| 453 |
+
it('should limit results to default 20 matches', async () => {
|
| 454 |
+
const params: GrepToolParams = { pattern: 'testword' };
|
| 455 |
+
const invocation = grepTool.build(params);
|
| 456 |
+
const result = await invocation.execute(abortSignal);
|
| 457 |
+
|
| 458 |
+
expect(result.llmContent).toContain('Found 20 matches');
|
| 459 |
+
expect(result.llmContent).toContain(
|
| 460 |
+
'showing first 20 of 30+ total matches',
|
| 461 |
+
);
|
| 462 |
+
expect(result.llmContent).toContain('WARNING: Results truncated');
|
| 463 |
+
expect(result.returnDisplay).toContain(
|
| 464 |
+
'Found 20 matches (truncated from 30+)',
|
| 465 |
+
);
|
| 466 |
+
});
|
| 467 |
+
|
| 468 |
+
it('should respect custom maxResults parameter', async () => {
|
| 469 |
+
const params: GrepToolParams = { pattern: 'testword', maxResults: 5 };
|
| 470 |
+
const invocation = grepTool.build(params);
|
| 471 |
+
const result = await invocation.execute(abortSignal);
|
| 472 |
+
|
| 473 |
+
expect(result.llmContent).toContain('Found 5 matches');
|
| 474 |
+
expect(result.llmContent).toContain(
|
| 475 |
+
'showing first 5 of 30+ total matches',
|
| 476 |
+
);
|
| 477 |
+
expect(result.llmContent).toContain('current: 5');
|
| 478 |
+
expect(result.returnDisplay).toContain(
|
| 479 |
+
'Found 5 matches (truncated from 30+)',
|
| 480 |
+
);
|
| 481 |
+
});
|
| 482 |
+
|
| 483 |
+
it('should not show truncation warning when all results fit', async () => {
|
| 484 |
+
const params: GrepToolParams = { pattern: 'testword', maxResults: 50 };
|
| 485 |
+
const invocation = grepTool.build(params);
|
| 486 |
+
const result = await invocation.execute(abortSignal);
|
| 487 |
+
|
| 488 |
+
expect(result.llmContent).toContain('Found 30 matches');
|
| 489 |
+
expect(result.llmContent).not.toContain('WARNING: Results truncated');
|
| 490 |
+
expect(result.llmContent).not.toContain('showing first');
|
| 491 |
+
expect(result.returnDisplay).toBe('Found 30 matches');
|
| 492 |
+
});
|
| 493 |
+
|
| 494 |
+
it('should validate maxResults parameter', () => {
|
| 495 |
+
const invalidParams = [
|
| 496 |
+
{ pattern: 'test', maxResults: 0 },
|
| 497 |
+
{ pattern: 'test', maxResults: 101 },
|
| 498 |
+
{ pattern: 'test', maxResults: -1 },
|
| 499 |
+
{ pattern: 'test', maxResults: 1.5 },
|
| 500 |
+
];
|
| 501 |
+
|
| 502 |
+
invalidParams.forEach((params) => {
|
| 503 |
+
const error = grepTool.validateToolParams(params as GrepToolParams);
|
| 504 |
+
expect(error).toBeTruthy(); // Just check that validation fails
|
| 505 |
+
expect(error).toMatch(/maxResults|must be/); // Check it's about maxResults validation
|
| 506 |
+
});
|
| 507 |
+
});
|
| 508 |
+
|
| 509 |
+
it('should accept valid maxResults parameter', () => {
|
| 510 |
+
const validParams = [
|
| 511 |
+
{ pattern: 'test', maxResults: 1 },
|
| 512 |
+
{ pattern: 'test', maxResults: 50 },
|
| 513 |
+
{ pattern: 'test', maxResults: 100 },
|
| 514 |
+
];
|
| 515 |
+
|
| 516 |
+
validParams.forEach((params) => {
|
| 517 |
+
const error = grepTool.validateToolParams(params);
|
| 518 |
+
expect(error).toBeNull();
|
| 519 |
+
});
|
| 520 |
+
});
|
| 521 |
+
});
|
| 522 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/grep.ts
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import fs from 'fs';
|
| 8 |
+
import fsPromises from 'fs/promises';
|
| 9 |
+
import path from 'path';
|
| 10 |
+
import { EOL } from 'os';
|
| 11 |
+
import { spawn } from 'child_process';
|
| 12 |
+
import { globStream } from 'glob';
|
| 13 |
+
import {
|
| 14 |
+
BaseDeclarativeTool,
|
| 15 |
+
BaseToolInvocation,
|
| 16 |
+
Kind,
|
| 17 |
+
ToolInvocation,
|
| 18 |
+
ToolResult,
|
| 19 |
+
} from './tools.js';
|
| 20 |
+
import { makeRelative, shortenPath } from '../utils/paths.js';
|
| 21 |
+
import { getErrorMessage, isNodeError } from '../utils/errors.js';
|
| 22 |
+
import { isGitRepository } from '../utils/gitUtils.js';
|
| 23 |
+
import { Config } from '../config/config.js';
|
| 24 |
+
|
| 25 |
+
// --- Interfaces ---
|
| 26 |
+
|
| 27 |
+
/**
|
| 28 |
+
* Parameters for the GrepTool
|
| 29 |
+
*/
|
| 30 |
+
export interface GrepToolParams {
|
| 31 |
+
/**
|
| 32 |
+
* The regular expression pattern to search for in file contents
|
| 33 |
+
*/
|
| 34 |
+
pattern: string;
|
| 35 |
+
|
| 36 |
+
/**
|
| 37 |
+
* The directory to search in (optional, defaults to current directory relative to root)
|
| 38 |
+
*/
|
| 39 |
+
path?: string;
|
| 40 |
+
|
| 41 |
+
/**
|
| 42 |
+
* File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")
|
| 43 |
+
*/
|
| 44 |
+
include?: string;
|
| 45 |
+
|
| 46 |
+
/**
|
| 47 |
+
* Maximum number of matches to return (optional, defaults to 20)
|
| 48 |
+
*/
|
| 49 |
+
maxResults?: number;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
/**
|
| 53 |
+
* Result object for a single grep match
|
| 54 |
+
*/
|
| 55 |
+
interface GrepMatch {
|
| 56 |
+
filePath: string;
|
| 57 |
+
lineNumber: number;
|
| 58 |
+
line: string;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
class GrepToolInvocation extends BaseToolInvocation<
|
| 62 |
+
GrepToolParams,
|
| 63 |
+
ToolResult
|
| 64 |
+
> {
|
| 65 |
+
constructor(
|
| 66 |
+
private readonly config: Config,
|
| 67 |
+
params: GrepToolParams,
|
| 68 |
+
) {
|
| 69 |
+
super(params);
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/**
|
| 73 |
+
* Checks if a path is within the root directory and resolves it.
|
| 74 |
+
* @param relativePath Path relative to the root directory (or undefined for root).
|
| 75 |
+
* @returns The absolute path if valid and exists, or null if no path specified (to search all directories).
|
| 76 |
+
* @throws {Error} If path is outside root, doesn't exist, or isn't a directory.
|
| 77 |
+
*/
|
| 78 |
+
private resolveAndValidatePath(relativePath?: string): string | null {
|
| 79 |
+
// If no path specified, return null to indicate searching all workspace directories
|
| 80 |
+
if (!relativePath) {
|
| 81 |
+
return null;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
const targetPath = path.resolve(this.config.getTargetDir(), relativePath);
|
| 85 |
+
|
| 86 |
+
// Security Check: Ensure the resolved path is within workspace boundaries
|
| 87 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 88 |
+
if (!workspaceContext.isPathWithinWorkspace(targetPath)) {
|
| 89 |
+
const directories = workspaceContext.getDirectories();
|
| 90 |
+
throw new Error(
|
| 91 |
+
`Path validation failed: Attempted path "${relativePath}" resolves outside the allowed workspace directories: ${directories.join(', ')}`,
|
| 92 |
+
);
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
// Check existence and type after resolving
|
| 96 |
+
try {
|
| 97 |
+
const stats = fs.statSync(targetPath);
|
| 98 |
+
if (!stats.isDirectory()) {
|
| 99 |
+
throw new Error(`Path is not a directory: ${targetPath}`);
|
| 100 |
+
}
|
| 101 |
+
} catch (error: unknown) {
|
| 102 |
+
if (isNodeError(error) && error.code !== 'ENOENT') {
|
| 103 |
+
throw new Error(`Path does not exist: ${targetPath}`);
|
| 104 |
+
}
|
| 105 |
+
throw new Error(
|
| 106 |
+
`Failed to access path stats for ${targetPath}: ${error}`,
|
| 107 |
+
);
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
return targetPath;
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
async execute(signal: AbortSignal): Promise<ToolResult> {
|
| 114 |
+
try {
|
| 115 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 116 |
+
const searchDirAbs = this.resolveAndValidatePath(this.params.path);
|
| 117 |
+
const searchDirDisplay = this.params.path || '.';
|
| 118 |
+
|
| 119 |
+
// Determine which directories to search
|
| 120 |
+
let searchDirectories: readonly string[];
|
| 121 |
+
if (searchDirAbs === null) {
|
| 122 |
+
// No path specified - search all workspace directories
|
| 123 |
+
searchDirectories = workspaceContext.getDirectories();
|
| 124 |
+
} else {
|
| 125 |
+
// Specific path provided - search only that directory
|
| 126 |
+
searchDirectories = [searchDirAbs];
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
// Collect matches from all search directories
|
| 130 |
+
let allMatches: GrepMatch[] = [];
|
| 131 |
+
const maxResults = this.params.maxResults ?? 20; // Default to 20 results
|
| 132 |
+
let totalMatchesFound = 0;
|
| 133 |
+
let searchTruncated = false;
|
| 134 |
+
|
| 135 |
+
for (const searchDir of searchDirectories) {
|
| 136 |
+
const matches = await this.performGrepSearch({
|
| 137 |
+
pattern: this.params.pattern,
|
| 138 |
+
path: searchDir,
|
| 139 |
+
include: this.params.include,
|
| 140 |
+
signal,
|
| 141 |
+
});
|
| 142 |
+
|
| 143 |
+
totalMatchesFound += matches.length;
|
| 144 |
+
|
| 145 |
+
// Add directory prefix if searching multiple directories
|
| 146 |
+
if (searchDirectories.length > 1) {
|
| 147 |
+
const dirName = path.basename(searchDir);
|
| 148 |
+
matches.forEach((match) => {
|
| 149 |
+
match.filePath = path.join(dirName, match.filePath);
|
| 150 |
+
});
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
// Apply result limiting
|
| 154 |
+
const remainingSlots = maxResults - allMatches.length;
|
| 155 |
+
if (remainingSlots <= 0) {
|
| 156 |
+
searchTruncated = true;
|
| 157 |
+
break;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
if (matches.length > remainingSlots) {
|
| 161 |
+
allMatches = allMatches.concat(matches.slice(0, remainingSlots));
|
| 162 |
+
searchTruncated = true;
|
| 163 |
+
break;
|
| 164 |
+
} else {
|
| 165 |
+
allMatches = allMatches.concat(matches);
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
let searchLocationDescription: string;
|
| 170 |
+
if (searchDirAbs === null) {
|
| 171 |
+
const numDirs = workspaceContext.getDirectories().length;
|
| 172 |
+
searchLocationDescription =
|
| 173 |
+
numDirs > 1
|
| 174 |
+
? `across ${numDirs} workspace directories`
|
| 175 |
+
: `in the workspace directory`;
|
| 176 |
+
} else {
|
| 177 |
+
searchLocationDescription = `in path "${searchDirDisplay}"`;
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
if (allMatches.length === 0) {
|
| 181 |
+
const noMatchMsg = `No matches found for pattern "${this.params.pattern}" ${searchLocationDescription}${this.params.include ? ` (filter: "${this.params.include}")` : ''}.`;
|
| 182 |
+
return { llmContent: noMatchMsg, returnDisplay: `No matches found` };
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
// Group matches by file
|
| 186 |
+
const matchesByFile = allMatches.reduce(
|
| 187 |
+
(acc, match) => {
|
| 188 |
+
const fileKey = match.filePath;
|
| 189 |
+
if (!acc[fileKey]) {
|
| 190 |
+
acc[fileKey] = [];
|
| 191 |
+
}
|
| 192 |
+
acc[fileKey].push(match);
|
| 193 |
+
acc[fileKey].sort((a, b) => a.lineNumber - b.lineNumber);
|
| 194 |
+
return acc;
|
| 195 |
+
},
|
| 196 |
+
{} as Record<string, GrepMatch[]>,
|
| 197 |
+
);
|
| 198 |
+
|
| 199 |
+
const matchCount = allMatches.length;
|
| 200 |
+
const matchTerm = matchCount === 1 ? 'match' : 'matches';
|
| 201 |
+
|
| 202 |
+
// Build the header with truncation info if needed
|
| 203 |
+
let headerText = `Found ${matchCount} ${matchTerm} for pattern "${this.params.pattern}" ${searchLocationDescription}${this.params.include ? ` (filter: "${this.params.include}")` : ''}`;
|
| 204 |
+
|
| 205 |
+
if (searchTruncated) {
|
| 206 |
+
headerText += ` (showing first ${matchCount} of ${totalMatchesFound}+ total matches)`;
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
let llmContent = `${headerText}:
|
| 210 |
+
---
|
| 211 |
+
`;
|
| 212 |
+
|
| 213 |
+
for (const filePath in matchesByFile) {
|
| 214 |
+
llmContent += `File: ${filePath}\n`;
|
| 215 |
+
matchesByFile[filePath].forEach((match) => {
|
| 216 |
+
const trimmedLine = match.line.trim();
|
| 217 |
+
llmContent += `L${match.lineNumber}: ${trimmedLine}\n`;
|
| 218 |
+
});
|
| 219 |
+
llmContent += '---\n';
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
// Add truncation guidance if results were limited
|
| 223 |
+
if (searchTruncated) {
|
| 224 |
+
llmContent += `\nWARNING: Results truncated to prevent context overflow. To see more results:
|
| 225 |
+
- Use a more specific pattern to reduce matches
|
| 226 |
+
- Add file filters with the 'include' parameter (e.g., "*.js", "src/**")
|
| 227 |
+
- Specify a narrower 'path' to search in a subdirectory
|
| 228 |
+
- Increase 'maxResults' parameter if you need more matches (current: ${maxResults})`;
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
let displayText = `Found ${matchCount} ${matchTerm}`;
|
| 232 |
+
if (searchTruncated) {
|
| 233 |
+
displayText += ` (truncated from ${totalMatchesFound}+)`;
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
return {
|
| 237 |
+
llmContent: llmContent.trim(),
|
| 238 |
+
returnDisplay: displayText,
|
| 239 |
+
};
|
| 240 |
+
} catch (error) {
|
| 241 |
+
console.error(`Error during GrepLogic execution: ${error}`);
|
| 242 |
+
const errorMessage = getErrorMessage(error);
|
| 243 |
+
return {
|
| 244 |
+
llmContent: `Error during grep search operation: ${errorMessage}`,
|
| 245 |
+
returnDisplay: `Error: ${errorMessage}`,
|
| 246 |
+
};
|
| 247 |
+
}
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
/**
|
| 251 |
+
* Checks if a command is available in the system's PATH.
|
| 252 |
+
* @param {string} command The command name (e.g., 'git', 'grep').
|
| 253 |
+
* @returns {Promise<boolean>} True if the command is available, false otherwise.
|
| 254 |
+
*/
|
| 255 |
+
private isCommandAvailable(command: string): Promise<boolean> {
|
| 256 |
+
return new Promise((resolve) => {
|
| 257 |
+
const checkCommand = process.platform === 'win32' ? 'where' : 'command';
|
| 258 |
+
const checkArgs =
|
| 259 |
+
process.platform === 'win32' ? [command] : ['-v', command];
|
| 260 |
+
try {
|
| 261 |
+
const child = spawn(checkCommand, checkArgs, {
|
| 262 |
+
stdio: 'ignore',
|
| 263 |
+
shell: process.platform === 'win32',
|
| 264 |
+
});
|
| 265 |
+
child.on('close', (code) => resolve(code === 0));
|
| 266 |
+
child.on('error', () => resolve(false));
|
| 267 |
+
} catch {
|
| 268 |
+
resolve(false);
|
| 269 |
+
}
|
| 270 |
+
});
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
/**
|
| 274 |
+
* Parses the standard output of grep-like commands (git grep, system grep).
|
| 275 |
+
* Expects format: filePath:lineNumber:lineContent
|
| 276 |
+
* Handles colons within file paths and line content correctly.
|
| 277 |
+
* @param {string} output The raw stdout string.
|
| 278 |
+
* @param {string} basePath The absolute directory the search was run from, for relative paths.
|
| 279 |
+
* @returns {GrepMatch[]} Array of match objects.
|
| 280 |
+
*/
|
| 281 |
+
private parseGrepOutput(output: string, basePath: string): GrepMatch[] {
|
| 282 |
+
const results: GrepMatch[] = [];
|
| 283 |
+
if (!output) return results;
|
| 284 |
+
|
| 285 |
+
const lines = output.split(EOL); // Use OS-specific end-of-line
|
| 286 |
+
|
| 287 |
+
for (const line of lines) {
|
| 288 |
+
if (!line.trim()) continue;
|
| 289 |
+
|
| 290 |
+
// Find the index of the first colon.
|
| 291 |
+
const firstColonIndex = line.indexOf(':');
|
| 292 |
+
if (firstColonIndex === -1) continue; // Malformed
|
| 293 |
+
|
| 294 |
+
// Find the index of the second colon, searching *after* the first one.
|
| 295 |
+
const secondColonIndex = line.indexOf(':', firstColonIndex + 1);
|
| 296 |
+
if (secondColonIndex === -1) continue; // Malformed
|
| 297 |
+
|
| 298 |
+
// Extract parts based on the found colon indices
|
| 299 |
+
const filePathRaw = line.substring(0, firstColonIndex);
|
| 300 |
+
const lineNumberStr = line.substring(
|
| 301 |
+
firstColonIndex + 1,
|
| 302 |
+
secondColonIndex,
|
| 303 |
+
);
|
| 304 |
+
const lineContent = line.substring(secondColonIndex + 1);
|
| 305 |
+
|
| 306 |
+
const lineNumber = parseInt(lineNumberStr, 10);
|
| 307 |
+
|
| 308 |
+
if (!isNaN(lineNumber)) {
|
| 309 |
+
const absoluteFilePath = path.resolve(basePath, filePathRaw);
|
| 310 |
+
const relativeFilePath = path.relative(basePath, absoluteFilePath);
|
| 311 |
+
|
| 312 |
+
results.push({
|
| 313 |
+
filePath: relativeFilePath || path.basename(absoluteFilePath),
|
| 314 |
+
lineNumber,
|
| 315 |
+
line: lineContent,
|
| 316 |
+
});
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
return results;
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
/**
|
| 323 |
+
* Gets a description of the grep operation
|
| 324 |
+
* @param params Parameters for the grep operation
|
| 325 |
+
* @returns A string describing the grep
|
| 326 |
+
*/
|
| 327 |
+
getDescription(): string {
|
| 328 |
+
let description = `'${this.params.pattern}'`;
|
| 329 |
+
if (this.params.include) {
|
| 330 |
+
description += ` in ${this.params.include}`;
|
| 331 |
+
}
|
| 332 |
+
if (this.params.path) {
|
| 333 |
+
const resolvedPath = path.resolve(
|
| 334 |
+
this.config.getTargetDir(),
|
| 335 |
+
this.params.path,
|
| 336 |
+
);
|
| 337 |
+
if (
|
| 338 |
+
resolvedPath === this.config.getTargetDir() ||
|
| 339 |
+
this.params.path === '.'
|
| 340 |
+
) {
|
| 341 |
+
description += ` within ./`;
|
| 342 |
+
} else {
|
| 343 |
+
const relativePath = makeRelative(
|
| 344 |
+
resolvedPath,
|
| 345 |
+
this.config.getTargetDir(),
|
| 346 |
+
);
|
| 347 |
+
description += ` within ${shortenPath(relativePath)}`;
|
| 348 |
+
}
|
| 349 |
+
} else {
|
| 350 |
+
// When no path is specified, indicate searching all workspace directories
|
| 351 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 352 |
+
const directories = workspaceContext.getDirectories();
|
| 353 |
+
if (directories.length > 1) {
|
| 354 |
+
description += ` across all workspace directories`;
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
return description;
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
/**
|
| 361 |
+
* Performs the actual search using the prioritized strategies.
|
| 362 |
+
* @param options Search options including pattern, absolute path, and include glob.
|
| 363 |
+
* @returns A promise resolving to an array of match objects.
|
| 364 |
+
*/
|
| 365 |
+
private async performGrepSearch(options: {
|
| 366 |
+
pattern: string;
|
| 367 |
+
path: string; // Expects absolute path
|
| 368 |
+
include?: string;
|
| 369 |
+
signal: AbortSignal;
|
| 370 |
+
}): Promise<GrepMatch[]> {
|
| 371 |
+
const { pattern, path: absolutePath, include } = options;
|
| 372 |
+
let strategyUsed = 'none';
|
| 373 |
+
|
| 374 |
+
try {
|
| 375 |
+
// --- Strategy 1: git grep ---
|
| 376 |
+
const isGit = isGitRepository(absolutePath);
|
| 377 |
+
const gitAvailable = isGit && (await this.isCommandAvailable('git'));
|
| 378 |
+
|
| 379 |
+
if (gitAvailable) {
|
| 380 |
+
strategyUsed = 'git grep';
|
| 381 |
+
const gitArgs = [
|
| 382 |
+
'grep',
|
| 383 |
+
'--untracked',
|
| 384 |
+
'-n',
|
| 385 |
+
'-E',
|
| 386 |
+
'--ignore-case',
|
| 387 |
+
pattern,
|
| 388 |
+
];
|
| 389 |
+
if (include) {
|
| 390 |
+
gitArgs.push('--', include);
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
try {
|
| 394 |
+
const output = await new Promise<string>((resolve, reject) => {
|
| 395 |
+
const child = spawn('git', gitArgs, {
|
| 396 |
+
cwd: absolutePath,
|
| 397 |
+
windowsHide: true,
|
| 398 |
+
});
|
| 399 |
+
const stdoutChunks: Buffer[] = [];
|
| 400 |
+
const stderrChunks: Buffer[] = [];
|
| 401 |
+
|
| 402 |
+
child.stdout.on('data', (chunk) => stdoutChunks.push(chunk));
|
| 403 |
+
child.stderr.on('data', (chunk) => stderrChunks.push(chunk));
|
| 404 |
+
child.on('error', (err) =>
|
| 405 |
+
reject(new Error(`Failed to start git grep: ${err.message}`)),
|
| 406 |
+
);
|
| 407 |
+
child.on('close', (code) => {
|
| 408 |
+
const stdoutData = Buffer.concat(stdoutChunks).toString('utf8');
|
| 409 |
+
const stderrData = Buffer.concat(stderrChunks).toString('utf8');
|
| 410 |
+
if (code === 0) resolve(stdoutData);
|
| 411 |
+
else if (code === 1)
|
| 412 |
+
resolve(''); // No matches
|
| 413 |
+
else
|
| 414 |
+
reject(
|
| 415 |
+
new Error(`git grep exited with code ${code}: ${stderrData}`),
|
| 416 |
+
);
|
| 417 |
+
});
|
| 418 |
+
});
|
| 419 |
+
return this.parseGrepOutput(output, absolutePath);
|
| 420 |
+
} catch (gitError: unknown) {
|
| 421 |
+
console.debug(
|
| 422 |
+
`GrepLogic: git grep failed: ${getErrorMessage(
|
| 423 |
+
gitError,
|
| 424 |
+
)}. Falling back...`,
|
| 425 |
+
);
|
| 426 |
+
}
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
// --- Strategy 2: System grep ---
|
| 430 |
+
const grepAvailable = await this.isCommandAvailable('grep');
|
| 431 |
+
if (grepAvailable) {
|
| 432 |
+
strategyUsed = 'system grep';
|
| 433 |
+
const grepArgs = ['-r', '-n', '-H', '-E'];
|
| 434 |
+
const commonExcludes = ['.git', 'node_modules', 'bower_components'];
|
| 435 |
+
commonExcludes.forEach((dir) => grepArgs.push(`--exclude-dir=${dir}`));
|
| 436 |
+
if (include) {
|
| 437 |
+
grepArgs.push(`--include=${include}`);
|
| 438 |
+
}
|
| 439 |
+
grepArgs.push(pattern);
|
| 440 |
+
grepArgs.push('.');
|
| 441 |
+
|
| 442 |
+
try {
|
| 443 |
+
const output = await new Promise<string>((resolve, reject) => {
|
| 444 |
+
const child = spawn('grep', grepArgs, {
|
| 445 |
+
cwd: absolutePath,
|
| 446 |
+
windowsHide: true,
|
| 447 |
+
});
|
| 448 |
+
const stdoutChunks: Buffer[] = [];
|
| 449 |
+
const stderrChunks: Buffer[] = [];
|
| 450 |
+
|
| 451 |
+
const onData = (chunk: Buffer) => stdoutChunks.push(chunk);
|
| 452 |
+
const onStderr = (chunk: Buffer) => {
|
| 453 |
+
const stderrStr = chunk.toString();
|
| 454 |
+
// Suppress common harmless stderr messages
|
| 455 |
+
if (
|
| 456 |
+
!stderrStr.includes('Permission denied') &&
|
| 457 |
+
!/grep:.*: Is a directory/i.test(stderrStr)
|
| 458 |
+
) {
|
| 459 |
+
stderrChunks.push(chunk);
|
| 460 |
+
}
|
| 461 |
+
};
|
| 462 |
+
const onError = (err: Error) => {
|
| 463 |
+
cleanup();
|
| 464 |
+
reject(new Error(`Failed to start system grep: ${err.message}`));
|
| 465 |
+
};
|
| 466 |
+
const onClose = (code: number | null) => {
|
| 467 |
+
const stdoutData = Buffer.concat(stdoutChunks).toString('utf8');
|
| 468 |
+
const stderrData = Buffer.concat(stderrChunks)
|
| 469 |
+
.toString('utf8')
|
| 470 |
+
.trim();
|
| 471 |
+
cleanup();
|
| 472 |
+
if (code === 0) resolve(stdoutData);
|
| 473 |
+
else if (code === 1)
|
| 474 |
+
resolve(''); // No matches
|
| 475 |
+
else {
|
| 476 |
+
if (stderrData)
|
| 477 |
+
reject(
|
| 478 |
+
new Error(
|
| 479 |
+
`System grep exited with code ${code}: ${stderrData}`,
|
| 480 |
+
),
|
| 481 |
+
);
|
| 482 |
+
else resolve(''); // Exit code > 1 but no stderr, likely just suppressed errors
|
| 483 |
+
}
|
| 484 |
+
};
|
| 485 |
+
|
| 486 |
+
const cleanup = () => {
|
| 487 |
+
child.stdout.removeListener('data', onData);
|
| 488 |
+
child.stderr.removeListener('data', onStderr);
|
| 489 |
+
child.removeListener('error', onError);
|
| 490 |
+
child.removeListener('close', onClose);
|
| 491 |
+
if (child.connected) {
|
| 492 |
+
child.disconnect();
|
| 493 |
+
}
|
| 494 |
+
};
|
| 495 |
+
|
| 496 |
+
child.stdout.on('data', onData);
|
| 497 |
+
child.stderr.on('data', onStderr);
|
| 498 |
+
child.on('error', onError);
|
| 499 |
+
child.on('close', onClose);
|
| 500 |
+
});
|
| 501 |
+
return this.parseGrepOutput(output, absolutePath);
|
| 502 |
+
} catch (grepError: unknown) {
|
| 503 |
+
console.debug(
|
| 504 |
+
`GrepLogic: System grep failed: ${getErrorMessage(
|
| 505 |
+
grepError,
|
| 506 |
+
)}. Falling back...`,
|
| 507 |
+
);
|
| 508 |
+
}
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
// --- Strategy 3: Pure JavaScript Fallback ---
|
| 512 |
+
console.debug(
|
| 513 |
+
'GrepLogic: Falling back to JavaScript grep implementation.',
|
| 514 |
+
);
|
| 515 |
+
strategyUsed = 'javascript fallback';
|
| 516 |
+
const globPattern = include ? include : '**/*';
|
| 517 |
+
|
| 518 |
+
// Get the file discovery service to check ignore patterns
|
| 519 |
+
const fileDiscovery = this.config.getFileService();
|
| 520 |
+
|
| 521 |
+
// Basic ignore patterns
|
| 522 |
+
const ignorePatterns = [
|
| 523 |
+
'.git/**',
|
| 524 |
+
'node_modules/**',
|
| 525 |
+
'bower_components/**',
|
| 526 |
+
'.svn/**',
|
| 527 |
+
'.hg/**',
|
| 528 |
+
...fileDiscovery.getGeminiIgnorePatterns(),
|
| 529 |
+
]; // Use glob patterns for ignores here
|
| 530 |
+
|
| 531 |
+
const filesIterator = globStream(globPattern, {
|
| 532 |
+
cwd: absolutePath,
|
| 533 |
+
dot: true,
|
| 534 |
+
ignore: ignorePatterns,
|
| 535 |
+
absolute: true,
|
| 536 |
+
nodir: true,
|
| 537 |
+
signal: options.signal,
|
| 538 |
+
});
|
| 539 |
+
|
| 540 |
+
const regex = new RegExp(pattern, 'i');
|
| 541 |
+
const allMatches: GrepMatch[] = [];
|
| 542 |
+
|
| 543 |
+
for await (const filePath of filesIterator) {
|
| 544 |
+
const fileAbsolutePath = filePath as string;
|
| 545 |
+
try {
|
| 546 |
+
const content = await fsPromises.readFile(fileAbsolutePath, 'utf8');
|
| 547 |
+
const lines = content.split(/\r?\n/);
|
| 548 |
+
lines.forEach((line, index) => {
|
| 549 |
+
if (regex.test(line)) {
|
| 550 |
+
allMatches.push({
|
| 551 |
+
filePath:
|
| 552 |
+
path.relative(absolutePath, fileAbsolutePath) ||
|
| 553 |
+
path.basename(fileAbsolutePath),
|
| 554 |
+
lineNumber: index + 1,
|
| 555 |
+
line,
|
| 556 |
+
});
|
| 557 |
+
}
|
| 558 |
+
});
|
| 559 |
+
} catch (readError: unknown) {
|
| 560 |
+
// Ignore errors like permission denied or file gone during read
|
| 561 |
+
if (!isNodeError(readError) || readError.code !== 'ENOENT') {
|
| 562 |
+
console.debug(
|
| 563 |
+
`GrepLogic: Could not read/process ${fileAbsolutePath}: ${getErrorMessage(
|
| 564 |
+
readError,
|
| 565 |
+
)}`,
|
| 566 |
+
);
|
| 567 |
+
}
|
| 568 |
+
}
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
return allMatches;
|
| 572 |
+
} catch (error: unknown) {
|
| 573 |
+
console.error(
|
| 574 |
+
`GrepLogic: Error in performGrepSearch (Strategy: ${strategyUsed}): ${getErrorMessage(
|
| 575 |
+
error,
|
| 576 |
+
)}`,
|
| 577 |
+
);
|
| 578 |
+
throw error; // Re-throw
|
| 579 |
+
}
|
| 580 |
+
}
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
// --- GrepLogic Class ---
|
| 584 |
+
|
| 585 |
+
/**
|
| 586 |
+
* Implementation of the Grep tool logic (moved from CLI)
|
| 587 |
+
*/
|
| 588 |
+
export class GrepTool extends BaseDeclarativeTool<GrepToolParams, ToolResult> {
|
| 589 |
+
static readonly Name = 'search_file_content'; // Keep static name
|
| 590 |
+
|
| 591 |
+
constructor(private readonly config: Config) {
|
| 592 |
+
super(
|
| 593 |
+
GrepTool.Name,
|
| 594 |
+
'SearchText',
|
| 595 |
+
'Searches for a regular expression pattern within the content of files in a specified directory (or current working directory). Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.',
|
| 596 |
+
Kind.Search,
|
| 597 |
+
{
|
| 598 |
+
properties: {
|
| 599 |
+
pattern: {
|
| 600 |
+
description:
|
| 601 |
+
"The regular expression (regex) pattern to search for within file contents (e.g., 'function\\s+myFunction', 'import\\s+\\{.*\\}\\s+from\\s+.*').",
|
| 602 |
+
type: 'string',
|
| 603 |
+
},
|
| 604 |
+
path: {
|
| 605 |
+
description:
|
| 606 |
+
'Optional: The absolute path to the directory to search within. If omitted, searches the current working directory.',
|
| 607 |
+
type: 'string',
|
| 608 |
+
},
|
| 609 |
+
include: {
|
| 610 |
+
description:
|
| 611 |
+
"Optional: A glob pattern to filter which files are searched (e.g., '*.js', '*.{ts,tsx}', 'src/**'). If omitted, searches all files (respecting potential global ignores).",
|
| 612 |
+
type: 'string',
|
| 613 |
+
},
|
| 614 |
+
maxResults: {
|
| 615 |
+
description:
|
| 616 |
+
'Optional: Maximum number of matches to return to prevent context overflow (default: 20, max: 100). Use lower values for broad searches, higher for specific searches.',
|
| 617 |
+
type: 'number',
|
| 618 |
+
minimum: 1,
|
| 619 |
+
maximum: 100,
|
| 620 |
+
},
|
| 621 |
+
},
|
| 622 |
+
required: ['pattern'],
|
| 623 |
+
type: 'object',
|
| 624 |
+
},
|
| 625 |
+
);
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
/**
|
| 629 |
+
* Checks if a path is within the root directory and resolves it.
|
| 630 |
+
* @param relativePath Path relative to the root directory (or undefined for root).
|
| 631 |
+
* @returns The absolute path if valid and exists, or null if no path specified (to search all directories).
|
| 632 |
+
* @throws {Error} If path is outside root, doesn't exist, or isn't a directory.
|
| 633 |
+
*/
|
| 634 |
+
private resolveAndValidatePath(relativePath?: string): string | null {
|
| 635 |
+
// If no path specified, return null to indicate searching all workspace directories
|
| 636 |
+
if (!relativePath) {
|
| 637 |
+
return null;
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
const targetPath = path.resolve(this.config.getTargetDir(), relativePath);
|
| 641 |
+
|
| 642 |
+
// Security Check: Ensure the resolved path is within workspace boundaries
|
| 643 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 644 |
+
if (!workspaceContext.isPathWithinWorkspace(targetPath)) {
|
| 645 |
+
const directories = workspaceContext.getDirectories();
|
| 646 |
+
throw new Error(
|
| 647 |
+
`Path validation failed: Attempted path "${relativePath}" resolves outside the allowed workspace directories: ${directories.join(', ')}`,
|
| 648 |
+
);
|
| 649 |
+
}
|
| 650 |
+
|
| 651 |
+
// Check existence and type after resolving
|
| 652 |
+
try {
|
| 653 |
+
const stats = fs.statSync(targetPath);
|
| 654 |
+
if (!stats.isDirectory()) {
|
| 655 |
+
throw new Error(`Path is not a directory: ${targetPath}`);
|
| 656 |
+
}
|
| 657 |
+
} catch (error: unknown) {
|
| 658 |
+
if (isNodeError(error) && error.code !== 'ENOENT') {
|
| 659 |
+
throw new Error(`Path does not exist: ${targetPath}`);
|
| 660 |
+
}
|
| 661 |
+
throw new Error(
|
| 662 |
+
`Failed to access path stats for ${targetPath}: ${error}`,
|
| 663 |
+
);
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
return targetPath;
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
/**
|
| 670 |
+
* Validates the parameters for the tool
|
| 671 |
+
* @param params Parameters to validate
|
| 672 |
+
* @returns An error message string if invalid, null otherwise
|
| 673 |
+
*/
|
| 674 |
+
protected override validateToolParamValues(
|
| 675 |
+
params: GrepToolParams,
|
| 676 |
+
): string | null {
|
| 677 |
+
try {
|
| 678 |
+
new RegExp(params.pattern);
|
| 679 |
+
} catch (error) {
|
| 680 |
+
return `Invalid regular expression pattern provided: ${params.pattern}. Error: ${getErrorMessage(error)}`;
|
| 681 |
+
}
|
| 682 |
+
|
| 683 |
+
// Validate maxResults if provided
|
| 684 |
+
if (params.maxResults !== undefined) {
|
| 685 |
+
if (
|
| 686 |
+
!Number.isInteger(params.maxResults) ||
|
| 687 |
+
params.maxResults < 1 ||
|
| 688 |
+
params.maxResults > 100
|
| 689 |
+
) {
|
| 690 |
+
return `maxResults must be an integer between 1 and 100, got: ${params.maxResults}`;
|
| 691 |
+
}
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
// Only validate path if one is provided
|
| 695 |
+
if (params.path) {
|
| 696 |
+
try {
|
| 697 |
+
this.resolveAndValidatePath(params.path);
|
| 698 |
+
} catch (error) {
|
| 699 |
+
return getErrorMessage(error);
|
| 700 |
+
}
|
| 701 |
+
}
|
| 702 |
+
|
| 703 |
+
return null; // Parameters are valid
|
| 704 |
+
}
|
| 705 |
+
|
| 706 |
+
protected createInvocation(
|
| 707 |
+
params: GrepToolParams,
|
| 708 |
+
): ToolInvocation<GrepToolParams, ToolResult> {
|
| 709 |
+
return new GrepToolInvocation(this.config, params);
|
| 710 |
+
}
|
| 711 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/ls.test.ts
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
| 8 |
+
|
| 9 |
+
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
| 10 |
+
import fs from 'fs';
|
| 11 |
+
import path from 'path';
|
| 12 |
+
|
| 13 |
+
vi.mock('fs', () => ({
|
| 14 |
+
default: {
|
| 15 |
+
statSync: vi.fn(),
|
| 16 |
+
readdirSync: vi.fn(),
|
| 17 |
+
},
|
| 18 |
+
statSync: vi.fn(),
|
| 19 |
+
readdirSync: vi.fn(),
|
| 20 |
+
}));
|
| 21 |
+
import { LSTool } from './ls.js';
|
| 22 |
+
import { Config } from '../config/config.js';
|
| 23 |
+
import { WorkspaceContext } from '../utils/workspaceContext.js';
|
| 24 |
+
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
|
| 25 |
+
|
| 26 |
+
describe('LSTool', () => {
|
| 27 |
+
let lsTool: LSTool;
|
| 28 |
+
let mockConfig: Config;
|
| 29 |
+
let mockWorkspaceContext: WorkspaceContext;
|
| 30 |
+
let mockFileService: FileDiscoveryService;
|
| 31 |
+
const mockPrimaryDir = '/home/user/project';
|
| 32 |
+
const mockSecondaryDir = '/home/user/other-project';
|
| 33 |
+
|
| 34 |
+
beforeEach(() => {
|
| 35 |
+
vi.resetAllMocks();
|
| 36 |
+
|
| 37 |
+
// Mock WorkspaceContext
|
| 38 |
+
mockWorkspaceContext = {
|
| 39 |
+
getDirectories: vi
|
| 40 |
+
.fn()
|
| 41 |
+
.mockReturnValue([mockPrimaryDir, mockSecondaryDir]),
|
| 42 |
+
isPathWithinWorkspace: vi
|
| 43 |
+
.fn()
|
| 44 |
+
.mockImplementation(
|
| 45 |
+
(path) =>
|
| 46 |
+
path.startsWith(mockPrimaryDir) ||
|
| 47 |
+
path.startsWith(mockSecondaryDir),
|
| 48 |
+
),
|
| 49 |
+
addDirectory: vi.fn(),
|
| 50 |
+
} as unknown as WorkspaceContext;
|
| 51 |
+
|
| 52 |
+
// Mock FileService
|
| 53 |
+
mockFileService = {
|
| 54 |
+
shouldGitIgnoreFile: vi.fn().mockReturnValue(false),
|
| 55 |
+
shouldGeminiIgnoreFile: vi.fn().mockReturnValue(false),
|
| 56 |
+
} as unknown as FileDiscoveryService;
|
| 57 |
+
|
| 58 |
+
// Mock Config
|
| 59 |
+
mockConfig = {
|
| 60 |
+
getTargetDir: vi.fn().mockReturnValue(mockPrimaryDir),
|
| 61 |
+
getWorkspaceContext: vi.fn().mockReturnValue(mockWorkspaceContext),
|
| 62 |
+
getFileService: vi.fn().mockReturnValue(mockFileService),
|
| 63 |
+
getFileFilteringOptions: vi.fn().mockReturnValue({
|
| 64 |
+
respectGitIgnore: true,
|
| 65 |
+
respectGeminiIgnore: true,
|
| 66 |
+
}),
|
| 67 |
+
} as unknown as Config;
|
| 68 |
+
|
| 69 |
+
lsTool = new LSTool(mockConfig);
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
describe('parameter validation', () => {
|
| 73 |
+
it('should accept valid absolute paths within workspace', () => {
|
| 74 |
+
const params = {
|
| 75 |
+
path: '/home/user/project/src',
|
| 76 |
+
};
|
| 77 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 78 |
+
isDirectory: () => true,
|
| 79 |
+
} as fs.Stats);
|
| 80 |
+
const invocation = lsTool.build(params);
|
| 81 |
+
expect(invocation).toBeDefined();
|
| 82 |
+
});
|
| 83 |
+
|
| 84 |
+
it('should reject relative paths', () => {
|
| 85 |
+
const params = {
|
| 86 |
+
path: './src',
|
| 87 |
+
};
|
| 88 |
+
|
| 89 |
+
expect(() => lsTool.build(params)).toThrow(
|
| 90 |
+
'Path must be absolute: ./src',
|
| 91 |
+
);
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it('should reject paths outside workspace with clear error message', () => {
|
| 95 |
+
const params = {
|
| 96 |
+
path: '/etc/passwd',
|
| 97 |
+
};
|
| 98 |
+
|
| 99 |
+
expect(() => lsTool.build(params)).toThrow(
|
| 100 |
+
'Path must be within one of the workspace directories: /home/user/project, /home/user/other-project',
|
| 101 |
+
);
|
| 102 |
+
});
|
| 103 |
+
|
| 104 |
+
it('should accept paths in secondary workspace directory', () => {
|
| 105 |
+
const params = {
|
| 106 |
+
path: '/home/user/other-project/lib',
|
| 107 |
+
};
|
| 108 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 109 |
+
isDirectory: () => true,
|
| 110 |
+
} as fs.Stats);
|
| 111 |
+
const invocation = lsTool.build(params);
|
| 112 |
+
expect(invocation).toBeDefined();
|
| 113 |
+
});
|
| 114 |
+
});
|
| 115 |
+
|
| 116 |
+
describe('execute', () => {
|
| 117 |
+
it('should list files in a directory', async () => {
|
| 118 |
+
const testPath = '/home/user/project/src';
|
| 119 |
+
const mockFiles = ['file1.ts', 'file2.ts', 'subdir'];
|
| 120 |
+
const mockStats = {
|
| 121 |
+
isDirectory: vi.fn(),
|
| 122 |
+
mtime: new Date(),
|
| 123 |
+
size: 1024,
|
| 124 |
+
};
|
| 125 |
+
|
| 126 |
+
vi.mocked(fs.statSync).mockImplementation((path: any) => {
|
| 127 |
+
const pathStr = path.toString();
|
| 128 |
+
if (pathStr === testPath) {
|
| 129 |
+
return { isDirectory: () => true } as fs.Stats;
|
| 130 |
+
}
|
| 131 |
+
// For individual files
|
| 132 |
+
if (pathStr.toString().endsWith('subdir')) {
|
| 133 |
+
return { ...mockStats, isDirectory: () => true, size: 0 } as fs.Stats;
|
| 134 |
+
}
|
| 135 |
+
return { ...mockStats, isDirectory: () => false } as fs.Stats;
|
| 136 |
+
});
|
| 137 |
+
|
| 138 |
+
vi.mocked(fs.readdirSync).mockReturnValue(mockFiles as any);
|
| 139 |
+
|
| 140 |
+
const invocation = lsTool.build({ path: testPath });
|
| 141 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 142 |
+
|
| 143 |
+
expect(result.llmContent).toContain('[DIR] subdir');
|
| 144 |
+
expect(result.llmContent).toContain('file1.ts');
|
| 145 |
+
expect(result.llmContent).toContain('file2.ts');
|
| 146 |
+
expect(result.returnDisplay).toBe('Listed 3 item(s).');
|
| 147 |
+
});
|
| 148 |
+
|
| 149 |
+
it('should list files from secondary workspace directory', async () => {
|
| 150 |
+
const testPath = '/home/user/other-project/lib';
|
| 151 |
+
const mockFiles = ['module1.js', 'module2.js'];
|
| 152 |
+
|
| 153 |
+
vi.mocked(fs.statSync).mockImplementation((path: any) => {
|
| 154 |
+
if (path.toString() === testPath) {
|
| 155 |
+
return { isDirectory: () => true } as fs.Stats;
|
| 156 |
+
}
|
| 157 |
+
return {
|
| 158 |
+
isDirectory: () => false,
|
| 159 |
+
mtime: new Date(),
|
| 160 |
+
size: 2048,
|
| 161 |
+
} as fs.Stats;
|
| 162 |
+
});
|
| 163 |
+
|
| 164 |
+
vi.mocked(fs.readdirSync).mockReturnValue(mockFiles as any);
|
| 165 |
+
|
| 166 |
+
const invocation = lsTool.build({ path: testPath });
|
| 167 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 168 |
+
|
| 169 |
+
expect(result.llmContent).toContain('module1.js');
|
| 170 |
+
expect(result.llmContent).toContain('module2.js');
|
| 171 |
+
expect(result.returnDisplay).toBe('Listed 2 item(s).');
|
| 172 |
+
});
|
| 173 |
+
|
| 174 |
+
it('should handle empty directories', async () => {
|
| 175 |
+
const testPath = '/home/user/project/empty';
|
| 176 |
+
|
| 177 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 178 |
+
isDirectory: () => true,
|
| 179 |
+
} as fs.Stats);
|
| 180 |
+
vi.mocked(fs.readdirSync).mockReturnValue([]);
|
| 181 |
+
|
| 182 |
+
const invocation = lsTool.build({ path: testPath });
|
| 183 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 184 |
+
|
| 185 |
+
expect(result.llmContent).toBe(
|
| 186 |
+
'Directory /home/user/project/empty is empty.',
|
| 187 |
+
);
|
| 188 |
+
expect(result.returnDisplay).toBe('Directory is empty.');
|
| 189 |
+
});
|
| 190 |
+
|
| 191 |
+
it('should respect ignore patterns', async () => {
|
| 192 |
+
const testPath = '/home/user/project/src';
|
| 193 |
+
const mockFiles = ['test.js', 'test.spec.js', 'index.js'];
|
| 194 |
+
|
| 195 |
+
vi.mocked(fs.statSync).mockImplementation((path: any) => {
|
| 196 |
+
const pathStr = path.toString();
|
| 197 |
+
if (pathStr === testPath) {
|
| 198 |
+
return { isDirectory: () => true } as fs.Stats;
|
| 199 |
+
}
|
| 200 |
+
return {
|
| 201 |
+
isDirectory: () => false,
|
| 202 |
+
mtime: new Date(),
|
| 203 |
+
size: 1024,
|
| 204 |
+
} as fs.Stats;
|
| 205 |
+
});
|
| 206 |
+
vi.mocked(fs.readdirSync).mockReturnValue(mockFiles as any);
|
| 207 |
+
|
| 208 |
+
const invocation = lsTool.build({
|
| 209 |
+
path: testPath,
|
| 210 |
+
ignore: ['*.spec.js'],
|
| 211 |
+
});
|
| 212 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 213 |
+
|
| 214 |
+
expect(result.llmContent).toContain('test.js');
|
| 215 |
+
expect(result.llmContent).toContain('index.js');
|
| 216 |
+
expect(result.llmContent).not.toContain('test.spec.js');
|
| 217 |
+
expect(result.returnDisplay).toBe('Listed 2 item(s).');
|
| 218 |
+
});
|
| 219 |
+
|
| 220 |
+
it('should respect gitignore patterns', async () => {
|
| 221 |
+
const testPath = '/home/user/project/src';
|
| 222 |
+
const mockFiles = ['file1.js', 'file2.js', 'ignored.js'];
|
| 223 |
+
|
| 224 |
+
vi.mocked(fs.statSync).mockImplementation((path: any) => {
|
| 225 |
+
const pathStr = path.toString();
|
| 226 |
+
if (pathStr === testPath) {
|
| 227 |
+
return { isDirectory: () => true } as fs.Stats;
|
| 228 |
+
}
|
| 229 |
+
return {
|
| 230 |
+
isDirectory: () => false,
|
| 231 |
+
mtime: new Date(),
|
| 232 |
+
size: 1024,
|
| 233 |
+
} as fs.Stats;
|
| 234 |
+
});
|
| 235 |
+
vi.mocked(fs.readdirSync).mockReturnValue(mockFiles as any);
|
| 236 |
+
(mockFileService.shouldGitIgnoreFile as any).mockImplementation(
|
| 237 |
+
(path: string) => path.includes('ignored.js'),
|
| 238 |
+
);
|
| 239 |
+
|
| 240 |
+
const invocation = lsTool.build({ path: testPath });
|
| 241 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 242 |
+
|
| 243 |
+
expect(result.llmContent).toContain('file1.js');
|
| 244 |
+
expect(result.llmContent).toContain('file2.js');
|
| 245 |
+
expect(result.llmContent).not.toContain('ignored.js');
|
| 246 |
+
expect(result.returnDisplay).toBe('Listed 2 item(s). (1 git-ignored)');
|
| 247 |
+
});
|
| 248 |
+
|
| 249 |
+
it('should respect geminiignore patterns', async () => {
|
| 250 |
+
const testPath = '/home/user/project/src';
|
| 251 |
+
const mockFiles = ['file1.js', 'file2.js', 'private.js'];
|
| 252 |
+
|
| 253 |
+
vi.mocked(fs.statSync).mockImplementation((path: any) => {
|
| 254 |
+
const pathStr = path.toString();
|
| 255 |
+
if (pathStr === testPath) {
|
| 256 |
+
return { isDirectory: () => true } as fs.Stats;
|
| 257 |
+
}
|
| 258 |
+
return {
|
| 259 |
+
isDirectory: () => false,
|
| 260 |
+
mtime: new Date(),
|
| 261 |
+
size: 1024,
|
| 262 |
+
} as fs.Stats;
|
| 263 |
+
});
|
| 264 |
+
vi.mocked(fs.readdirSync).mockReturnValue(mockFiles as any);
|
| 265 |
+
(mockFileService.shouldGeminiIgnoreFile as any).mockImplementation(
|
| 266 |
+
(path: string) => path.includes('private.js'),
|
| 267 |
+
);
|
| 268 |
+
|
| 269 |
+
const invocation = lsTool.build({ path: testPath });
|
| 270 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 271 |
+
|
| 272 |
+
expect(result.llmContent).toContain('file1.js');
|
| 273 |
+
expect(result.llmContent).toContain('file2.js');
|
| 274 |
+
expect(result.llmContent).not.toContain('private.js');
|
| 275 |
+
expect(result.returnDisplay).toBe('Listed 2 item(s). (1 gemini-ignored)');
|
| 276 |
+
});
|
| 277 |
+
|
| 278 |
+
it('should handle non-directory paths', async () => {
|
| 279 |
+
const testPath = '/home/user/project/file.txt';
|
| 280 |
+
|
| 281 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 282 |
+
isDirectory: () => false,
|
| 283 |
+
} as fs.Stats);
|
| 284 |
+
|
| 285 |
+
const invocation = lsTool.build({ path: testPath });
|
| 286 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 287 |
+
|
| 288 |
+
expect(result.llmContent).toContain('Path is not a directory');
|
| 289 |
+
expect(result.returnDisplay).toBe('Error: Path is not a directory.');
|
| 290 |
+
});
|
| 291 |
+
|
| 292 |
+
it('should handle non-existent paths', async () => {
|
| 293 |
+
const testPath = '/home/user/project/does-not-exist';
|
| 294 |
+
|
| 295 |
+
vi.mocked(fs.statSync).mockImplementation(() => {
|
| 296 |
+
throw new Error('ENOENT: no such file or directory');
|
| 297 |
+
});
|
| 298 |
+
|
| 299 |
+
const invocation = lsTool.build({ path: testPath });
|
| 300 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 301 |
+
|
| 302 |
+
expect(result.llmContent).toContain('Error listing directory');
|
| 303 |
+
expect(result.returnDisplay).toBe('Error: Failed to list directory.');
|
| 304 |
+
});
|
| 305 |
+
|
| 306 |
+
it('should sort directories first, then files alphabetically', async () => {
|
| 307 |
+
const testPath = '/home/user/project/src';
|
| 308 |
+
const mockFiles = ['z-file.ts', 'a-dir', 'b-file.ts', 'c-dir'];
|
| 309 |
+
|
| 310 |
+
vi.mocked(fs.statSync).mockImplementation((path: any) => {
|
| 311 |
+
if (path.toString() === testPath) {
|
| 312 |
+
return { isDirectory: () => true } as fs.Stats;
|
| 313 |
+
}
|
| 314 |
+
if (path.toString().endsWith('-dir')) {
|
| 315 |
+
return {
|
| 316 |
+
isDirectory: () => true,
|
| 317 |
+
mtime: new Date(),
|
| 318 |
+
size: 0,
|
| 319 |
+
} as fs.Stats;
|
| 320 |
+
}
|
| 321 |
+
return {
|
| 322 |
+
isDirectory: () => false,
|
| 323 |
+
mtime: new Date(),
|
| 324 |
+
size: 1024,
|
| 325 |
+
} as fs.Stats;
|
| 326 |
+
});
|
| 327 |
+
|
| 328 |
+
vi.mocked(fs.readdirSync).mockReturnValue(mockFiles as any);
|
| 329 |
+
|
| 330 |
+
const invocation = lsTool.build({ path: testPath });
|
| 331 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 332 |
+
|
| 333 |
+
const lines = (
|
| 334 |
+
typeof result.llmContent === 'string' ? result.llmContent : ''
|
| 335 |
+
).split('\n');
|
| 336 |
+
const entries = lines.slice(1).filter((line: string) => line.trim()); // Skip header
|
| 337 |
+
expect(entries[0]).toBe('[DIR] a-dir');
|
| 338 |
+
expect(entries[1]).toBe('[DIR] c-dir');
|
| 339 |
+
expect(entries[2]).toBe('b-file.ts');
|
| 340 |
+
expect(entries[3]).toBe('z-file.ts');
|
| 341 |
+
});
|
| 342 |
+
|
| 343 |
+
it('should handle permission errors gracefully', async () => {
|
| 344 |
+
const testPath = '/home/user/project/restricted';
|
| 345 |
+
|
| 346 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 347 |
+
isDirectory: () => true,
|
| 348 |
+
} as fs.Stats);
|
| 349 |
+
vi.mocked(fs.readdirSync).mockImplementation(() => {
|
| 350 |
+
throw new Error('EACCES: permission denied');
|
| 351 |
+
});
|
| 352 |
+
|
| 353 |
+
const invocation = lsTool.build({ path: testPath });
|
| 354 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 355 |
+
|
| 356 |
+
expect(result.llmContent).toContain('Error listing directory');
|
| 357 |
+
expect(result.llmContent).toContain('permission denied');
|
| 358 |
+
expect(result.returnDisplay).toBe('Error: Failed to list directory.');
|
| 359 |
+
});
|
| 360 |
+
|
| 361 |
+
it('should throw for invalid params at build time', async () => {
|
| 362 |
+
expect(() => lsTool.build({ path: '../outside' })).toThrow(
|
| 363 |
+
'Path must be absolute: ../outside',
|
| 364 |
+
);
|
| 365 |
+
});
|
| 366 |
+
|
| 367 |
+
it('should handle errors accessing individual files during listing', async () => {
|
| 368 |
+
const testPath = '/home/user/project/src';
|
| 369 |
+
const mockFiles = ['accessible.ts', 'inaccessible.ts'];
|
| 370 |
+
|
| 371 |
+
vi.mocked(fs.statSync).mockImplementation((path: any) => {
|
| 372 |
+
if (path.toString() === testPath) {
|
| 373 |
+
return { isDirectory: () => true } as fs.Stats;
|
| 374 |
+
}
|
| 375 |
+
if (path.toString().endsWith('inaccessible.ts')) {
|
| 376 |
+
throw new Error('EACCES: permission denied');
|
| 377 |
+
}
|
| 378 |
+
return {
|
| 379 |
+
isDirectory: () => false,
|
| 380 |
+
mtime: new Date(),
|
| 381 |
+
size: 1024,
|
| 382 |
+
} as fs.Stats;
|
| 383 |
+
});
|
| 384 |
+
|
| 385 |
+
vi.mocked(fs.readdirSync).mockReturnValue(mockFiles as any);
|
| 386 |
+
|
| 387 |
+
// Spy on console.error to verify it's called
|
| 388 |
+
const consoleErrorSpy = vi
|
| 389 |
+
.spyOn(console, 'error')
|
| 390 |
+
.mockImplementation(() => {});
|
| 391 |
+
|
| 392 |
+
const invocation = lsTool.build({ path: testPath });
|
| 393 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 394 |
+
|
| 395 |
+
// Should still list the accessible file
|
| 396 |
+
expect(result.llmContent).toContain('accessible.ts');
|
| 397 |
+
expect(result.llmContent).not.toContain('inaccessible.ts');
|
| 398 |
+
expect(result.returnDisplay).toBe('Listed 1 item(s).');
|
| 399 |
+
|
| 400 |
+
// Verify error was logged
|
| 401 |
+
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
| 402 |
+
expect.stringContaining('Error accessing'),
|
| 403 |
+
);
|
| 404 |
+
|
| 405 |
+
consoleErrorSpy.mockRestore();
|
| 406 |
+
});
|
| 407 |
+
});
|
| 408 |
+
|
| 409 |
+
describe('getDescription', () => {
|
| 410 |
+
it('should return shortened relative path', () => {
|
| 411 |
+
const params = {
|
| 412 |
+
path: `${mockPrimaryDir}/deeply/nested/directory`,
|
| 413 |
+
};
|
| 414 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 415 |
+
isDirectory: () => true,
|
| 416 |
+
} as fs.Stats);
|
| 417 |
+
const invocation = lsTool.build(params);
|
| 418 |
+
const description = invocation.getDescription();
|
| 419 |
+
expect(description).toBe(path.join('deeply', 'nested', 'directory'));
|
| 420 |
+
});
|
| 421 |
+
|
| 422 |
+
it('should handle paths in secondary workspace', () => {
|
| 423 |
+
const params = {
|
| 424 |
+
path: `${mockSecondaryDir}/lib`,
|
| 425 |
+
};
|
| 426 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 427 |
+
isDirectory: () => true,
|
| 428 |
+
} as fs.Stats);
|
| 429 |
+
const invocation = lsTool.build(params);
|
| 430 |
+
const description = invocation.getDescription();
|
| 431 |
+
expect(description).toBe(path.join('..', 'other-project', 'lib'));
|
| 432 |
+
});
|
| 433 |
+
});
|
| 434 |
+
|
| 435 |
+
describe('workspace boundary validation', () => {
|
| 436 |
+
it('should accept paths in primary workspace directory', () => {
|
| 437 |
+
const params = { path: `${mockPrimaryDir}/src` };
|
| 438 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 439 |
+
isDirectory: () => true,
|
| 440 |
+
} as fs.Stats);
|
| 441 |
+
expect(lsTool.build(params)).toBeDefined();
|
| 442 |
+
});
|
| 443 |
+
|
| 444 |
+
it('should accept paths in secondary workspace directory', () => {
|
| 445 |
+
const params = { path: `${mockSecondaryDir}/lib` };
|
| 446 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 447 |
+
isDirectory: () => true,
|
| 448 |
+
} as fs.Stats);
|
| 449 |
+
expect(lsTool.build(params)).toBeDefined();
|
| 450 |
+
});
|
| 451 |
+
|
| 452 |
+
it('should reject paths outside all workspace directories', () => {
|
| 453 |
+
const params = { path: '/etc/passwd' };
|
| 454 |
+
expect(() => lsTool.build(params)).toThrow(
|
| 455 |
+
'Path must be within one of the workspace directories',
|
| 456 |
+
);
|
| 457 |
+
});
|
| 458 |
+
|
| 459 |
+
it('should list files from secondary workspace directory', async () => {
|
| 460 |
+
const testPath = `${mockSecondaryDir}/tests`;
|
| 461 |
+
const mockFiles = ['test1.spec.ts', 'test2.spec.ts'];
|
| 462 |
+
|
| 463 |
+
vi.mocked(fs.statSync).mockImplementation((path: any) => {
|
| 464 |
+
if (path.toString() === testPath) {
|
| 465 |
+
return { isDirectory: () => true } as fs.Stats;
|
| 466 |
+
}
|
| 467 |
+
return {
|
| 468 |
+
isDirectory: () => false,
|
| 469 |
+
mtime: new Date(),
|
| 470 |
+
size: 512,
|
| 471 |
+
} as fs.Stats;
|
| 472 |
+
});
|
| 473 |
+
|
| 474 |
+
vi.mocked(fs.readdirSync).mockReturnValue(mockFiles as any);
|
| 475 |
+
|
| 476 |
+
const invocation = lsTool.build({ path: testPath });
|
| 477 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 478 |
+
|
| 479 |
+
expect(result.llmContent).toContain('test1.spec.ts');
|
| 480 |
+
expect(result.llmContent).toContain('test2.spec.ts');
|
| 481 |
+
expect(result.returnDisplay).toBe('Listed 2 item(s).');
|
| 482 |
+
});
|
| 483 |
+
});
|
| 484 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/ls.ts
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import fs from 'fs';
|
| 8 |
+
import path from 'path';
|
| 9 |
+
import {
|
| 10 |
+
BaseDeclarativeTool,
|
| 11 |
+
BaseToolInvocation,
|
| 12 |
+
Kind,
|
| 13 |
+
ToolInvocation,
|
| 14 |
+
ToolResult,
|
| 15 |
+
} from './tools.js';
|
| 16 |
+
import { makeRelative, shortenPath } from '../utils/paths.js';
|
| 17 |
+
import { Config, DEFAULT_FILE_FILTERING_OPTIONS } from '../config/config.js';
|
| 18 |
+
|
| 19 |
+
/**
|
| 20 |
+
* Parameters for the LS tool
|
| 21 |
+
*/
|
| 22 |
+
export interface LSToolParams {
|
| 23 |
+
/**
|
| 24 |
+
* The absolute path to the directory to list
|
| 25 |
+
*/
|
| 26 |
+
path: string;
|
| 27 |
+
|
| 28 |
+
/**
|
| 29 |
+
* Array of glob patterns to ignore (optional)
|
| 30 |
+
*/
|
| 31 |
+
ignore?: string[];
|
| 32 |
+
|
| 33 |
+
/**
|
| 34 |
+
* Whether to respect .gitignore and .geminiignore patterns (optional, defaults to true)
|
| 35 |
+
*/
|
| 36 |
+
file_filtering_options?: {
|
| 37 |
+
respect_git_ignore?: boolean;
|
| 38 |
+
respect_gemini_ignore?: boolean;
|
| 39 |
+
};
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/**
|
| 43 |
+
* File entry returned by LS tool
|
| 44 |
+
*/
|
| 45 |
+
export interface FileEntry {
|
| 46 |
+
/**
|
| 47 |
+
* Name of the file or directory
|
| 48 |
+
*/
|
| 49 |
+
name: string;
|
| 50 |
+
|
| 51 |
+
/**
|
| 52 |
+
* Absolute path to the file or directory
|
| 53 |
+
*/
|
| 54 |
+
path: string;
|
| 55 |
+
|
| 56 |
+
/**
|
| 57 |
+
* Whether this entry is a directory
|
| 58 |
+
*/
|
| 59 |
+
isDirectory: boolean;
|
| 60 |
+
|
| 61 |
+
/**
|
| 62 |
+
* Size of the file in bytes (0 for directories)
|
| 63 |
+
*/
|
| 64 |
+
size: number;
|
| 65 |
+
|
| 66 |
+
/**
|
| 67 |
+
* Last modified timestamp
|
| 68 |
+
*/
|
| 69 |
+
modifiedTime: Date;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
class LSToolInvocation extends BaseToolInvocation<LSToolParams, ToolResult> {
|
| 73 |
+
constructor(
|
| 74 |
+
private readonly config: Config,
|
| 75 |
+
params: LSToolParams,
|
| 76 |
+
) {
|
| 77 |
+
super(params);
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
/**
|
| 81 |
+
* Checks if a filename matches any of the ignore patterns
|
| 82 |
+
* @param filename Filename to check
|
| 83 |
+
* @param patterns Array of glob patterns to check against
|
| 84 |
+
* @returns True if the filename should be ignored
|
| 85 |
+
*/
|
| 86 |
+
private shouldIgnore(filename: string, patterns?: string[]): boolean {
|
| 87 |
+
if (!patterns || patterns.length === 0) {
|
| 88 |
+
return false;
|
| 89 |
+
}
|
| 90 |
+
for (const pattern of patterns) {
|
| 91 |
+
// Convert glob pattern to RegExp
|
| 92 |
+
const regexPattern = pattern
|
| 93 |
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
| 94 |
+
.replace(/\*/g, '.*')
|
| 95 |
+
.replace(/\?/g, '.');
|
| 96 |
+
const regex = new RegExp(`^${regexPattern}$`);
|
| 97 |
+
if (regex.test(filename)) {
|
| 98 |
+
return true;
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
return false;
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
/**
|
| 105 |
+
* Gets a description of the file reading operation
|
| 106 |
+
* @returns A string describing the file being read
|
| 107 |
+
*/
|
| 108 |
+
getDescription(): string {
|
| 109 |
+
const relativePath = makeRelative(
|
| 110 |
+
this.params.path,
|
| 111 |
+
this.config.getTargetDir(),
|
| 112 |
+
);
|
| 113 |
+
return shortenPath(relativePath);
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// Helper for consistent error formatting
|
| 117 |
+
private errorResult(llmContent: string, returnDisplay: string): ToolResult {
|
| 118 |
+
return {
|
| 119 |
+
llmContent,
|
| 120 |
+
// Keep returnDisplay simpler in core logic
|
| 121 |
+
returnDisplay: `Error: ${returnDisplay}`,
|
| 122 |
+
};
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
/**
|
| 126 |
+
* Executes the LS operation with the given parameters
|
| 127 |
+
* @returns Result of the LS operation
|
| 128 |
+
*/
|
| 129 |
+
async execute(_signal: AbortSignal): Promise<ToolResult> {
|
| 130 |
+
try {
|
| 131 |
+
const stats = fs.statSync(this.params.path);
|
| 132 |
+
if (!stats) {
|
| 133 |
+
// fs.statSync throws on non-existence, so this check might be redundant
|
| 134 |
+
// but keeping for clarity. Error message adjusted.
|
| 135 |
+
return this.errorResult(
|
| 136 |
+
`Error: Directory not found or inaccessible: ${this.params.path}`,
|
| 137 |
+
`Directory not found or inaccessible.`,
|
| 138 |
+
);
|
| 139 |
+
}
|
| 140 |
+
if (!stats.isDirectory()) {
|
| 141 |
+
return this.errorResult(
|
| 142 |
+
`Error: Path is not a directory: ${this.params.path}`,
|
| 143 |
+
`Path is not a directory.`,
|
| 144 |
+
);
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
const files = fs.readdirSync(this.params.path);
|
| 148 |
+
|
| 149 |
+
const defaultFileIgnores =
|
| 150 |
+
this.config.getFileFilteringOptions() ?? DEFAULT_FILE_FILTERING_OPTIONS;
|
| 151 |
+
|
| 152 |
+
const fileFilteringOptions = {
|
| 153 |
+
respectGitIgnore:
|
| 154 |
+
this.params.file_filtering_options?.respect_git_ignore ??
|
| 155 |
+
defaultFileIgnores.respectGitIgnore,
|
| 156 |
+
respectGeminiIgnore:
|
| 157 |
+
this.params.file_filtering_options?.respect_gemini_ignore ??
|
| 158 |
+
defaultFileIgnores.respectGeminiIgnore,
|
| 159 |
+
};
|
| 160 |
+
|
| 161 |
+
// Get centralized file discovery service
|
| 162 |
+
|
| 163 |
+
const fileDiscovery = this.config.getFileService();
|
| 164 |
+
|
| 165 |
+
const entries: FileEntry[] = [];
|
| 166 |
+
let gitIgnoredCount = 0;
|
| 167 |
+
let geminiIgnoredCount = 0;
|
| 168 |
+
|
| 169 |
+
if (files.length === 0) {
|
| 170 |
+
// Changed error message to be more neutral for LLM
|
| 171 |
+
return {
|
| 172 |
+
llmContent: `Directory ${this.params.path} is empty.`,
|
| 173 |
+
returnDisplay: `Directory is empty.`,
|
| 174 |
+
};
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
for (const file of files) {
|
| 178 |
+
if (this.shouldIgnore(file, this.params.ignore)) {
|
| 179 |
+
continue;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
const fullPath = path.join(this.params.path, file);
|
| 183 |
+
const relativePath = path.relative(
|
| 184 |
+
this.config.getTargetDir(),
|
| 185 |
+
fullPath,
|
| 186 |
+
);
|
| 187 |
+
|
| 188 |
+
// Check if this file should be ignored based on git or gemini ignore rules
|
| 189 |
+
if (
|
| 190 |
+
fileFilteringOptions.respectGitIgnore &&
|
| 191 |
+
fileDiscovery.shouldGitIgnoreFile(relativePath)
|
| 192 |
+
) {
|
| 193 |
+
gitIgnoredCount++;
|
| 194 |
+
continue;
|
| 195 |
+
}
|
| 196 |
+
if (
|
| 197 |
+
fileFilteringOptions.respectGeminiIgnore &&
|
| 198 |
+
fileDiscovery.shouldGeminiIgnoreFile(relativePath)
|
| 199 |
+
) {
|
| 200 |
+
geminiIgnoredCount++;
|
| 201 |
+
continue;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
try {
|
| 205 |
+
const stats = fs.statSync(fullPath);
|
| 206 |
+
const isDir = stats.isDirectory();
|
| 207 |
+
entries.push({
|
| 208 |
+
name: file,
|
| 209 |
+
path: fullPath,
|
| 210 |
+
isDirectory: isDir,
|
| 211 |
+
size: isDir ? 0 : stats.size,
|
| 212 |
+
modifiedTime: stats.mtime,
|
| 213 |
+
});
|
| 214 |
+
} catch (error) {
|
| 215 |
+
// Log error internally but don't fail the whole listing
|
| 216 |
+
console.error(`Error accessing ${fullPath}: ${error}`);
|
| 217 |
+
}
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
// Sort entries (directories first, then alphabetically)
|
| 221 |
+
entries.sort((a, b) => {
|
| 222 |
+
if (a.isDirectory && !b.isDirectory) return -1;
|
| 223 |
+
if (!a.isDirectory && b.isDirectory) return 1;
|
| 224 |
+
return a.name.localeCompare(b.name);
|
| 225 |
+
});
|
| 226 |
+
|
| 227 |
+
// Create formatted content for LLM
|
| 228 |
+
const directoryContent = entries
|
| 229 |
+
.map((entry) => `${entry.isDirectory ? '[DIR] ' : ''}${entry.name}`)
|
| 230 |
+
.join('\n');
|
| 231 |
+
|
| 232 |
+
let resultMessage = `Directory listing for ${this.params.path}:\n${directoryContent}`;
|
| 233 |
+
const ignoredMessages = [];
|
| 234 |
+
if (gitIgnoredCount > 0) {
|
| 235 |
+
ignoredMessages.push(`${gitIgnoredCount} git-ignored`);
|
| 236 |
+
}
|
| 237 |
+
if (geminiIgnoredCount > 0) {
|
| 238 |
+
ignoredMessages.push(`${geminiIgnoredCount} gemini-ignored`);
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
if (ignoredMessages.length > 0) {
|
| 242 |
+
resultMessage += `\n\n(${ignoredMessages.join(', ')})`;
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
let displayMessage = `Listed ${entries.length} item(s).`;
|
| 246 |
+
if (ignoredMessages.length > 0) {
|
| 247 |
+
displayMessage += ` (${ignoredMessages.join(', ')})`;
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
return {
|
| 251 |
+
llmContent: resultMessage,
|
| 252 |
+
returnDisplay: displayMessage,
|
| 253 |
+
};
|
| 254 |
+
} catch (error) {
|
| 255 |
+
const errorMsg = `Error listing directory: ${error instanceof Error ? error.message : String(error)}`;
|
| 256 |
+
return this.errorResult(errorMsg, 'Failed to list directory.');
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
/**
|
| 262 |
+
* Implementation of the LS tool logic
|
| 263 |
+
*/
|
| 264 |
+
export class LSTool extends BaseDeclarativeTool<LSToolParams, ToolResult> {
|
| 265 |
+
static readonly Name = 'list_directory';
|
| 266 |
+
|
| 267 |
+
constructor(private config: Config) {
|
| 268 |
+
super(
|
| 269 |
+
LSTool.Name,
|
| 270 |
+
'ReadFolder',
|
| 271 |
+
'Lists the names of files and subdirectories directly within a specified directory path. Can optionally ignore entries matching provided glob patterns.',
|
| 272 |
+
Kind.Search,
|
| 273 |
+
{
|
| 274 |
+
properties: {
|
| 275 |
+
path: {
|
| 276 |
+
description:
|
| 277 |
+
'The absolute path to the directory to list (must be absolute, not relative)',
|
| 278 |
+
type: 'string',
|
| 279 |
+
},
|
| 280 |
+
ignore: {
|
| 281 |
+
description: 'List of glob patterns to ignore',
|
| 282 |
+
items: {
|
| 283 |
+
type: 'string',
|
| 284 |
+
},
|
| 285 |
+
type: 'array',
|
| 286 |
+
},
|
| 287 |
+
file_filtering_options: {
|
| 288 |
+
description:
|
| 289 |
+
'Optional: Whether to respect ignore patterns from .gitignore or .geminiignore',
|
| 290 |
+
type: 'object',
|
| 291 |
+
properties: {
|
| 292 |
+
respect_git_ignore: {
|
| 293 |
+
description:
|
| 294 |
+
'Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true.',
|
| 295 |
+
type: 'boolean',
|
| 296 |
+
},
|
| 297 |
+
respect_gemini_ignore: {
|
| 298 |
+
description:
|
| 299 |
+
'Optional: Whether to respect .geminiignore patterns when listing files. Defaults to true.',
|
| 300 |
+
type: 'boolean',
|
| 301 |
+
},
|
| 302 |
+
},
|
| 303 |
+
},
|
| 304 |
+
},
|
| 305 |
+
required: ['path'],
|
| 306 |
+
type: 'object',
|
| 307 |
+
},
|
| 308 |
+
);
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
/**
|
| 312 |
+
* Validates the parameters for the tool
|
| 313 |
+
* @param params Parameters to validate
|
| 314 |
+
* @returns An error message string if invalid, null otherwise
|
| 315 |
+
*/
|
| 316 |
+
protected override validateToolParamValues(
|
| 317 |
+
params: LSToolParams,
|
| 318 |
+
): string | null {
|
| 319 |
+
if (!path.isAbsolute(params.path)) {
|
| 320 |
+
return `Path must be absolute: ${params.path}`;
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 324 |
+
if (!workspaceContext.isPathWithinWorkspace(params.path)) {
|
| 325 |
+
const directories = workspaceContext.getDirectories();
|
| 326 |
+
return `Path must be within one of the workspace directories: ${directories.join(
|
| 327 |
+
', ',
|
| 328 |
+
)}`;
|
| 329 |
+
}
|
| 330 |
+
return null;
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
protected createInvocation(
|
| 334 |
+
params: LSToolParams,
|
| 335 |
+
): ToolInvocation<LSToolParams, ToolResult> {
|
| 336 |
+
return new LSToolInvocation(this.config, params);
|
| 337 |
+
}
|
| 338 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/mcp-client-manager.test.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
| 8 |
+
import { McpClientManager } from './mcp-client-manager.js';
|
| 9 |
+
import { McpClient } from './mcp-client.js';
|
| 10 |
+
import { ToolRegistry } from './tool-registry.js';
|
| 11 |
+
import { PromptRegistry } from '../prompts/prompt-registry.js';
|
| 12 |
+
import { WorkspaceContext } from '../utils/workspaceContext.js';
|
| 13 |
+
|
| 14 |
+
vi.mock('./mcp-client.js', async () => {
|
| 15 |
+
const originalModule = await vi.importActual('./mcp-client.js');
|
| 16 |
+
return {
|
| 17 |
+
...originalModule,
|
| 18 |
+
McpClient: vi.fn(),
|
| 19 |
+
populateMcpServerCommand: vi.fn(() => ({
|
| 20 |
+
'test-server': {},
|
| 21 |
+
})),
|
| 22 |
+
};
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
describe('McpClientManager', () => {
|
| 26 |
+
afterEach(() => {
|
| 27 |
+
vi.restoreAllMocks();
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
it('should discover tools from all servers', async () => {
|
| 31 |
+
const mockedMcpClient = {
|
| 32 |
+
connect: vi.fn(),
|
| 33 |
+
discover: vi.fn(),
|
| 34 |
+
disconnect: vi.fn(),
|
| 35 |
+
getStatus: vi.fn(),
|
| 36 |
+
};
|
| 37 |
+
vi.mocked(McpClient).mockReturnValue(
|
| 38 |
+
mockedMcpClient as unknown as McpClient,
|
| 39 |
+
);
|
| 40 |
+
const manager = new McpClientManager(
|
| 41 |
+
{
|
| 42 |
+
'test-server': {},
|
| 43 |
+
},
|
| 44 |
+
'',
|
| 45 |
+
{} as ToolRegistry,
|
| 46 |
+
{} as PromptRegistry,
|
| 47 |
+
false,
|
| 48 |
+
{} as WorkspaceContext,
|
| 49 |
+
);
|
| 50 |
+
await manager.discoverAllMcpTools();
|
| 51 |
+
expect(mockedMcpClient.connect).toHaveBeenCalledOnce();
|
| 52 |
+
expect(mockedMcpClient.discover).toHaveBeenCalledOnce();
|
| 53 |
+
});
|
| 54 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/mcp-client-manager.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { MCPServerConfig } from '../config/config.js';
|
| 8 |
+
import { ToolRegistry } from './tool-registry.js';
|
| 9 |
+
import { PromptRegistry } from '../prompts/prompt-registry.js';
|
| 10 |
+
import {
|
| 11 |
+
McpClient,
|
| 12 |
+
MCPDiscoveryState,
|
| 13 |
+
populateMcpServerCommand,
|
| 14 |
+
} from './mcp-client.js';
|
| 15 |
+
import { getErrorMessage } from '../utils/errors.js';
|
| 16 |
+
import { WorkspaceContext } from '../utils/workspaceContext.js';
|
| 17 |
+
|
| 18 |
+
/**
|
| 19 |
+
* Manages the lifecycle of multiple MCP clients, including local child processes.
|
| 20 |
+
* This class is responsible for starting, stopping, and discovering tools from
|
| 21 |
+
* a collection of MCP servers defined in the configuration.
|
| 22 |
+
*/
|
| 23 |
+
export class McpClientManager {
|
| 24 |
+
private clients: Map<string, McpClient> = new Map();
|
| 25 |
+
private readonly mcpServers: Record<string, MCPServerConfig>;
|
| 26 |
+
private readonly mcpServerCommand: string | undefined;
|
| 27 |
+
private readonly toolRegistry: ToolRegistry;
|
| 28 |
+
private readonly promptRegistry: PromptRegistry;
|
| 29 |
+
private readonly debugMode: boolean;
|
| 30 |
+
private readonly workspaceContext: WorkspaceContext;
|
| 31 |
+
private discoveryState: MCPDiscoveryState = MCPDiscoveryState.NOT_STARTED;
|
| 32 |
+
|
| 33 |
+
constructor(
|
| 34 |
+
mcpServers: Record<string, MCPServerConfig>,
|
| 35 |
+
mcpServerCommand: string | undefined,
|
| 36 |
+
toolRegistry: ToolRegistry,
|
| 37 |
+
promptRegistry: PromptRegistry,
|
| 38 |
+
debugMode: boolean,
|
| 39 |
+
workspaceContext: WorkspaceContext,
|
| 40 |
+
) {
|
| 41 |
+
this.mcpServers = mcpServers;
|
| 42 |
+
this.mcpServerCommand = mcpServerCommand;
|
| 43 |
+
this.toolRegistry = toolRegistry;
|
| 44 |
+
this.promptRegistry = promptRegistry;
|
| 45 |
+
this.debugMode = debugMode;
|
| 46 |
+
this.workspaceContext = workspaceContext;
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
/**
|
| 50 |
+
* Initiates the tool discovery process for all configured MCP servers.
|
| 51 |
+
* It connects to each server, discovers its available tools, and registers
|
| 52 |
+
* them with the `ToolRegistry`.
|
| 53 |
+
*/
|
| 54 |
+
async discoverAllMcpTools(): Promise<void> {
|
| 55 |
+
await this.stop();
|
| 56 |
+
this.discoveryState = MCPDiscoveryState.IN_PROGRESS;
|
| 57 |
+
const servers = populateMcpServerCommand(
|
| 58 |
+
this.mcpServers,
|
| 59 |
+
this.mcpServerCommand,
|
| 60 |
+
);
|
| 61 |
+
|
| 62 |
+
const discoveryPromises = Object.entries(servers).map(
|
| 63 |
+
async ([name, config]) => {
|
| 64 |
+
const client = new McpClient(
|
| 65 |
+
name,
|
| 66 |
+
config,
|
| 67 |
+
this.toolRegistry,
|
| 68 |
+
this.promptRegistry,
|
| 69 |
+
this.workspaceContext,
|
| 70 |
+
this.debugMode,
|
| 71 |
+
);
|
| 72 |
+
this.clients.set(name, client);
|
| 73 |
+
try {
|
| 74 |
+
await client.connect();
|
| 75 |
+
await client.discover();
|
| 76 |
+
} catch (error) {
|
| 77 |
+
// Log the error but don't let a single failed server stop the others
|
| 78 |
+
console.error(
|
| 79 |
+
`Error during discovery for server '${name}': ${getErrorMessage(
|
| 80 |
+
error,
|
| 81 |
+
)}`,
|
| 82 |
+
);
|
| 83 |
+
}
|
| 84 |
+
},
|
| 85 |
+
);
|
| 86 |
+
|
| 87 |
+
await Promise.all(discoveryPromises);
|
| 88 |
+
this.discoveryState = MCPDiscoveryState.COMPLETED;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
/**
|
| 92 |
+
* Stops all running local MCP servers and closes all client connections.
|
| 93 |
+
* This is the cleanup method to be called on application exit.
|
| 94 |
+
*/
|
| 95 |
+
async stop(): Promise<void> {
|
| 96 |
+
const disconnectionPromises = Array.from(this.clients.entries()).map(
|
| 97 |
+
async ([name, client]) => {
|
| 98 |
+
try {
|
| 99 |
+
await client.disconnect();
|
| 100 |
+
} catch (error) {
|
| 101 |
+
console.error(
|
| 102 |
+
`Error stopping client '${name}': ${getErrorMessage(error)}`,
|
| 103 |
+
);
|
| 104 |
+
}
|
| 105 |
+
},
|
| 106 |
+
);
|
| 107 |
+
|
| 108 |
+
await Promise.all(disconnectionPromises);
|
| 109 |
+
this.clients.clear();
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
getDiscoveryState(): MCPDiscoveryState {
|
| 113 |
+
return this.discoveryState;
|
| 114 |
+
}
|
| 115 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/mcp-client.test.ts
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
| 8 |
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
| 9 |
+
import {
|
| 10 |
+
populateMcpServerCommand,
|
| 11 |
+
createTransport,
|
| 12 |
+
isEnabled,
|
| 13 |
+
hasValidTypes,
|
| 14 |
+
McpClient,
|
| 15 |
+
} from './mcp-client.js';
|
| 16 |
+
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
|
| 17 |
+
import * as SdkClientStdioLib from '@modelcontextprotocol/sdk/client/stdio.js';
|
| 18 |
+
import * as ClientLib from '@modelcontextprotocol/sdk/client/index.js';
|
| 19 |
+
import * as GenAiLib from '@google/genai';
|
| 20 |
+
import { GoogleCredentialProvider } from '../mcp/google-auth-provider.js';
|
| 21 |
+
import { AuthProviderType } from '../config/config.js';
|
| 22 |
+
import { PromptRegistry } from '../prompts/prompt-registry.js';
|
| 23 |
+
import { ToolRegistry } from './tool-registry.js';
|
| 24 |
+
import { WorkspaceContext } from '../utils/workspaceContext.js';
|
| 25 |
+
|
| 26 |
+
vi.mock('@modelcontextprotocol/sdk/client/stdio.js');
|
| 27 |
+
vi.mock('@modelcontextprotocol/sdk/client/index.js');
|
| 28 |
+
vi.mock('@google/genai');
|
| 29 |
+
vi.mock('../mcp/oauth-provider.js');
|
| 30 |
+
vi.mock('../mcp/oauth-token-storage.js');
|
| 31 |
+
|
| 32 |
+
describe('mcp-client', () => {
|
| 33 |
+
afterEach(() => {
|
| 34 |
+
vi.restoreAllMocks();
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
describe('McpClient', () => {
|
| 38 |
+
it('should discover tools', async () => {
|
| 39 |
+
const mockedClient = {
|
| 40 |
+
connect: vi.fn(),
|
| 41 |
+
discover: vi.fn(),
|
| 42 |
+
disconnect: vi.fn(),
|
| 43 |
+
getStatus: vi.fn(),
|
| 44 |
+
registerCapabilities: vi.fn(),
|
| 45 |
+
setRequestHandler: vi.fn(),
|
| 46 |
+
};
|
| 47 |
+
vi.mocked(ClientLib.Client).mockReturnValue(
|
| 48 |
+
mockedClient as unknown as ClientLib.Client,
|
| 49 |
+
);
|
| 50 |
+
vi.spyOn(SdkClientStdioLib, 'StdioClientTransport').mockReturnValue(
|
| 51 |
+
{} as SdkClientStdioLib.StdioClientTransport,
|
| 52 |
+
);
|
| 53 |
+
const mockedMcpToTool = vi.mocked(GenAiLib.mcpToTool).mockReturnValue({
|
| 54 |
+
tool: () => ({
|
| 55 |
+
functionDeclarations: [
|
| 56 |
+
{
|
| 57 |
+
name: 'testFunction',
|
| 58 |
+
},
|
| 59 |
+
],
|
| 60 |
+
}),
|
| 61 |
+
} as unknown as GenAiLib.CallableTool);
|
| 62 |
+
const mockedToolRegistry = {
|
| 63 |
+
registerTool: vi.fn(),
|
| 64 |
+
} as unknown as ToolRegistry;
|
| 65 |
+
const client = new McpClient(
|
| 66 |
+
'test-server',
|
| 67 |
+
{
|
| 68 |
+
command: 'test-command',
|
| 69 |
+
},
|
| 70 |
+
mockedToolRegistry,
|
| 71 |
+
{} as PromptRegistry,
|
| 72 |
+
{} as WorkspaceContext,
|
| 73 |
+
false,
|
| 74 |
+
);
|
| 75 |
+
await client.connect();
|
| 76 |
+
await client.discover();
|
| 77 |
+
expect(mockedMcpToTool).toHaveBeenCalledOnce();
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
it('should skip tools if a parameter is missing a type', async () => {
|
| 81 |
+
const consoleWarnSpy = vi
|
| 82 |
+
.spyOn(console, 'warn')
|
| 83 |
+
.mockImplementation(() => {});
|
| 84 |
+
const mockedClient = {
|
| 85 |
+
connect: vi.fn(),
|
| 86 |
+
discover: vi.fn(),
|
| 87 |
+
disconnect: vi.fn(),
|
| 88 |
+
getStatus: vi.fn(),
|
| 89 |
+
registerCapabilities: vi.fn(),
|
| 90 |
+
setRequestHandler: vi.fn(),
|
| 91 |
+
tool: vi.fn(),
|
| 92 |
+
};
|
| 93 |
+
vi.mocked(ClientLib.Client).mockReturnValue(
|
| 94 |
+
mockedClient as unknown as ClientLib.Client,
|
| 95 |
+
);
|
| 96 |
+
vi.spyOn(SdkClientStdioLib, 'StdioClientTransport').mockReturnValue(
|
| 97 |
+
{} as SdkClientStdioLib.StdioClientTransport,
|
| 98 |
+
);
|
| 99 |
+
vi.mocked(GenAiLib.mcpToTool).mockReturnValue({
|
| 100 |
+
tool: () =>
|
| 101 |
+
Promise.resolve({
|
| 102 |
+
functionDeclarations: [
|
| 103 |
+
{
|
| 104 |
+
name: 'validTool',
|
| 105 |
+
parametersJsonSchema: {
|
| 106 |
+
type: 'object',
|
| 107 |
+
properties: {
|
| 108 |
+
param1: { type: 'string' },
|
| 109 |
+
},
|
| 110 |
+
},
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
name: 'invalidTool',
|
| 114 |
+
parametersJsonSchema: {
|
| 115 |
+
type: 'object',
|
| 116 |
+
properties: {
|
| 117 |
+
param1: { description: 'a param with no type' },
|
| 118 |
+
},
|
| 119 |
+
},
|
| 120 |
+
},
|
| 121 |
+
],
|
| 122 |
+
}),
|
| 123 |
+
} as unknown as GenAiLib.CallableTool);
|
| 124 |
+
const mockedToolRegistry = {
|
| 125 |
+
registerTool: vi.fn(),
|
| 126 |
+
} as unknown as ToolRegistry;
|
| 127 |
+
const client = new McpClient(
|
| 128 |
+
'test-server',
|
| 129 |
+
{
|
| 130 |
+
command: 'test-command',
|
| 131 |
+
},
|
| 132 |
+
mockedToolRegistry,
|
| 133 |
+
{} as PromptRegistry,
|
| 134 |
+
{} as WorkspaceContext,
|
| 135 |
+
false,
|
| 136 |
+
);
|
| 137 |
+
await client.connect();
|
| 138 |
+
await client.discover();
|
| 139 |
+
expect(mockedToolRegistry.registerTool).toHaveBeenCalledOnce();
|
| 140 |
+
expect(consoleWarnSpy).toHaveBeenCalledOnce();
|
| 141 |
+
expect(consoleWarnSpy).toHaveBeenCalledWith(
|
| 142 |
+
`Skipping tool 'invalidTool' from MCP server 'test-server' because it has ` +
|
| 143 |
+
`missing types in its parameter schema. Please file an issue with the owner of the MCP server.`,
|
| 144 |
+
);
|
| 145 |
+
consoleWarnSpy.mockRestore();
|
| 146 |
+
});
|
| 147 |
+
|
| 148 |
+
it('should handle errors when discovering prompts', async () => {
|
| 149 |
+
const consoleErrorSpy = vi
|
| 150 |
+
.spyOn(console, 'error')
|
| 151 |
+
.mockImplementation(() => {});
|
| 152 |
+
const mockedClient = {
|
| 153 |
+
connect: vi.fn(),
|
| 154 |
+
discover: vi.fn(),
|
| 155 |
+
disconnect: vi.fn(),
|
| 156 |
+
getStatus: vi.fn(),
|
| 157 |
+
registerCapabilities: vi.fn(),
|
| 158 |
+
setRequestHandler: vi.fn(),
|
| 159 |
+
getServerCapabilities: vi.fn().mockReturnValue({ prompts: {} }),
|
| 160 |
+
request: vi.fn().mockRejectedValue(new Error('Test error')),
|
| 161 |
+
};
|
| 162 |
+
vi.mocked(ClientLib.Client).mockReturnValue(
|
| 163 |
+
mockedClient as unknown as ClientLib.Client,
|
| 164 |
+
);
|
| 165 |
+
vi.spyOn(SdkClientStdioLib, 'StdioClientTransport').mockReturnValue(
|
| 166 |
+
{} as SdkClientStdioLib.StdioClientTransport,
|
| 167 |
+
);
|
| 168 |
+
vi.mocked(GenAiLib.mcpToTool).mockReturnValue({
|
| 169 |
+
tool: () => Promise.resolve({ functionDeclarations: [] }),
|
| 170 |
+
} as unknown as GenAiLib.CallableTool);
|
| 171 |
+
const client = new McpClient(
|
| 172 |
+
'test-server',
|
| 173 |
+
{
|
| 174 |
+
command: 'test-command',
|
| 175 |
+
},
|
| 176 |
+
{} as ToolRegistry,
|
| 177 |
+
{} as PromptRegistry,
|
| 178 |
+
{} as WorkspaceContext,
|
| 179 |
+
false,
|
| 180 |
+
);
|
| 181 |
+
await client.connect();
|
| 182 |
+
await expect(client.discover()).rejects.toThrow(
|
| 183 |
+
'No prompts or tools found on the server.',
|
| 184 |
+
);
|
| 185 |
+
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
| 186 |
+
`Error discovering prompts from test-server: Test error`,
|
| 187 |
+
);
|
| 188 |
+
consoleErrorSpy.mockRestore();
|
| 189 |
+
});
|
| 190 |
+
});
|
| 191 |
+
describe('appendMcpServerCommand', () => {
|
| 192 |
+
it('should do nothing if no MCP servers or command are configured', () => {
|
| 193 |
+
const out = populateMcpServerCommand({}, undefined);
|
| 194 |
+
expect(out).toEqual({});
|
| 195 |
+
});
|
| 196 |
+
|
| 197 |
+
it('should discover tools via mcpServerCommand', () => {
|
| 198 |
+
const commandString = 'command --arg1 value1';
|
| 199 |
+
const out = populateMcpServerCommand({}, commandString);
|
| 200 |
+
expect(out).toEqual({
|
| 201 |
+
mcp: {
|
| 202 |
+
command: 'command',
|
| 203 |
+
args: ['--arg1', 'value1'],
|
| 204 |
+
},
|
| 205 |
+
});
|
| 206 |
+
});
|
| 207 |
+
|
| 208 |
+
it('should handle error if mcpServerCommand parsing fails', () => {
|
| 209 |
+
expect(() => populateMcpServerCommand({}, 'derp && herp')).toThrowError();
|
| 210 |
+
});
|
| 211 |
+
});
|
| 212 |
+
|
| 213 |
+
describe('createTransport', () => {
|
| 214 |
+
describe('should connect via httpUrl', () => {
|
| 215 |
+
it('without headers', async () => {
|
| 216 |
+
const transport = await createTransport(
|
| 217 |
+
'test-server',
|
| 218 |
+
{
|
| 219 |
+
httpUrl: 'http://test-server',
|
| 220 |
+
},
|
| 221 |
+
false,
|
| 222 |
+
);
|
| 223 |
+
|
| 224 |
+
expect(transport).toEqual(
|
| 225 |
+
new StreamableHTTPClientTransport(new URL('http://test-server'), {}),
|
| 226 |
+
);
|
| 227 |
+
});
|
| 228 |
+
|
| 229 |
+
it('with headers', async () => {
|
| 230 |
+
const transport = await createTransport(
|
| 231 |
+
'test-server',
|
| 232 |
+
{
|
| 233 |
+
httpUrl: 'http://test-server',
|
| 234 |
+
headers: { Authorization: 'derp' },
|
| 235 |
+
},
|
| 236 |
+
false,
|
| 237 |
+
);
|
| 238 |
+
|
| 239 |
+
expect(transport).toEqual(
|
| 240 |
+
new StreamableHTTPClientTransport(new URL('http://test-server'), {
|
| 241 |
+
requestInit: {
|
| 242 |
+
headers: { Authorization: 'derp' },
|
| 243 |
+
},
|
| 244 |
+
}),
|
| 245 |
+
);
|
| 246 |
+
});
|
| 247 |
+
});
|
| 248 |
+
|
| 249 |
+
describe('should connect via url', () => {
|
| 250 |
+
it('without headers', async () => {
|
| 251 |
+
const transport = await createTransport(
|
| 252 |
+
'test-server',
|
| 253 |
+
{
|
| 254 |
+
url: 'http://test-server',
|
| 255 |
+
},
|
| 256 |
+
false,
|
| 257 |
+
);
|
| 258 |
+
expect(transport).toEqual(
|
| 259 |
+
new SSEClientTransport(new URL('http://test-server'), {}),
|
| 260 |
+
);
|
| 261 |
+
});
|
| 262 |
+
|
| 263 |
+
it('with headers', async () => {
|
| 264 |
+
const transport = await createTransport(
|
| 265 |
+
'test-server',
|
| 266 |
+
{
|
| 267 |
+
url: 'http://test-server',
|
| 268 |
+
headers: { Authorization: 'derp' },
|
| 269 |
+
},
|
| 270 |
+
false,
|
| 271 |
+
);
|
| 272 |
+
|
| 273 |
+
expect(transport).toEqual(
|
| 274 |
+
new SSEClientTransport(new URL('http://test-server'), {
|
| 275 |
+
requestInit: {
|
| 276 |
+
headers: { Authorization: 'derp' },
|
| 277 |
+
},
|
| 278 |
+
}),
|
| 279 |
+
);
|
| 280 |
+
});
|
| 281 |
+
});
|
| 282 |
+
|
| 283 |
+
it('should connect via command', async () => {
|
| 284 |
+
const mockedTransport = vi
|
| 285 |
+
.spyOn(SdkClientStdioLib, 'StdioClientTransport')
|
| 286 |
+
.mockReturnValue({} as SdkClientStdioLib.StdioClientTransport);
|
| 287 |
+
|
| 288 |
+
await createTransport(
|
| 289 |
+
'test-server',
|
| 290 |
+
{
|
| 291 |
+
command: 'test-command',
|
| 292 |
+
args: ['--foo', 'bar'],
|
| 293 |
+
env: { FOO: 'bar' },
|
| 294 |
+
cwd: 'test/cwd',
|
| 295 |
+
},
|
| 296 |
+
false,
|
| 297 |
+
);
|
| 298 |
+
|
| 299 |
+
expect(mockedTransport).toHaveBeenCalledWith({
|
| 300 |
+
command: 'test-command',
|
| 301 |
+
args: ['--foo', 'bar'],
|
| 302 |
+
cwd: 'test/cwd',
|
| 303 |
+
env: { ...process.env, FOO: 'bar' },
|
| 304 |
+
stderr: 'pipe',
|
| 305 |
+
});
|
| 306 |
+
});
|
| 307 |
+
|
| 308 |
+
describe('useGoogleCredentialProvider', () => {
|
| 309 |
+
it('should use GoogleCredentialProvider when specified', async () => {
|
| 310 |
+
const transport = await createTransport(
|
| 311 |
+
'test-server',
|
| 312 |
+
{
|
| 313 |
+
httpUrl: 'http://test.googleapis.com',
|
| 314 |
+
authProviderType: AuthProviderType.GOOGLE_CREDENTIALS,
|
| 315 |
+
oauth: {
|
| 316 |
+
scopes: ['scope1'],
|
| 317 |
+
},
|
| 318 |
+
},
|
| 319 |
+
false,
|
| 320 |
+
);
|
| 321 |
+
|
| 322 |
+
expect(transport).toBeInstanceOf(StreamableHTTPClientTransport);
|
| 323 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 324 |
+
const authProvider = (transport as any)._authProvider;
|
| 325 |
+
expect(authProvider).toBeInstanceOf(GoogleCredentialProvider);
|
| 326 |
+
});
|
| 327 |
+
|
| 328 |
+
it('should use GoogleCredentialProvider with SSE transport', async () => {
|
| 329 |
+
const transport = await createTransport(
|
| 330 |
+
'test-server',
|
| 331 |
+
{
|
| 332 |
+
url: 'http://test.googleapis.com',
|
| 333 |
+
authProviderType: AuthProviderType.GOOGLE_CREDENTIALS,
|
| 334 |
+
oauth: {
|
| 335 |
+
scopes: ['scope1'],
|
| 336 |
+
},
|
| 337 |
+
},
|
| 338 |
+
false,
|
| 339 |
+
);
|
| 340 |
+
|
| 341 |
+
expect(transport).toBeInstanceOf(SSEClientTransport);
|
| 342 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 343 |
+
const authProvider = (transport as any)._authProvider;
|
| 344 |
+
expect(authProvider).toBeInstanceOf(GoogleCredentialProvider);
|
| 345 |
+
});
|
| 346 |
+
|
| 347 |
+
it('should throw an error if no URL is provided with GoogleCredentialProvider', async () => {
|
| 348 |
+
await expect(
|
| 349 |
+
createTransport(
|
| 350 |
+
'test-server',
|
| 351 |
+
{
|
| 352 |
+
authProviderType: AuthProviderType.GOOGLE_CREDENTIALS,
|
| 353 |
+
oauth: {
|
| 354 |
+
scopes: ['scope1'],
|
| 355 |
+
},
|
| 356 |
+
},
|
| 357 |
+
false,
|
| 358 |
+
),
|
| 359 |
+
).rejects.toThrow(
|
| 360 |
+
'URL must be provided in the config for Google Credentials provider',
|
| 361 |
+
);
|
| 362 |
+
});
|
| 363 |
+
});
|
| 364 |
+
});
|
| 365 |
+
describe('isEnabled', () => {
|
| 366 |
+
const funcDecl = { name: 'myTool' };
|
| 367 |
+
const serverName = 'myServer';
|
| 368 |
+
|
| 369 |
+
it('should return true if no include or exclude lists are provided', () => {
|
| 370 |
+
const mcpServerConfig = {};
|
| 371 |
+
expect(isEnabled(funcDecl, serverName, mcpServerConfig)).toBe(true);
|
| 372 |
+
});
|
| 373 |
+
|
| 374 |
+
it('should return false if the tool is in the exclude list', () => {
|
| 375 |
+
const mcpServerConfig = { excludeTools: ['myTool'] };
|
| 376 |
+
expect(isEnabled(funcDecl, serverName, mcpServerConfig)).toBe(false);
|
| 377 |
+
});
|
| 378 |
+
|
| 379 |
+
it('should return true if the tool is in the include list', () => {
|
| 380 |
+
const mcpServerConfig = { includeTools: ['myTool'] };
|
| 381 |
+
expect(isEnabled(funcDecl, serverName, mcpServerConfig)).toBe(true);
|
| 382 |
+
});
|
| 383 |
+
|
| 384 |
+
it('should return true if the tool is in the include list with parentheses', () => {
|
| 385 |
+
const mcpServerConfig = { includeTools: ['myTool()'] };
|
| 386 |
+
expect(isEnabled(funcDecl, serverName, mcpServerConfig)).toBe(true);
|
| 387 |
+
});
|
| 388 |
+
|
| 389 |
+
it('should return false if the include list exists but does not contain the tool', () => {
|
| 390 |
+
const mcpServerConfig = { includeTools: ['anotherTool'] };
|
| 391 |
+
expect(isEnabled(funcDecl, serverName, mcpServerConfig)).toBe(false);
|
| 392 |
+
});
|
| 393 |
+
|
| 394 |
+
it('should return false if the tool is in both the include and exclude lists', () => {
|
| 395 |
+
const mcpServerConfig = {
|
| 396 |
+
includeTools: ['myTool'],
|
| 397 |
+
excludeTools: ['myTool'],
|
| 398 |
+
};
|
| 399 |
+
expect(isEnabled(funcDecl, serverName, mcpServerConfig)).toBe(false);
|
| 400 |
+
});
|
| 401 |
+
|
| 402 |
+
it('should return false if the function declaration has no name', () => {
|
| 403 |
+
const namelessFuncDecl = {};
|
| 404 |
+
const mcpServerConfig = {};
|
| 405 |
+
expect(isEnabled(namelessFuncDecl, serverName, mcpServerConfig)).toBe(
|
| 406 |
+
false,
|
| 407 |
+
);
|
| 408 |
+
});
|
| 409 |
+
});
|
| 410 |
+
|
| 411 |
+
describe('hasValidTypes', () => {
|
| 412 |
+
it('should return true for a valid schema with anyOf', () => {
|
| 413 |
+
const schema = {
|
| 414 |
+
anyOf: [{ type: 'string' }, { type: 'number' }],
|
| 415 |
+
};
|
| 416 |
+
expect(hasValidTypes(schema)).toBe(true);
|
| 417 |
+
});
|
| 418 |
+
|
| 419 |
+
it('should return false for an invalid schema with anyOf', () => {
|
| 420 |
+
const schema = {
|
| 421 |
+
anyOf: [{ type: 'string' }, { description: 'no type' }],
|
| 422 |
+
};
|
| 423 |
+
expect(hasValidTypes(schema)).toBe(false);
|
| 424 |
+
});
|
| 425 |
+
|
| 426 |
+
it('should return true for a valid schema with allOf', () => {
|
| 427 |
+
const schema = {
|
| 428 |
+
allOf: [
|
| 429 |
+
{ type: 'string' },
|
| 430 |
+
{ type: 'object', properties: { foo: { type: 'string' } } },
|
| 431 |
+
],
|
| 432 |
+
};
|
| 433 |
+
expect(hasValidTypes(schema)).toBe(true);
|
| 434 |
+
});
|
| 435 |
+
|
| 436 |
+
it('should return false for an invalid schema with allOf', () => {
|
| 437 |
+
const schema = {
|
| 438 |
+
allOf: [{ type: 'string' }, { description: 'no type' }],
|
| 439 |
+
};
|
| 440 |
+
expect(hasValidTypes(schema)).toBe(false);
|
| 441 |
+
});
|
| 442 |
+
|
| 443 |
+
it('should return true for a valid schema with oneOf', () => {
|
| 444 |
+
const schema = {
|
| 445 |
+
oneOf: [{ type: 'string' }, { type: 'number' }],
|
| 446 |
+
};
|
| 447 |
+
expect(hasValidTypes(schema)).toBe(true);
|
| 448 |
+
});
|
| 449 |
+
|
| 450 |
+
it('should return false for an invalid schema with oneOf', () => {
|
| 451 |
+
const schema = {
|
| 452 |
+
oneOf: [{ type: 'string' }, { description: 'no type' }],
|
| 453 |
+
};
|
| 454 |
+
expect(hasValidTypes(schema)).toBe(false);
|
| 455 |
+
});
|
| 456 |
+
|
| 457 |
+
it('should return true for a valid schema with nested subschemas', () => {
|
| 458 |
+
const schema = {
|
| 459 |
+
anyOf: [
|
| 460 |
+
{ type: 'string' },
|
| 461 |
+
{
|
| 462 |
+
allOf: [
|
| 463 |
+
{ type: 'object', properties: { a: { type: 'string' } } },
|
| 464 |
+
{ type: 'object', properties: { b: { type: 'number' } } },
|
| 465 |
+
],
|
| 466 |
+
},
|
| 467 |
+
],
|
| 468 |
+
};
|
| 469 |
+
expect(hasValidTypes(schema)).toBe(true);
|
| 470 |
+
});
|
| 471 |
+
|
| 472 |
+
it('should return false for an invalid schema with nested subschemas', () => {
|
| 473 |
+
const schema = {
|
| 474 |
+
anyOf: [
|
| 475 |
+
{ type: 'string' },
|
| 476 |
+
{
|
| 477 |
+
allOf: [
|
| 478 |
+
{ type: 'object', properties: { a: { type: 'string' } } },
|
| 479 |
+
{ description: 'no type' },
|
| 480 |
+
],
|
| 481 |
+
},
|
| 482 |
+
],
|
| 483 |
+
};
|
| 484 |
+
expect(hasValidTypes(schema)).toBe(false);
|
| 485 |
+
});
|
| 486 |
+
|
| 487 |
+
it('should return true for a schema with a type and subschemas', () => {
|
| 488 |
+
const schema = {
|
| 489 |
+
type: 'string',
|
| 490 |
+
anyOf: [{ minLength: 1 }, { maxLength: 5 }],
|
| 491 |
+
};
|
| 492 |
+
expect(hasValidTypes(schema)).toBe(true);
|
| 493 |
+
});
|
| 494 |
+
|
| 495 |
+
it('should return false for a schema with no type and no subschemas', () => {
|
| 496 |
+
const schema = {
|
| 497 |
+
description: 'a schema with no type',
|
| 498 |
+
};
|
| 499 |
+
expect(hasValidTypes(schema)).toBe(false);
|
| 500 |
+
});
|
| 501 |
+
|
| 502 |
+
it('should return true for a valid schema', () => {
|
| 503 |
+
const schema = {
|
| 504 |
+
type: 'object',
|
| 505 |
+
properties: {
|
| 506 |
+
param1: { type: 'string' },
|
| 507 |
+
},
|
| 508 |
+
};
|
| 509 |
+
expect(hasValidTypes(schema)).toBe(true);
|
| 510 |
+
});
|
| 511 |
+
|
| 512 |
+
it('should return false if a parameter is missing a type', () => {
|
| 513 |
+
const schema = {
|
| 514 |
+
type: 'object',
|
| 515 |
+
properties: {
|
| 516 |
+
param1: { description: 'a param with no type' },
|
| 517 |
+
},
|
| 518 |
+
};
|
| 519 |
+
expect(hasValidTypes(schema)).toBe(false);
|
| 520 |
+
});
|
| 521 |
+
|
| 522 |
+
it('should return false if a nested parameter is missing a type', () => {
|
| 523 |
+
const schema = {
|
| 524 |
+
type: 'object',
|
| 525 |
+
properties: {
|
| 526 |
+
param1: {
|
| 527 |
+
type: 'object',
|
| 528 |
+
properties: {
|
| 529 |
+
nestedParam: {
|
| 530 |
+
description: 'a nested param with no type',
|
| 531 |
+
},
|
| 532 |
+
},
|
| 533 |
+
},
|
| 534 |
+
},
|
| 535 |
+
};
|
| 536 |
+
expect(hasValidTypes(schema)).toBe(false);
|
| 537 |
+
});
|
| 538 |
+
|
| 539 |
+
it('should return false if an array item is missing a type', () => {
|
| 540 |
+
const schema = {
|
| 541 |
+
type: 'object',
|
| 542 |
+
properties: {
|
| 543 |
+
param1: {
|
| 544 |
+
type: 'array',
|
| 545 |
+
items: {
|
| 546 |
+
description: 'an array item with no type',
|
| 547 |
+
},
|
| 548 |
+
},
|
| 549 |
+
},
|
| 550 |
+
};
|
| 551 |
+
expect(hasValidTypes(schema)).toBe(false);
|
| 552 |
+
});
|
| 553 |
+
|
| 554 |
+
it('should return true for a schema with no properties', () => {
|
| 555 |
+
const schema = {
|
| 556 |
+
type: 'object',
|
| 557 |
+
};
|
| 558 |
+
expect(hasValidTypes(schema)).toBe(true);
|
| 559 |
+
});
|
| 560 |
+
|
| 561 |
+
it('should return true for a schema with an empty properties object', () => {
|
| 562 |
+
const schema = {
|
| 563 |
+
type: 'object',
|
| 564 |
+
properties: {},
|
| 565 |
+
};
|
| 566 |
+
expect(hasValidTypes(schema)).toBe(true);
|
| 567 |
+
});
|
| 568 |
+
});
|
| 569 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/mcp-client.ts
ADDED
|
@@ -0,0 +1,1375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
| 8 |
+
import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
|
| 9 |
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
| 10 |
+
import {
|
| 11 |
+
SSEClientTransport,
|
| 12 |
+
SSEClientTransportOptions,
|
| 13 |
+
} from '@modelcontextprotocol/sdk/client/sse.js';
|
| 14 |
+
import {
|
| 15 |
+
StreamableHTTPClientTransport,
|
| 16 |
+
StreamableHTTPClientTransportOptions,
|
| 17 |
+
} from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
| 18 |
+
import {
|
| 19 |
+
Prompt,
|
| 20 |
+
ListPromptsResultSchema,
|
| 21 |
+
GetPromptResult,
|
| 22 |
+
GetPromptResultSchema,
|
| 23 |
+
ListRootsRequestSchema,
|
| 24 |
+
} from '@modelcontextprotocol/sdk/types.js';
|
| 25 |
+
import { parse } from 'shell-quote';
|
| 26 |
+
import { AuthProviderType, MCPServerConfig } from '../config/config.js';
|
| 27 |
+
import { GoogleCredentialProvider } from '../mcp/google-auth-provider.js';
|
| 28 |
+
import { DiscoveredMCPTool } from './mcp-tool.js';
|
| 29 |
+
|
| 30 |
+
import { FunctionDeclaration, mcpToTool } from '@google/genai';
|
| 31 |
+
import { ToolRegistry } from './tool-registry.js';
|
| 32 |
+
import { PromptRegistry } from '../prompts/prompt-registry.js';
|
| 33 |
+
import { MCPOAuthProvider } from '../mcp/oauth-provider.js';
|
| 34 |
+
import { OAuthUtils } from '../mcp/oauth-utils.js';
|
| 35 |
+
import { MCPOAuthTokenStorage } from '../mcp/oauth-token-storage.js';
|
| 36 |
+
import { getErrorMessage } from '../utils/errors.js';
|
| 37 |
+
import { basename } from 'node:path';
|
| 38 |
+
import { pathToFileURL } from 'node:url';
|
| 39 |
+
import { Unsubscribe, WorkspaceContext } from '../utils/workspaceContext.js';
|
| 40 |
+
|
| 41 |
+
export const MCP_DEFAULT_TIMEOUT_MSEC = 10 * 60 * 1000; // default to 10 minutes
|
| 42 |
+
|
| 43 |
+
export type DiscoveredMCPPrompt = Prompt & {
|
| 44 |
+
serverName: string;
|
| 45 |
+
invoke: (params: Record<string, unknown>) => Promise<GetPromptResult>;
|
| 46 |
+
};
|
| 47 |
+
|
| 48 |
+
/**
|
| 49 |
+
* Enum representing the connection status of an MCP server
|
| 50 |
+
*/
|
| 51 |
+
export enum MCPServerStatus {
|
| 52 |
+
/** Server is disconnected or experiencing errors */
|
| 53 |
+
DISCONNECTED = 'disconnected',
|
| 54 |
+
/** Server is in the process of connecting */
|
| 55 |
+
CONNECTING = 'connecting',
|
| 56 |
+
/** Server is connected and ready to use */
|
| 57 |
+
CONNECTED = 'connected',
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/**
|
| 61 |
+
* Enum representing the overall MCP discovery state
|
| 62 |
+
*/
|
| 63 |
+
export enum MCPDiscoveryState {
|
| 64 |
+
/** Discovery has not started yet */
|
| 65 |
+
NOT_STARTED = 'not_started',
|
| 66 |
+
/** Discovery is currently in progress */
|
| 67 |
+
IN_PROGRESS = 'in_progress',
|
| 68 |
+
/** Discovery has completed (with or without errors) */
|
| 69 |
+
COMPLETED = 'completed',
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
/**
|
| 73 |
+
* A client for a single MCP server.
|
| 74 |
+
*
|
| 75 |
+
* This class is responsible for connecting to, discovering tools from, and
|
| 76 |
+
* managing the state of a single MCP server.
|
| 77 |
+
*/
|
| 78 |
+
export class McpClient {
|
| 79 |
+
private client: Client;
|
| 80 |
+
private transport: Transport | undefined;
|
| 81 |
+
private status: MCPServerStatus = MCPServerStatus.DISCONNECTED;
|
| 82 |
+
private isDisconnecting = false;
|
| 83 |
+
|
| 84 |
+
constructor(
|
| 85 |
+
private readonly serverName: string,
|
| 86 |
+
private readonly serverConfig: MCPServerConfig,
|
| 87 |
+
private readonly toolRegistry: ToolRegistry,
|
| 88 |
+
private readonly promptRegistry: PromptRegistry,
|
| 89 |
+
private readonly workspaceContext: WorkspaceContext,
|
| 90 |
+
private readonly debugMode: boolean,
|
| 91 |
+
) {
|
| 92 |
+
this.client = new Client({
|
| 93 |
+
name: `gemini-cli-mcp-client-${this.serverName}`,
|
| 94 |
+
version: '0.0.1',
|
| 95 |
+
});
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
/**
|
| 99 |
+
* Connects to the MCP server.
|
| 100 |
+
*/
|
| 101 |
+
async connect(): Promise<void> {
|
| 102 |
+
this.isDisconnecting = false;
|
| 103 |
+
this.updateStatus(MCPServerStatus.CONNECTING);
|
| 104 |
+
try {
|
| 105 |
+
this.transport = await this.createTransport();
|
| 106 |
+
|
| 107 |
+
this.client.onerror = (error) => {
|
| 108 |
+
if (this.isDisconnecting) {
|
| 109 |
+
return;
|
| 110 |
+
}
|
| 111 |
+
console.error(`MCP ERROR (${this.serverName}):`, error.toString());
|
| 112 |
+
this.updateStatus(MCPServerStatus.DISCONNECTED);
|
| 113 |
+
};
|
| 114 |
+
|
| 115 |
+
this.client.registerCapabilities({
|
| 116 |
+
roots: {},
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
this.client.setRequestHandler(ListRootsRequestSchema, async () => {
|
| 120 |
+
const roots = [];
|
| 121 |
+
for (const dir of this.workspaceContext.getDirectories()) {
|
| 122 |
+
roots.push({
|
| 123 |
+
uri: pathToFileURL(dir).toString(),
|
| 124 |
+
name: basename(dir),
|
| 125 |
+
});
|
| 126 |
+
}
|
| 127 |
+
return {
|
| 128 |
+
roots,
|
| 129 |
+
};
|
| 130 |
+
});
|
| 131 |
+
|
| 132 |
+
await this.client.connect(this.transport, {
|
| 133 |
+
timeout: this.serverConfig.timeout,
|
| 134 |
+
});
|
| 135 |
+
|
| 136 |
+
this.updateStatus(MCPServerStatus.CONNECTED);
|
| 137 |
+
} catch (error) {
|
| 138 |
+
this.updateStatus(MCPServerStatus.DISCONNECTED);
|
| 139 |
+
throw error;
|
| 140 |
+
}
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
/**
|
| 144 |
+
* Discovers tools and prompts from the MCP server.
|
| 145 |
+
*/
|
| 146 |
+
async discover(): Promise<void> {
|
| 147 |
+
if (this.status !== MCPServerStatus.CONNECTED) {
|
| 148 |
+
throw new Error('Client is not connected.');
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
const prompts = await this.discoverPrompts();
|
| 152 |
+
const tools = await this.discoverTools();
|
| 153 |
+
|
| 154 |
+
if (prompts.length === 0 && tools.length === 0) {
|
| 155 |
+
throw new Error('No prompts or tools found on the server.');
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
for (const tool of tools) {
|
| 159 |
+
this.toolRegistry.registerTool(tool);
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
/**
|
| 164 |
+
* Disconnects from the MCP server.
|
| 165 |
+
*/
|
| 166 |
+
async disconnect(): Promise<void> {
|
| 167 |
+
this.isDisconnecting = true;
|
| 168 |
+
if (this.transport) {
|
| 169 |
+
await this.transport.close();
|
| 170 |
+
}
|
| 171 |
+
this.client.close();
|
| 172 |
+
this.updateStatus(MCPServerStatus.DISCONNECTED);
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
/**
|
| 176 |
+
* Returns the current status of the client.
|
| 177 |
+
*/
|
| 178 |
+
getStatus(): MCPServerStatus {
|
| 179 |
+
return this.status;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
private updateStatus(status: MCPServerStatus): void {
|
| 183 |
+
this.status = status;
|
| 184 |
+
updateMCPServerStatus(this.serverName, status);
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
private async createTransport(): Promise<Transport> {
|
| 188 |
+
return createTransport(this.serverName, this.serverConfig, this.debugMode);
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
private async discoverTools(): Promise<DiscoveredMCPTool[]> {
|
| 192 |
+
return discoverTools(this.serverName, this.serverConfig, this.client);
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
private async discoverPrompts(): Promise<Prompt[]> {
|
| 196 |
+
return discoverPrompts(this.serverName, this.client, this.promptRegistry);
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
/**
|
| 201 |
+
* Map to track the status of each MCP server within the core package
|
| 202 |
+
*/
|
| 203 |
+
const serverStatuses: Map<string, MCPServerStatus> = new Map();
|
| 204 |
+
|
| 205 |
+
/**
|
| 206 |
+
* Track the overall MCP discovery state
|
| 207 |
+
*/
|
| 208 |
+
let mcpDiscoveryState: MCPDiscoveryState = MCPDiscoveryState.NOT_STARTED;
|
| 209 |
+
|
| 210 |
+
/**
|
| 211 |
+
* Map to track which MCP servers have been discovered to require OAuth
|
| 212 |
+
*/
|
| 213 |
+
export const mcpServerRequiresOAuth: Map<string, boolean> = new Map();
|
| 214 |
+
|
| 215 |
+
/**
|
| 216 |
+
* Event listeners for MCP server status changes
|
| 217 |
+
*/
|
| 218 |
+
type StatusChangeListener = (
|
| 219 |
+
serverName: string,
|
| 220 |
+
status: MCPServerStatus,
|
| 221 |
+
) => void;
|
| 222 |
+
const statusChangeListeners: StatusChangeListener[] = [];
|
| 223 |
+
|
| 224 |
+
/**
|
| 225 |
+
* Add a listener for MCP server status changes
|
| 226 |
+
*/
|
| 227 |
+
export function addMCPStatusChangeListener(
|
| 228 |
+
listener: StatusChangeListener,
|
| 229 |
+
): void {
|
| 230 |
+
statusChangeListeners.push(listener);
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
/**
|
| 234 |
+
* Remove a listener for MCP server status changes
|
| 235 |
+
*/
|
| 236 |
+
export function removeMCPStatusChangeListener(
|
| 237 |
+
listener: StatusChangeListener,
|
| 238 |
+
): void {
|
| 239 |
+
const index = statusChangeListeners.indexOf(listener);
|
| 240 |
+
if (index !== -1) {
|
| 241 |
+
statusChangeListeners.splice(index, 1);
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
/**
|
| 246 |
+
* Update the status of an MCP server
|
| 247 |
+
*/
|
| 248 |
+
export function updateMCPServerStatus(
|
| 249 |
+
serverName: string,
|
| 250 |
+
status: MCPServerStatus,
|
| 251 |
+
): void {
|
| 252 |
+
serverStatuses.set(serverName, status);
|
| 253 |
+
// Notify all listeners
|
| 254 |
+
for (const listener of statusChangeListeners) {
|
| 255 |
+
listener(serverName, status);
|
| 256 |
+
}
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
/**
|
| 260 |
+
* Get the current status of an MCP server
|
| 261 |
+
*/
|
| 262 |
+
export function getMCPServerStatus(serverName: string): MCPServerStatus {
|
| 263 |
+
return serverStatuses.get(serverName) || MCPServerStatus.DISCONNECTED;
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
/**
|
| 267 |
+
* Get all MCP server statuses
|
| 268 |
+
*/
|
| 269 |
+
export function getAllMCPServerStatuses(): Map<string, MCPServerStatus> {
|
| 270 |
+
return new Map(serverStatuses);
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
/**
|
| 274 |
+
* Get the current MCP discovery state
|
| 275 |
+
*/
|
| 276 |
+
export function getMCPDiscoveryState(): MCPDiscoveryState {
|
| 277 |
+
return mcpDiscoveryState;
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
/**
|
| 281 |
+
* Extract WWW-Authenticate header from error message string.
|
| 282 |
+
* This is a more robust approach than regex matching.
|
| 283 |
+
*
|
| 284 |
+
* @param errorString The error message string
|
| 285 |
+
* @returns The www-authenticate header value if found, null otherwise
|
| 286 |
+
*/
|
| 287 |
+
function extractWWWAuthenticateHeader(errorString: string): string | null {
|
| 288 |
+
// Try multiple patterns to extract the header
|
| 289 |
+
const patterns = [
|
| 290 |
+
/www-authenticate:\s*([^\n\r]+)/i,
|
| 291 |
+
/WWW-Authenticate:\s*([^\n\r]+)/i,
|
| 292 |
+
/"www-authenticate":\s*"([^"]+)"/i,
|
| 293 |
+
/'www-authenticate':\s*'([^']+)'/i,
|
| 294 |
+
];
|
| 295 |
+
|
| 296 |
+
for (const pattern of patterns) {
|
| 297 |
+
const match = errorString.match(pattern);
|
| 298 |
+
if (match) {
|
| 299 |
+
return match[1].trim();
|
| 300 |
+
}
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
return null;
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
/**
|
| 307 |
+
* Handle automatic OAuth discovery and authentication for a server.
|
| 308 |
+
*
|
| 309 |
+
* @param mcpServerName The name of the MCP server
|
| 310 |
+
* @param mcpServerConfig The MCP server configuration
|
| 311 |
+
* @param wwwAuthenticate The www-authenticate header value
|
| 312 |
+
* @returns True if OAuth was successfully configured and authenticated, false otherwise
|
| 313 |
+
*/
|
| 314 |
+
async function handleAutomaticOAuth(
|
| 315 |
+
mcpServerName: string,
|
| 316 |
+
mcpServerConfig: MCPServerConfig,
|
| 317 |
+
wwwAuthenticate: string,
|
| 318 |
+
): Promise<boolean> {
|
| 319 |
+
try {
|
| 320 |
+
console.log(`🔐 '${mcpServerName}' requires OAuth authentication`);
|
| 321 |
+
|
| 322 |
+
// Always try to parse the resource metadata URI from the www-authenticate header
|
| 323 |
+
let oauthConfig;
|
| 324 |
+
const resourceMetadataUri =
|
| 325 |
+
OAuthUtils.parseWWWAuthenticateHeader(wwwAuthenticate);
|
| 326 |
+
if (resourceMetadataUri) {
|
| 327 |
+
oauthConfig = await OAuthUtils.discoverOAuthConfig(resourceMetadataUri);
|
| 328 |
+
} else if (mcpServerConfig.url) {
|
| 329 |
+
// Fallback: try to discover OAuth config from the base URL for SSE
|
| 330 |
+
const sseUrl = new URL(mcpServerConfig.url);
|
| 331 |
+
const baseUrl = `${sseUrl.protocol}//${sseUrl.host}`;
|
| 332 |
+
oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
|
| 333 |
+
} else if (mcpServerConfig.httpUrl) {
|
| 334 |
+
// Fallback: try to discover OAuth config from the base URL for HTTP
|
| 335 |
+
const httpUrl = new URL(mcpServerConfig.httpUrl);
|
| 336 |
+
const baseUrl = `${httpUrl.protocol}//${httpUrl.host}`;
|
| 337 |
+
oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
if (!oauthConfig) {
|
| 341 |
+
console.error(
|
| 342 |
+
`❌ Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`,
|
| 343 |
+
);
|
| 344 |
+
return false;
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
// OAuth configuration discovered - proceed with authentication
|
| 348 |
+
|
| 349 |
+
// Create OAuth configuration for authentication
|
| 350 |
+
const oauthAuthConfig = {
|
| 351 |
+
enabled: true,
|
| 352 |
+
authorizationUrl: oauthConfig.authorizationUrl,
|
| 353 |
+
tokenUrl: oauthConfig.tokenUrl,
|
| 354 |
+
scopes: oauthConfig.scopes || [],
|
| 355 |
+
};
|
| 356 |
+
|
| 357 |
+
// Perform OAuth authentication
|
| 358 |
+
// Pass the server URL for proper discovery
|
| 359 |
+
const serverUrl = mcpServerConfig.httpUrl || mcpServerConfig.url;
|
| 360 |
+
console.log(
|
| 361 |
+
`Starting OAuth authentication for server '${mcpServerName}'...`,
|
| 362 |
+
);
|
| 363 |
+
await MCPOAuthProvider.authenticate(
|
| 364 |
+
mcpServerName,
|
| 365 |
+
oauthAuthConfig,
|
| 366 |
+
serverUrl,
|
| 367 |
+
);
|
| 368 |
+
|
| 369 |
+
console.log(
|
| 370 |
+
`OAuth authentication successful for server '${mcpServerName}'`,
|
| 371 |
+
);
|
| 372 |
+
return true;
|
| 373 |
+
} catch (error) {
|
| 374 |
+
console.error(
|
| 375 |
+
`Failed to handle automatic OAuth for server '${mcpServerName}': ${getErrorMessage(error)}`,
|
| 376 |
+
);
|
| 377 |
+
return false;
|
| 378 |
+
}
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
/**
|
| 382 |
+
* Create a transport with OAuth token for the given server configuration.
|
| 383 |
+
*
|
| 384 |
+
* @param mcpServerName The name of the MCP server
|
| 385 |
+
* @param mcpServerConfig The MCP server configuration
|
| 386 |
+
* @param accessToken The OAuth access token
|
| 387 |
+
* @returns The transport with OAuth token, or null if creation fails
|
| 388 |
+
*/
|
| 389 |
+
async function createTransportWithOAuth(
|
| 390 |
+
mcpServerName: string,
|
| 391 |
+
mcpServerConfig: MCPServerConfig,
|
| 392 |
+
accessToken: string,
|
| 393 |
+
): Promise<StreamableHTTPClientTransport | SSEClientTransport | null> {
|
| 394 |
+
try {
|
| 395 |
+
if (mcpServerConfig.httpUrl) {
|
| 396 |
+
// Create HTTP transport with OAuth token
|
| 397 |
+
const oauthTransportOptions: StreamableHTTPClientTransportOptions = {
|
| 398 |
+
requestInit: {
|
| 399 |
+
headers: {
|
| 400 |
+
...mcpServerConfig.headers,
|
| 401 |
+
Authorization: `Bearer ${accessToken}`,
|
| 402 |
+
},
|
| 403 |
+
},
|
| 404 |
+
};
|
| 405 |
+
|
| 406 |
+
return new StreamableHTTPClientTransport(
|
| 407 |
+
new URL(mcpServerConfig.httpUrl),
|
| 408 |
+
oauthTransportOptions,
|
| 409 |
+
);
|
| 410 |
+
} else if (mcpServerConfig.url) {
|
| 411 |
+
// Create SSE transport with OAuth token in Authorization header
|
| 412 |
+
return new SSEClientTransport(new URL(mcpServerConfig.url), {
|
| 413 |
+
requestInit: {
|
| 414 |
+
headers: {
|
| 415 |
+
...mcpServerConfig.headers,
|
| 416 |
+
Authorization: `Bearer ${accessToken}`,
|
| 417 |
+
},
|
| 418 |
+
},
|
| 419 |
+
});
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
return null;
|
| 423 |
+
} catch (error) {
|
| 424 |
+
console.error(
|
| 425 |
+
`Failed to create OAuth transport for server '${mcpServerName}': ${getErrorMessage(error)}`,
|
| 426 |
+
);
|
| 427 |
+
return null;
|
| 428 |
+
}
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
/**
|
| 432 |
+
* Discovers tools from all configured MCP servers and registers them with the tool registry.
|
| 433 |
+
* It orchestrates the connection and discovery process for each server defined in the
|
| 434 |
+
* configuration, as well as any server specified via a command-line argument.
|
| 435 |
+
*
|
| 436 |
+
* @param mcpServers A record of named MCP server configurations.
|
| 437 |
+
* @param mcpServerCommand An optional command string for a dynamically specified MCP server.
|
| 438 |
+
* @param toolRegistry The central registry where discovered tools will be registered.
|
| 439 |
+
* @returns A promise that resolves when the discovery process has been attempted for all servers.
|
| 440 |
+
*/
|
| 441 |
+
export async function discoverMcpTools(
|
| 442 |
+
mcpServers: Record<string, MCPServerConfig>,
|
| 443 |
+
mcpServerCommand: string | undefined,
|
| 444 |
+
toolRegistry: ToolRegistry,
|
| 445 |
+
promptRegistry: PromptRegistry,
|
| 446 |
+
debugMode: boolean,
|
| 447 |
+
workspaceContext: WorkspaceContext,
|
| 448 |
+
): Promise<void> {
|
| 449 |
+
mcpDiscoveryState = MCPDiscoveryState.IN_PROGRESS;
|
| 450 |
+
try {
|
| 451 |
+
mcpServers = populateMcpServerCommand(mcpServers, mcpServerCommand);
|
| 452 |
+
|
| 453 |
+
const discoveryPromises = Object.entries(mcpServers).map(
|
| 454 |
+
([mcpServerName, mcpServerConfig]) =>
|
| 455 |
+
connectAndDiscover(
|
| 456 |
+
mcpServerName,
|
| 457 |
+
mcpServerConfig,
|
| 458 |
+
toolRegistry,
|
| 459 |
+
promptRegistry,
|
| 460 |
+
debugMode,
|
| 461 |
+
workspaceContext,
|
| 462 |
+
),
|
| 463 |
+
);
|
| 464 |
+
await Promise.all(discoveryPromises);
|
| 465 |
+
} finally {
|
| 466 |
+
mcpDiscoveryState = MCPDiscoveryState.COMPLETED;
|
| 467 |
+
}
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
/** Visible for Testing */
|
| 471 |
+
export function populateMcpServerCommand(
|
| 472 |
+
mcpServers: Record<string, MCPServerConfig>,
|
| 473 |
+
mcpServerCommand: string | undefined,
|
| 474 |
+
): Record<string, MCPServerConfig> {
|
| 475 |
+
if (mcpServerCommand) {
|
| 476 |
+
const cmd = mcpServerCommand;
|
| 477 |
+
const args = parse(cmd, process.env) as string[];
|
| 478 |
+
if (args.some((arg) => typeof arg !== 'string')) {
|
| 479 |
+
throw new Error('failed to parse mcpServerCommand: ' + cmd);
|
| 480 |
+
}
|
| 481 |
+
// use generic server name 'mcp'
|
| 482 |
+
mcpServers['mcp'] = {
|
| 483 |
+
command: args[0],
|
| 484 |
+
args: args.slice(1),
|
| 485 |
+
};
|
| 486 |
+
}
|
| 487 |
+
return mcpServers;
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
/**
|
| 491 |
+
* Connects to an MCP server and discovers available tools, registering them with the tool registry.
|
| 492 |
+
* This function handles the complete lifecycle of connecting to a server, discovering tools,
|
| 493 |
+
* and cleaning up resources if no tools are found.
|
| 494 |
+
*
|
| 495 |
+
* @param mcpServerName The name identifier for this MCP server
|
| 496 |
+
* @param mcpServerConfig Configuration object containing connection details
|
| 497 |
+
* @param toolRegistry The registry to register discovered tools with
|
| 498 |
+
* @returns Promise that resolves when discovery is complete
|
| 499 |
+
*/
|
| 500 |
+
export async function connectAndDiscover(
|
| 501 |
+
mcpServerName: string,
|
| 502 |
+
mcpServerConfig: MCPServerConfig,
|
| 503 |
+
toolRegistry: ToolRegistry,
|
| 504 |
+
promptRegistry: PromptRegistry,
|
| 505 |
+
debugMode: boolean,
|
| 506 |
+
workspaceContext: WorkspaceContext,
|
| 507 |
+
): Promise<void> {
|
| 508 |
+
updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTING);
|
| 509 |
+
|
| 510 |
+
let mcpClient: Client | undefined;
|
| 511 |
+
try {
|
| 512 |
+
mcpClient = await connectToMcpServer(
|
| 513 |
+
mcpServerName,
|
| 514 |
+
mcpServerConfig,
|
| 515 |
+
debugMode,
|
| 516 |
+
workspaceContext,
|
| 517 |
+
);
|
| 518 |
+
|
| 519 |
+
mcpClient.onerror = (error) => {
|
| 520 |
+
console.error(`MCP ERROR (${mcpServerName}):`, error.toString());
|
| 521 |
+
updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
|
| 522 |
+
};
|
| 523 |
+
|
| 524 |
+
// Attempt to discover both prompts and tools
|
| 525 |
+
const prompts = await discoverPrompts(
|
| 526 |
+
mcpServerName,
|
| 527 |
+
mcpClient,
|
| 528 |
+
promptRegistry,
|
| 529 |
+
);
|
| 530 |
+
const tools = await discoverTools(
|
| 531 |
+
mcpServerName,
|
| 532 |
+
mcpServerConfig,
|
| 533 |
+
mcpClient,
|
| 534 |
+
);
|
| 535 |
+
|
| 536 |
+
// If we have neither prompts nor tools, it's a failed discovery
|
| 537 |
+
if (prompts.length === 0 && tools.length === 0) {
|
| 538 |
+
throw new Error('No prompts or tools found on the server.');
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
// If we found anything, the server is connected
|
| 542 |
+
updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTED);
|
| 543 |
+
|
| 544 |
+
// Register any discovered tools
|
| 545 |
+
for (const tool of tools) {
|
| 546 |
+
toolRegistry.registerTool(tool);
|
| 547 |
+
}
|
| 548 |
+
} catch (error) {
|
| 549 |
+
if (mcpClient) {
|
| 550 |
+
mcpClient.close();
|
| 551 |
+
}
|
| 552 |
+
console.error(
|
| 553 |
+
`Error connecting to MCP server '${mcpServerName}': ${getErrorMessage(
|
| 554 |
+
error,
|
| 555 |
+
)}`,
|
| 556 |
+
);
|
| 557 |
+
updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
|
| 558 |
+
}
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
/**
|
| 562 |
+
* Recursively validates that a JSON schema and all its nested properties and
|
| 563 |
+
* items have a `type` defined.
|
| 564 |
+
*
|
| 565 |
+
* @param schema The JSON schema to validate.
|
| 566 |
+
* @returns `true` if the schema is valid, `false` otherwise.
|
| 567 |
+
*
|
| 568 |
+
* @visiblefortesting
|
| 569 |
+
*/
|
| 570 |
+
export function hasValidTypes(schema: unknown): boolean {
|
| 571 |
+
if (typeof schema !== 'object' || schema === null) {
|
| 572 |
+
// Not a schema object we can validate, or not a schema at all.
|
| 573 |
+
// Treat as valid as it has no properties to be invalid.
|
| 574 |
+
return true;
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
const s = schema as Record<string, unknown>;
|
| 578 |
+
|
| 579 |
+
if (!s['type']) {
|
| 580 |
+
// These keywords contain an array of schemas that should be validated.
|
| 581 |
+
//
|
| 582 |
+
// If no top level type was given, then they must each have a type.
|
| 583 |
+
let hasSubSchema = false;
|
| 584 |
+
const schemaArrayKeywords = ['anyOf', 'allOf', 'oneOf'];
|
| 585 |
+
for (const keyword of schemaArrayKeywords) {
|
| 586 |
+
const subSchemas = s[keyword];
|
| 587 |
+
if (Array.isArray(subSchemas)) {
|
| 588 |
+
hasSubSchema = true;
|
| 589 |
+
for (const subSchema of subSchemas) {
|
| 590 |
+
if (!hasValidTypes(subSchema)) {
|
| 591 |
+
return false;
|
| 592 |
+
}
|
| 593 |
+
}
|
| 594 |
+
}
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
// If the node itself is missing a type and had no subschemas, then it isn't valid.
|
| 598 |
+
if (!hasSubSchema) return false;
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
if (s['type'] === 'object' && s['properties']) {
|
| 602 |
+
if (typeof s['properties'] === 'object' && s['properties'] !== null) {
|
| 603 |
+
for (const prop of Object.values(s['properties'])) {
|
| 604 |
+
if (!hasValidTypes(prop)) {
|
| 605 |
+
return false;
|
| 606 |
+
}
|
| 607 |
+
}
|
| 608 |
+
}
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
if (s['type'] === 'array' && s['items']) {
|
| 612 |
+
if (!hasValidTypes(s['items'])) {
|
| 613 |
+
return false;
|
| 614 |
+
}
|
| 615 |
+
}
|
| 616 |
+
|
| 617 |
+
return true;
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
/**
|
| 621 |
+
* Discovers and sanitizes tools from a connected MCP client.
|
| 622 |
+
* It retrieves function declarations from the client, filters out disabled tools,
|
| 623 |
+
* generates valid names for them, and wraps them in `DiscoveredMCPTool` instances.
|
| 624 |
+
*
|
| 625 |
+
* @param mcpServerName The name of the MCP server.
|
| 626 |
+
* @param mcpServerConfig The configuration for the MCP server.
|
| 627 |
+
* @param mcpClient The active MCP client instance.
|
| 628 |
+
* @returns A promise that resolves to an array of discovered and enabled tools.
|
| 629 |
+
* @throws An error if no enabled tools are found or if the server provides invalid function declarations.
|
| 630 |
+
*/
|
| 631 |
+
export async function discoverTools(
|
| 632 |
+
mcpServerName: string,
|
| 633 |
+
mcpServerConfig: MCPServerConfig,
|
| 634 |
+
mcpClient: Client,
|
| 635 |
+
): Promise<DiscoveredMCPTool[]> {
|
| 636 |
+
try {
|
| 637 |
+
const mcpCallableTool = mcpToTool(mcpClient);
|
| 638 |
+
const tool = await mcpCallableTool.tool();
|
| 639 |
+
|
| 640 |
+
if (!Array.isArray(tool.functionDeclarations)) {
|
| 641 |
+
// This is a valid case for a prompt-only server
|
| 642 |
+
return [];
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
const discoveredTools: DiscoveredMCPTool[] = [];
|
| 646 |
+
for (const funcDecl of tool.functionDeclarations) {
|
| 647 |
+
try {
|
| 648 |
+
if (!isEnabled(funcDecl, mcpServerName, mcpServerConfig)) {
|
| 649 |
+
continue;
|
| 650 |
+
}
|
| 651 |
+
|
| 652 |
+
if (!hasValidTypes(funcDecl.parametersJsonSchema)) {
|
| 653 |
+
console.warn(
|
| 654 |
+
`Skipping tool '${funcDecl.name}' from MCP server '${mcpServerName}' ` +
|
| 655 |
+
`because it has missing types in its parameter schema. Please file an ` +
|
| 656 |
+
`issue with the owner of the MCP server.`,
|
| 657 |
+
);
|
| 658 |
+
continue;
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
discoveredTools.push(
|
| 662 |
+
new DiscoveredMCPTool(
|
| 663 |
+
mcpCallableTool,
|
| 664 |
+
mcpServerName,
|
| 665 |
+
funcDecl.name!,
|
| 666 |
+
funcDecl.description ?? '',
|
| 667 |
+
funcDecl.parametersJsonSchema ?? { type: 'object', properties: {} },
|
| 668 |
+
mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
|
| 669 |
+
mcpServerConfig.trust,
|
| 670 |
+
),
|
| 671 |
+
);
|
| 672 |
+
} catch (error) {
|
| 673 |
+
console.error(
|
| 674 |
+
`Error discovering tool: '${
|
| 675 |
+
funcDecl.name
|
| 676 |
+
}' from MCP server '${mcpServerName}': ${(error as Error).message}`,
|
| 677 |
+
);
|
| 678 |
+
}
|
| 679 |
+
}
|
| 680 |
+
return discoveredTools;
|
| 681 |
+
} catch (error) {
|
| 682 |
+
if (
|
| 683 |
+
error instanceof Error &&
|
| 684 |
+
!error.message?.includes('Method not found')
|
| 685 |
+
) {
|
| 686 |
+
console.error(
|
| 687 |
+
`Error discovering tools from ${mcpServerName}: ${getErrorMessage(
|
| 688 |
+
error,
|
| 689 |
+
)}`,
|
| 690 |
+
);
|
| 691 |
+
}
|
| 692 |
+
return [];
|
| 693 |
+
}
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
/**
|
| 697 |
+
* Discovers and logs prompts from a connected MCP client.
|
| 698 |
+
* It retrieves prompt declarations from the client and logs their names.
|
| 699 |
+
*
|
| 700 |
+
* @param mcpServerName The name of the MCP server.
|
| 701 |
+
* @param mcpClient The active MCP client instance.
|
| 702 |
+
*/
|
| 703 |
+
export async function discoverPrompts(
|
| 704 |
+
mcpServerName: string,
|
| 705 |
+
mcpClient: Client,
|
| 706 |
+
promptRegistry: PromptRegistry,
|
| 707 |
+
): Promise<Prompt[]> {
|
| 708 |
+
try {
|
| 709 |
+
// Only request prompts if the server supports them.
|
| 710 |
+
if (mcpClient.getServerCapabilities()?.prompts == null) return [];
|
| 711 |
+
|
| 712 |
+
const response = await mcpClient.request(
|
| 713 |
+
{ method: 'prompts/list', params: {} },
|
| 714 |
+
ListPromptsResultSchema,
|
| 715 |
+
);
|
| 716 |
+
|
| 717 |
+
for (const prompt of response.prompts) {
|
| 718 |
+
promptRegistry.registerPrompt({
|
| 719 |
+
...prompt,
|
| 720 |
+
serverName: mcpServerName,
|
| 721 |
+
invoke: (params: Record<string, unknown>) =>
|
| 722 |
+
invokeMcpPrompt(mcpServerName, mcpClient, prompt.name, params),
|
| 723 |
+
});
|
| 724 |
+
}
|
| 725 |
+
return response.prompts;
|
| 726 |
+
} catch (error) {
|
| 727 |
+
// It's okay if this fails, not all servers will have prompts.
|
| 728 |
+
// Don't log an error if the method is not found, which is a common case.
|
| 729 |
+
if (
|
| 730 |
+
error instanceof Error &&
|
| 731 |
+
!error.message?.includes('Method not found')
|
| 732 |
+
) {
|
| 733 |
+
console.error(
|
| 734 |
+
`Error discovering prompts from ${mcpServerName}: ${getErrorMessage(
|
| 735 |
+
error,
|
| 736 |
+
)}`,
|
| 737 |
+
);
|
| 738 |
+
}
|
| 739 |
+
return [];
|
| 740 |
+
}
|
| 741 |
+
}
|
| 742 |
+
|
| 743 |
+
/**
|
| 744 |
+
* Invokes a prompt on a connected MCP client.
|
| 745 |
+
*
|
| 746 |
+
* @param mcpServerName The name of the MCP server.
|
| 747 |
+
* @param mcpClient The active MCP client instance.
|
| 748 |
+
* @param promptName The name of the prompt to invoke.
|
| 749 |
+
* @param promptParams The parameters to pass to the prompt.
|
| 750 |
+
* @returns A promise that resolves to the result of the prompt invocation.
|
| 751 |
+
*/
|
| 752 |
+
export async function invokeMcpPrompt(
|
| 753 |
+
mcpServerName: string,
|
| 754 |
+
mcpClient: Client,
|
| 755 |
+
promptName: string,
|
| 756 |
+
promptParams: Record<string, unknown>,
|
| 757 |
+
): Promise<GetPromptResult> {
|
| 758 |
+
try {
|
| 759 |
+
const response = await mcpClient.request(
|
| 760 |
+
{
|
| 761 |
+
method: 'prompts/get',
|
| 762 |
+
params: {
|
| 763 |
+
name: promptName,
|
| 764 |
+
arguments: promptParams,
|
| 765 |
+
},
|
| 766 |
+
},
|
| 767 |
+
GetPromptResultSchema,
|
| 768 |
+
);
|
| 769 |
+
|
| 770 |
+
return response;
|
| 771 |
+
} catch (error) {
|
| 772 |
+
if (
|
| 773 |
+
error instanceof Error &&
|
| 774 |
+
!error.message?.includes('Method not found')
|
| 775 |
+
) {
|
| 776 |
+
console.error(
|
| 777 |
+
`Error invoking prompt '${promptName}' from ${mcpServerName} ${promptParams}: ${getErrorMessage(
|
| 778 |
+
error,
|
| 779 |
+
)}`,
|
| 780 |
+
);
|
| 781 |
+
}
|
| 782 |
+
throw error;
|
| 783 |
+
}
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
/**
|
| 787 |
+
* Creates and connects an MCP client to a server based on the provided configuration.
|
| 788 |
+
* It determines the appropriate transport (Stdio, SSE, or Streamable HTTP) and
|
| 789 |
+
* establishes a connection. It also applies a patch to handle request timeouts.
|
| 790 |
+
*
|
| 791 |
+
* @param mcpServerName The name of the MCP server, used for logging and identification.
|
| 792 |
+
* @param mcpServerConfig The configuration specifying how to connect to the server.
|
| 793 |
+
* @returns A promise that resolves to a connected MCP `Client` instance.
|
| 794 |
+
* @throws An error if the connection fails or the configuration is invalid.
|
| 795 |
+
*/
|
| 796 |
+
export async function connectToMcpServer(
|
| 797 |
+
mcpServerName: string,
|
| 798 |
+
mcpServerConfig: MCPServerConfig,
|
| 799 |
+
debugMode: boolean,
|
| 800 |
+
workspaceContext: WorkspaceContext,
|
| 801 |
+
): Promise<Client> {
|
| 802 |
+
const mcpClient = new Client({
|
| 803 |
+
name: 'qwen-code-mcp-client',
|
| 804 |
+
version: '0.0.1',
|
| 805 |
+
});
|
| 806 |
+
|
| 807 |
+
mcpClient.registerCapabilities({
|
| 808 |
+
roots: {
|
| 809 |
+
listChanged: true,
|
| 810 |
+
},
|
| 811 |
+
});
|
| 812 |
+
|
| 813 |
+
mcpClient.setRequestHandler(ListRootsRequestSchema, async () => {
|
| 814 |
+
const roots = [];
|
| 815 |
+
for (const dir of workspaceContext.getDirectories()) {
|
| 816 |
+
roots.push({
|
| 817 |
+
uri: pathToFileURL(dir).toString(),
|
| 818 |
+
name: basename(dir),
|
| 819 |
+
});
|
| 820 |
+
}
|
| 821 |
+
return {
|
| 822 |
+
roots,
|
| 823 |
+
};
|
| 824 |
+
});
|
| 825 |
+
|
| 826 |
+
let unlistenDirectories: Unsubscribe | undefined =
|
| 827 |
+
workspaceContext.onDirectoriesChanged(async () => {
|
| 828 |
+
try {
|
| 829 |
+
await mcpClient.notification({
|
| 830 |
+
method: 'notifications/roots/list_changed',
|
| 831 |
+
});
|
| 832 |
+
} catch (_) {
|
| 833 |
+
// If this fails, its almost certainly because the connection was closed
|
| 834 |
+
// and we should just stop listening for future directory changes.
|
| 835 |
+
unlistenDirectories?.();
|
| 836 |
+
unlistenDirectories = undefined;
|
| 837 |
+
}
|
| 838 |
+
});
|
| 839 |
+
|
| 840 |
+
// Attempt to pro-actively unsubscribe if the mcp client closes. This API is
|
| 841 |
+
// very brittle though so we don't have any guarantees, hence the try/catch
|
| 842 |
+
// above as well.
|
| 843 |
+
//
|
| 844 |
+
// Be a good steward and don't just bash over onclose.
|
| 845 |
+
const oldOnClose = mcpClient.onclose;
|
| 846 |
+
mcpClient.onclose = () => {
|
| 847 |
+
oldOnClose?.();
|
| 848 |
+
unlistenDirectories?.();
|
| 849 |
+
unlistenDirectories = undefined;
|
| 850 |
+
};
|
| 851 |
+
|
| 852 |
+
// patch Client.callTool to use request timeout as genai McpCallTool.callTool does not do it
|
| 853 |
+
// TODO: remove this hack once GenAI SDK does callTool with request options
|
| 854 |
+
if ('callTool' in mcpClient) {
|
| 855 |
+
const origCallTool = mcpClient.callTool.bind(mcpClient);
|
| 856 |
+
mcpClient.callTool = function (params, resultSchema, options) {
|
| 857 |
+
return origCallTool(params, resultSchema, {
|
| 858 |
+
...options,
|
| 859 |
+
timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
|
| 860 |
+
});
|
| 861 |
+
};
|
| 862 |
+
}
|
| 863 |
+
|
| 864 |
+
try {
|
| 865 |
+
const transport = await createTransport(
|
| 866 |
+
mcpServerName,
|
| 867 |
+
mcpServerConfig,
|
| 868 |
+
debugMode,
|
| 869 |
+
);
|
| 870 |
+
try {
|
| 871 |
+
await mcpClient.connect(transport, {
|
| 872 |
+
timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
|
| 873 |
+
});
|
| 874 |
+
return mcpClient;
|
| 875 |
+
} catch (error) {
|
| 876 |
+
await transport.close();
|
| 877 |
+
throw error;
|
| 878 |
+
}
|
| 879 |
+
} catch (error) {
|
| 880 |
+
// Check if this is a 401 error that might indicate OAuth is required
|
| 881 |
+
const errorString = String(error);
|
| 882 |
+
if (
|
| 883 |
+
errorString.includes('401') &&
|
| 884 |
+
(mcpServerConfig.httpUrl || mcpServerConfig.url)
|
| 885 |
+
) {
|
| 886 |
+
mcpServerRequiresOAuth.set(mcpServerName, true);
|
| 887 |
+
// Only trigger automatic OAuth discovery for HTTP servers or when OAuth is explicitly configured
|
| 888 |
+
// For SSE servers, we should not trigger new OAuth flows automatically
|
| 889 |
+
const shouldTriggerOAuth =
|
| 890 |
+
mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
|
| 891 |
+
|
| 892 |
+
if (!shouldTriggerOAuth) {
|
| 893 |
+
// For SSE servers without explicit OAuth config, if a token was found but rejected, report it accurately.
|
| 894 |
+
const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
|
| 895 |
+
if (credentials) {
|
| 896 |
+
const hasStoredTokens = await MCPOAuthProvider.getValidToken(
|
| 897 |
+
mcpServerName,
|
| 898 |
+
{
|
| 899 |
+
// Pass client ID if available
|
| 900 |
+
clientId: credentials.clientId,
|
| 901 |
+
},
|
| 902 |
+
);
|
| 903 |
+
if (hasStoredTokens) {
|
| 904 |
+
console.log(
|
| 905 |
+
`Stored OAuth token for SSE server '${mcpServerName}' was rejected. ` +
|
| 906 |
+
`Please re-authenticate using: /mcp auth ${mcpServerName}`,
|
| 907 |
+
);
|
| 908 |
+
} else {
|
| 909 |
+
console.log(
|
| 910 |
+
`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
|
| 911 |
+
`Please authenticate using: /mcp auth ${mcpServerName}`,
|
| 912 |
+
);
|
| 913 |
+
}
|
| 914 |
+
}
|
| 915 |
+
throw new Error(
|
| 916 |
+
`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
|
| 917 |
+
`Please authenticate using: /mcp auth ${mcpServerName}`,
|
| 918 |
+
);
|
| 919 |
+
}
|
| 920 |
+
|
| 921 |
+
// Try to extract www-authenticate header from the error
|
| 922 |
+
let wwwAuthenticate = extractWWWAuthenticateHeader(errorString);
|
| 923 |
+
|
| 924 |
+
// If we didn't get the header from the error string, try to get it from the server
|
| 925 |
+
if (!wwwAuthenticate && mcpServerConfig.url) {
|
| 926 |
+
console.log(
|
| 927 |
+
`No www-authenticate header in error, trying to fetch it from server...`,
|
| 928 |
+
);
|
| 929 |
+
try {
|
| 930 |
+
const response = await fetch(mcpServerConfig.url, {
|
| 931 |
+
method: 'HEAD',
|
| 932 |
+
headers: {
|
| 933 |
+
Accept: 'text/event-stream',
|
| 934 |
+
},
|
| 935 |
+
signal: AbortSignal.timeout(5000),
|
| 936 |
+
});
|
| 937 |
+
|
| 938 |
+
if (response.status === 401) {
|
| 939 |
+
wwwAuthenticate = response.headers.get('www-authenticate');
|
| 940 |
+
if (wwwAuthenticate) {
|
| 941 |
+
console.log(
|
| 942 |
+
`Found www-authenticate header from server: ${wwwAuthenticate}`,
|
| 943 |
+
);
|
| 944 |
+
}
|
| 945 |
+
}
|
| 946 |
+
} catch (fetchError) {
|
| 947 |
+
console.debug(
|
| 948 |
+
`Failed to fetch www-authenticate header: ${getErrorMessage(fetchError)}`,
|
| 949 |
+
);
|
| 950 |
+
}
|
| 951 |
+
}
|
| 952 |
+
|
| 953 |
+
if (wwwAuthenticate) {
|
| 954 |
+
console.log(
|
| 955 |
+
`Received 401 with www-authenticate header: ${wwwAuthenticate}`,
|
| 956 |
+
);
|
| 957 |
+
|
| 958 |
+
// Try automatic OAuth discovery and authentication
|
| 959 |
+
const oauthSuccess = await handleAutomaticOAuth(
|
| 960 |
+
mcpServerName,
|
| 961 |
+
mcpServerConfig,
|
| 962 |
+
wwwAuthenticate,
|
| 963 |
+
);
|
| 964 |
+
if (oauthSuccess) {
|
| 965 |
+
// Retry connection with OAuth token
|
| 966 |
+
console.log(
|
| 967 |
+
`Retrying connection to '${mcpServerName}' with OAuth token...`,
|
| 968 |
+
);
|
| 969 |
+
|
| 970 |
+
// Get the valid token - we need to create a proper OAuth config
|
| 971 |
+
// The token should already be available from the authentication process
|
| 972 |
+
const credentials =
|
| 973 |
+
await MCPOAuthTokenStorage.getToken(mcpServerName);
|
| 974 |
+
if (credentials) {
|
| 975 |
+
const accessToken = await MCPOAuthProvider.getValidToken(
|
| 976 |
+
mcpServerName,
|
| 977 |
+
{
|
| 978 |
+
// Pass client ID if available
|
| 979 |
+
clientId: credentials.clientId,
|
| 980 |
+
},
|
| 981 |
+
);
|
| 982 |
+
|
| 983 |
+
if (accessToken) {
|
| 984 |
+
// Create transport with OAuth token
|
| 985 |
+
const oauthTransport = await createTransportWithOAuth(
|
| 986 |
+
mcpServerName,
|
| 987 |
+
mcpServerConfig,
|
| 988 |
+
accessToken,
|
| 989 |
+
);
|
| 990 |
+
if (oauthTransport) {
|
| 991 |
+
try {
|
| 992 |
+
await mcpClient.connect(oauthTransport, {
|
| 993 |
+
timeout:
|
| 994 |
+
mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
|
| 995 |
+
});
|
| 996 |
+
// Connection successful with OAuth
|
| 997 |
+
return mcpClient;
|
| 998 |
+
} catch (retryError) {
|
| 999 |
+
console.error(
|
| 1000 |
+
`Failed to connect with OAuth token: ${getErrorMessage(
|
| 1001 |
+
retryError,
|
| 1002 |
+
)}`,
|
| 1003 |
+
);
|
| 1004 |
+
throw retryError;
|
| 1005 |
+
}
|
| 1006 |
+
} else {
|
| 1007 |
+
console.error(
|
| 1008 |
+
`Failed to create OAuth transport for server '${mcpServerName}'`,
|
| 1009 |
+
);
|
| 1010 |
+
throw new Error(
|
| 1011 |
+
`Failed to create OAuth transport for server '${mcpServerName}'`,
|
| 1012 |
+
);
|
| 1013 |
+
}
|
| 1014 |
+
} else {
|
| 1015 |
+
console.error(
|
| 1016 |
+
`Failed to get OAuth token for server '${mcpServerName}'`,
|
| 1017 |
+
);
|
| 1018 |
+
throw new Error(
|
| 1019 |
+
`Failed to get OAuth token for server '${mcpServerName}'`,
|
| 1020 |
+
);
|
| 1021 |
+
}
|
| 1022 |
+
} else {
|
| 1023 |
+
console.error(
|
| 1024 |
+
`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`,
|
| 1025 |
+
);
|
| 1026 |
+
throw new Error(
|
| 1027 |
+
`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`,
|
| 1028 |
+
);
|
| 1029 |
+
}
|
| 1030 |
+
} else {
|
| 1031 |
+
console.error(
|
| 1032 |
+
`Failed to handle automatic OAuth for server '${mcpServerName}'`,
|
| 1033 |
+
);
|
| 1034 |
+
throw new Error(
|
| 1035 |
+
`Failed to handle automatic OAuth for server '${mcpServerName}'`,
|
| 1036 |
+
);
|
| 1037 |
+
}
|
| 1038 |
+
} else {
|
| 1039 |
+
// No www-authenticate header found, but we got a 401
|
| 1040 |
+
// Only try OAuth discovery for HTTP servers or when OAuth is explicitly configured
|
| 1041 |
+
// For SSE servers, we should not trigger new OAuth flows automatically
|
| 1042 |
+
const shouldTryDiscovery =
|
| 1043 |
+
mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
|
| 1044 |
+
|
| 1045 |
+
if (!shouldTryDiscovery) {
|
| 1046 |
+
const credentials =
|
| 1047 |
+
await MCPOAuthTokenStorage.getToken(mcpServerName);
|
| 1048 |
+
if (credentials) {
|
| 1049 |
+
const hasStoredTokens = await MCPOAuthProvider.getValidToken(
|
| 1050 |
+
mcpServerName,
|
| 1051 |
+
{
|
| 1052 |
+
// Pass client ID if available
|
| 1053 |
+
clientId: credentials.clientId,
|
| 1054 |
+
},
|
| 1055 |
+
);
|
| 1056 |
+
if (hasStoredTokens) {
|
| 1057 |
+
console.log(
|
| 1058 |
+
`Stored OAuth token for SSE server '${mcpServerName}' was rejected. ` +
|
| 1059 |
+
`Please re-authenticate using: /mcp auth ${mcpServerName}`,
|
| 1060 |
+
);
|
| 1061 |
+
} else {
|
| 1062 |
+
console.log(
|
| 1063 |
+
`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
|
| 1064 |
+
`Please authenticate using: /mcp auth ${mcpServerName}`,
|
| 1065 |
+
);
|
| 1066 |
+
}
|
| 1067 |
+
}
|
| 1068 |
+
throw new Error(
|
| 1069 |
+
`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
|
| 1070 |
+
`Please authenticate using: /mcp auth ${mcpServerName}`,
|
| 1071 |
+
);
|
| 1072 |
+
}
|
| 1073 |
+
|
| 1074 |
+
// For SSE servers, try to discover OAuth configuration from the base URL
|
| 1075 |
+
console.log(`🔍 Attempting OAuth discovery for '${mcpServerName}'...`);
|
| 1076 |
+
|
| 1077 |
+
if (mcpServerConfig.url) {
|
| 1078 |
+
const sseUrl = new URL(mcpServerConfig.url);
|
| 1079 |
+
const baseUrl = `${sseUrl.protocol}//${sseUrl.host}`;
|
| 1080 |
+
|
| 1081 |
+
try {
|
| 1082 |
+
// Try to discover OAuth configuration from the base URL
|
| 1083 |
+
const oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
|
| 1084 |
+
if (oauthConfig) {
|
| 1085 |
+
console.log(
|
| 1086 |
+
`Discovered OAuth configuration from base URL for server '${mcpServerName}'`,
|
| 1087 |
+
);
|
| 1088 |
+
|
| 1089 |
+
// Create OAuth configuration for authentication
|
| 1090 |
+
const oauthAuthConfig = {
|
| 1091 |
+
enabled: true,
|
| 1092 |
+
authorizationUrl: oauthConfig.authorizationUrl,
|
| 1093 |
+
tokenUrl: oauthConfig.tokenUrl,
|
| 1094 |
+
scopes: oauthConfig.scopes || [],
|
| 1095 |
+
};
|
| 1096 |
+
|
| 1097 |
+
// Perform OAuth authentication
|
| 1098 |
+
// Pass the server URL for proper discovery
|
| 1099 |
+
const serverUrl = mcpServerConfig.httpUrl || mcpServerConfig.url;
|
| 1100 |
+
console.log(
|
| 1101 |
+
`Starting OAuth authentication for server '${mcpServerName}'...`,
|
| 1102 |
+
);
|
| 1103 |
+
await MCPOAuthProvider.authenticate(
|
| 1104 |
+
mcpServerName,
|
| 1105 |
+
oauthAuthConfig,
|
| 1106 |
+
serverUrl,
|
| 1107 |
+
);
|
| 1108 |
+
|
| 1109 |
+
// Retry connection with OAuth token
|
| 1110 |
+
const credentials =
|
| 1111 |
+
await MCPOAuthTokenStorage.getToken(mcpServerName);
|
| 1112 |
+
if (credentials) {
|
| 1113 |
+
const accessToken = await MCPOAuthProvider.getValidToken(
|
| 1114 |
+
mcpServerName,
|
| 1115 |
+
{
|
| 1116 |
+
// Pass client ID if available
|
| 1117 |
+
clientId: credentials.clientId,
|
| 1118 |
+
},
|
| 1119 |
+
);
|
| 1120 |
+
if (accessToken) {
|
| 1121 |
+
// Create transport with OAuth token
|
| 1122 |
+
const oauthTransport = await createTransportWithOAuth(
|
| 1123 |
+
mcpServerName,
|
| 1124 |
+
mcpServerConfig,
|
| 1125 |
+
accessToken,
|
| 1126 |
+
);
|
| 1127 |
+
if (oauthTransport) {
|
| 1128 |
+
try {
|
| 1129 |
+
await mcpClient.connect(oauthTransport, {
|
| 1130 |
+
timeout:
|
| 1131 |
+
mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
|
| 1132 |
+
});
|
| 1133 |
+
// Connection successful with OAuth
|
| 1134 |
+
return mcpClient;
|
| 1135 |
+
} catch (retryError) {
|
| 1136 |
+
console.error(
|
| 1137 |
+
`Failed to connect with OAuth token: ${getErrorMessage(
|
| 1138 |
+
retryError,
|
| 1139 |
+
)}`,
|
| 1140 |
+
);
|
| 1141 |
+
throw retryError;
|
| 1142 |
+
}
|
| 1143 |
+
} else {
|
| 1144 |
+
console.error(
|
| 1145 |
+
`Failed to create OAuth transport for server '${mcpServerName}'`,
|
| 1146 |
+
);
|
| 1147 |
+
throw new Error(
|
| 1148 |
+
`Failed to create OAuth transport for server '${mcpServerName}'`,
|
| 1149 |
+
);
|
| 1150 |
+
}
|
| 1151 |
+
} else {
|
| 1152 |
+
console.error(
|
| 1153 |
+
`Failed to get OAuth token for server '${mcpServerName}'`,
|
| 1154 |
+
);
|
| 1155 |
+
throw new Error(
|
| 1156 |
+
`Failed to get OAuth token for server '${mcpServerName}'`,
|
| 1157 |
+
);
|
| 1158 |
+
}
|
| 1159 |
+
} else {
|
| 1160 |
+
console.error(
|
| 1161 |
+
`Failed to get stored credentials for server '${mcpServerName}'`,
|
| 1162 |
+
);
|
| 1163 |
+
throw new Error(
|
| 1164 |
+
`Failed to get stored credentials for server '${mcpServerName}'`,
|
| 1165 |
+
);
|
| 1166 |
+
}
|
| 1167 |
+
} else {
|
| 1168 |
+
console.error(
|
| 1169 |
+
`❌ Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`,
|
| 1170 |
+
);
|
| 1171 |
+
throw new Error(
|
| 1172 |
+
`OAuth configuration failed for '${mcpServerName}'. Please authenticate manually with /mcp auth ${mcpServerName}`,
|
| 1173 |
+
);
|
| 1174 |
+
}
|
| 1175 |
+
} catch (discoveryError) {
|
| 1176 |
+
console.error(
|
| 1177 |
+
`❌ OAuth discovery failed for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`,
|
| 1178 |
+
);
|
| 1179 |
+
throw discoveryError;
|
| 1180 |
+
}
|
| 1181 |
+
} else {
|
| 1182 |
+
console.error(
|
| 1183 |
+
`❌ '${mcpServerName}' requires authentication but no OAuth configuration found`,
|
| 1184 |
+
);
|
| 1185 |
+
throw new Error(
|
| 1186 |
+
`MCP server '${mcpServerName}' requires authentication. Please configure OAuth or check server settings.`,
|
| 1187 |
+
);
|
| 1188 |
+
}
|
| 1189 |
+
}
|
| 1190 |
+
} else {
|
| 1191 |
+
// Handle other connection errors
|
| 1192 |
+
// Create a concise error message
|
| 1193 |
+
const errorMessage = (error as Error).message || String(error);
|
| 1194 |
+
const isNetworkError =
|
| 1195 |
+
errorMessage.includes('ENOTFOUND') ||
|
| 1196 |
+
errorMessage.includes('ECONNREFUSED');
|
| 1197 |
+
|
| 1198 |
+
let conciseError: string;
|
| 1199 |
+
if (isNetworkError) {
|
| 1200 |
+
conciseError = `Cannot connect to '${mcpServerName}' - server may be down or URL incorrect`;
|
| 1201 |
+
} else {
|
| 1202 |
+
conciseError = `Connection failed for '${mcpServerName}': ${errorMessage}`;
|
| 1203 |
+
}
|
| 1204 |
+
|
| 1205 |
+
if (process.env['SANDBOX']) {
|
| 1206 |
+
conciseError += ` (check sandbox availability)`;
|
| 1207 |
+
}
|
| 1208 |
+
|
| 1209 |
+
throw new Error(conciseError);
|
| 1210 |
+
}
|
| 1211 |
+
}
|
| 1212 |
+
}
|
| 1213 |
+
|
| 1214 |
+
/** Visible for Testing */
|
| 1215 |
+
export async function createTransport(
|
| 1216 |
+
mcpServerName: string,
|
| 1217 |
+
mcpServerConfig: MCPServerConfig,
|
| 1218 |
+
debugMode: boolean,
|
| 1219 |
+
): Promise<Transport> {
|
| 1220 |
+
if (
|
| 1221 |
+
mcpServerConfig.authProviderType === AuthProviderType.GOOGLE_CREDENTIALS
|
| 1222 |
+
) {
|
| 1223 |
+
const provider = new GoogleCredentialProvider(mcpServerConfig);
|
| 1224 |
+
const transportOptions:
|
| 1225 |
+
| StreamableHTTPClientTransportOptions
|
| 1226 |
+
| SSEClientTransportOptions = {
|
| 1227 |
+
authProvider: provider,
|
| 1228 |
+
};
|
| 1229 |
+
if (mcpServerConfig.httpUrl) {
|
| 1230 |
+
return new StreamableHTTPClientTransport(
|
| 1231 |
+
new URL(mcpServerConfig.httpUrl),
|
| 1232 |
+
transportOptions,
|
| 1233 |
+
);
|
| 1234 |
+
} else if (mcpServerConfig.url) {
|
| 1235 |
+
return new SSEClientTransport(
|
| 1236 |
+
new URL(mcpServerConfig.url),
|
| 1237 |
+
transportOptions,
|
| 1238 |
+
);
|
| 1239 |
+
}
|
| 1240 |
+
throw new Error('No URL configured for Google Credentials MCP server');
|
| 1241 |
+
}
|
| 1242 |
+
|
| 1243 |
+
// Check if we have OAuth configuration or stored tokens
|
| 1244 |
+
let accessToken: string | null = null;
|
| 1245 |
+
let hasOAuthConfig = mcpServerConfig.oauth?.enabled;
|
| 1246 |
+
|
| 1247 |
+
if (hasOAuthConfig && mcpServerConfig.oauth) {
|
| 1248 |
+
accessToken = await MCPOAuthProvider.getValidToken(
|
| 1249 |
+
mcpServerName,
|
| 1250 |
+
mcpServerConfig.oauth,
|
| 1251 |
+
);
|
| 1252 |
+
|
| 1253 |
+
if (!accessToken) {
|
| 1254 |
+
console.error(
|
| 1255 |
+
`MCP server '${mcpServerName}' requires OAuth authentication. ` +
|
| 1256 |
+
`Please authenticate using the /mcp auth command.`,
|
| 1257 |
+
);
|
| 1258 |
+
throw new Error(
|
| 1259 |
+
`MCP server '${mcpServerName}' requires OAuth authentication. ` +
|
| 1260 |
+
`Please authenticate using the /mcp auth command.`,
|
| 1261 |
+
);
|
| 1262 |
+
}
|
| 1263 |
+
} else {
|
| 1264 |
+
// Check if we have stored OAuth tokens for this server (from previous authentication)
|
| 1265 |
+
const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
|
| 1266 |
+
if (credentials) {
|
| 1267 |
+
accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, {
|
| 1268 |
+
// Pass client ID if available
|
| 1269 |
+
clientId: credentials.clientId,
|
| 1270 |
+
});
|
| 1271 |
+
|
| 1272 |
+
if (accessToken) {
|
| 1273 |
+
hasOAuthConfig = true;
|
| 1274 |
+
console.log(`Found stored OAuth token for server '${mcpServerName}'`);
|
| 1275 |
+
}
|
| 1276 |
+
}
|
| 1277 |
+
}
|
| 1278 |
+
|
| 1279 |
+
if (mcpServerConfig.httpUrl) {
|
| 1280 |
+
const transportOptions: StreamableHTTPClientTransportOptions = {};
|
| 1281 |
+
|
| 1282 |
+
// Set up headers with OAuth token if available
|
| 1283 |
+
if (hasOAuthConfig && accessToken) {
|
| 1284 |
+
transportOptions.requestInit = {
|
| 1285 |
+
headers: {
|
| 1286 |
+
...mcpServerConfig.headers,
|
| 1287 |
+
Authorization: `Bearer ${accessToken}`,
|
| 1288 |
+
},
|
| 1289 |
+
};
|
| 1290 |
+
} else if (mcpServerConfig.headers) {
|
| 1291 |
+
transportOptions.requestInit = {
|
| 1292 |
+
headers: mcpServerConfig.headers,
|
| 1293 |
+
};
|
| 1294 |
+
}
|
| 1295 |
+
|
| 1296 |
+
return new StreamableHTTPClientTransport(
|
| 1297 |
+
new URL(mcpServerConfig.httpUrl),
|
| 1298 |
+
transportOptions,
|
| 1299 |
+
);
|
| 1300 |
+
}
|
| 1301 |
+
|
| 1302 |
+
if (mcpServerConfig.url) {
|
| 1303 |
+
const transportOptions: SSEClientTransportOptions = {};
|
| 1304 |
+
|
| 1305 |
+
// Set up headers with OAuth token if available
|
| 1306 |
+
if (hasOAuthConfig && accessToken) {
|
| 1307 |
+
transportOptions.requestInit = {
|
| 1308 |
+
headers: {
|
| 1309 |
+
...mcpServerConfig.headers,
|
| 1310 |
+
Authorization: `Bearer ${accessToken}`,
|
| 1311 |
+
},
|
| 1312 |
+
};
|
| 1313 |
+
} else if (mcpServerConfig.headers) {
|
| 1314 |
+
transportOptions.requestInit = {
|
| 1315 |
+
headers: mcpServerConfig.headers,
|
| 1316 |
+
};
|
| 1317 |
+
}
|
| 1318 |
+
|
| 1319 |
+
return new SSEClientTransport(
|
| 1320 |
+
new URL(mcpServerConfig.url),
|
| 1321 |
+
transportOptions,
|
| 1322 |
+
);
|
| 1323 |
+
}
|
| 1324 |
+
|
| 1325 |
+
if (mcpServerConfig.command) {
|
| 1326 |
+
const transport = new StdioClientTransport({
|
| 1327 |
+
command: mcpServerConfig.command,
|
| 1328 |
+
args: mcpServerConfig.args || [],
|
| 1329 |
+
env: {
|
| 1330 |
+
...process.env,
|
| 1331 |
+
...(mcpServerConfig.env || {}),
|
| 1332 |
+
} as Record<string, string>,
|
| 1333 |
+
cwd: mcpServerConfig.cwd,
|
| 1334 |
+
stderr: 'pipe',
|
| 1335 |
+
});
|
| 1336 |
+
if (debugMode) {
|
| 1337 |
+
transport.stderr!.on('data', (data) => {
|
| 1338 |
+
const stderrStr = data.toString().trim();
|
| 1339 |
+
console.debug(`[DEBUG] [MCP STDERR (${mcpServerName})]: `, stderrStr);
|
| 1340 |
+
});
|
| 1341 |
+
}
|
| 1342 |
+
return transport;
|
| 1343 |
+
}
|
| 1344 |
+
|
| 1345 |
+
throw new Error(
|
| 1346 |
+
`Invalid configuration: missing httpUrl (for Streamable HTTP), url (for SSE), and command (for stdio).`,
|
| 1347 |
+
);
|
| 1348 |
+
}
|
| 1349 |
+
|
| 1350 |
+
/** Visible for testing */
|
| 1351 |
+
export function isEnabled(
|
| 1352 |
+
funcDecl: FunctionDeclaration,
|
| 1353 |
+
mcpServerName: string,
|
| 1354 |
+
mcpServerConfig: MCPServerConfig,
|
| 1355 |
+
): boolean {
|
| 1356 |
+
if (!funcDecl.name) {
|
| 1357 |
+
console.warn(
|
| 1358 |
+
`Discovered a function declaration without a name from MCP server '${mcpServerName}'. Skipping.`,
|
| 1359 |
+
);
|
| 1360 |
+
return false;
|
| 1361 |
+
}
|
| 1362 |
+
const { includeTools, excludeTools } = mcpServerConfig;
|
| 1363 |
+
|
| 1364 |
+
// excludeTools takes precedence over includeTools
|
| 1365 |
+
if (excludeTools && excludeTools.includes(funcDecl.name)) {
|
| 1366 |
+
return false;
|
| 1367 |
+
}
|
| 1368 |
+
|
| 1369 |
+
return (
|
| 1370 |
+
!includeTools ||
|
| 1371 |
+
includeTools.some(
|
| 1372 |
+
(tool) => tool === funcDecl.name || tool.startsWith(`${funcDecl.name}(`),
|
| 1373 |
+
)
|
| 1374 |
+
);
|
| 1375 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/mcp-tool.test.ts
ADDED
|
@@ -0,0 +1,746 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
| 8 |
+
import {
|
| 9 |
+
describe,
|
| 10 |
+
it,
|
| 11 |
+
expect,
|
| 12 |
+
vi,
|
| 13 |
+
beforeEach,
|
| 14 |
+
afterEach,
|
| 15 |
+
Mocked,
|
| 16 |
+
} from 'vitest';
|
| 17 |
+
import { DiscoveredMCPTool, generateValidName } from './mcp-tool.js'; // Added getStringifiedResultForDisplay
|
| 18 |
+
import { ToolResult, ToolConfirmationOutcome } from './tools.js'; // Added ToolConfirmationOutcome
|
| 19 |
+
import { CallableTool, Part } from '@google/genai';
|
| 20 |
+
|
| 21 |
+
// Mock @google/genai mcpToTool and CallableTool
|
| 22 |
+
// We only need to mock the parts of CallableTool that DiscoveredMCPTool uses.
|
| 23 |
+
const mockCallTool = vi.fn();
|
| 24 |
+
const mockToolMethod = vi.fn();
|
| 25 |
+
|
| 26 |
+
const mockCallableToolInstance: Mocked<CallableTool> = {
|
| 27 |
+
tool: mockToolMethod as any, // Not directly used by DiscoveredMCPTool instance methods
|
| 28 |
+
callTool: mockCallTool as any,
|
| 29 |
+
// Add other methods if DiscoveredMCPTool starts using them
|
| 30 |
+
};
|
| 31 |
+
|
| 32 |
+
describe('generateValidName', () => {
|
| 33 |
+
it('should return a valid name for a simple function', () => {
|
| 34 |
+
expect(generateValidName('myFunction')).toBe('myFunction');
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
it('should replace invalid characters with underscores', () => {
|
| 38 |
+
expect(generateValidName('invalid-name with spaces')).toBe(
|
| 39 |
+
'invalid-name_with_spaces',
|
| 40 |
+
);
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
it('should truncate long names', () => {
|
| 44 |
+
expect(generateValidName('x'.repeat(80))).toBe(
|
| 45 |
+
'xxxxxxxxxxxxxxxxxxxxxxxxxxxx___xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
|
| 46 |
+
);
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
it('should handle names with only invalid characters', () => {
|
| 50 |
+
expect(generateValidName('!@#$%^&*()')).toBe('__________');
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
it('should handle names that are exactly 63 characters long', () => {
|
| 54 |
+
expect(generateValidName('a'.repeat(63)).length).toBe(63);
|
| 55 |
+
});
|
| 56 |
+
|
| 57 |
+
it('should handle names that are exactly 64 characters long', () => {
|
| 58 |
+
expect(generateValidName('a'.repeat(64)).length).toBe(63);
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
it('should handle names that are longer than 64 characters', () => {
|
| 62 |
+
expect(generateValidName('a'.repeat(80)).length).toBe(63);
|
| 63 |
+
});
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
describe('DiscoveredMCPTool', () => {
|
| 67 |
+
const serverName = 'mock-mcp-server';
|
| 68 |
+
const serverToolName = 'actual-server-tool-name';
|
| 69 |
+
const baseDescription = 'A test MCP tool.';
|
| 70 |
+
const inputSchema: Record<string, unknown> = {
|
| 71 |
+
type: 'object' as const,
|
| 72 |
+
properties: { param: { type: 'string' } },
|
| 73 |
+
required: ['param'],
|
| 74 |
+
};
|
| 75 |
+
|
| 76 |
+
let tool: DiscoveredMCPTool;
|
| 77 |
+
|
| 78 |
+
beforeEach(() => {
|
| 79 |
+
mockCallTool.mockClear();
|
| 80 |
+
mockToolMethod.mockClear();
|
| 81 |
+
tool = new DiscoveredMCPTool(
|
| 82 |
+
mockCallableToolInstance,
|
| 83 |
+
serverName,
|
| 84 |
+
serverToolName,
|
| 85 |
+
baseDescription,
|
| 86 |
+
inputSchema,
|
| 87 |
+
);
|
| 88 |
+
// Clear allowlist before each relevant test, especially for shouldConfirmExecute
|
| 89 |
+
const invocation = tool.build({ param: 'mock' }) as any;
|
| 90 |
+
invocation.constructor.allowlist.clear();
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
afterEach(() => {
|
| 94 |
+
vi.restoreAllMocks();
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
describe('constructor', () => {
|
| 98 |
+
it('should set properties correctly', () => {
|
| 99 |
+
expect(tool.name).toBe(serverToolName);
|
| 100 |
+
expect(tool.schema.name).toBe(serverToolName);
|
| 101 |
+
expect(tool.schema.description).toBe(baseDescription);
|
| 102 |
+
expect(tool.schema.parameters).toBeUndefined();
|
| 103 |
+
expect(tool.schema.parametersJsonSchema).toEqual(inputSchema);
|
| 104 |
+
expect(tool.serverToolName).toBe(serverToolName);
|
| 105 |
+
expect(tool.timeout).toBeUndefined();
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
it('should accept and store a custom timeout', () => {
|
| 109 |
+
const customTimeout = 5000;
|
| 110 |
+
const toolWithTimeout = new DiscoveredMCPTool(
|
| 111 |
+
mockCallableToolInstance,
|
| 112 |
+
serverName,
|
| 113 |
+
serverToolName,
|
| 114 |
+
baseDescription,
|
| 115 |
+
inputSchema,
|
| 116 |
+
customTimeout,
|
| 117 |
+
);
|
| 118 |
+
expect(toolWithTimeout.timeout).toBe(customTimeout);
|
| 119 |
+
});
|
| 120 |
+
});
|
| 121 |
+
|
| 122 |
+
describe('execute', () => {
|
| 123 |
+
it('should call mcpTool.callTool with correct parameters and format display output', async () => {
|
| 124 |
+
const params = { param: 'testValue' };
|
| 125 |
+
const mockToolSuccessResultObject = {
|
| 126 |
+
success: true,
|
| 127 |
+
details: 'executed',
|
| 128 |
+
};
|
| 129 |
+
const mockFunctionResponseContent = [
|
| 130 |
+
{
|
| 131 |
+
type: 'text',
|
| 132 |
+
text: JSON.stringify(mockToolSuccessResultObject),
|
| 133 |
+
},
|
| 134 |
+
];
|
| 135 |
+
const mockMcpToolResponseParts: Part[] = [
|
| 136 |
+
{
|
| 137 |
+
functionResponse: {
|
| 138 |
+
name: serverToolName,
|
| 139 |
+
response: { content: mockFunctionResponseContent },
|
| 140 |
+
},
|
| 141 |
+
},
|
| 142 |
+
];
|
| 143 |
+
mockCallTool.mockResolvedValue(mockMcpToolResponseParts);
|
| 144 |
+
|
| 145 |
+
const invocation = tool.build(params);
|
| 146 |
+
const toolResult: ToolResult = await invocation.execute(
|
| 147 |
+
new AbortController().signal,
|
| 148 |
+
);
|
| 149 |
+
|
| 150 |
+
expect(mockCallTool).toHaveBeenCalledWith([
|
| 151 |
+
{ name: serverToolName, args: params },
|
| 152 |
+
]);
|
| 153 |
+
|
| 154 |
+
const stringifiedResponseContent = JSON.stringify(
|
| 155 |
+
mockToolSuccessResultObject,
|
| 156 |
+
);
|
| 157 |
+
expect(toolResult.llmContent).toEqual([
|
| 158 |
+
{ text: stringifiedResponseContent },
|
| 159 |
+
]);
|
| 160 |
+
expect(toolResult.returnDisplay).toBe(stringifiedResponseContent);
|
| 161 |
+
});
|
| 162 |
+
|
| 163 |
+
it('should handle empty result from getStringifiedResultForDisplay', async () => {
|
| 164 |
+
const params = { param: 'testValue' };
|
| 165 |
+
const mockMcpToolResponsePartsEmpty: Part[] = [];
|
| 166 |
+
mockCallTool.mockResolvedValue(mockMcpToolResponsePartsEmpty);
|
| 167 |
+
const invocation = tool.build(params);
|
| 168 |
+
const toolResult: ToolResult = await invocation.execute(
|
| 169 |
+
new AbortController().signal,
|
| 170 |
+
);
|
| 171 |
+
expect(toolResult.returnDisplay).toBe('```json\n[]\n```');
|
| 172 |
+
expect(toolResult.llmContent).toEqual([
|
| 173 |
+
{ text: '[Error: Could not parse tool response]' },
|
| 174 |
+
]);
|
| 175 |
+
});
|
| 176 |
+
|
| 177 |
+
it('should propagate rejection if mcpTool.callTool rejects', async () => {
|
| 178 |
+
const params = { param: 'failCase' };
|
| 179 |
+
const expectedError = new Error('MCP call failed');
|
| 180 |
+
mockCallTool.mockRejectedValue(expectedError);
|
| 181 |
+
|
| 182 |
+
const invocation = tool.build(params);
|
| 183 |
+
await expect(
|
| 184 |
+
invocation.execute(new AbortController().signal),
|
| 185 |
+
).rejects.toThrow(expectedError);
|
| 186 |
+
});
|
| 187 |
+
|
| 188 |
+
it.each([
|
| 189 |
+
{ isErrorValue: true, description: 'true (bool)' },
|
| 190 |
+
{ isErrorValue: 'true', description: '"true" (str)' },
|
| 191 |
+
])(
|
| 192 |
+
'should consider a ToolResult with isError $description to be a failure',
|
| 193 |
+
async ({ isErrorValue }) => {
|
| 194 |
+
const tool = new DiscoveredMCPTool(
|
| 195 |
+
mockCallableToolInstance,
|
| 196 |
+
serverName,
|
| 197 |
+
serverToolName,
|
| 198 |
+
baseDescription,
|
| 199 |
+
inputSchema,
|
| 200 |
+
);
|
| 201 |
+
const params = { param: 'isErrorTrueCase' };
|
| 202 |
+
|
| 203 |
+
const errorResponse = { isError: isErrorValue };
|
| 204 |
+
const mockMcpToolResponseParts: Part[] = [
|
| 205 |
+
{
|
| 206 |
+
functionResponse: {
|
| 207 |
+
name: serverToolName,
|
| 208 |
+
response: { error: errorResponse },
|
| 209 |
+
},
|
| 210 |
+
},
|
| 211 |
+
];
|
| 212 |
+
mockCallTool.mockResolvedValue(mockMcpToolResponseParts);
|
| 213 |
+
const expectedError = new Error(
|
| 214 |
+
`MCP tool '${serverToolName}' reported tool error with response: ${JSON.stringify(
|
| 215 |
+
mockMcpToolResponseParts,
|
| 216 |
+
)}`,
|
| 217 |
+
);
|
| 218 |
+
|
| 219 |
+
const invocation = tool.build(params);
|
| 220 |
+
await expect(
|
| 221 |
+
invocation.execute(new AbortController().signal),
|
| 222 |
+
).rejects.toThrow(expectedError);
|
| 223 |
+
},
|
| 224 |
+
);
|
| 225 |
+
|
| 226 |
+
it.each([
|
| 227 |
+
{ isErrorValue: false, description: 'false (bool)' },
|
| 228 |
+
{ isErrorValue: 'false', description: '"false" (str)' },
|
| 229 |
+
])(
|
| 230 |
+
'should consider a ToolResult with isError ${description} to be a success',
|
| 231 |
+
async ({ isErrorValue }) => {
|
| 232 |
+
const tool = new DiscoveredMCPTool(
|
| 233 |
+
mockCallableToolInstance,
|
| 234 |
+
serverName,
|
| 235 |
+
serverToolName,
|
| 236 |
+
baseDescription,
|
| 237 |
+
inputSchema,
|
| 238 |
+
);
|
| 239 |
+
const params = { param: 'isErrorFalseCase' };
|
| 240 |
+
const mockToolSuccessResultObject = {
|
| 241 |
+
success: true,
|
| 242 |
+
details: 'executed',
|
| 243 |
+
};
|
| 244 |
+
const mockFunctionResponseContent = [
|
| 245 |
+
{
|
| 246 |
+
type: 'text',
|
| 247 |
+
text: JSON.stringify(mockToolSuccessResultObject),
|
| 248 |
+
},
|
| 249 |
+
];
|
| 250 |
+
|
| 251 |
+
const errorResponse = { isError: isErrorValue };
|
| 252 |
+
const mockMcpToolResponseParts: Part[] = [
|
| 253 |
+
{
|
| 254 |
+
functionResponse: {
|
| 255 |
+
name: serverToolName,
|
| 256 |
+
response: {
|
| 257 |
+
error: errorResponse,
|
| 258 |
+
content: mockFunctionResponseContent,
|
| 259 |
+
},
|
| 260 |
+
},
|
| 261 |
+
},
|
| 262 |
+
];
|
| 263 |
+
mockCallTool.mockResolvedValue(mockMcpToolResponseParts);
|
| 264 |
+
|
| 265 |
+
const invocation = tool.build(params);
|
| 266 |
+
const toolResult = await invocation.execute(
|
| 267 |
+
new AbortController().signal,
|
| 268 |
+
);
|
| 269 |
+
|
| 270 |
+
const stringifiedResponseContent = JSON.stringify(
|
| 271 |
+
mockToolSuccessResultObject,
|
| 272 |
+
);
|
| 273 |
+
expect(toolResult.llmContent).toEqual([
|
| 274 |
+
{ text: stringifiedResponseContent },
|
| 275 |
+
]);
|
| 276 |
+
expect(toolResult.returnDisplay).toBe(stringifiedResponseContent);
|
| 277 |
+
},
|
| 278 |
+
);
|
| 279 |
+
|
| 280 |
+
it('should handle a simple text response correctly', async () => {
|
| 281 |
+
const params = { param: 'test' };
|
| 282 |
+
const successMessage = 'This is a success message.';
|
| 283 |
+
|
| 284 |
+
// Simulate the response from the GenAI SDK, which wraps the MCP
|
| 285 |
+
// response in a functionResponse Part.
|
| 286 |
+
const sdkResponse: Part[] = [
|
| 287 |
+
{
|
| 288 |
+
functionResponse: {
|
| 289 |
+
name: serverToolName,
|
| 290 |
+
response: {
|
| 291 |
+
// The `content` array contains MCP ContentBlocks.
|
| 292 |
+
content: [{ type: 'text', text: successMessage }],
|
| 293 |
+
},
|
| 294 |
+
},
|
| 295 |
+
},
|
| 296 |
+
];
|
| 297 |
+
mockCallTool.mockResolvedValue(sdkResponse);
|
| 298 |
+
|
| 299 |
+
const invocation = tool.build(params);
|
| 300 |
+
const toolResult = await invocation.execute(new AbortController().signal);
|
| 301 |
+
|
| 302 |
+
// 1. Assert that the llmContent sent to the scheduler is a clean Part array.
|
| 303 |
+
expect(toolResult.llmContent).toEqual([{ text: successMessage }]);
|
| 304 |
+
|
| 305 |
+
// 2. Assert that the display output is the simple text message.
|
| 306 |
+
expect(toolResult.returnDisplay).toBe(successMessage);
|
| 307 |
+
|
| 308 |
+
// 3. Verify that the underlying callTool was made correctly.
|
| 309 |
+
expect(mockCallTool).toHaveBeenCalledWith([
|
| 310 |
+
{ name: serverToolName, args: params },
|
| 311 |
+
]);
|
| 312 |
+
});
|
| 313 |
+
|
| 314 |
+
it('should handle an AudioBlock response', async () => {
|
| 315 |
+
const params = { param: 'play' };
|
| 316 |
+
const sdkResponse: Part[] = [
|
| 317 |
+
{
|
| 318 |
+
functionResponse: {
|
| 319 |
+
name: serverToolName,
|
| 320 |
+
response: {
|
| 321 |
+
content: [
|
| 322 |
+
{
|
| 323 |
+
type: 'audio',
|
| 324 |
+
data: 'BASE64_AUDIO_DATA',
|
| 325 |
+
mimeType: 'audio/mp3',
|
| 326 |
+
},
|
| 327 |
+
],
|
| 328 |
+
},
|
| 329 |
+
},
|
| 330 |
+
},
|
| 331 |
+
];
|
| 332 |
+
mockCallTool.mockResolvedValue(sdkResponse);
|
| 333 |
+
|
| 334 |
+
const invocation = tool.build(params);
|
| 335 |
+
const toolResult = await invocation.execute(new AbortController().signal);
|
| 336 |
+
|
| 337 |
+
expect(toolResult.llmContent).toEqual([
|
| 338 |
+
{
|
| 339 |
+
text: `[Tool '${serverToolName}' provided the following audio data with mime-type: audio/mp3]`,
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
inlineData: {
|
| 343 |
+
mimeType: 'audio/mp3',
|
| 344 |
+
data: 'BASE64_AUDIO_DATA',
|
| 345 |
+
},
|
| 346 |
+
},
|
| 347 |
+
]);
|
| 348 |
+
expect(toolResult.returnDisplay).toBe('[Audio: audio/mp3]');
|
| 349 |
+
});
|
| 350 |
+
|
| 351 |
+
it('should handle a ResourceLinkBlock response', async () => {
|
| 352 |
+
const params = { param: 'get' };
|
| 353 |
+
const sdkResponse: Part[] = [
|
| 354 |
+
{
|
| 355 |
+
functionResponse: {
|
| 356 |
+
name: serverToolName,
|
| 357 |
+
response: {
|
| 358 |
+
content: [
|
| 359 |
+
{
|
| 360 |
+
type: 'resource_link',
|
| 361 |
+
uri: 'file:///path/to/thing',
|
| 362 |
+
name: 'resource-name',
|
| 363 |
+
title: 'My Resource',
|
| 364 |
+
},
|
| 365 |
+
],
|
| 366 |
+
},
|
| 367 |
+
},
|
| 368 |
+
},
|
| 369 |
+
];
|
| 370 |
+
mockCallTool.mockResolvedValue(sdkResponse);
|
| 371 |
+
|
| 372 |
+
const invocation = tool.build(params);
|
| 373 |
+
const toolResult = await invocation.execute(new AbortController().signal);
|
| 374 |
+
|
| 375 |
+
expect(toolResult.llmContent).toEqual([
|
| 376 |
+
{
|
| 377 |
+
text: 'Resource Link: My Resource at file:///path/to/thing',
|
| 378 |
+
},
|
| 379 |
+
]);
|
| 380 |
+
expect(toolResult.returnDisplay).toBe(
|
| 381 |
+
'[Link to My Resource: file:///path/to/thing]',
|
| 382 |
+
);
|
| 383 |
+
});
|
| 384 |
+
|
| 385 |
+
it('should handle an embedded text ResourceBlock response', async () => {
|
| 386 |
+
const params = { param: 'get' };
|
| 387 |
+
const sdkResponse: Part[] = [
|
| 388 |
+
{
|
| 389 |
+
functionResponse: {
|
| 390 |
+
name: serverToolName,
|
| 391 |
+
response: {
|
| 392 |
+
content: [
|
| 393 |
+
{
|
| 394 |
+
type: 'resource',
|
| 395 |
+
resource: {
|
| 396 |
+
uri: 'file:///path/to/text.txt',
|
| 397 |
+
text: 'This is the text content.',
|
| 398 |
+
mimeType: 'text/plain',
|
| 399 |
+
},
|
| 400 |
+
},
|
| 401 |
+
],
|
| 402 |
+
},
|
| 403 |
+
},
|
| 404 |
+
},
|
| 405 |
+
];
|
| 406 |
+
mockCallTool.mockResolvedValue(sdkResponse);
|
| 407 |
+
|
| 408 |
+
const invocation = tool.build(params);
|
| 409 |
+
const toolResult = await invocation.execute(new AbortController().signal);
|
| 410 |
+
|
| 411 |
+
expect(toolResult.llmContent).toEqual([
|
| 412 |
+
{ text: 'This is the text content.' },
|
| 413 |
+
]);
|
| 414 |
+
expect(toolResult.returnDisplay).toBe('This is the text content.');
|
| 415 |
+
});
|
| 416 |
+
|
| 417 |
+
it('should handle an embedded binary ResourceBlock response', async () => {
|
| 418 |
+
const params = { param: 'get' };
|
| 419 |
+
const sdkResponse: Part[] = [
|
| 420 |
+
{
|
| 421 |
+
functionResponse: {
|
| 422 |
+
name: serverToolName,
|
| 423 |
+
response: {
|
| 424 |
+
content: [
|
| 425 |
+
{
|
| 426 |
+
type: 'resource',
|
| 427 |
+
resource: {
|
| 428 |
+
uri: 'file:///path/to/data.bin',
|
| 429 |
+
blob: 'BASE64_BINARY_DATA',
|
| 430 |
+
mimeType: 'application/octet-stream',
|
| 431 |
+
},
|
| 432 |
+
},
|
| 433 |
+
],
|
| 434 |
+
},
|
| 435 |
+
},
|
| 436 |
+
},
|
| 437 |
+
];
|
| 438 |
+
mockCallTool.mockResolvedValue(sdkResponse);
|
| 439 |
+
|
| 440 |
+
const invocation = tool.build(params);
|
| 441 |
+
const toolResult = await invocation.execute(new AbortController().signal);
|
| 442 |
+
|
| 443 |
+
expect(toolResult.llmContent).toEqual([
|
| 444 |
+
{
|
| 445 |
+
text: `[Tool '${serverToolName}' provided the following embedded resource with mime-type: application/octet-stream]`,
|
| 446 |
+
},
|
| 447 |
+
{
|
| 448 |
+
inlineData: {
|
| 449 |
+
mimeType: 'application/octet-stream',
|
| 450 |
+
data: 'BASE64_BINARY_DATA',
|
| 451 |
+
},
|
| 452 |
+
},
|
| 453 |
+
]);
|
| 454 |
+
expect(toolResult.returnDisplay).toBe(
|
| 455 |
+
'[Embedded Resource: application/octet-stream]',
|
| 456 |
+
);
|
| 457 |
+
});
|
| 458 |
+
|
| 459 |
+
it('should handle a mix of content block types', async () => {
|
| 460 |
+
const params = { param: 'complex' };
|
| 461 |
+
const sdkResponse: Part[] = [
|
| 462 |
+
{
|
| 463 |
+
functionResponse: {
|
| 464 |
+
name: serverToolName,
|
| 465 |
+
response: {
|
| 466 |
+
content: [
|
| 467 |
+
{ type: 'text', text: 'First part.' },
|
| 468 |
+
{
|
| 469 |
+
type: 'image',
|
| 470 |
+
data: 'BASE64_IMAGE_DATA',
|
| 471 |
+
mimeType: 'image/jpeg',
|
| 472 |
+
},
|
| 473 |
+
{ type: 'text', text: 'Second part.' },
|
| 474 |
+
],
|
| 475 |
+
},
|
| 476 |
+
},
|
| 477 |
+
},
|
| 478 |
+
];
|
| 479 |
+
mockCallTool.mockResolvedValue(sdkResponse);
|
| 480 |
+
|
| 481 |
+
const invocation = tool.build(params);
|
| 482 |
+
const toolResult = await invocation.execute(new AbortController().signal);
|
| 483 |
+
|
| 484 |
+
expect(toolResult.llmContent).toEqual([
|
| 485 |
+
{ text: 'First part.' },
|
| 486 |
+
{
|
| 487 |
+
text: `[Tool '${serverToolName}' provided the following image data with mime-type: image/jpeg]`,
|
| 488 |
+
},
|
| 489 |
+
{
|
| 490 |
+
inlineData: {
|
| 491 |
+
mimeType: 'image/jpeg',
|
| 492 |
+
data: 'BASE64_IMAGE_DATA',
|
| 493 |
+
},
|
| 494 |
+
},
|
| 495 |
+
{ text: 'Second part.' },
|
| 496 |
+
]);
|
| 497 |
+
expect(toolResult.returnDisplay).toBe(
|
| 498 |
+
'First part.\n[Image: image/jpeg]\nSecond part.',
|
| 499 |
+
);
|
| 500 |
+
});
|
| 501 |
+
|
| 502 |
+
it('should ignore unknown content block types', async () => {
|
| 503 |
+
const params = { param: 'test' };
|
| 504 |
+
const sdkResponse: Part[] = [
|
| 505 |
+
{
|
| 506 |
+
functionResponse: {
|
| 507 |
+
name: serverToolName,
|
| 508 |
+
response: {
|
| 509 |
+
content: [
|
| 510 |
+
{ type: 'text', text: 'Valid part.' },
|
| 511 |
+
{ type: 'future_block', data: 'some-data' },
|
| 512 |
+
],
|
| 513 |
+
},
|
| 514 |
+
},
|
| 515 |
+
},
|
| 516 |
+
];
|
| 517 |
+
mockCallTool.mockResolvedValue(sdkResponse);
|
| 518 |
+
|
| 519 |
+
const invocation = tool.build(params);
|
| 520 |
+
const toolResult = await invocation.execute(new AbortController().signal);
|
| 521 |
+
|
| 522 |
+
expect(toolResult.llmContent).toEqual([{ text: 'Valid part.' }]);
|
| 523 |
+
expect(toolResult.returnDisplay).toBe(
|
| 524 |
+
'Valid part.\n[Unknown content type: future_block]',
|
| 525 |
+
);
|
| 526 |
+
});
|
| 527 |
+
|
| 528 |
+
it('should handle a complex mix of content block types', async () => {
|
| 529 |
+
const params = { param: 'super-complex' };
|
| 530 |
+
const sdkResponse: Part[] = [
|
| 531 |
+
{
|
| 532 |
+
functionResponse: {
|
| 533 |
+
name: serverToolName,
|
| 534 |
+
response: {
|
| 535 |
+
content: [
|
| 536 |
+
{ type: 'text', text: 'Here is a resource.' },
|
| 537 |
+
{
|
| 538 |
+
type: 'resource_link',
|
| 539 |
+
uri: 'file:///path/to/resource',
|
| 540 |
+
name: 'resource-name',
|
| 541 |
+
title: 'My Resource',
|
| 542 |
+
},
|
| 543 |
+
{
|
| 544 |
+
type: 'resource',
|
| 545 |
+
resource: {
|
| 546 |
+
uri: 'file:///path/to/text.txt',
|
| 547 |
+
text: 'Embedded text content.',
|
| 548 |
+
mimeType: 'text/plain',
|
| 549 |
+
},
|
| 550 |
+
},
|
| 551 |
+
{
|
| 552 |
+
type: 'image',
|
| 553 |
+
data: 'BASE64_IMAGE_DATA',
|
| 554 |
+
mimeType: 'image/jpeg',
|
| 555 |
+
},
|
| 556 |
+
],
|
| 557 |
+
},
|
| 558 |
+
},
|
| 559 |
+
},
|
| 560 |
+
];
|
| 561 |
+
mockCallTool.mockResolvedValue(sdkResponse);
|
| 562 |
+
|
| 563 |
+
const invocation = tool.build(params);
|
| 564 |
+
const toolResult = await invocation.execute(new AbortController().signal);
|
| 565 |
+
|
| 566 |
+
expect(toolResult.llmContent).toEqual([
|
| 567 |
+
{ text: 'Here is a resource.' },
|
| 568 |
+
{
|
| 569 |
+
text: 'Resource Link: My Resource at file:///path/to/resource',
|
| 570 |
+
},
|
| 571 |
+
{ text: 'Embedded text content.' },
|
| 572 |
+
{
|
| 573 |
+
text: `[Tool '${serverToolName}' provided the following image data with mime-type: image/jpeg]`,
|
| 574 |
+
},
|
| 575 |
+
{
|
| 576 |
+
inlineData: {
|
| 577 |
+
mimeType: 'image/jpeg',
|
| 578 |
+
data: 'BASE64_IMAGE_DATA',
|
| 579 |
+
},
|
| 580 |
+
},
|
| 581 |
+
]);
|
| 582 |
+
expect(toolResult.returnDisplay).toBe(
|
| 583 |
+
'Here is a resource.\n[Link to My Resource: file:///path/to/resource]\nEmbedded text content.\n[Image: image/jpeg]',
|
| 584 |
+
);
|
| 585 |
+
});
|
| 586 |
+
});
|
| 587 |
+
|
| 588 |
+
describe('shouldConfirmExecute', () => {
|
| 589 |
+
it('should return false if trust is true', async () => {
|
| 590 |
+
const trustedTool = new DiscoveredMCPTool(
|
| 591 |
+
mockCallableToolInstance,
|
| 592 |
+
serverName,
|
| 593 |
+
serverToolName,
|
| 594 |
+
baseDescription,
|
| 595 |
+
inputSchema,
|
| 596 |
+
undefined,
|
| 597 |
+
true,
|
| 598 |
+
);
|
| 599 |
+
const invocation = trustedTool.build({ param: 'mock' });
|
| 600 |
+
expect(
|
| 601 |
+
await invocation.shouldConfirmExecute(new AbortController().signal),
|
| 602 |
+
).toBe(false);
|
| 603 |
+
});
|
| 604 |
+
|
| 605 |
+
it('should return false if server is allowlisted', async () => {
|
| 606 |
+
const invocation = tool.build({ param: 'mock' }) as any;
|
| 607 |
+
invocation.constructor.allowlist.add(serverName);
|
| 608 |
+
expect(
|
| 609 |
+
await invocation.shouldConfirmExecute(new AbortController().signal),
|
| 610 |
+
).toBe(false);
|
| 611 |
+
});
|
| 612 |
+
|
| 613 |
+
it('should return false if tool is allowlisted', async () => {
|
| 614 |
+
const toolAllowlistKey = `${serverName}.${serverToolName}`;
|
| 615 |
+
const invocation = tool.build({ param: 'mock' }) as any;
|
| 616 |
+
invocation.constructor.allowlist.add(toolAllowlistKey);
|
| 617 |
+
expect(
|
| 618 |
+
await invocation.shouldConfirmExecute(new AbortController().signal),
|
| 619 |
+
).toBe(false);
|
| 620 |
+
});
|
| 621 |
+
|
| 622 |
+
it('should return confirmation details if not trusted and not allowlisted', async () => {
|
| 623 |
+
const invocation = tool.build({ param: 'mock' });
|
| 624 |
+
const confirmation = await invocation.shouldConfirmExecute(
|
| 625 |
+
new AbortController().signal,
|
| 626 |
+
);
|
| 627 |
+
expect(confirmation).not.toBe(false);
|
| 628 |
+
if (confirmation && confirmation.type === 'mcp') {
|
| 629 |
+
// Type guard for ToolMcpConfirmationDetails
|
| 630 |
+
expect(confirmation.type).toBe('mcp');
|
| 631 |
+
expect(confirmation.serverName).toBe(serverName);
|
| 632 |
+
expect(confirmation.toolName).toBe(serverToolName);
|
| 633 |
+
} else if (confirmation) {
|
| 634 |
+
// Handle other possible confirmation types if necessary, or strengthen test if only MCP is expected
|
| 635 |
+
throw new Error(
|
| 636 |
+
'Confirmation was not of expected type MCP or was false',
|
| 637 |
+
);
|
| 638 |
+
} else {
|
| 639 |
+
throw new Error(
|
| 640 |
+
'Confirmation details not in expected format or was false',
|
| 641 |
+
);
|
| 642 |
+
}
|
| 643 |
+
});
|
| 644 |
+
|
| 645 |
+
it('should add server to allowlist on ProceedAlwaysServer', async () => {
|
| 646 |
+
const invocation = tool.build({ param: 'mock' }) as any;
|
| 647 |
+
const confirmation = await invocation.shouldConfirmExecute(
|
| 648 |
+
new AbortController().signal,
|
| 649 |
+
);
|
| 650 |
+
expect(confirmation).not.toBe(false);
|
| 651 |
+
if (
|
| 652 |
+
confirmation &&
|
| 653 |
+
typeof confirmation === 'object' &&
|
| 654 |
+
'onConfirm' in confirmation &&
|
| 655 |
+
typeof confirmation.onConfirm === 'function'
|
| 656 |
+
) {
|
| 657 |
+
await confirmation.onConfirm(
|
| 658 |
+
ToolConfirmationOutcome.ProceedAlwaysServer,
|
| 659 |
+
);
|
| 660 |
+
expect(invocation.constructor.allowlist.has(serverName)).toBe(true);
|
| 661 |
+
} else {
|
| 662 |
+
throw new Error(
|
| 663 |
+
'Confirmation details or onConfirm not in expected format',
|
| 664 |
+
);
|
| 665 |
+
}
|
| 666 |
+
});
|
| 667 |
+
|
| 668 |
+
it('should add tool to allowlist on ProceedAlwaysTool', async () => {
|
| 669 |
+
const toolAllowlistKey = `${serverName}.${serverToolName}`;
|
| 670 |
+
const invocation = tool.build({ param: 'mock' }) as any;
|
| 671 |
+
const confirmation = await invocation.shouldConfirmExecute(
|
| 672 |
+
new AbortController().signal,
|
| 673 |
+
);
|
| 674 |
+
expect(confirmation).not.toBe(false);
|
| 675 |
+
if (
|
| 676 |
+
confirmation &&
|
| 677 |
+
typeof confirmation === 'object' &&
|
| 678 |
+
'onConfirm' in confirmation &&
|
| 679 |
+
typeof confirmation.onConfirm === 'function'
|
| 680 |
+
) {
|
| 681 |
+
await confirmation.onConfirm(ToolConfirmationOutcome.ProceedAlwaysTool);
|
| 682 |
+
expect(invocation.constructor.allowlist.has(toolAllowlistKey)).toBe(
|
| 683 |
+
true,
|
| 684 |
+
);
|
| 685 |
+
} else {
|
| 686 |
+
throw new Error(
|
| 687 |
+
'Confirmation details or onConfirm not in expected format',
|
| 688 |
+
);
|
| 689 |
+
}
|
| 690 |
+
});
|
| 691 |
+
|
| 692 |
+
it('should handle Cancel confirmation outcome', async () => {
|
| 693 |
+
const invocation = tool.build({ param: 'mock' }) as any;
|
| 694 |
+
const confirmation = await invocation.shouldConfirmExecute(
|
| 695 |
+
new AbortController().signal,
|
| 696 |
+
);
|
| 697 |
+
expect(confirmation).not.toBe(false);
|
| 698 |
+
if (
|
| 699 |
+
confirmation &&
|
| 700 |
+
typeof confirmation === 'object' &&
|
| 701 |
+
'onConfirm' in confirmation &&
|
| 702 |
+
typeof confirmation.onConfirm === 'function'
|
| 703 |
+
) {
|
| 704 |
+
// Cancel should not add anything to allowlist
|
| 705 |
+
await confirmation.onConfirm(ToolConfirmationOutcome.Cancel);
|
| 706 |
+
expect(invocation.constructor.allowlist.has(serverName)).toBe(false);
|
| 707 |
+
expect(
|
| 708 |
+
invocation.constructor.allowlist.has(
|
| 709 |
+
`${serverName}.${serverToolName}`,
|
| 710 |
+
),
|
| 711 |
+
).toBe(false);
|
| 712 |
+
} else {
|
| 713 |
+
throw new Error(
|
| 714 |
+
'Confirmation details or onConfirm not in expected format',
|
| 715 |
+
);
|
| 716 |
+
}
|
| 717 |
+
});
|
| 718 |
+
|
| 719 |
+
it('should handle ProceedOnce confirmation outcome', async () => {
|
| 720 |
+
const invocation = tool.build({ param: 'mock' }) as any;
|
| 721 |
+
const confirmation = await invocation.shouldConfirmExecute(
|
| 722 |
+
new AbortController().signal,
|
| 723 |
+
);
|
| 724 |
+
expect(confirmation).not.toBe(false);
|
| 725 |
+
if (
|
| 726 |
+
confirmation &&
|
| 727 |
+
typeof confirmation === 'object' &&
|
| 728 |
+
'onConfirm' in confirmation &&
|
| 729 |
+
typeof confirmation.onConfirm === 'function'
|
| 730 |
+
) {
|
| 731 |
+
// ProceedOnce should not add anything to allowlist
|
| 732 |
+
await confirmation.onConfirm(ToolConfirmationOutcome.ProceedOnce);
|
| 733 |
+
expect(invocation.constructor.allowlist.has(serverName)).toBe(false);
|
| 734 |
+
expect(
|
| 735 |
+
invocation.constructor.allowlist.has(
|
| 736 |
+
`${serverName}.${serverToolName}`,
|
| 737 |
+
),
|
| 738 |
+
).toBe(false);
|
| 739 |
+
} else {
|
| 740 |
+
throw new Error(
|
| 741 |
+
'Confirmation details or onConfirm not in expected format',
|
| 742 |
+
);
|
| 743 |
+
}
|
| 744 |
+
});
|
| 745 |
+
});
|
| 746 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/mcp-tool.ts
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import {
|
| 8 |
+
BaseDeclarativeTool,
|
| 9 |
+
BaseToolInvocation,
|
| 10 |
+
Kind,
|
| 11 |
+
ToolCallConfirmationDetails,
|
| 12 |
+
ToolConfirmationOutcome,
|
| 13 |
+
ToolInvocation,
|
| 14 |
+
ToolMcpConfirmationDetails,
|
| 15 |
+
ToolResult,
|
| 16 |
+
} from './tools.js';
|
| 17 |
+
import { CallableTool, FunctionCall, Part } from '@google/genai';
|
| 18 |
+
|
| 19 |
+
type ToolParams = Record<string, unknown>;
|
| 20 |
+
|
| 21 |
+
// Discriminated union for MCP Content Blocks to ensure type safety.
|
| 22 |
+
type McpTextBlock = {
|
| 23 |
+
type: 'text';
|
| 24 |
+
text: string;
|
| 25 |
+
};
|
| 26 |
+
|
| 27 |
+
type McpMediaBlock = {
|
| 28 |
+
type: 'image' | 'audio';
|
| 29 |
+
mimeType: string;
|
| 30 |
+
data: string;
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
type McpResourceBlock = {
|
| 34 |
+
type: 'resource';
|
| 35 |
+
resource: {
|
| 36 |
+
text?: string;
|
| 37 |
+
blob?: string;
|
| 38 |
+
mimeType?: string;
|
| 39 |
+
};
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
type McpResourceLinkBlock = {
|
| 43 |
+
type: 'resource_link';
|
| 44 |
+
uri: string;
|
| 45 |
+
title?: string;
|
| 46 |
+
name?: string;
|
| 47 |
+
};
|
| 48 |
+
|
| 49 |
+
type McpContentBlock =
|
| 50 |
+
| McpTextBlock
|
| 51 |
+
| McpMediaBlock
|
| 52 |
+
| McpResourceBlock
|
| 53 |
+
| McpResourceLinkBlock;
|
| 54 |
+
|
| 55 |
+
class DiscoveredMCPToolInvocation extends BaseToolInvocation<
|
| 56 |
+
ToolParams,
|
| 57 |
+
ToolResult
|
| 58 |
+
> {
|
| 59 |
+
private static readonly allowlist: Set<string> = new Set();
|
| 60 |
+
|
| 61 |
+
constructor(
|
| 62 |
+
private readonly mcpTool: CallableTool,
|
| 63 |
+
readonly serverName: string,
|
| 64 |
+
readonly serverToolName: string,
|
| 65 |
+
readonly displayName: string,
|
| 66 |
+
readonly timeout?: number,
|
| 67 |
+
readonly trust?: boolean,
|
| 68 |
+
params: ToolParams = {},
|
| 69 |
+
) {
|
| 70 |
+
super(params);
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
override async shouldConfirmExecute(
|
| 74 |
+
_abortSignal: AbortSignal,
|
| 75 |
+
): Promise<ToolCallConfirmationDetails | false> {
|
| 76 |
+
const serverAllowListKey = this.serverName;
|
| 77 |
+
const toolAllowListKey = `${this.serverName}.${this.serverToolName}`;
|
| 78 |
+
|
| 79 |
+
if (this.trust) {
|
| 80 |
+
return false; // server is trusted, no confirmation needed
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
if (
|
| 84 |
+
DiscoveredMCPToolInvocation.allowlist.has(serverAllowListKey) ||
|
| 85 |
+
DiscoveredMCPToolInvocation.allowlist.has(toolAllowListKey)
|
| 86 |
+
) {
|
| 87 |
+
return false; // server and/or tool already allowlisted
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
const confirmationDetails: ToolMcpConfirmationDetails = {
|
| 91 |
+
type: 'mcp',
|
| 92 |
+
title: 'Confirm MCP Tool Execution',
|
| 93 |
+
serverName: this.serverName,
|
| 94 |
+
toolName: this.serverToolName, // Display original tool name in confirmation
|
| 95 |
+
toolDisplayName: this.displayName, // Display global registry name exposed to model and user
|
| 96 |
+
onConfirm: async (outcome: ToolConfirmationOutcome) => {
|
| 97 |
+
if (outcome === ToolConfirmationOutcome.ProceedAlwaysServer) {
|
| 98 |
+
DiscoveredMCPToolInvocation.allowlist.add(serverAllowListKey);
|
| 99 |
+
} else if (outcome === ToolConfirmationOutcome.ProceedAlwaysTool) {
|
| 100 |
+
DiscoveredMCPToolInvocation.allowlist.add(toolAllowListKey);
|
| 101 |
+
}
|
| 102 |
+
},
|
| 103 |
+
};
|
| 104 |
+
return confirmationDetails;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// Determine if the response contains tool errors
|
| 108 |
+
// This is needed because CallToolResults should return errors inside the response.
|
| 109 |
+
// ref: https://modelcontextprotocol.io/specification/2025-06-18/schema#calltoolresult
|
| 110 |
+
isMCPToolError(rawResponseParts: Part[]): boolean {
|
| 111 |
+
const functionResponse = rawResponseParts?.[0]?.functionResponse;
|
| 112 |
+
const response = functionResponse?.response;
|
| 113 |
+
|
| 114 |
+
interface McpError {
|
| 115 |
+
isError?: boolean | string;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
if (response) {
|
| 119 |
+
const error = (response as { error?: McpError })?.error;
|
| 120 |
+
const isError = error?.isError;
|
| 121 |
+
|
| 122 |
+
if (error && (isError === true || isError === 'true')) {
|
| 123 |
+
return true;
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
return false;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
async execute(): Promise<ToolResult> {
|
| 130 |
+
const functionCalls: FunctionCall[] = [
|
| 131 |
+
{
|
| 132 |
+
name: this.serverToolName,
|
| 133 |
+
args: this.params,
|
| 134 |
+
},
|
| 135 |
+
];
|
| 136 |
+
|
| 137 |
+
const rawResponseParts = await this.mcpTool.callTool(functionCalls);
|
| 138 |
+
|
| 139 |
+
// Ensure the response is not an error
|
| 140 |
+
if (this.isMCPToolError(rawResponseParts)) {
|
| 141 |
+
throw new Error(
|
| 142 |
+
`MCP tool '${this.serverToolName}' reported tool error with response: ${JSON.stringify(rawResponseParts)}`,
|
| 143 |
+
);
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
const transformedParts = transformMcpContentToParts(rawResponseParts);
|
| 147 |
+
|
| 148 |
+
return {
|
| 149 |
+
llmContent: transformedParts,
|
| 150 |
+
returnDisplay: getStringifiedResultForDisplay(rawResponseParts),
|
| 151 |
+
};
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
getDescription(): string {
|
| 155 |
+
return this.displayName;
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
export class DiscoveredMCPTool extends BaseDeclarativeTool<
|
| 160 |
+
ToolParams,
|
| 161 |
+
ToolResult
|
| 162 |
+
> {
|
| 163 |
+
constructor(
|
| 164 |
+
private readonly mcpTool: CallableTool,
|
| 165 |
+
readonly serverName: string,
|
| 166 |
+
readonly serverToolName: string,
|
| 167 |
+
description: string,
|
| 168 |
+
override readonly parameterSchema: unknown,
|
| 169 |
+
readonly timeout?: number,
|
| 170 |
+
readonly trust?: boolean,
|
| 171 |
+
nameOverride?: string,
|
| 172 |
+
) {
|
| 173 |
+
super(
|
| 174 |
+
nameOverride ?? generateValidName(serverToolName),
|
| 175 |
+
`${serverToolName} (${serverName} MCP Server)`,
|
| 176 |
+
description,
|
| 177 |
+
Kind.Other,
|
| 178 |
+
parameterSchema,
|
| 179 |
+
true, // isOutputMarkdown
|
| 180 |
+
false, // canUpdateOutput
|
| 181 |
+
);
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
asFullyQualifiedTool(): DiscoveredMCPTool {
|
| 185 |
+
return new DiscoveredMCPTool(
|
| 186 |
+
this.mcpTool,
|
| 187 |
+
this.serverName,
|
| 188 |
+
this.serverToolName,
|
| 189 |
+
this.description,
|
| 190 |
+
this.parameterSchema,
|
| 191 |
+
this.timeout,
|
| 192 |
+
this.trust,
|
| 193 |
+
`${this.serverName}__${this.serverToolName}`,
|
| 194 |
+
);
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
protected createInvocation(
|
| 198 |
+
params: ToolParams,
|
| 199 |
+
): ToolInvocation<ToolParams, ToolResult> {
|
| 200 |
+
return new DiscoveredMCPToolInvocation(
|
| 201 |
+
this.mcpTool,
|
| 202 |
+
this.serverName,
|
| 203 |
+
this.serverToolName,
|
| 204 |
+
this.displayName,
|
| 205 |
+
this.timeout,
|
| 206 |
+
this.trust,
|
| 207 |
+
params,
|
| 208 |
+
);
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
function transformTextBlock(block: McpTextBlock): Part {
|
| 213 |
+
return { text: block.text };
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
function transformImageAudioBlock(
|
| 217 |
+
block: McpMediaBlock,
|
| 218 |
+
toolName: string,
|
| 219 |
+
): Part[] {
|
| 220 |
+
return [
|
| 221 |
+
{
|
| 222 |
+
text: `[Tool '${toolName}' provided the following ${
|
| 223 |
+
block.type
|
| 224 |
+
} data with mime-type: ${block.mimeType}]`,
|
| 225 |
+
},
|
| 226 |
+
{
|
| 227 |
+
inlineData: {
|
| 228 |
+
mimeType: block.mimeType,
|
| 229 |
+
data: block.data,
|
| 230 |
+
},
|
| 231 |
+
},
|
| 232 |
+
];
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
function transformResourceBlock(
|
| 236 |
+
block: McpResourceBlock,
|
| 237 |
+
toolName: string,
|
| 238 |
+
): Part | Part[] | null {
|
| 239 |
+
const resource = block.resource;
|
| 240 |
+
if (resource?.text) {
|
| 241 |
+
return { text: resource.text };
|
| 242 |
+
}
|
| 243 |
+
if (resource?.blob) {
|
| 244 |
+
const mimeType = resource.mimeType || 'application/octet-stream';
|
| 245 |
+
return [
|
| 246 |
+
{
|
| 247 |
+
text: `[Tool '${toolName}' provided the following embedded resource with mime-type: ${mimeType}]`,
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
inlineData: {
|
| 251 |
+
mimeType,
|
| 252 |
+
data: resource.blob,
|
| 253 |
+
},
|
| 254 |
+
},
|
| 255 |
+
];
|
| 256 |
+
}
|
| 257 |
+
return null;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
function transformResourceLinkBlock(block: McpResourceLinkBlock): Part {
|
| 261 |
+
return {
|
| 262 |
+
text: `Resource Link: ${block.title || block.name} at ${block.uri}`,
|
| 263 |
+
};
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
/**
|
| 267 |
+
* Transforms the raw MCP content blocks from the SDK response into a
|
| 268 |
+
* standard GenAI Part array.
|
| 269 |
+
* @param sdkResponse The raw Part[] array from `mcpTool.callTool()`.
|
| 270 |
+
* @returns A clean Part[] array ready for the scheduler.
|
| 271 |
+
*/
|
| 272 |
+
function transformMcpContentToParts(sdkResponse: Part[]): Part[] {
|
| 273 |
+
const funcResponse = sdkResponse?.[0]?.functionResponse;
|
| 274 |
+
const mcpContent = funcResponse?.response?.['content'] as McpContentBlock[];
|
| 275 |
+
const toolName = funcResponse?.name || 'unknown tool';
|
| 276 |
+
|
| 277 |
+
if (!Array.isArray(mcpContent)) {
|
| 278 |
+
return [{ text: '[Error: Could not parse tool response]' }];
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
const transformed = mcpContent.flatMap(
|
| 282 |
+
(block: McpContentBlock): Part | Part[] | null => {
|
| 283 |
+
switch (block.type) {
|
| 284 |
+
case 'text':
|
| 285 |
+
return transformTextBlock(block);
|
| 286 |
+
case 'image':
|
| 287 |
+
case 'audio':
|
| 288 |
+
return transformImageAudioBlock(block, toolName);
|
| 289 |
+
case 'resource':
|
| 290 |
+
return transformResourceBlock(block, toolName);
|
| 291 |
+
case 'resource_link':
|
| 292 |
+
return transformResourceLinkBlock(block);
|
| 293 |
+
default:
|
| 294 |
+
return null;
|
| 295 |
+
}
|
| 296 |
+
},
|
| 297 |
+
);
|
| 298 |
+
|
| 299 |
+
return transformed.filter((part): part is Part => part !== null);
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
/**
|
| 303 |
+
* Processes the raw response from the MCP tool to generate a clean,
|
| 304 |
+
* human-readable string for display in the CLI. It summarizes non-text
|
| 305 |
+
* content and presents text directly.
|
| 306 |
+
*
|
| 307 |
+
* @param rawResponse The raw Part[] array from the GenAI SDK.
|
| 308 |
+
* @returns A formatted string representing the tool's output.
|
| 309 |
+
*/
|
| 310 |
+
function getStringifiedResultForDisplay(rawResponse: Part[]): string {
|
| 311 |
+
const mcpContent = rawResponse?.[0]?.functionResponse?.response?.[
|
| 312 |
+
'content'
|
| 313 |
+
] as McpContentBlock[];
|
| 314 |
+
|
| 315 |
+
if (!Array.isArray(mcpContent)) {
|
| 316 |
+
return '```json\n' + JSON.stringify(rawResponse, null, 2) + '\n```';
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
const displayParts = mcpContent.map((block: McpContentBlock): string => {
|
| 320 |
+
switch (block.type) {
|
| 321 |
+
case 'text':
|
| 322 |
+
return block.text;
|
| 323 |
+
case 'image':
|
| 324 |
+
return `[Image: ${block.mimeType}]`;
|
| 325 |
+
case 'audio':
|
| 326 |
+
return `[Audio: ${block.mimeType}]`;
|
| 327 |
+
case 'resource_link':
|
| 328 |
+
return `[Link to ${block.title || block.name}: ${block.uri}]`;
|
| 329 |
+
case 'resource':
|
| 330 |
+
if (block.resource?.text) {
|
| 331 |
+
return block.resource.text;
|
| 332 |
+
}
|
| 333 |
+
return `[Embedded Resource: ${
|
| 334 |
+
block.resource?.mimeType || 'unknown type'
|
| 335 |
+
}]`;
|
| 336 |
+
default:
|
| 337 |
+
return `[Unknown content type: ${(block as { type: string }).type}]`;
|
| 338 |
+
}
|
| 339 |
+
});
|
| 340 |
+
|
| 341 |
+
return displayParts.join('\n');
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
/** Visible for testing */
|
| 345 |
+
export function generateValidName(name: string) {
|
| 346 |
+
// Replace invalid characters (based on 400 error message from Gemini API) with underscores
|
| 347 |
+
let validToolname = name.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
| 348 |
+
|
| 349 |
+
// If longer than 63 characters, replace middle with '___'
|
| 350 |
+
// (Gemini API says max length 64, but actual limit seems to be 63)
|
| 351 |
+
if (validToolname.length > 63) {
|
| 352 |
+
validToolname =
|
| 353 |
+
validToolname.slice(0, 28) + '___' + validToolname.slice(-32);
|
| 354 |
+
}
|
| 355 |
+
return validToolname;
|
| 356 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/memoryTool.test.ts
ADDED
|
@@ -0,0 +1,595 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { vi, describe, it, expect, beforeEach, afterEach, Mock } from 'vitest';
|
| 8 |
+
import {
|
| 9 |
+
MemoryTool,
|
| 10 |
+
setGeminiMdFilename,
|
| 11 |
+
getCurrentGeminiMdFilename,
|
| 12 |
+
getAllGeminiMdFilenames,
|
| 13 |
+
DEFAULT_CONTEXT_FILENAME,
|
| 14 |
+
} from './memoryTool.js';
|
| 15 |
+
import * as fs from 'fs/promises';
|
| 16 |
+
import * as path from 'path';
|
| 17 |
+
import * as os from 'os';
|
| 18 |
+
import { ToolConfirmationOutcome } from './tools.js';
|
| 19 |
+
|
| 20 |
+
// Mock dependencies
|
| 21 |
+
vi.mock('fs/promises');
|
| 22 |
+
vi.mock('os');
|
| 23 |
+
|
| 24 |
+
const MEMORY_SECTION_HEADER = '## Qwen Added Memories';
|
| 25 |
+
|
| 26 |
+
// Define a type for our fsAdapter to ensure consistency
|
| 27 |
+
interface FsAdapter {
|
| 28 |
+
readFile: (path: string, encoding: 'utf-8') => Promise<string>;
|
| 29 |
+
writeFile: (path: string, data: string, encoding: 'utf-8') => Promise<void>;
|
| 30 |
+
mkdir: (
|
| 31 |
+
path: string,
|
| 32 |
+
options: { recursive: boolean },
|
| 33 |
+
) => Promise<string | undefined>;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
describe('MemoryTool', () => {
|
| 37 |
+
const mockAbortSignal = new AbortController().signal;
|
| 38 |
+
|
| 39 |
+
const mockFsAdapter: {
|
| 40 |
+
readFile: Mock<FsAdapter['readFile']>;
|
| 41 |
+
writeFile: Mock<FsAdapter['writeFile']>;
|
| 42 |
+
mkdir: Mock<FsAdapter['mkdir']>;
|
| 43 |
+
} = {
|
| 44 |
+
readFile: vi.fn(),
|
| 45 |
+
writeFile: vi.fn(),
|
| 46 |
+
mkdir: vi.fn(),
|
| 47 |
+
};
|
| 48 |
+
|
| 49 |
+
beforeEach(() => {
|
| 50 |
+
vi.mocked(os.homedir).mockReturnValue(path.join('/mock', 'home'));
|
| 51 |
+
mockFsAdapter.readFile.mockReset();
|
| 52 |
+
mockFsAdapter.writeFile.mockReset().mockResolvedValue(undefined);
|
| 53 |
+
mockFsAdapter.mkdir
|
| 54 |
+
.mockReset()
|
| 55 |
+
.mockResolvedValue(undefined as string | undefined);
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
afterEach(() => {
|
| 59 |
+
vi.restoreAllMocks();
|
| 60 |
+
// Reset GEMINI_MD_FILENAME to its original value after each test
|
| 61 |
+
setGeminiMdFilename(DEFAULT_CONTEXT_FILENAME);
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
describe('setGeminiMdFilename', () => {
|
| 65 |
+
it('should update currentGeminiMdFilename when a valid new name is provided', () => {
|
| 66 |
+
const newName = 'CUSTOM_CONTEXT.md';
|
| 67 |
+
setGeminiMdFilename(newName);
|
| 68 |
+
expect(getCurrentGeminiMdFilename()).toBe(newName);
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
it('should not update currentGeminiMdFilename if the new name is empty or whitespace', () => {
|
| 72 |
+
const initialName = getCurrentGeminiMdFilename(); // Get current before trying to change
|
| 73 |
+
setGeminiMdFilename(' ');
|
| 74 |
+
expect(getCurrentGeminiMdFilename()).toBe(initialName);
|
| 75 |
+
|
| 76 |
+
setGeminiMdFilename('');
|
| 77 |
+
expect(getCurrentGeminiMdFilename()).toBe(initialName);
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
it('should handle an array of filenames', () => {
|
| 81 |
+
const newNames = ['CUSTOM_CONTEXT.md', 'ANOTHER_CONTEXT.md'];
|
| 82 |
+
setGeminiMdFilename(newNames);
|
| 83 |
+
expect(getCurrentGeminiMdFilename()).toBe('CUSTOM_CONTEXT.md');
|
| 84 |
+
expect(getAllGeminiMdFilenames()).toEqual(newNames);
|
| 85 |
+
});
|
| 86 |
+
});
|
| 87 |
+
|
| 88 |
+
describe('performAddMemoryEntry (static method)', () => {
|
| 89 |
+
let testFilePath: string;
|
| 90 |
+
|
| 91 |
+
beforeEach(() => {
|
| 92 |
+
testFilePath = path.join(os.homedir(), '.qwen', DEFAULT_CONTEXT_FILENAME);
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it('should create section and save a fact if file does not exist', async () => {
|
| 96 |
+
mockFsAdapter.readFile.mockRejectedValue({ code: 'ENOENT' }); // Simulate file not found
|
| 97 |
+
const fact = 'The sky is blue';
|
| 98 |
+
await MemoryTool.performAddMemoryEntry(fact, testFilePath, mockFsAdapter);
|
| 99 |
+
|
| 100 |
+
expect(mockFsAdapter.mkdir).toHaveBeenCalledWith(
|
| 101 |
+
path.dirname(testFilePath),
|
| 102 |
+
{
|
| 103 |
+
recursive: true,
|
| 104 |
+
},
|
| 105 |
+
);
|
| 106 |
+
expect(mockFsAdapter.writeFile).toHaveBeenCalledOnce();
|
| 107 |
+
const writeFileCall = mockFsAdapter.writeFile.mock.calls[0];
|
| 108 |
+
expect(writeFileCall[0]).toBe(testFilePath);
|
| 109 |
+
const expectedContent = `${MEMORY_SECTION_HEADER}\n- ${fact}\n`;
|
| 110 |
+
expect(writeFileCall[1]).toBe(expectedContent);
|
| 111 |
+
expect(writeFileCall[2]).toBe('utf-8');
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
it('should create section and save a fact if file is empty', async () => {
|
| 115 |
+
mockFsAdapter.readFile.mockResolvedValue(''); // Simulate empty file
|
| 116 |
+
const fact = 'The sky is blue';
|
| 117 |
+
await MemoryTool.performAddMemoryEntry(fact, testFilePath, mockFsAdapter);
|
| 118 |
+
const writeFileCall = mockFsAdapter.writeFile.mock.calls[0];
|
| 119 |
+
const expectedContent = `${MEMORY_SECTION_HEADER}\n- ${fact}\n`;
|
| 120 |
+
expect(writeFileCall[1]).toBe(expectedContent);
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
+
it('should add a fact to an existing section', async () => {
|
| 124 |
+
const initialContent = `Some preamble.\n\n${MEMORY_SECTION_HEADER}\n- Existing fact 1\n`;
|
| 125 |
+
mockFsAdapter.readFile.mockResolvedValue(initialContent);
|
| 126 |
+
const fact = 'New fact 2';
|
| 127 |
+
await MemoryTool.performAddMemoryEntry(fact, testFilePath, mockFsAdapter);
|
| 128 |
+
|
| 129 |
+
expect(mockFsAdapter.writeFile).toHaveBeenCalledOnce();
|
| 130 |
+
const writeFileCall = mockFsAdapter.writeFile.mock.calls[0];
|
| 131 |
+
const expectedContent = `Some preamble.\n\n${MEMORY_SECTION_HEADER}\n- Existing fact 1\n- ${fact}\n`;
|
| 132 |
+
expect(writeFileCall[1]).toBe(expectedContent);
|
| 133 |
+
});
|
| 134 |
+
|
| 135 |
+
it('should add a fact to an existing empty section', async () => {
|
| 136 |
+
const initialContent = `Some preamble.\n\n${MEMORY_SECTION_HEADER}\n`; // Empty section
|
| 137 |
+
mockFsAdapter.readFile.mockResolvedValue(initialContent);
|
| 138 |
+
const fact = 'First fact in section';
|
| 139 |
+
await MemoryTool.performAddMemoryEntry(fact, testFilePath, mockFsAdapter);
|
| 140 |
+
|
| 141 |
+
expect(mockFsAdapter.writeFile).toHaveBeenCalledOnce();
|
| 142 |
+
const writeFileCall = mockFsAdapter.writeFile.mock.calls[0];
|
| 143 |
+
const expectedContent = `Some preamble.\n\n${MEMORY_SECTION_HEADER}\n- ${fact}\n`;
|
| 144 |
+
expect(writeFileCall[1]).toBe(expectedContent);
|
| 145 |
+
});
|
| 146 |
+
|
| 147 |
+
it('should add a fact when other ## sections exist and preserve spacing', async () => {
|
| 148 |
+
const initialContent = `${MEMORY_SECTION_HEADER}\n- Fact 1\n\n## Another Section\nSome other text.`;
|
| 149 |
+
mockFsAdapter.readFile.mockResolvedValue(initialContent);
|
| 150 |
+
const fact = 'Fact 2';
|
| 151 |
+
await MemoryTool.performAddMemoryEntry(fact, testFilePath, mockFsAdapter);
|
| 152 |
+
|
| 153 |
+
expect(mockFsAdapter.writeFile).toHaveBeenCalledOnce();
|
| 154 |
+
const writeFileCall = mockFsAdapter.writeFile.mock.calls[0];
|
| 155 |
+
// Note: The implementation ensures a single newline at the end if content exists.
|
| 156 |
+
const expectedContent = `${MEMORY_SECTION_HEADER}\n- Fact 1\n- ${fact}\n\n## Another Section\nSome other text.\n`;
|
| 157 |
+
expect(writeFileCall[1]).toBe(expectedContent);
|
| 158 |
+
});
|
| 159 |
+
|
| 160 |
+
it('should correctly trim and add a fact that starts with a dash', async () => {
|
| 161 |
+
mockFsAdapter.readFile.mockResolvedValue(`${MEMORY_SECTION_HEADER}\n`);
|
| 162 |
+
const fact = '- - My fact with dashes';
|
| 163 |
+
await MemoryTool.performAddMemoryEntry(fact, testFilePath, mockFsAdapter);
|
| 164 |
+
const writeFileCall = mockFsAdapter.writeFile.mock.calls[0];
|
| 165 |
+
const expectedContent = `${MEMORY_SECTION_HEADER}\n- My fact with dashes\n`;
|
| 166 |
+
expect(writeFileCall[1]).toBe(expectedContent);
|
| 167 |
+
});
|
| 168 |
+
|
| 169 |
+
it('should handle error from fsAdapter.writeFile', async () => {
|
| 170 |
+
mockFsAdapter.readFile.mockResolvedValue('');
|
| 171 |
+
mockFsAdapter.writeFile.mockRejectedValue(new Error('Disk full'));
|
| 172 |
+
const fact = 'This will fail';
|
| 173 |
+
await expect(
|
| 174 |
+
MemoryTool.performAddMemoryEntry(fact, testFilePath, mockFsAdapter),
|
| 175 |
+
).rejects.toThrow('[MemoryTool] Failed to add memory entry: Disk full');
|
| 176 |
+
});
|
| 177 |
+
});
|
| 178 |
+
|
| 179 |
+
describe('execute (instance method)', () => {
|
| 180 |
+
let memoryTool: MemoryTool;
|
| 181 |
+
let performAddMemoryEntrySpy: Mock<typeof MemoryTool.performAddMemoryEntry>;
|
| 182 |
+
|
| 183 |
+
beforeEach(() => {
|
| 184 |
+
memoryTool = new MemoryTool();
|
| 185 |
+
// Spy on the static method for these tests
|
| 186 |
+
performAddMemoryEntrySpy = vi
|
| 187 |
+
.spyOn(MemoryTool, 'performAddMemoryEntry')
|
| 188 |
+
.mockResolvedValue(undefined) as Mock<
|
| 189 |
+
typeof MemoryTool.performAddMemoryEntry
|
| 190 |
+
>;
|
| 191 |
+
// Cast needed as spyOn returns MockInstance
|
| 192 |
+
});
|
| 193 |
+
|
| 194 |
+
it('should have correct name, displayName, description, and schema', () => {
|
| 195 |
+
expect(memoryTool.name).toBe('save_memory');
|
| 196 |
+
expect(memoryTool.displayName).toBe('Save Memory');
|
| 197 |
+
expect(memoryTool.description).toContain(
|
| 198 |
+
'Saves a specific piece of information',
|
| 199 |
+
);
|
| 200 |
+
expect(memoryTool.schema).toBeDefined();
|
| 201 |
+
expect(memoryTool.schema.name).toBe('save_memory');
|
| 202 |
+
expect(memoryTool.schema.parametersJsonSchema).toBeDefined();
|
| 203 |
+
});
|
| 204 |
+
|
| 205 |
+
it('should call performAddMemoryEntry with correct parameters and return success for global scope', async () => {
|
| 206 |
+
const params = { fact: 'The sky is blue', scope: 'global' as const };
|
| 207 |
+
const invocation = memoryTool.build(params);
|
| 208 |
+
const result = await invocation.execute(mockAbortSignal);
|
| 209 |
+
|
| 210 |
+
// Use getCurrentGeminiMdFilename for the default expectation before any setGeminiMdFilename calls in a test
|
| 211 |
+
const expectedFilePath = path.join(
|
| 212 |
+
os.homedir(),
|
| 213 |
+
'.qwen',
|
| 214 |
+
getCurrentGeminiMdFilename(), // This will be DEFAULT_CONTEXT_FILENAME unless changed by a test
|
| 215 |
+
);
|
| 216 |
+
|
| 217 |
+
// For this test, we expect the actual fs methods to be passed
|
| 218 |
+
const expectedFsArgument = {
|
| 219 |
+
readFile: fs.readFile,
|
| 220 |
+
writeFile: fs.writeFile,
|
| 221 |
+
mkdir: fs.mkdir,
|
| 222 |
+
};
|
| 223 |
+
|
| 224 |
+
expect(performAddMemoryEntrySpy).toHaveBeenCalledWith(
|
| 225 |
+
params.fact,
|
| 226 |
+
expectedFilePath,
|
| 227 |
+
expectedFsArgument,
|
| 228 |
+
);
|
| 229 |
+
const successMessage = `Okay, I've remembered that in global memory: "${params.fact}"`;
|
| 230 |
+
expect(result.llmContent).toBe(
|
| 231 |
+
JSON.stringify({ success: true, message: successMessage }),
|
| 232 |
+
);
|
| 233 |
+
expect(result.returnDisplay).toBe(successMessage);
|
| 234 |
+
});
|
| 235 |
+
|
| 236 |
+
it('should call performAddMemoryEntry with correct parameters and return success for project scope', async () => {
|
| 237 |
+
const params = { fact: 'The sky is blue', scope: 'project' as const };
|
| 238 |
+
const invocation = memoryTool.build(params);
|
| 239 |
+
const result = await invocation.execute(mockAbortSignal);
|
| 240 |
+
|
| 241 |
+
// For project scope, expect the file to be in current working directory
|
| 242 |
+
const expectedFilePath = path.join(
|
| 243 |
+
process.cwd(),
|
| 244 |
+
getCurrentGeminiMdFilename(),
|
| 245 |
+
);
|
| 246 |
+
|
| 247 |
+
// For this test, we expect the actual fs methods to be passed
|
| 248 |
+
const expectedFsArgument = {
|
| 249 |
+
readFile: fs.readFile,
|
| 250 |
+
writeFile: fs.writeFile,
|
| 251 |
+
mkdir: fs.mkdir,
|
| 252 |
+
};
|
| 253 |
+
|
| 254 |
+
expect(performAddMemoryEntrySpy).toHaveBeenCalledWith(
|
| 255 |
+
params.fact,
|
| 256 |
+
expectedFilePath,
|
| 257 |
+
expectedFsArgument,
|
| 258 |
+
);
|
| 259 |
+
const successMessage = `Okay, I've remembered that in project memory: "${params.fact}"`;
|
| 260 |
+
expect(result.llmContent).toBe(
|
| 261 |
+
JSON.stringify({ success: true, message: successMessage }),
|
| 262 |
+
);
|
| 263 |
+
expect(result.returnDisplay).toBe(successMessage);
|
| 264 |
+
});
|
| 265 |
+
|
| 266 |
+
it('should return an error if fact is empty', async () => {
|
| 267 |
+
const params = { fact: ' ' }; // Empty fact
|
| 268 |
+
expect(memoryTool.validateToolParams(params)).toBe(
|
| 269 |
+
'Parameter "fact" must be a non-empty string.',
|
| 270 |
+
);
|
| 271 |
+
expect(() => memoryTool.build(params)).toThrow(
|
| 272 |
+
'Parameter "fact" must be a non-empty string.',
|
| 273 |
+
);
|
| 274 |
+
});
|
| 275 |
+
|
| 276 |
+
it('should handle errors from performAddMemoryEntry', async () => {
|
| 277 |
+
const params = { fact: 'This will fail', scope: 'global' as const };
|
| 278 |
+
const underlyingError = new Error(
|
| 279 |
+
'[MemoryTool] Failed to add memory entry: Disk full',
|
| 280 |
+
);
|
| 281 |
+
performAddMemoryEntrySpy.mockRejectedValue(underlyingError);
|
| 282 |
+
|
| 283 |
+
const invocation = memoryTool.build(params);
|
| 284 |
+
const result = await invocation.execute(mockAbortSignal);
|
| 285 |
+
|
| 286 |
+
expect(result.llmContent).toBe(
|
| 287 |
+
JSON.stringify({
|
| 288 |
+
success: false,
|
| 289 |
+
error: `Failed to save memory. Detail: ${underlyingError.message}`,
|
| 290 |
+
}),
|
| 291 |
+
);
|
| 292 |
+
expect(result.returnDisplay).toBe(
|
| 293 |
+
`Error saving memory: ${underlyingError.message}`,
|
| 294 |
+
);
|
| 295 |
+
});
|
| 296 |
+
|
| 297 |
+
it('should return error when executing without scope parameter', async () => {
|
| 298 |
+
const params = { fact: 'Test fact' };
|
| 299 |
+
const invocation = memoryTool.build(params);
|
| 300 |
+
const result = await invocation.execute(mockAbortSignal);
|
| 301 |
+
|
| 302 |
+
expect(result.llmContent).toContain(
|
| 303 |
+
'Please specify where to save this memory',
|
| 304 |
+
);
|
| 305 |
+
expect(result.returnDisplay).toContain('Global:');
|
| 306 |
+
expect(result.returnDisplay).toContain('Project:');
|
| 307 |
+
});
|
| 308 |
+
});
|
| 309 |
+
|
| 310 |
+
describe('shouldConfirmExecute', () => {
|
| 311 |
+
let memoryTool: MemoryTool;
|
| 312 |
+
|
| 313 |
+
beforeEach(() => {
|
| 314 |
+
memoryTool = new MemoryTool();
|
| 315 |
+
// Mock fs.readFile to return empty string (file doesn't exist)
|
| 316 |
+
vi.mocked(fs.readFile).mockResolvedValue('');
|
| 317 |
+
|
| 318 |
+
// Clear allowlist before each test to ensure clean state
|
| 319 |
+
const invocation = memoryTool.build({ fact: 'test', scope: 'global' });
|
| 320 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 321 |
+
(invocation.constructor as any).allowlist.clear();
|
| 322 |
+
});
|
| 323 |
+
|
| 324 |
+
it('should return confirmation details when memory file is not allowlisted for global scope', async () => {
|
| 325 |
+
const params = { fact: 'Test fact', scope: 'global' as const };
|
| 326 |
+
const invocation = memoryTool.build(params);
|
| 327 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 328 |
+
|
| 329 |
+
expect(result).toBeDefined();
|
| 330 |
+
expect(result).not.toBe(false);
|
| 331 |
+
|
| 332 |
+
if (result && result.type === 'edit') {
|
| 333 |
+
const expectedPath = path.join('~', '.qwen', 'QWEN.md');
|
| 334 |
+
expect(result.title).toBe(
|
| 335 |
+
`Confirm Memory Save: ${expectedPath} (global)`,
|
| 336 |
+
);
|
| 337 |
+
expect(result.fileName).toContain(path.join('mock', 'home', '.qwen'));
|
| 338 |
+
expect(result.fileName).toContain('QWEN.md');
|
| 339 |
+
expect(result.fileDiff).toContain('Index: QWEN.md');
|
| 340 |
+
expect(result.fileDiff).toContain('+## Qwen Added Memories');
|
| 341 |
+
expect(result.fileDiff).toContain('+- Test fact');
|
| 342 |
+
expect(result.originalContent).toBe('');
|
| 343 |
+
expect(result.newContent).toContain('## Qwen Added Memories');
|
| 344 |
+
expect(result.newContent).toContain('- Test fact');
|
| 345 |
+
}
|
| 346 |
+
});
|
| 347 |
+
|
| 348 |
+
it('should return confirmation details when memory file is not allowlisted for project scope', async () => {
|
| 349 |
+
const params = { fact: 'Test fact', scope: 'project' as const };
|
| 350 |
+
const invocation = memoryTool.build(params);
|
| 351 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 352 |
+
|
| 353 |
+
expect(result).toBeDefined();
|
| 354 |
+
expect(result).not.toBe(false);
|
| 355 |
+
|
| 356 |
+
if (result && result.type === 'edit') {
|
| 357 |
+
const expectedPath = path.join(process.cwd(), 'QWEN.md');
|
| 358 |
+
expect(result.title).toBe(
|
| 359 |
+
`Confirm Memory Save: ${expectedPath} (project)`,
|
| 360 |
+
);
|
| 361 |
+
expect(result.fileName).toBe(expectedPath);
|
| 362 |
+
expect(result.fileDiff).toContain('Index: QWEN.md');
|
| 363 |
+
expect(result.fileDiff).toContain('+## Qwen Added Memories');
|
| 364 |
+
expect(result.fileDiff).toContain('+- Test fact');
|
| 365 |
+
expect(result.originalContent).toBe('');
|
| 366 |
+
expect(result.newContent).toContain('## Qwen Added Memories');
|
| 367 |
+
expect(result.newContent).toContain('- Test fact');
|
| 368 |
+
}
|
| 369 |
+
});
|
| 370 |
+
|
| 371 |
+
it('should return false when memory file is already allowlisted for global scope', async () => {
|
| 372 |
+
const params = { fact: 'Test fact', scope: 'global' as const };
|
| 373 |
+
const memoryFilePath = path.join(
|
| 374 |
+
os.homedir(),
|
| 375 |
+
'.qwen',
|
| 376 |
+
getCurrentGeminiMdFilename(),
|
| 377 |
+
);
|
| 378 |
+
|
| 379 |
+
const invocation = memoryTool.build(params);
|
| 380 |
+
// Add the memory file to the allowlist with the scope-specific key format
|
| 381 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 382 |
+
(invocation.constructor as any).allowlist.add(`${memoryFilePath}_global`);
|
| 383 |
+
|
| 384 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 385 |
+
|
| 386 |
+
expect(result).toBe(false);
|
| 387 |
+
});
|
| 388 |
+
|
| 389 |
+
it('should return false when memory file is already allowlisted for project scope', async () => {
|
| 390 |
+
const params = { fact: 'Test fact', scope: 'project' as const };
|
| 391 |
+
const memoryFilePath = path.join(
|
| 392 |
+
process.cwd(),
|
| 393 |
+
getCurrentGeminiMdFilename(),
|
| 394 |
+
);
|
| 395 |
+
|
| 396 |
+
const invocation = memoryTool.build(params);
|
| 397 |
+
// Add the memory file to the allowlist with the scope-specific key format
|
| 398 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 399 |
+
(invocation.constructor as any).allowlist.add(
|
| 400 |
+
`${memoryFilePath}_project`,
|
| 401 |
+
);
|
| 402 |
+
|
| 403 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 404 |
+
|
| 405 |
+
expect(result).toBe(false);
|
| 406 |
+
});
|
| 407 |
+
|
| 408 |
+
it('should add memory file to allowlist when ProceedAlways is confirmed for global scope', async () => {
|
| 409 |
+
const params = { fact: 'Test fact', scope: 'global' as const };
|
| 410 |
+
const memoryFilePath = path.join(
|
| 411 |
+
os.homedir(),
|
| 412 |
+
'.qwen',
|
| 413 |
+
getCurrentGeminiMdFilename(),
|
| 414 |
+
);
|
| 415 |
+
|
| 416 |
+
const invocation = memoryTool.build(params);
|
| 417 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 418 |
+
|
| 419 |
+
expect(result).toBeDefined();
|
| 420 |
+
expect(result).not.toBe(false);
|
| 421 |
+
|
| 422 |
+
if (result && result.type === 'edit') {
|
| 423 |
+
// Simulate the onConfirm callback
|
| 424 |
+
await result.onConfirm(ToolConfirmationOutcome.ProceedAlways);
|
| 425 |
+
|
| 426 |
+
// Check that the memory file was added to the allowlist with the scope-specific key format
|
| 427 |
+
expect(
|
| 428 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 429 |
+
(invocation.constructor as any).allowlist.has(
|
| 430 |
+
`${memoryFilePath}_global`,
|
| 431 |
+
),
|
| 432 |
+
).toBe(true);
|
| 433 |
+
}
|
| 434 |
+
});
|
| 435 |
+
|
| 436 |
+
it('should add memory file to allowlist when ProceedAlways is confirmed for project scope', async () => {
|
| 437 |
+
const params = { fact: 'Test fact', scope: 'project' as const };
|
| 438 |
+
const memoryFilePath = path.join(
|
| 439 |
+
process.cwd(),
|
| 440 |
+
getCurrentGeminiMdFilename(),
|
| 441 |
+
);
|
| 442 |
+
|
| 443 |
+
const invocation = memoryTool.build(params);
|
| 444 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 445 |
+
|
| 446 |
+
expect(result).toBeDefined();
|
| 447 |
+
expect(result).not.toBe(false);
|
| 448 |
+
|
| 449 |
+
if (result && result.type === 'edit') {
|
| 450 |
+
// Simulate the onConfirm callback
|
| 451 |
+
await result.onConfirm(ToolConfirmationOutcome.ProceedAlways);
|
| 452 |
+
|
| 453 |
+
// Check that the memory file was added to the allowlist with the scope-specific key format
|
| 454 |
+
expect(
|
| 455 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 456 |
+
(invocation.constructor as any).allowlist.has(
|
| 457 |
+
`${memoryFilePath}_project`,
|
| 458 |
+
),
|
| 459 |
+
).toBe(true);
|
| 460 |
+
}
|
| 461 |
+
});
|
| 462 |
+
|
| 463 |
+
it('should not add memory file to allowlist when other outcomes are confirmed', async () => {
|
| 464 |
+
const params = { fact: 'Test fact', scope: 'global' as const };
|
| 465 |
+
const memoryFilePath = path.join(
|
| 466 |
+
os.homedir(),
|
| 467 |
+
'.qwen',
|
| 468 |
+
getCurrentGeminiMdFilename(),
|
| 469 |
+
);
|
| 470 |
+
|
| 471 |
+
const invocation = memoryTool.build(params);
|
| 472 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 473 |
+
|
| 474 |
+
expect(result).toBeDefined();
|
| 475 |
+
expect(result).not.toBe(false);
|
| 476 |
+
|
| 477 |
+
if (result && result.type === 'edit') {
|
| 478 |
+
// Simulate the onConfirm callback with different outcomes
|
| 479 |
+
await result.onConfirm(ToolConfirmationOutcome.ProceedOnce);
|
| 480 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 481 |
+
const allowlist = (invocation.constructor as any).allowlist;
|
| 482 |
+
expect(allowlist.has(`${memoryFilePath}_global`)).toBe(false);
|
| 483 |
+
|
| 484 |
+
await result.onConfirm(ToolConfirmationOutcome.Cancel);
|
| 485 |
+
expect(allowlist.has(`${memoryFilePath}_global`)).toBe(false);
|
| 486 |
+
}
|
| 487 |
+
});
|
| 488 |
+
|
| 489 |
+
it('should handle existing memory file with content for global scope', async () => {
|
| 490 |
+
const params = { fact: 'New fact', scope: 'global' as const };
|
| 491 |
+
const existingContent =
|
| 492 |
+
'Some existing content.\n\n## Qwen Added Memories\n- Old fact\n';
|
| 493 |
+
|
| 494 |
+
// Mock fs.readFile to return existing content
|
| 495 |
+
vi.mocked(fs.readFile).mockResolvedValue(existingContent);
|
| 496 |
+
|
| 497 |
+
const invocation = memoryTool.build(params);
|
| 498 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 499 |
+
|
| 500 |
+
expect(result).toBeDefined();
|
| 501 |
+
expect(result).not.toBe(false);
|
| 502 |
+
|
| 503 |
+
if (result && result.type === 'edit') {
|
| 504 |
+
const expectedPath = path.join('~', '.qwen', 'QWEN.md');
|
| 505 |
+
expect(result.title).toBe(
|
| 506 |
+
`Confirm Memory Save: ${expectedPath} (global)`,
|
| 507 |
+
);
|
| 508 |
+
expect(result.fileDiff).toContain('Index: QWEN.md');
|
| 509 |
+
expect(result.fileDiff).toContain('+- New fact');
|
| 510 |
+
expect(result.originalContent).toBe(existingContent);
|
| 511 |
+
expect(result.newContent).toContain('- Old fact');
|
| 512 |
+
expect(result.newContent).toContain('- New fact');
|
| 513 |
+
}
|
| 514 |
+
});
|
| 515 |
+
|
| 516 |
+
it('should prompt for scope selection when scope is not specified', async () => {
|
| 517 |
+
const params = { fact: 'Test fact' };
|
| 518 |
+
const invocation = memoryTool.build(params);
|
| 519 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 520 |
+
|
| 521 |
+
expect(result).toBeDefined();
|
| 522 |
+
expect(result).not.toBe(false);
|
| 523 |
+
|
| 524 |
+
if (result && result.type === 'edit') {
|
| 525 |
+
expect(result.title).toContain('Choose Memory Location');
|
| 526 |
+
expect(result.title).toContain('GLOBAL');
|
| 527 |
+
expect(result.title).toContain('PROJECT');
|
| 528 |
+
expect(result.fileName).toBe('QWEN.md');
|
| 529 |
+
expect(result.fileDiff).toContain('Test fact');
|
| 530 |
+
expect(result.fileDiff).toContain('--- QWEN.md');
|
| 531 |
+
expect(result.fileDiff).toContain('+++ QWEN.md');
|
| 532 |
+
expect(result.fileDiff).toContain('+- Test fact');
|
| 533 |
+
expect(result.originalContent).toContain('scope: global');
|
| 534 |
+
expect(result.originalContent).toContain('INSTRUCTIONS:');
|
| 535 |
+
}
|
| 536 |
+
});
|
| 537 |
+
|
| 538 |
+
it('should show correct file paths in scope selection prompt', async () => {
|
| 539 |
+
const params = { fact: 'Test fact' };
|
| 540 |
+
const invocation = memoryTool.build(params);
|
| 541 |
+
const result = await invocation.shouldConfirmExecute(mockAbortSignal);
|
| 542 |
+
|
| 543 |
+
expect(result).toBeDefined();
|
| 544 |
+
expect(result).not.toBe(false);
|
| 545 |
+
|
| 546 |
+
if (result && result.type === 'edit') {
|
| 547 |
+
const globalPath = path.join('~', '.qwen', 'QWEN.md');
|
| 548 |
+
const projectPath = path.join(process.cwd(), 'QWEN.md');
|
| 549 |
+
|
| 550 |
+
expect(result.fileDiff).toContain(`Global: ${globalPath}`);
|
| 551 |
+
expect(result.fileDiff).toContain(`Project: ${projectPath}`);
|
| 552 |
+
expect(result.fileDiff).toContain('(shared across all projects)');
|
| 553 |
+
expect(result.fileDiff).toContain('(current project only)');
|
| 554 |
+
}
|
| 555 |
+
});
|
| 556 |
+
});
|
| 557 |
+
|
| 558 |
+
describe('getDescription', () => {
|
| 559 |
+
let memoryTool: MemoryTool;
|
| 560 |
+
|
| 561 |
+
beforeEach(() => {
|
| 562 |
+
memoryTool = new MemoryTool();
|
| 563 |
+
});
|
| 564 |
+
|
| 565 |
+
it('should return correct description for global scope', () => {
|
| 566 |
+
const params = { fact: 'Test fact', scope: 'global' as const };
|
| 567 |
+
const invocation = memoryTool.build(params);
|
| 568 |
+
const description = invocation.getDescription();
|
| 569 |
+
|
| 570 |
+
const expectedPath = path.join('~', '.qwen', 'QWEN.md');
|
| 571 |
+
expect(description).toBe(`${expectedPath} (global)`);
|
| 572 |
+
});
|
| 573 |
+
|
| 574 |
+
it('should return correct description for project scope', () => {
|
| 575 |
+
const params = { fact: 'Test fact', scope: 'project' as const };
|
| 576 |
+
const invocation = memoryTool.build(params);
|
| 577 |
+
const description = invocation.getDescription();
|
| 578 |
+
|
| 579 |
+
const expectedPath = path.join(process.cwd(), 'QWEN.md');
|
| 580 |
+
expect(description).toBe(`${expectedPath} (project)`);
|
| 581 |
+
});
|
| 582 |
+
|
| 583 |
+
it('should show choice prompt when scope is not specified', () => {
|
| 584 |
+
const params = { fact: 'Test fact' };
|
| 585 |
+
const invocation = memoryTool.build(params);
|
| 586 |
+
const description = invocation.getDescription();
|
| 587 |
+
|
| 588 |
+
const globalPath = path.join('~', '.qwen', 'QWEN.md');
|
| 589 |
+
const projectPath = path.join(process.cwd(), 'QWEN.md');
|
| 590 |
+
expect(description).toBe(
|
| 591 |
+
`CHOOSE: ${globalPath} (global) OR ${projectPath} (project)`,
|
| 592 |
+
);
|
| 593 |
+
});
|
| 594 |
+
});
|
| 595 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/memoryTool.ts
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import {
|
| 8 |
+
BaseDeclarativeTool,
|
| 9 |
+
BaseToolInvocation,
|
| 10 |
+
Kind,
|
| 11 |
+
ToolResult,
|
| 12 |
+
ToolEditConfirmationDetails,
|
| 13 |
+
ToolConfirmationOutcome,
|
| 14 |
+
} from './tools.js';
|
| 15 |
+
import { FunctionDeclaration } from '@google/genai';
|
| 16 |
+
import * as fs from 'fs/promises';
|
| 17 |
+
import * as path from 'path';
|
| 18 |
+
import { homedir } from 'os';
|
| 19 |
+
import * as Diff from 'diff';
|
| 20 |
+
import { DEFAULT_DIFF_OPTIONS } from './diffOptions.js';
|
| 21 |
+
import { tildeifyPath } from '../utils/paths.js';
|
| 22 |
+
import { ModifiableDeclarativeTool, ModifyContext } from './modifiable-tool.js';
|
| 23 |
+
|
| 24 |
+
const memoryToolSchemaData: FunctionDeclaration = {
|
| 25 |
+
name: 'save_memory',
|
| 26 |
+
description:
|
| 27 |
+
'Saves a specific piece of information or fact to your long-term memory. Use this when the user explicitly asks you to remember something, or when they state a clear, concise fact that seems important to retain for future interactions.',
|
| 28 |
+
parametersJsonSchema: {
|
| 29 |
+
type: 'object',
|
| 30 |
+
properties: {
|
| 31 |
+
fact: {
|
| 32 |
+
type: 'string',
|
| 33 |
+
description:
|
| 34 |
+
'The specific fact or piece of information to remember. Should be a clear, self-contained statement.',
|
| 35 |
+
},
|
| 36 |
+
scope: {
|
| 37 |
+
type: 'string',
|
| 38 |
+
description:
|
| 39 |
+
'Where to save the memory: "global" saves to user-level ~/.qwen/QWEN.md (shared across all projects), "project" saves to current project\'s QWEN.md (project-specific). If not specified, will prompt user to choose.',
|
| 40 |
+
enum: ['global', 'project'],
|
| 41 |
+
},
|
| 42 |
+
},
|
| 43 |
+
required: ['fact'],
|
| 44 |
+
},
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
const memoryToolDescription = `
|
| 48 |
+
Saves a specific piece of information or fact to your long-term memory.
|
| 49 |
+
|
| 50 |
+
Use this tool:
|
| 51 |
+
|
| 52 |
+
- When the user explicitly asks you to remember something (e.g., "Remember that I like pineapple on pizza", "Please save this: my cat's name is Whiskers").
|
| 53 |
+
- When the user states a clear, concise fact about themselves, their preferences, or their environment that seems important for you to retain for future interactions to provide a more personalized and effective assistance.
|
| 54 |
+
|
| 55 |
+
Do NOT use this tool:
|
| 56 |
+
|
| 57 |
+
- To remember conversational context that is only relevant for the current session.
|
| 58 |
+
- To save long, complex, or rambling pieces of text. The fact should be relatively short and to the point.
|
| 59 |
+
- If you are unsure whether the information is a fact worth remembering long-term. If in doubt, you can ask the user, "Should I remember that for you?"
|
| 60 |
+
|
| 61 |
+
## Parameters
|
| 62 |
+
|
| 63 |
+
- \`fact\` (string, required): The specific fact or piece of information to remember. This should be a clear, self-contained statement. For example, if the user says "My favorite color is blue", the fact would be "My favorite color is blue".
|
| 64 |
+
- \`scope\` (string, optional): Where to save the memory:
|
| 65 |
+
- "global": Saves to user-level ~/.qwen/QWEN.md (shared across all projects)
|
| 66 |
+
- "project": Saves to current project's QWEN.md (project-specific)
|
| 67 |
+
- If not specified, the tool will ask the user where they want to save the memory.
|
| 68 |
+
`;
|
| 69 |
+
|
| 70 |
+
export const GEMINI_CONFIG_DIR = '.qwen';
|
| 71 |
+
export const DEFAULT_CONTEXT_FILENAME = 'QWEN.md';
|
| 72 |
+
export const MEMORY_SECTION_HEADER = '## Qwen Added Memories';
|
| 73 |
+
|
| 74 |
+
// This variable will hold the currently configured filename for QWEN.md context files.
|
| 75 |
+
// It defaults to DEFAULT_CONTEXT_FILENAME but can be overridden by setGeminiMdFilename.
|
| 76 |
+
let currentGeminiMdFilename: string | string[] = DEFAULT_CONTEXT_FILENAME;
|
| 77 |
+
|
| 78 |
+
export function setGeminiMdFilename(newFilename: string | string[]): void {
|
| 79 |
+
if (Array.isArray(newFilename)) {
|
| 80 |
+
if (newFilename.length > 0) {
|
| 81 |
+
currentGeminiMdFilename = newFilename.map((name) => name.trim());
|
| 82 |
+
}
|
| 83 |
+
} else if (newFilename && newFilename.trim() !== '') {
|
| 84 |
+
currentGeminiMdFilename = newFilename.trim();
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
export function getCurrentGeminiMdFilename(): string {
|
| 89 |
+
if (Array.isArray(currentGeminiMdFilename)) {
|
| 90 |
+
return currentGeminiMdFilename[0];
|
| 91 |
+
}
|
| 92 |
+
return currentGeminiMdFilename;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
export function getAllGeminiMdFilenames(): string[] {
|
| 96 |
+
if (Array.isArray(currentGeminiMdFilename)) {
|
| 97 |
+
return currentGeminiMdFilename;
|
| 98 |
+
}
|
| 99 |
+
return [currentGeminiMdFilename];
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
interface SaveMemoryParams {
|
| 103 |
+
fact: string;
|
| 104 |
+
modified_by_user?: boolean;
|
| 105 |
+
modified_content?: string;
|
| 106 |
+
scope?: 'global' | 'project';
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
function getGlobalMemoryFilePath(): string {
|
| 110 |
+
return path.join(homedir(), GEMINI_CONFIG_DIR, getCurrentGeminiMdFilename());
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
function getProjectMemoryFilePath(): string {
|
| 114 |
+
return path.join(process.cwd(), getCurrentGeminiMdFilename());
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
function getMemoryFilePath(scope: 'global' | 'project' = 'global'): string {
|
| 118 |
+
return scope === 'project'
|
| 119 |
+
? getProjectMemoryFilePath()
|
| 120 |
+
: getGlobalMemoryFilePath();
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
/**
|
| 124 |
+
* Ensures proper newline separation before appending content.
|
| 125 |
+
*/
|
| 126 |
+
function ensureNewlineSeparation(currentContent: string): string {
|
| 127 |
+
if (currentContent.length === 0) return '';
|
| 128 |
+
if (currentContent.endsWith('\n\n') || currentContent.endsWith('\r\n\r\n'))
|
| 129 |
+
return '';
|
| 130 |
+
if (currentContent.endsWith('\n') || currentContent.endsWith('\r\n'))
|
| 131 |
+
return '\n';
|
| 132 |
+
return '\n\n';
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
/**
|
| 136 |
+
* Reads the current content of the memory file
|
| 137 |
+
*/
|
| 138 |
+
async function readMemoryFileContent(
|
| 139 |
+
scope: 'global' | 'project' = 'global',
|
| 140 |
+
): Promise<string> {
|
| 141 |
+
try {
|
| 142 |
+
return await fs.readFile(getMemoryFilePath(scope), 'utf-8');
|
| 143 |
+
} catch (err) {
|
| 144 |
+
const error = err as Error & { code?: string };
|
| 145 |
+
if (!(error instanceof Error) || error.code !== 'ENOENT') throw err;
|
| 146 |
+
return '';
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
/**
|
| 151 |
+
* Computes the new content that would result from adding a memory entry
|
| 152 |
+
*/
|
| 153 |
+
function computeNewContent(currentContent: string, fact: string): string {
|
| 154 |
+
let processedText = fact.trim();
|
| 155 |
+
processedText = processedText.replace(/^(-+\s*)+/, '').trim();
|
| 156 |
+
const newMemoryItem = `- ${processedText}`;
|
| 157 |
+
|
| 158 |
+
const headerIndex = currentContent.indexOf(MEMORY_SECTION_HEADER);
|
| 159 |
+
|
| 160 |
+
if (headerIndex === -1) {
|
| 161 |
+
// Header not found, append header and then the entry
|
| 162 |
+
const separator = ensureNewlineSeparation(currentContent);
|
| 163 |
+
return (
|
| 164 |
+
currentContent +
|
| 165 |
+
`${separator}${MEMORY_SECTION_HEADER}\n${newMemoryItem}\n`
|
| 166 |
+
);
|
| 167 |
+
} else {
|
| 168 |
+
// Header found, find where to insert the new memory entry
|
| 169 |
+
const startOfSectionContent = headerIndex + MEMORY_SECTION_HEADER.length;
|
| 170 |
+
let endOfSectionIndex = currentContent.indexOf(
|
| 171 |
+
'\n## ',
|
| 172 |
+
startOfSectionContent,
|
| 173 |
+
);
|
| 174 |
+
if (endOfSectionIndex === -1) {
|
| 175 |
+
endOfSectionIndex = currentContent.length; // End of file
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
const beforeSectionMarker = currentContent
|
| 179 |
+
.substring(0, startOfSectionContent)
|
| 180 |
+
.trimEnd();
|
| 181 |
+
let sectionContent = currentContent
|
| 182 |
+
.substring(startOfSectionContent, endOfSectionIndex)
|
| 183 |
+
.trimEnd();
|
| 184 |
+
const afterSectionMarker = currentContent.substring(endOfSectionIndex);
|
| 185 |
+
|
| 186 |
+
sectionContent += `\n${newMemoryItem}`;
|
| 187 |
+
return (
|
| 188 |
+
`${beforeSectionMarker}\n${sectionContent.trimStart()}\n${afterSectionMarker}`.trimEnd() +
|
| 189 |
+
'\n'
|
| 190 |
+
);
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
class MemoryToolInvocation extends BaseToolInvocation<
|
| 195 |
+
SaveMemoryParams,
|
| 196 |
+
ToolResult
|
| 197 |
+
> {
|
| 198 |
+
private static readonly allowlist: Set<string> = new Set();
|
| 199 |
+
|
| 200 |
+
getDescription(): string {
|
| 201 |
+
if (!this.params.scope) {
|
| 202 |
+
const globalPath = tildeifyPath(getMemoryFilePath('global'));
|
| 203 |
+
const projectPath = tildeifyPath(getMemoryFilePath('project'));
|
| 204 |
+
return `CHOOSE: ${globalPath} (global) OR ${projectPath} (project)`;
|
| 205 |
+
}
|
| 206 |
+
const scope = this.params.scope;
|
| 207 |
+
const memoryFilePath = getMemoryFilePath(scope);
|
| 208 |
+
return `${tildeifyPath(memoryFilePath)} (${scope})`;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
override async shouldConfirmExecute(
|
| 212 |
+
_abortSignal: AbortSignal,
|
| 213 |
+
): Promise<ToolEditConfirmationDetails | false> {
|
| 214 |
+
// When scope is not specified, show a choice dialog defaulting to global
|
| 215 |
+
if (!this.params.scope) {
|
| 216 |
+
// Show preview of what would be added to global by default
|
| 217 |
+
const defaultScope = 'global';
|
| 218 |
+
const currentContent = await readMemoryFileContent(defaultScope);
|
| 219 |
+
const newContent = computeNewContent(currentContent, this.params.fact);
|
| 220 |
+
|
| 221 |
+
const globalPath = tildeifyPath(getMemoryFilePath('global'));
|
| 222 |
+
const projectPath = tildeifyPath(getMemoryFilePath('project'));
|
| 223 |
+
|
| 224 |
+
const fileName = path.basename(getMemoryFilePath(defaultScope));
|
| 225 |
+
const choiceText = `Choose where to save this memory:
|
| 226 |
+
|
| 227 |
+
"${this.params.fact}"
|
| 228 |
+
|
| 229 |
+
Options:
|
| 230 |
+
- Global: ${globalPath} (shared across all projects)
|
| 231 |
+
- Project: ${projectPath} (current project only)
|
| 232 |
+
|
| 233 |
+
Preview of changes to be made to GLOBAL memory:
|
| 234 |
+
`;
|
| 235 |
+
const fileDiff =
|
| 236 |
+
choiceText +
|
| 237 |
+
Diff.createPatch(
|
| 238 |
+
fileName,
|
| 239 |
+
currentContent,
|
| 240 |
+
newContent,
|
| 241 |
+
'Current',
|
| 242 |
+
'Proposed (Global)',
|
| 243 |
+
DEFAULT_DIFF_OPTIONS,
|
| 244 |
+
);
|
| 245 |
+
|
| 246 |
+
const confirmationDetails: ToolEditConfirmationDetails = {
|
| 247 |
+
type: 'edit',
|
| 248 |
+
title: `Choose Memory Location: GLOBAL (${globalPath}) or PROJECT (${projectPath})`,
|
| 249 |
+
fileName,
|
| 250 |
+
filePath: getMemoryFilePath(defaultScope),
|
| 251 |
+
fileDiff,
|
| 252 |
+
originalContent: `scope: global\n\n# INSTRUCTIONS:\n# - Click "Yes" to save to GLOBAL memory: ${globalPath}\n# - Click "Modify with external editor" and change "global" to "project" to save to PROJECT memory: ${projectPath}\n\n${currentContent}`,
|
| 253 |
+
newContent: `scope: global\n\n# INSTRUCTIONS:\n# - Click "Yes" to save to GLOBAL memory: ${globalPath}\n# - Click "Modify with external editor" and change "global" to "project" to save to PROJECT memory: ${projectPath}\n\n${newContent}`,
|
| 254 |
+
onConfirm: async (_outcome: ToolConfirmationOutcome) => {
|
| 255 |
+
// Will be handled in createUpdatedParams
|
| 256 |
+
},
|
| 257 |
+
};
|
| 258 |
+
return confirmationDetails;
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
// Only check allowlist when scope is specified
|
| 262 |
+
const scope = this.params.scope;
|
| 263 |
+
const memoryFilePath = getMemoryFilePath(scope);
|
| 264 |
+
const allowlistKey = `${memoryFilePath}_${scope}`;
|
| 265 |
+
|
| 266 |
+
if (MemoryToolInvocation.allowlist.has(allowlistKey)) {
|
| 267 |
+
return false;
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
// Read current content of the memory file
|
| 271 |
+
const currentContent = await readMemoryFileContent(scope);
|
| 272 |
+
|
| 273 |
+
// Calculate the new content that will be written to the memory file
|
| 274 |
+
const newContent = computeNewContent(currentContent, this.params.fact);
|
| 275 |
+
|
| 276 |
+
const fileName = path.basename(memoryFilePath);
|
| 277 |
+
const fileDiff = Diff.createPatch(
|
| 278 |
+
fileName,
|
| 279 |
+
currentContent,
|
| 280 |
+
newContent,
|
| 281 |
+
'Current',
|
| 282 |
+
'Proposed',
|
| 283 |
+
DEFAULT_DIFF_OPTIONS,
|
| 284 |
+
);
|
| 285 |
+
|
| 286 |
+
const confirmationDetails: ToolEditConfirmationDetails = {
|
| 287 |
+
type: 'edit',
|
| 288 |
+
title: `Confirm Memory Save: ${tildeifyPath(memoryFilePath)} (${scope})`,
|
| 289 |
+
fileName: memoryFilePath,
|
| 290 |
+
filePath: memoryFilePath,
|
| 291 |
+
fileDiff,
|
| 292 |
+
originalContent: currentContent,
|
| 293 |
+
newContent,
|
| 294 |
+
onConfirm: async (outcome: ToolConfirmationOutcome) => {
|
| 295 |
+
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
| 296 |
+
MemoryToolInvocation.allowlist.add(allowlistKey);
|
| 297 |
+
}
|
| 298 |
+
},
|
| 299 |
+
};
|
| 300 |
+
return confirmationDetails;
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
async execute(_signal: AbortSignal): Promise<ToolResult> {
|
| 304 |
+
const { fact, modified_by_user, modified_content } = this.params;
|
| 305 |
+
|
| 306 |
+
if (!fact || typeof fact !== 'string' || fact.trim() === '') {
|
| 307 |
+
const errorMessage = 'Parameter "fact" must be a non-empty string.';
|
| 308 |
+
return {
|
| 309 |
+
llmContent: JSON.stringify({ success: false, error: errorMessage }),
|
| 310 |
+
returnDisplay: `Error: ${errorMessage}`,
|
| 311 |
+
};
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
// If scope is not specified and user didn't modify content, return error prompting for choice
|
| 315 |
+
if (!this.params.scope && !modified_by_user) {
|
| 316 |
+
const globalPath = tildeifyPath(getMemoryFilePath('global'));
|
| 317 |
+
const projectPath = tildeifyPath(getMemoryFilePath('project'));
|
| 318 |
+
const errorMessage = `Please specify where to save this memory:
|
| 319 |
+
|
| 320 |
+
Global: ${globalPath} (shared across all projects)
|
| 321 |
+
Project: ${projectPath} (current project only)`;
|
| 322 |
+
|
| 323 |
+
return {
|
| 324 |
+
llmContent: JSON.stringify({
|
| 325 |
+
success: false,
|
| 326 |
+
error: 'Please specify where to save this memory',
|
| 327 |
+
}),
|
| 328 |
+
returnDisplay: errorMessage,
|
| 329 |
+
};
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
const scope = this.params.scope || 'global';
|
| 333 |
+
const memoryFilePath = getMemoryFilePath(scope);
|
| 334 |
+
|
| 335 |
+
try {
|
| 336 |
+
if (modified_by_user && modified_content !== undefined) {
|
| 337 |
+
// User modified the content in external editor, write it directly
|
| 338 |
+
await fs.mkdir(path.dirname(memoryFilePath), {
|
| 339 |
+
recursive: true,
|
| 340 |
+
});
|
| 341 |
+
await fs.writeFile(memoryFilePath, modified_content, 'utf-8');
|
| 342 |
+
const successMessage = `Okay, I've updated the ${scope} memory file with your modifications.`;
|
| 343 |
+
return {
|
| 344 |
+
llmContent: JSON.stringify({
|
| 345 |
+
success: true,
|
| 346 |
+
message: successMessage,
|
| 347 |
+
}),
|
| 348 |
+
returnDisplay: successMessage,
|
| 349 |
+
};
|
| 350 |
+
} else {
|
| 351 |
+
// Use the normal memory entry logic
|
| 352 |
+
await MemoryTool.performAddMemoryEntry(fact, memoryFilePath, {
|
| 353 |
+
readFile: fs.readFile,
|
| 354 |
+
writeFile: fs.writeFile,
|
| 355 |
+
mkdir: fs.mkdir,
|
| 356 |
+
});
|
| 357 |
+
const successMessage = `Okay, I've remembered that in ${scope} memory: "${fact}"`;
|
| 358 |
+
return {
|
| 359 |
+
llmContent: JSON.stringify({
|
| 360 |
+
success: true,
|
| 361 |
+
message: successMessage,
|
| 362 |
+
}),
|
| 363 |
+
returnDisplay: successMessage,
|
| 364 |
+
};
|
| 365 |
+
}
|
| 366 |
+
} catch (error) {
|
| 367 |
+
const errorMessage =
|
| 368 |
+
error instanceof Error ? error.message : String(error);
|
| 369 |
+
console.error(
|
| 370 |
+
`[MemoryTool] Error executing save_memory for fact "${fact}" in ${scope}: ${errorMessage}`,
|
| 371 |
+
);
|
| 372 |
+
return {
|
| 373 |
+
llmContent: JSON.stringify({
|
| 374 |
+
success: false,
|
| 375 |
+
error: `Failed to save memory. Detail: ${errorMessage}`,
|
| 376 |
+
}),
|
| 377 |
+
returnDisplay: `Error saving memory: ${errorMessage}`,
|
| 378 |
+
};
|
| 379 |
+
}
|
| 380 |
+
}
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
export class MemoryTool
|
| 384 |
+
extends BaseDeclarativeTool<SaveMemoryParams, ToolResult>
|
| 385 |
+
implements ModifiableDeclarativeTool<SaveMemoryParams>
|
| 386 |
+
{
|
| 387 |
+
static readonly Name: string = memoryToolSchemaData.name!;
|
| 388 |
+
constructor() {
|
| 389 |
+
super(
|
| 390 |
+
MemoryTool.Name,
|
| 391 |
+
'Save Memory',
|
| 392 |
+
memoryToolDescription,
|
| 393 |
+
Kind.Think,
|
| 394 |
+
memoryToolSchemaData.parametersJsonSchema as Record<string, unknown>,
|
| 395 |
+
);
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
protected override validateToolParamValues(
|
| 399 |
+
params: SaveMemoryParams,
|
| 400 |
+
): string | null {
|
| 401 |
+
if (params.fact.trim() === '') {
|
| 402 |
+
return 'Parameter "fact" must be a non-empty string.';
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
return null;
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
protected createInvocation(params: SaveMemoryParams) {
|
| 409 |
+
return new MemoryToolInvocation(params);
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
static async performAddMemoryEntry(
|
| 413 |
+
text: string,
|
| 414 |
+
memoryFilePath: string,
|
| 415 |
+
fsAdapter: {
|
| 416 |
+
readFile: (path: string, encoding: 'utf-8') => Promise<string>;
|
| 417 |
+
writeFile: (
|
| 418 |
+
path: string,
|
| 419 |
+
data: string,
|
| 420 |
+
encoding: 'utf-8',
|
| 421 |
+
) => Promise<void>;
|
| 422 |
+
mkdir: (
|
| 423 |
+
path: string,
|
| 424 |
+
options: { recursive: boolean },
|
| 425 |
+
) => Promise<string | undefined>;
|
| 426 |
+
},
|
| 427 |
+
): Promise<void> {
|
| 428 |
+
let processedText = text.trim();
|
| 429 |
+
// Remove leading hyphens and spaces that might be misinterpreted as markdown list items
|
| 430 |
+
processedText = processedText.replace(/^(-+\s*)+/, '').trim();
|
| 431 |
+
const newMemoryItem = `- ${processedText}`;
|
| 432 |
+
|
| 433 |
+
try {
|
| 434 |
+
await fsAdapter.mkdir(path.dirname(memoryFilePath), { recursive: true });
|
| 435 |
+
let content = '';
|
| 436 |
+
try {
|
| 437 |
+
content = await fsAdapter.readFile(memoryFilePath, 'utf-8');
|
| 438 |
+
} catch (_e) {
|
| 439 |
+
// File doesn't exist, will be created with header and item.
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
const headerIndex = content.indexOf(MEMORY_SECTION_HEADER);
|
| 443 |
+
|
| 444 |
+
if (headerIndex === -1) {
|
| 445 |
+
// Header not found, append header and then the entry
|
| 446 |
+
const separator = ensureNewlineSeparation(content);
|
| 447 |
+
content += `${separator}${MEMORY_SECTION_HEADER}\n${newMemoryItem}\n`;
|
| 448 |
+
} else {
|
| 449 |
+
// Header found, find where to insert the new memory entry
|
| 450 |
+
const startOfSectionContent =
|
| 451 |
+
headerIndex + MEMORY_SECTION_HEADER.length;
|
| 452 |
+
let endOfSectionIndex = content.indexOf('\n## ', startOfSectionContent);
|
| 453 |
+
if (endOfSectionIndex === -1) {
|
| 454 |
+
endOfSectionIndex = content.length; // End of file
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
const beforeSectionMarker = content
|
| 458 |
+
.substring(0, startOfSectionContent)
|
| 459 |
+
.trimEnd();
|
| 460 |
+
let sectionContent = content
|
| 461 |
+
.substring(startOfSectionContent, endOfSectionIndex)
|
| 462 |
+
.trimEnd();
|
| 463 |
+
const afterSectionMarker = content.substring(endOfSectionIndex);
|
| 464 |
+
|
| 465 |
+
sectionContent += `\n${newMemoryItem}`;
|
| 466 |
+
content =
|
| 467 |
+
`${beforeSectionMarker}\n${sectionContent.trimStart()}\n${afterSectionMarker}`.trimEnd() +
|
| 468 |
+
'\n';
|
| 469 |
+
}
|
| 470 |
+
await fsAdapter.writeFile(memoryFilePath, content, 'utf-8');
|
| 471 |
+
} catch (error) {
|
| 472 |
+
console.error(
|
| 473 |
+
`[MemoryTool] Error adding memory entry to ${memoryFilePath}:`,
|
| 474 |
+
error,
|
| 475 |
+
);
|
| 476 |
+
throw new Error(
|
| 477 |
+
`[MemoryTool] Failed to add memory entry: ${error instanceof Error ? error.message : String(error)}`,
|
| 478 |
+
);
|
| 479 |
+
}
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
getModifyContext(_abortSignal: AbortSignal): ModifyContext<SaveMemoryParams> {
|
| 483 |
+
return {
|
| 484 |
+
getFilePath: (params: SaveMemoryParams) => {
|
| 485 |
+
// Determine scope from modified content or default
|
| 486 |
+
let scope = params.scope || 'global';
|
| 487 |
+
if (params.modified_content) {
|
| 488 |
+
const scopeMatch = params.modified_content.match(
|
| 489 |
+
/^scope:\s*(global|project)\s*\n/i,
|
| 490 |
+
);
|
| 491 |
+
if (scopeMatch) {
|
| 492 |
+
scope = scopeMatch[1].toLowerCase() as 'global' | 'project';
|
| 493 |
+
}
|
| 494 |
+
}
|
| 495 |
+
return getMemoryFilePath(scope);
|
| 496 |
+
},
|
| 497 |
+
getCurrentContent: async (params: SaveMemoryParams): Promise<string> => {
|
| 498 |
+
// Check if content starts with scope directive
|
| 499 |
+
if (params.modified_content) {
|
| 500 |
+
const scopeMatch = params.modified_content.match(
|
| 501 |
+
/^scope:\s*(global|project)\s*\n/i,
|
| 502 |
+
);
|
| 503 |
+
if (scopeMatch) {
|
| 504 |
+
const scope = scopeMatch[1].toLowerCase() as 'global' | 'project';
|
| 505 |
+
const content = await readMemoryFileContent(scope);
|
| 506 |
+
const globalPath = tildeifyPath(getMemoryFilePath('global'));
|
| 507 |
+
const projectPath = tildeifyPath(getMemoryFilePath('project'));
|
| 508 |
+
return `scope: ${scope}\n\n# INSTRUCTIONS:\n# - Save as "global" for GLOBAL memory: ${globalPath}\n# - Save as "project" for PROJECT memory: ${projectPath}\n\n${content}`;
|
| 509 |
+
}
|
| 510 |
+
}
|
| 511 |
+
const scope = params.scope || 'global';
|
| 512 |
+
const content = await readMemoryFileContent(scope);
|
| 513 |
+
const globalPath = tildeifyPath(getMemoryFilePath('global'));
|
| 514 |
+
const projectPath = tildeifyPath(getMemoryFilePath('project'));
|
| 515 |
+
return `scope: ${scope}\n\n# INSTRUCTIONS:\n# - Save as "global" for GLOBAL memory: ${globalPath}\n# - Save as "project" for PROJECT memory: ${projectPath}\n\n${content}`;
|
| 516 |
+
},
|
| 517 |
+
getProposedContent: async (params: SaveMemoryParams): Promise<string> => {
|
| 518 |
+
let scope = params.scope || 'global';
|
| 519 |
+
|
| 520 |
+
// Check if modified content has scope directive
|
| 521 |
+
if (params.modified_content) {
|
| 522 |
+
const scopeMatch = params.modified_content.match(
|
| 523 |
+
/^scope:\s*(global|project)\s*\n/i,
|
| 524 |
+
);
|
| 525 |
+
if (scopeMatch) {
|
| 526 |
+
scope = scopeMatch[1].toLowerCase() as 'global' | 'project';
|
| 527 |
+
}
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
const currentContent = await readMemoryFileContent(scope);
|
| 531 |
+
const newContent = computeNewContent(currentContent, params.fact);
|
| 532 |
+
const globalPath = tildeifyPath(getMemoryFilePath('global'));
|
| 533 |
+
const projectPath = tildeifyPath(getMemoryFilePath('project'));
|
| 534 |
+
return `scope: ${scope}\n\n# INSTRUCTIONS:\n# - Save as "global" for GLOBAL memory: ${globalPath}\n# - Save as "project" for PROJECT memory: ${projectPath}\n\n${newContent}`;
|
| 535 |
+
},
|
| 536 |
+
createUpdatedParams: (
|
| 537 |
+
_oldContent: string,
|
| 538 |
+
modifiedProposedContent: string,
|
| 539 |
+
originalParams: SaveMemoryParams,
|
| 540 |
+
): SaveMemoryParams => {
|
| 541 |
+
// Parse user's scope choice from modified content
|
| 542 |
+
const scopeMatch = modifiedProposedContent.match(
|
| 543 |
+
/^scope:\s*(global|project)/i,
|
| 544 |
+
);
|
| 545 |
+
const scope = scopeMatch
|
| 546 |
+
? (scopeMatch[1].toLowerCase() as 'global' | 'project')
|
| 547 |
+
: 'global';
|
| 548 |
+
|
| 549 |
+
// Strip out the scope directive and instruction lines, keep only the actual memory content
|
| 550 |
+
const contentWithoutScope = modifiedProposedContent.replace(
|
| 551 |
+
/^scope:\s*(global|project)\s*\n/,
|
| 552 |
+
'',
|
| 553 |
+
);
|
| 554 |
+
const actualContent = contentWithoutScope
|
| 555 |
+
.replace(/^#[^\n]*\n/gm, '')
|
| 556 |
+
.replace(/^\s*\n/gm, '')
|
| 557 |
+
.trim();
|
| 558 |
+
|
| 559 |
+
return {
|
| 560 |
+
...originalParams,
|
| 561 |
+
scope,
|
| 562 |
+
modified_by_user: true,
|
| 563 |
+
modified_content: actualContent,
|
| 564 |
+
};
|
| 565 |
+
},
|
| 566 |
+
};
|
| 567 |
+
}
|
| 568 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/modifiable-tool.test.ts
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
|
| 8 |
+
import {
|
| 9 |
+
modifyWithEditor,
|
| 10 |
+
ModifyContext,
|
| 11 |
+
ModifiableDeclarativeTool,
|
| 12 |
+
isModifiableDeclarativeTool,
|
| 13 |
+
} from './modifiable-tool.js';
|
| 14 |
+
import { EditorType } from '../utils/editor.js';
|
| 15 |
+
import fs from 'fs';
|
| 16 |
+
import fsp from 'fs/promises';
|
| 17 |
+
import os from 'os';
|
| 18 |
+
import * as path from 'path';
|
| 19 |
+
|
| 20 |
+
// Mock dependencies
|
| 21 |
+
const mockOpenDiff = vi.hoisted(() => vi.fn());
|
| 22 |
+
const mockCreatePatch = vi.hoisted(() => vi.fn());
|
| 23 |
+
|
| 24 |
+
vi.mock('../utils/editor.js', () => ({
|
| 25 |
+
openDiff: mockOpenDiff,
|
| 26 |
+
}));
|
| 27 |
+
|
| 28 |
+
vi.mock('diff', () => ({
|
| 29 |
+
createPatch: mockCreatePatch,
|
| 30 |
+
}));
|
| 31 |
+
|
| 32 |
+
interface TestParams {
|
| 33 |
+
filePath: string;
|
| 34 |
+
someOtherParam: string;
|
| 35 |
+
modifiedContent?: string;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
describe('modifyWithEditor', () => {
|
| 39 |
+
let testProjectDir: string;
|
| 40 |
+
let mockModifyContext: ModifyContext<TestParams>;
|
| 41 |
+
let mockParams: TestParams;
|
| 42 |
+
let currentContent: string;
|
| 43 |
+
let proposedContent: string;
|
| 44 |
+
let modifiedContent: string;
|
| 45 |
+
let abortSignal: AbortSignal;
|
| 46 |
+
|
| 47 |
+
beforeEach(async () => {
|
| 48 |
+
vi.resetAllMocks();
|
| 49 |
+
|
| 50 |
+
testProjectDir = await fsp.mkdtemp(
|
| 51 |
+
path.join(os.tmpdir(), 'modifiable-tool-test-'),
|
| 52 |
+
);
|
| 53 |
+
abortSignal = new AbortController().signal;
|
| 54 |
+
|
| 55 |
+
currentContent = 'original content\nline 2\nline 3';
|
| 56 |
+
proposedContent = 'modified content\nline 2\nline 3';
|
| 57 |
+
modifiedContent = 'user modified content\nline 2\nline 3\nnew line';
|
| 58 |
+
mockParams = {
|
| 59 |
+
filePath: path.join(testProjectDir, 'test.txt'),
|
| 60 |
+
someOtherParam: 'value',
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
mockModifyContext = {
|
| 64 |
+
getFilePath: vi.fn().mockReturnValue(mockParams.filePath),
|
| 65 |
+
getCurrentContent: vi.fn().mockResolvedValue(currentContent),
|
| 66 |
+
getProposedContent: vi.fn().mockResolvedValue(proposedContent),
|
| 67 |
+
createUpdatedParams: vi
|
| 68 |
+
.fn()
|
| 69 |
+
.mockImplementation((oldContent, modifiedContent, originalParams) => ({
|
| 70 |
+
...originalParams,
|
| 71 |
+
modifiedContent,
|
| 72 |
+
oldContent,
|
| 73 |
+
})),
|
| 74 |
+
};
|
| 75 |
+
|
| 76 |
+
mockOpenDiff.mockImplementation(async (_oldPath, newPath) => {
|
| 77 |
+
await fsp.writeFile(newPath, modifiedContent, 'utf8');
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
mockCreatePatch.mockReturnValue('mock diff content');
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
afterEach(async () => {
|
| 84 |
+
vi.restoreAllMocks();
|
| 85 |
+
await fsp.rm(testProjectDir, { recursive: true, force: true });
|
| 86 |
+
const diffDir = path.join(os.tmpdir(), 'qwen-code-tool-modify-diffs');
|
| 87 |
+
await fsp.rm(diffDir, { recursive: true, force: true });
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
describe('successful modification', () => {
|
| 91 |
+
it('should successfully modify content with VSCode editor', async () => {
|
| 92 |
+
const result = await modifyWithEditor(
|
| 93 |
+
mockParams,
|
| 94 |
+
mockModifyContext,
|
| 95 |
+
'vscode' as EditorType,
|
| 96 |
+
abortSignal,
|
| 97 |
+
vi.fn(),
|
| 98 |
+
);
|
| 99 |
+
|
| 100 |
+
expect(mockModifyContext.getCurrentContent).toHaveBeenCalledWith(
|
| 101 |
+
mockParams,
|
| 102 |
+
);
|
| 103 |
+
expect(mockModifyContext.getProposedContent).toHaveBeenCalledWith(
|
| 104 |
+
mockParams,
|
| 105 |
+
);
|
| 106 |
+
expect(mockModifyContext.getFilePath).toHaveBeenCalledWith(mockParams);
|
| 107 |
+
|
| 108 |
+
expect(mockOpenDiff).toHaveBeenCalledOnce();
|
| 109 |
+
const [oldFilePath, newFilePath] = mockOpenDiff.mock.calls[0];
|
| 110 |
+
|
| 111 |
+
expect(mockModifyContext.createUpdatedParams).toHaveBeenCalledWith(
|
| 112 |
+
currentContent,
|
| 113 |
+
modifiedContent,
|
| 114 |
+
mockParams,
|
| 115 |
+
);
|
| 116 |
+
|
| 117 |
+
expect(mockCreatePatch).toHaveBeenCalledWith(
|
| 118 |
+
path.basename(mockParams.filePath),
|
| 119 |
+
currentContent,
|
| 120 |
+
modifiedContent,
|
| 121 |
+
'Current',
|
| 122 |
+
'Proposed',
|
| 123 |
+
expect.objectContaining({
|
| 124 |
+
context: 3,
|
| 125 |
+
ignoreWhitespace: true,
|
| 126 |
+
}),
|
| 127 |
+
);
|
| 128 |
+
|
| 129 |
+
// Check that temp files are deleted.
|
| 130 |
+
await expect(fsp.access(oldFilePath)).rejects.toThrow();
|
| 131 |
+
await expect(fsp.access(newFilePath)).rejects.toThrow();
|
| 132 |
+
|
| 133 |
+
expect(result).toEqual({
|
| 134 |
+
updatedParams: {
|
| 135 |
+
...mockParams,
|
| 136 |
+
modifiedContent,
|
| 137 |
+
oldContent: currentContent,
|
| 138 |
+
},
|
| 139 |
+
updatedDiff: 'mock diff content',
|
| 140 |
+
});
|
| 141 |
+
});
|
| 142 |
+
|
| 143 |
+
it('should create temp directory if it does not exist', async () => {
|
| 144 |
+
const diffDir = path.join(os.tmpdir(), 'qwen-code-tool-modify-diffs');
|
| 145 |
+
await fsp.rm(diffDir, { recursive: true, force: true }).catch(() => {});
|
| 146 |
+
|
| 147 |
+
await modifyWithEditor(
|
| 148 |
+
mockParams,
|
| 149 |
+
mockModifyContext,
|
| 150 |
+
'vscode' as EditorType,
|
| 151 |
+
abortSignal,
|
| 152 |
+
vi.fn(),
|
| 153 |
+
);
|
| 154 |
+
|
| 155 |
+
const stats = await fsp.stat(diffDir);
|
| 156 |
+
expect(stats.isDirectory()).toBe(true);
|
| 157 |
+
});
|
| 158 |
+
|
| 159 |
+
it('should not create temp directory if it already exists', async () => {
|
| 160 |
+
const diffDir = path.join(os.tmpdir(), 'qwen-code-tool-modify-diffs');
|
| 161 |
+
await fsp.mkdir(diffDir, { recursive: true });
|
| 162 |
+
|
| 163 |
+
const mkdirSpy = vi.spyOn(fs, 'mkdirSync');
|
| 164 |
+
|
| 165 |
+
await modifyWithEditor(
|
| 166 |
+
mockParams,
|
| 167 |
+
mockModifyContext,
|
| 168 |
+
'vscode' as EditorType,
|
| 169 |
+
abortSignal,
|
| 170 |
+
vi.fn(),
|
| 171 |
+
);
|
| 172 |
+
|
| 173 |
+
expect(mkdirSpy).not.toHaveBeenCalled();
|
| 174 |
+
mkdirSpy.mockRestore();
|
| 175 |
+
});
|
| 176 |
+
});
|
| 177 |
+
|
| 178 |
+
it('should handle missing old temp file gracefully', async () => {
|
| 179 |
+
mockOpenDiff.mockImplementation(async (oldPath, newPath) => {
|
| 180 |
+
await fsp.writeFile(newPath, modifiedContent, 'utf8');
|
| 181 |
+
await fsp.unlink(oldPath);
|
| 182 |
+
});
|
| 183 |
+
|
| 184 |
+
const result = await modifyWithEditor(
|
| 185 |
+
mockParams,
|
| 186 |
+
mockModifyContext,
|
| 187 |
+
'vscode' as EditorType,
|
| 188 |
+
abortSignal,
|
| 189 |
+
vi.fn(),
|
| 190 |
+
);
|
| 191 |
+
|
| 192 |
+
expect(mockCreatePatch).toHaveBeenCalledWith(
|
| 193 |
+
path.basename(mockParams.filePath),
|
| 194 |
+
'',
|
| 195 |
+
modifiedContent,
|
| 196 |
+
'Current',
|
| 197 |
+
'Proposed',
|
| 198 |
+
expect.objectContaining({
|
| 199 |
+
context: 3,
|
| 200 |
+
ignoreWhitespace: true,
|
| 201 |
+
}),
|
| 202 |
+
);
|
| 203 |
+
|
| 204 |
+
expect(result.updatedParams).toBeDefined();
|
| 205 |
+
expect(result.updatedDiff).toBe('mock diff content');
|
| 206 |
+
});
|
| 207 |
+
|
| 208 |
+
it('should handle missing new temp file gracefully', async () => {
|
| 209 |
+
mockOpenDiff.mockImplementation(async (_oldPath, newPath) => {
|
| 210 |
+
await fsp.unlink(newPath);
|
| 211 |
+
});
|
| 212 |
+
|
| 213 |
+
const result = await modifyWithEditor(
|
| 214 |
+
mockParams,
|
| 215 |
+
mockModifyContext,
|
| 216 |
+
'vscode' as EditorType,
|
| 217 |
+
abortSignal,
|
| 218 |
+
vi.fn(),
|
| 219 |
+
);
|
| 220 |
+
|
| 221 |
+
expect(mockCreatePatch).toHaveBeenCalledWith(
|
| 222 |
+
path.basename(mockParams.filePath),
|
| 223 |
+
currentContent,
|
| 224 |
+
'',
|
| 225 |
+
'Current',
|
| 226 |
+
'Proposed',
|
| 227 |
+
expect.objectContaining({
|
| 228 |
+
context: 3,
|
| 229 |
+
ignoreWhitespace: true,
|
| 230 |
+
}),
|
| 231 |
+
);
|
| 232 |
+
|
| 233 |
+
expect(result.updatedParams).toBeDefined();
|
| 234 |
+
expect(result.updatedDiff).toBe('mock diff content');
|
| 235 |
+
});
|
| 236 |
+
|
| 237 |
+
it('should clean up temp files even if editor fails', async () => {
|
| 238 |
+
const editorError = new Error('Editor failed to open');
|
| 239 |
+
mockOpenDiff.mockRejectedValue(editorError);
|
| 240 |
+
|
| 241 |
+
const writeSpy = vi.spyOn(fs, 'writeFileSync');
|
| 242 |
+
|
| 243 |
+
await expect(
|
| 244 |
+
modifyWithEditor(
|
| 245 |
+
mockParams,
|
| 246 |
+
mockModifyContext,
|
| 247 |
+
'vscode' as EditorType,
|
| 248 |
+
abortSignal,
|
| 249 |
+
vi.fn(),
|
| 250 |
+
),
|
| 251 |
+
).rejects.toThrow('Editor failed to open');
|
| 252 |
+
|
| 253 |
+
expect(writeSpy).toHaveBeenCalledTimes(2);
|
| 254 |
+
const oldFilePath = writeSpy.mock.calls[0][0] as string;
|
| 255 |
+
const newFilePath = writeSpy.mock.calls[1][0] as string;
|
| 256 |
+
|
| 257 |
+
await expect(fsp.access(oldFilePath)).rejects.toThrow();
|
| 258 |
+
await expect(fsp.access(newFilePath)).rejects.toThrow();
|
| 259 |
+
|
| 260 |
+
writeSpy.mockRestore();
|
| 261 |
+
});
|
| 262 |
+
|
| 263 |
+
it('should handle temp file cleanup errors gracefully', async () => {
|
| 264 |
+
const consoleErrorSpy = vi
|
| 265 |
+
.spyOn(console, 'error')
|
| 266 |
+
.mockImplementation(() => {});
|
| 267 |
+
vi.spyOn(fs, 'unlinkSync').mockImplementation(() => {
|
| 268 |
+
throw new Error('Failed to delete file');
|
| 269 |
+
});
|
| 270 |
+
|
| 271 |
+
await modifyWithEditor(
|
| 272 |
+
mockParams,
|
| 273 |
+
mockModifyContext,
|
| 274 |
+
'vscode' as EditorType,
|
| 275 |
+
abortSignal,
|
| 276 |
+
vi.fn(),
|
| 277 |
+
);
|
| 278 |
+
|
| 279 |
+
expect(consoleErrorSpy).toHaveBeenCalledTimes(2);
|
| 280 |
+
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
| 281 |
+
expect.stringContaining('Error deleting temp diff file:'),
|
| 282 |
+
);
|
| 283 |
+
|
| 284 |
+
consoleErrorSpy.mockRestore();
|
| 285 |
+
});
|
| 286 |
+
|
| 287 |
+
it('should create temp files with correct naming with extension', async () => {
|
| 288 |
+
const testFilePath = path.join(
|
| 289 |
+
testProjectDir,
|
| 290 |
+
'subfolder',
|
| 291 |
+
'test-file.txt',
|
| 292 |
+
);
|
| 293 |
+
mockModifyContext.getFilePath = vi.fn().mockReturnValue(testFilePath);
|
| 294 |
+
|
| 295 |
+
await modifyWithEditor(
|
| 296 |
+
mockParams,
|
| 297 |
+
mockModifyContext,
|
| 298 |
+
'vscode' as EditorType,
|
| 299 |
+
abortSignal,
|
| 300 |
+
vi.fn(),
|
| 301 |
+
);
|
| 302 |
+
|
| 303 |
+
expect(mockOpenDiff).toHaveBeenCalledOnce();
|
| 304 |
+
const [oldFilePath, newFilePath] = mockOpenDiff.mock.calls[0];
|
| 305 |
+
expect(oldFilePath).toMatch(/qwen-code-modify-test-file-old-\d+\.txt$/);
|
| 306 |
+
expect(newFilePath).toMatch(/qwen-code-modify-test-file-new-\d+\.txt$/);
|
| 307 |
+
|
| 308 |
+
const diffDir = path.join(os.tmpdir(), 'qwen-code-tool-modify-diffs');
|
| 309 |
+
expect(path.dirname(oldFilePath)).toBe(diffDir);
|
| 310 |
+
expect(path.dirname(newFilePath)).toBe(diffDir);
|
| 311 |
+
});
|
| 312 |
+
|
| 313 |
+
it('should create temp files with correct naming without extension', async () => {
|
| 314 |
+
const testFilePath = path.join(testProjectDir, 'subfolder', 'test-file');
|
| 315 |
+
mockModifyContext.getFilePath = vi.fn().mockReturnValue(testFilePath);
|
| 316 |
+
|
| 317 |
+
await modifyWithEditor(
|
| 318 |
+
mockParams,
|
| 319 |
+
mockModifyContext,
|
| 320 |
+
'vscode' as EditorType,
|
| 321 |
+
abortSignal,
|
| 322 |
+
vi.fn(),
|
| 323 |
+
);
|
| 324 |
+
|
| 325 |
+
expect(mockOpenDiff).toHaveBeenCalledOnce();
|
| 326 |
+
const [oldFilePath, newFilePath] = mockOpenDiff.mock.calls[0];
|
| 327 |
+
expect(oldFilePath).toMatch(/qwen-code-modify-test-file-old-\d+$/);
|
| 328 |
+
expect(newFilePath).toMatch(/qwen-code-modify-test-file-new-\d+$/);
|
| 329 |
+
|
| 330 |
+
const diffDir = path.join(os.tmpdir(), 'qwen-code-tool-modify-diffs');
|
| 331 |
+
expect(path.dirname(oldFilePath)).toBe(diffDir);
|
| 332 |
+
expect(path.dirname(newFilePath)).toBe(diffDir);
|
| 333 |
+
});
|
| 334 |
+
});
|
| 335 |
+
|
| 336 |
+
describe('isModifiableTool', () => {
|
| 337 |
+
it('should return true for objects with getModifyContext method', () => {
|
| 338 |
+
const mockTool = {
|
| 339 |
+
name: 'test-tool',
|
| 340 |
+
getModifyContext: vi.fn(),
|
| 341 |
+
} as unknown as ModifiableDeclarativeTool<TestParams>;
|
| 342 |
+
|
| 343 |
+
expect(isModifiableDeclarativeTool(mockTool)).toBe(true);
|
| 344 |
+
});
|
| 345 |
+
|
| 346 |
+
it('should return false for objects without getModifyContext method', () => {
|
| 347 |
+
const mockTool = {
|
| 348 |
+
name: 'test-tool',
|
| 349 |
+
} as unknown as ModifiableDeclarativeTool<TestParams>;
|
| 350 |
+
|
| 351 |
+
expect(isModifiableDeclarativeTool(mockTool)).toBe(false);
|
| 352 |
+
});
|
| 353 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/modifiable-tool.ts
ADDED
|
@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
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { EditorType, openDiff } from '../utils/editor.js';
|
| 8 |
+
import os from 'os';
|
| 9 |
+
import path from 'path';
|
| 10 |
+
import fs from 'fs';
|
| 11 |
+
import * as Diff from 'diff';
|
| 12 |
+
import { DEFAULT_DIFF_OPTIONS } from './diffOptions.js';
|
| 13 |
+
import { isNodeError } from '../utils/errors.js';
|
| 14 |
+
import { AnyDeclarativeTool, DeclarativeTool, ToolResult } from './tools.js';
|
| 15 |
+
|
| 16 |
+
/**
|
| 17 |
+
* A declarative tool that supports a modify operation.
|
| 18 |
+
*/
|
| 19 |
+
export interface ModifiableDeclarativeTool<TParams extends object>
|
| 20 |
+
extends DeclarativeTool<TParams, ToolResult> {
|
| 21 |
+
getModifyContext(abortSignal: AbortSignal): ModifyContext<TParams>;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
export interface ModifyContext<ToolParams> {
|
| 25 |
+
getFilePath: (params: ToolParams) => string;
|
| 26 |
+
|
| 27 |
+
getCurrentContent: (params: ToolParams) => Promise<string>;
|
| 28 |
+
|
| 29 |
+
getProposedContent: (params: ToolParams) => Promise<string>;
|
| 30 |
+
|
| 31 |
+
createUpdatedParams: (
|
| 32 |
+
oldContent: string,
|
| 33 |
+
modifiedProposedContent: string,
|
| 34 |
+
originalParams: ToolParams,
|
| 35 |
+
) => ToolParams;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
export interface ModifyResult<ToolParams> {
|
| 39 |
+
updatedParams: ToolParams;
|
| 40 |
+
updatedDiff: string;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
/**
|
| 44 |
+
* Type guard to check if a declarative tool is modifiable.
|
| 45 |
+
*/
|
| 46 |
+
export function isModifiableDeclarativeTool(
|
| 47 |
+
tool: AnyDeclarativeTool,
|
| 48 |
+
): tool is ModifiableDeclarativeTool<object> {
|
| 49 |
+
return 'getModifyContext' in tool;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
function createTempFilesForModify(
|
| 53 |
+
currentContent: string,
|
| 54 |
+
proposedContent: string,
|
| 55 |
+
file_path: string,
|
| 56 |
+
): { oldPath: string; newPath: string } {
|
| 57 |
+
const tempDir = os.tmpdir();
|
| 58 |
+
const diffDir = path.join(tempDir, 'qwen-code-tool-modify-diffs');
|
| 59 |
+
|
| 60 |
+
if (!fs.existsSync(diffDir)) {
|
| 61 |
+
fs.mkdirSync(diffDir, { recursive: true });
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
const ext = path.extname(file_path);
|
| 65 |
+
const fileName = path.basename(file_path, ext);
|
| 66 |
+
const timestamp = Date.now();
|
| 67 |
+
const tempOldPath = path.join(
|
| 68 |
+
diffDir,
|
| 69 |
+
`qwen-code-modify-${fileName}-old-${timestamp}${ext}`,
|
| 70 |
+
);
|
| 71 |
+
const tempNewPath = path.join(
|
| 72 |
+
diffDir,
|
| 73 |
+
`qwen-code-modify-${fileName}-new-${timestamp}${ext}`,
|
| 74 |
+
);
|
| 75 |
+
|
| 76 |
+
fs.writeFileSync(tempOldPath, currentContent, 'utf8');
|
| 77 |
+
fs.writeFileSync(tempNewPath, proposedContent, 'utf8');
|
| 78 |
+
|
| 79 |
+
return { oldPath: tempOldPath, newPath: tempNewPath };
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
function getUpdatedParams<ToolParams>(
|
| 83 |
+
tmpOldPath: string,
|
| 84 |
+
tempNewPath: string,
|
| 85 |
+
originalParams: ToolParams,
|
| 86 |
+
modifyContext: ModifyContext<ToolParams>,
|
| 87 |
+
): { updatedParams: ToolParams; updatedDiff: string } {
|
| 88 |
+
let oldContent = '';
|
| 89 |
+
let newContent = '';
|
| 90 |
+
|
| 91 |
+
try {
|
| 92 |
+
oldContent = fs.readFileSync(tmpOldPath, 'utf8');
|
| 93 |
+
} catch (err) {
|
| 94 |
+
if (!isNodeError(err) || err.code !== 'ENOENT') throw err;
|
| 95 |
+
oldContent = '';
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
try {
|
| 99 |
+
newContent = fs.readFileSync(tempNewPath, 'utf8');
|
| 100 |
+
} catch (err) {
|
| 101 |
+
if (!isNodeError(err) || err.code !== 'ENOENT') throw err;
|
| 102 |
+
newContent = '';
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
const updatedParams = modifyContext.createUpdatedParams(
|
| 106 |
+
oldContent,
|
| 107 |
+
newContent,
|
| 108 |
+
originalParams,
|
| 109 |
+
);
|
| 110 |
+
const updatedDiff = Diff.createPatch(
|
| 111 |
+
path.basename(modifyContext.getFilePath(originalParams)),
|
| 112 |
+
oldContent,
|
| 113 |
+
newContent,
|
| 114 |
+
'Current',
|
| 115 |
+
'Proposed',
|
| 116 |
+
DEFAULT_DIFF_OPTIONS,
|
| 117 |
+
);
|
| 118 |
+
|
| 119 |
+
return { updatedParams, updatedDiff };
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
function deleteTempFiles(oldPath: string, newPath: string): void {
|
| 123 |
+
try {
|
| 124 |
+
fs.unlinkSync(oldPath);
|
| 125 |
+
} catch {
|
| 126 |
+
console.error(`Error deleting temp diff file: ${oldPath}`);
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
try {
|
| 130 |
+
fs.unlinkSync(newPath);
|
| 131 |
+
} catch {
|
| 132 |
+
console.error(`Error deleting temp diff file: ${newPath}`);
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
/**
|
| 137 |
+
* Triggers an external editor for the user to modify the proposed content,
|
| 138 |
+
* and returns the updated tool parameters and the diff after the user has modified the proposed content.
|
| 139 |
+
*/
|
| 140 |
+
export async function modifyWithEditor<ToolParams>(
|
| 141 |
+
originalParams: ToolParams,
|
| 142 |
+
modifyContext: ModifyContext<ToolParams>,
|
| 143 |
+
editorType: EditorType,
|
| 144 |
+
_abortSignal: AbortSignal,
|
| 145 |
+
onEditorClose: () => void,
|
| 146 |
+
): Promise<ModifyResult<ToolParams>> {
|
| 147 |
+
const currentContent = await modifyContext.getCurrentContent(originalParams);
|
| 148 |
+
const proposedContent =
|
| 149 |
+
await modifyContext.getProposedContent(originalParams);
|
| 150 |
+
|
| 151 |
+
const { oldPath, newPath } = createTempFilesForModify(
|
| 152 |
+
currentContent,
|
| 153 |
+
proposedContent,
|
| 154 |
+
modifyContext.getFilePath(originalParams),
|
| 155 |
+
);
|
| 156 |
+
|
| 157 |
+
try {
|
| 158 |
+
await openDiff(oldPath, newPath, editorType, onEditorClose);
|
| 159 |
+
const result = getUpdatedParams(
|
| 160 |
+
oldPath,
|
| 161 |
+
newPath,
|
| 162 |
+
originalParams,
|
| 163 |
+
modifyContext,
|
| 164 |
+
);
|
| 165 |
+
|
| 166 |
+
return result;
|
| 167 |
+
} finally {
|
| 168 |
+
deleteTempFiles(oldPath, newPath);
|
| 169 |
+
}
|
| 170 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/read-file.test.ts
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
| 8 |
+
import { ReadFileTool, ReadFileToolParams } from './read-file.js';
|
| 9 |
+
import { ToolErrorType } from './tool-error.js';
|
| 10 |
+
import path from 'path';
|
| 11 |
+
import os from 'os';
|
| 12 |
+
import fs from 'fs';
|
| 13 |
+
import fsp from 'fs/promises';
|
| 14 |
+
import { Config } from '../config/config.js';
|
| 15 |
+
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
|
| 16 |
+
import { StandardFileSystemService } from '../services/fileSystemService.js';
|
| 17 |
+
import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js';
|
| 18 |
+
import { ToolInvocation, ToolResult } from './tools.js';
|
| 19 |
+
|
| 20 |
+
describe('ReadFileTool', () => {
|
| 21 |
+
let tempRootDir: string;
|
| 22 |
+
let tool: ReadFileTool;
|
| 23 |
+
const abortSignal = new AbortController().signal;
|
| 24 |
+
|
| 25 |
+
beforeEach(async () => {
|
| 26 |
+
// Create a unique temporary root directory for each test run
|
| 27 |
+
tempRootDir = await fsp.mkdtemp(
|
| 28 |
+
path.join(os.tmpdir(), 'read-file-tool-root-'),
|
| 29 |
+
);
|
| 30 |
+
|
| 31 |
+
const mockConfigInstance = {
|
| 32 |
+
getFileService: () => new FileDiscoveryService(tempRootDir),
|
| 33 |
+
getFileSystemService: () => new StandardFileSystemService(),
|
| 34 |
+
getTargetDir: () => tempRootDir,
|
| 35 |
+
getWorkspaceContext: () => createMockWorkspaceContext(tempRootDir),
|
| 36 |
+
} as unknown as Config;
|
| 37 |
+
tool = new ReadFileTool(mockConfigInstance);
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
afterEach(async () => {
|
| 41 |
+
// Clean up the temporary root directory
|
| 42 |
+
if (fs.existsSync(tempRootDir)) {
|
| 43 |
+
await fsp.rm(tempRootDir, { recursive: true, force: true });
|
| 44 |
+
}
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
describe('build', () => {
|
| 48 |
+
it('should return an invocation for valid params (absolute path within root)', () => {
|
| 49 |
+
const params: ReadFileToolParams = {
|
| 50 |
+
absolute_path: path.join(tempRootDir, 'test.txt'),
|
| 51 |
+
};
|
| 52 |
+
const result = tool.build(params);
|
| 53 |
+
expect(typeof result).not.toBe('string');
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
it('should throw error if file path is relative', () => {
|
| 57 |
+
const params: ReadFileToolParams = {
|
| 58 |
+
absolute_path: 'relative/path.txt',
|
| 59 |
+
};
|
| 60 |
+
expect(() => tool.build(params)).toThrow(
|
| 61 |
+
'File path must be absolute, but was relative: relative/path.txt. You must provide an absolute path.',
|
| 62 |
+
);
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
it('should throw error if path is outside root', () => {
|
| 66 |
+
const params: ReadFileToolParams = {
|
| 67 |
+
absolute_path: '/outside/root.txt',
|
| 68 |
+
};
|
| 69 |
+
expect(() => tool.build(params)).toThrow(
|
| 70 |
+
/File path must be within one of the workspace directories/,
|
| 71 |
+
);
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
it('should throw error if path is empty', () => {
|
| 75 |
+
const params: ReadFileToolParams = {
|
| 76 |
+
absolute_path: '',
|
| 77 |
+
};
|
| 78 |
+
expect(() => tool.build(params)).toThrow(
|
| 79 |
+
/The 'absolute_path' parameter must be non-empty./,
|
| 80 |
+
);
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
it('should throw error if offset is negative', () => {
|
| 84 |
+
const params: ReadFileToolParams = {
|
| 85 |
+
absolute_path: path.join(tempRootDir, 'test.txt'),
|
| 86 |
+
offset: -1,
|
| 87 |
+
};
|
| 88 |
+
expect(() => tool.build(params)).toThrow(
|
| 89 |
+
'Offset must be a non-negative number',
|
| 90 |
+
);
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
it('should throw error if limit is zero or negative', () => {
|
| 94 |
+
const params: ReadFileToolParams = {
|
| 95 |
+
absolute_path: path.join(tempRootDir, 'test.txt'),
|
| 96 |
+
limit: 0,
|
| 97 |
+
};
|
| 98 |
+
expect(() => tool.build(params)).toThrow(
|
| 99 |
+
'Limit must be a positive number',
|
| 100 |
+
);
|
| 101 |
+
});
|
| 102 |
+
});
|
| 103 |
+
|
| 104 |
+
describe('getDescription', () => {
|
| 105 |
+
it('should return relative path without limit/offset', () => {
|
| 106 |
+
const subDir = path.join(tempRootDir, 'sub', 'dir');
|
| 107 |
+
const params: ReadFileToolParams = {
|
| 108 |
+
absolute_path: path.join(subDir, 'file.txt'),
|
| 109 |
+
};
|
| 110 |
+
const invocation = tool.build(params);
|
| 111 |
+
expect(typeof invocation).not.toBe('string');
|
| 112 |
+
expect(
|
| 113 |
+
(
|
| 114 |
+
invocation as ToolInvocation<ReadFileToolParams, ToolResult>
|
| 115 |
+
).getDescription(),
|
| 116 |
+
).toBe(path.join('sub', 'dir', 'file.txt'));
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
it('should return shortened path when file path is deep', () => {
|
| 120 |
+
const deepPath = path.join(
|
| 121 |
+
tempRootDir,
|
| 122 |
+
'very',
|
| 123 |
+
'deep',
|
| 124 |
+
'directory',
|
| 125 |
+
'structure',
|
| 126 |
+
'that',
|
| 127 |
+
'exceeds',
|
| 128 |
+
'the',
|
| 129 |
+
'normal',
|
| 130 |
+
'limit',
|
| 131 |
+
'file.txt',
|
| 132 |
+
);
|
| 133 |
+
const params: ReadFileToolParams = { absolute_path: deepPath };
|
| 134 |
+
const invocation = tool.build(params);
|
| 135 |
+
expect(typeof invocation).not.toBe('string');
|
| 136 |
+
const desc = (
|
| 137 |
+
invocation as ToolInvocation<ReadFileToolParams, ToolResult>
|
| 138 |
+
).getDescription();
|
| 139 |
+
expect(desc).toContain('...');
|
| 140 |
+
expect(desc).toContain('file.txt');
|
| 141 |
+
});
|
| 142 |
+
|
| 143 |
+
it('should handle non-normalized file paths correctly', () => {
|
| 144 |
+
const subDir = path.join(tempRootDir, 'sub', 'dir');
|
| 145 |
+
const params: ReadFileToolParams = {
|
| 146 |
+
absolute_path: path.join(subDir, '..', 'dir', 'file.txt'),
|
| 147 |
+
};
|
| 148 |
+
const invocation = tool.build(params);
|
| 149 |
+
expect(typeof invocation).not.toBe('string');
|
| 150 |
+
expect(
|
| 151 |
+
(
|
| 152 |
+
invocation as ToolInvocation<ReadFileToolParams, ToolResult>
|
| 153 |
+
).getDescription(),
|
| 154 |
+
).toBe(path.join('sub', 'dir', 'file.txt'));
|
| 155 |
+
});
|
| 156 |
+
|
| 157 |
+
it('should return . if path is the root directory', () => {
|
| 158 |
+
const params: ReadFileToolParams = { absolute_path: tempRootDir };
|
| 159 |
+
const invocation = tool.build(params);
|
| 160 |
+
expect(typeof invocation).not.toBe('string');
|
| 161 |
+
expect(
|
| 162 |
+
(
|
| 163 |
+
invocation as ToolInvocation<ReadFileToolParams, ToolResult>
|
| 164 |
+
).getDescription(),
|
| 165 |
+
).toBe('.');
|
| 166 |
+
});
|
| 167 |
+
});
|
| 168 |
+
|
| 169 |
+
describe('execute', () => {
|
| 170 |
+
it('should return error if file does not exist', async () => {
|
| 171 |
+
const filePath = path.join(tempRootDir, 'nonexistent.txt');
|
| 172 |
+
const params: ReadFileToolParams = { absolute_path: filePath };
|
| 173 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 174 |
+
ReadFileToolParams,
|
| 175 |
+
ToolResult
|
| 176 |
+
>;
|
| 177 |
+
|
| 178 |
+
const result = await invocation.execute(abortSignal);
|
| 179 |
+
expect(result).toEqual({
|
| 180 |
+
llmContent:
|
| 181 |
+
'Could not read file because no file was found at the specified path.',
|
| 182 |
+
returnDisplay: 'File not found.',
|
| 183 |
+
error: {
|
| 184 |
+
message: `File not found: ${filePath}`,
|
| 185 |
+
type: ToolErrorType.FILE_NOT_FOUND,
|
| 186 |
+
},
|
| 187 |
+
});
|
| 188 |
+
});
|
| 189 |
+
|
| 190 |
+
it('should return success result for a text file', async () => {
|
| 191 |
+
const filePath = path.join(tempRootDir, 'textfile.txt');
|
| 192 |
+
const fileContent = 'This is a test file.';
|
| 193 |
+
await fsp.writeFile(filePath, fileContent, 'utf-8');
|
| 194 |
+
const params: ReadFileToolParams = { absolute_path: filePath };
|
| 195 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 196 |
+
ReadFileToolParams,
|
| 197 |
+
ToolResult
|
| 198 |
+
>;
|
| 199 |
+
|
| 200 |
+
expect(await invocation.execute(abortSignal)).toEqual({
|
| 201 |
+
llmContent: fileContent,
|
| 202 |
+
returnDisplay: '',
|
| 203 |
+
});
|
| 204 |
+
});
|
| 205 |
+
|
| 206 |
+
it('should return error if path is a directory', async () => {
|
| 207 |
+
const dirPath = path.join(tempRootDir, 'directory');
|
| 208 |
+
await fsp.mkdir(dirPath);
|
| 209 |
+
const params: ReadFileToolParams = { absolute_path: dirPath };
|
| 210 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 211 |
+
ReadFileToolParams,
|
| 212 |
+
ToolResult
|
| 213 |
+
>;
|
| 214 |
+
|
| 215 |
+
const result = await invocation.execute(abortSignal);
|
| 216 |
+
expect(result).toEqual({
|
| 217 |
+
llmContent:
|
| 218 |
+
'Could not read file because the provided path is a directory, not a file.',
|
| 219 |
+
returnDisplay: 'Path is a directory.',
|
| 220 |
+
error: {
|
| 221 |
+
message: `Path is a directory, not a file: ${dirPath}`,
|
| 222 |
+
type: ToolErrorType.INVALID_TOOL_PARAMS,
|
| 223 |
+
},
|
| 224 |
+
});
|
| 225 |
+
});
|
| 226 |
+
|
| 227 |
+
it('should return error for a file that is too large', async () => {
|
| 228 |
+
const filePath = path.join(tempRootDir, 'largefile.txt');
|
| 229 |
+
// 21MB of content exceeds 20MB limit
|
| 230 |
+
const largeContent = 'x'.repeat(21 * 1024 * 1024);
|
| 231 |
+
await fsp.writeFile(filePath, largeContent, 'utf-8');
|
| 232 |
+
const params: ReadFileToolParams = { absolute_path: filePath };
|
| 233 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 234 |
+
ReadFileToolParams,
|
| 235 |
+
ToolResult
|
| 236 |
+
>;
|
| 237 |
+
|
| 238 |
+
const result = await invocation.execute(abortSignal);
|
| 239 |
+
expect(result).toHaveProperty('error');
|
| 240 |
+
expect(result.error?.type).toBe(ToolErrorType.FILE_TOO_LARGE);
|
| 241 |
+
expect(result.error?.message).toContain(
|
| 242 |
+
'File size exceeds the 20MB limit',
|
| 243 |
+
);
|
| 244 |
+
});
|
| 245 |
+
|
| 246 |
+
it('should handle text file with lines exceeding maximum length', async () => {
|
| 247 |
+
const filePath = path.join(tempRootDir, 'longlines.txt');
|
| 248 |
+
const longLine = 'a'.repeat(2500); // Exceeds MAX_LINE_LENGTH_TEXT_FILE (2000)
|
| 249 |
+
const fileContent = `Short line\n${longLine}\nAnother short line`;
|
| 250 |
+
await fsp.writeFile(filePath, fileContent, 'utf-8');
|
| 251 |
+
const params: ReadFileToolParams = { absolute_path: filePath };
|
| 252 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 253 |
+
ReadFileToolParams,
|
| 254 |
+
ToolResult
|
| 255 |
+
>;
|
| 256 |
+
|
| 257 |
+
const result = await invocation.execute(abortSignal);
|
| 258 |
+
expect(result.llmContent).toContain(
|
| 259 |
+
'IMPORTANT: The file content has been truncated',
|
| 260 |
+
);
|
| 261 |
+
expect(result.llmContent).toContain('--- FILE CONTENT (truncated) ---');
|
| 262 |
+
expect(result.returnDisplay).toContain('some lines were shortened');
|
| 263 |
+
});
|
| 264 |
+
|
| 265 |
+
it('should handle image file and return appropriate content', async () => {
|
| 266 |
+
const imagePath = path.join(tempRootDir, 'image.png');
|
| 267 |
+
// Minimal PNG header
|
| 268 |
+
const pngHeader = Buffer.from([
|
| 269 |
+
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
| 270 |
+
]);
|
| 271 |
+
await fsp.writeFile(imagePath, pngHeader);
|
| 272 |
+
const params: ReadFileToolParams = { absolute_path: imagePath };
|
| 273 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 274 |
+
ReadFileToolParams,
|
| 275 |
+
ToolResult
|
| 276 |
+
>;
|
| 277 |
+
|
| 278 |
+
const result = await invocation.execute(abortSignal);
|
| 279 |
+
expect(result.llmContent).toEqual({
|
| 280 |
+
inlineData: {
|
| 281 |
+
data: pngHeader.toString('base64'),
|
| 282 |
+
mimeType: 'image/png',
|
| 283 |
+
},
|
| 284 |
+
});
|
| 285 |
+
expect(result.returnDisplay).toBe('Read image file: image.png');
|
| 286 |
+
});
|
| 287 |
+
|
| 288 |
+
it('should handle PDF file and return appropriate content', async () => {
|
| 289 |
+
const pdfPath = path.join(tempRootDir, 'document.pdf');
|
| 290 |
+
// Minimal PDF header
|
| 291 |
+
const pdfHeader = Buffer.from('%PDF-1.4');
|
| 292 |
+
await fsp.writeFile(pdfPath, pdfHeader);
|
| 293 |
+
const params: ReadFileToolParams = { absolute_path: pdfPath };
|
| 294 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 295 |
+
ReadFileToolParams,
|
| 296 |
+
ToolResult
|
| 297 |
+
>;
|
| 298 |
+
|
| 299 |
+
const result = await invocation.execute(abortSignal);
|
| 300 |
+
expect(result.llmContent).toEqual({
|
| 301 |
+
inlineData: {
|
| 302 |
+
data: pdfHeader.toString('base64'),
|
| 303 |
+
mimeType: 'application/pdf',
|
| 304 |
+
},
|
| 305 |
+
});
|
| 306 |
+
expect(result.returnDisplay).toBe('Read pdf file: document.pdf');
|
| 307 |
+
});
|
| 308 |
+
|
| 309 |
+
it('should handle binary file and skip content', async () => {
|
| 310 |
+
const binPath = path.join(tempRootDir, 'binary.bin');
|
| 311 |
+
// Binary data with null bytes
|
| 312 |
+
const binaryData = Buffer.from([0x00, 0xff, 0x00, 0xff]);
|
| 313 |
+
await fsp.writeFile(binPath, binaryData);
|
| 314 |
+
const params: ReadFileToolParams = { absolute_path: binPath };
|
| 315 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 316 |
+
ReadFileToolParams,
|
| 317 |
+
ToolResult
|
| 318 |
+
>;
|
| 319 |
+
|
| 320 |
+
const result = await invocation.execute(abortSignal);
|
| 321 |
+
expect(result.llmContent).toBe(
|
| 322 |
+
'Cannot display content of binary file: binary.bin',
|
| 323 |
+
);
|
| 324 |
+
expect(result.returnDisplay).toBe('Skipped binary file: binary.bin');
|
| 325 |
+
});
|
| 326 |
+
|
| 327 |
+
it('should handle SVG file as text', async () => {
|
| 328 |
+
const svgPath = path.join(tempRootDir, 'image.svg');
|
| 329 |
+
const svgContent = '<svg><circle cx="50" cy="50" r="40"/></svg>';
|
| 330 |
+
await fsp.writeFile(svgPath, svgContent, 'utf-8');
|
| 331 |
+
const params: ReadFileToolParams = { absolute_path: svgPath };
|
| 332 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 333 |
+
ReadFileToolParams,
|
| 334 |
+
ToolResult
|
| 335 |
+
>;
|
| 336 |
+
|
| 337 |
+
const result = await invocation.execute(abortSignal);
|
| 338 |
+
expect(result.llmContent).toBe(svgContent);
|
| 339 |
+
expect(result.returnDisplay).toBe('Read SVG as text: image.svg');
|
| 340 |
+
});
|
| 341 |
+
|
| 342 |
+
it('should handle large SVG file', async () => {
|
| 343 |
+
const svgPath = path.join(tempRootDir, 'large.svg');
|
| 344 |
+
// Create SVG content larger than 1MB
|
| 345 |
+
const largeContent = '<svg>' + 'x'.repeat(1024 * 1024 + 1) + '</svg>';
|
| 346 |
+
await fsp.writeFile(svgPath, largeContent, 'utf-8');
|
| 347 |
+
const params: ReadFileToolParams = { absolute_path: svgPath };
|
| 348 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 349 |
+
ReadFileToolParams,
|
| 350 |
+
ToolResult
|
| 351 |
+
>;
|
| 352 |
+
|
| 353 |
+
const result = await invocation.execute(abortSignal);
|
| 354 |
+
expect(result.llmContent).toBe(
|
| 355 |
+
'Cannot display content of SVG file larger than 1MB: large.svg',
|
| 356 |
+
);
|
| 357 |
+
expect(result.returnDisplay).toBe(
|
| 358 |
+
'Skipped large SVG file (>1MB): large.svg',
|
| 359 |
+
);
|
| 360 |
+
});
|
| 361 |
+
|
| 362 |
+
it('should handle empty file', async () => {
|
| 363 |
+
const emptyPath = path.join(tempRootDir, 'empty.txt');
|
| 364 |
+
await fsp.writeFile(emptyPath, '', 'utf-8');
|
| 365 |
+
const params: ReadFileToolParams = { absolute_path: emptyPath };
|
| 366 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 367 |
+
ReadFileToolParams,
|
| 368 |
+
ToolResult
|
| 369 |
+
>;
|
| 370 |
+
|
| 371 |
+
const result = await invocation.execute(abortSignal);
|
| 372 |
+
expect(result.llmContent).toBe('');
|
| 373 |
+
expect(result.returnDisplay).toBe('');
|
| 374 |
+
});
|
| 375 |
+
|
| 376 |
+
it('should support offset and limit for text files', async () => {
|
| 377 |
+
const filePath = path.join(tempRootDir, 'paginated.txt');
|
| 378 |
+
const lines = Array.from({ length: 20 }, (_, i) => `Line ${i + 1}`);
|
| 379 |
+
const fileContent = lines.join('\n');
|
| 380 |
+
await fsp.writeFile(filePath, fileContent, 'utf-8');
|
| 381 |
+
|
| 382 |
+
const params: ReadFileToolParams = {
|
| 383 |
+
absolute_path: filePath,
|
| 384 |
+
offset: 5, // Start from line 6
|
| 385 |
+
limit: 3,
|
| 386 |
+
};
|
| 387 |
+
const invocation = tool.build(params) as ToolInvocation<
|
| 388 |
+
ReadFileToolParams,
|
| 389 |
+
ToolResult
|
| 390 |
+
>;
|
| 391 |
+
|
| 392 |
+
const result = await invocation.execute(abortSignal);
|
| 393 |
+
expect(result.llmContent).toContain(
|
| 394 |
+
'IMPORTANT: The file content has been truncated',
|
| 395 |
+
);
|
| 396 |
+
expect(result.llmContent).toContain(
|
| 397 |
+
'Status: Showing lines 6-8 of 20 total lines',
|
| 398 |
+
);
|
| 399 |
+
expect(result.llmContent).toContain('Line 6');
|
| 400 |
+
expect(result.llmContent).toContain('Line 7');
|
| 401 |
+
expect(result.llmContent).toContain('Line 8');
|
| 402 |
+
expect(result.returnDisplay).toBe(
|
| 403 |
+
'Read lines 6-8 of 20 from paginated.txt',
|
| 404 |
+
);
|
| 405 |
+
});
|
| 406 |
+
|
| 407 |
+
describe('with .geminiignore', () => {
|
| 408 |
+
beforeEach(async () => {
|
| 409 |
+
await fsp.writeFile(
|
| 410 |
+
path.join(tempRootDir, '.geminiignore'),
|
| 411 |
+
['foo.*', 'ignored/'].join('\n'),
|
| 412 |
+
);
|
| 413 |
+
});
|
| 414 |
+
|
| 415 |
+
it('should throw error if path is ignored by a .geminiignore pattern', async () => {
|
| 416 |
+
const ignoredFilePath = path.join(tempRootDir, 'foo.bar');
|
| 417 |
+
await fsp.writeFile(ignoredFilePath, 'content', 'utf-8');
|
| 418 |
+
const params: ReadFileToolParams = {
|
| 419 |
+
absolute_path: ignoredFilePath,
|
| 420 |
+
};
|
| 421 |
+
const expectedError = `File path '${ignoredFilePath}' is ignored by .geminiignore pattern(s).`;
|
| 422 |
+
expect(() => tool.build(params)).toThrow(expectedError);
|
| 423 |
+
});
|
| 424 |
+
|
| 425 |
+
it('should throw error if file is in an ignored directory', async () => {
|
| 426 |
+
const ignoredDirPath = path.join(tempRootDir, 'ignored');
|
| 427 |
+
await fsp.mkdir(ignoredDirPath, { recursive: true });
|
| 428 |
+
const ignoredFilePath = path.join(ignoredDirPath, 'file.txt');
|
| 429 |
+
await fsp.writeFile(ignoredFilePath, 'content', 'utf-8');
|
| 430 |
+
const params: ReadFileToolParams = {
|
| 431 |
+
absolute_path: ignoredFilePath,
|
| 432 |
+
};
|
| 433 |
+
const expectedError = `File path '${ignoredFilePath}' is ignored by .geminiignore pattern(s).`;
|
| 434 |
+
expect(() => tool.build(params)).toThrow(expectedError);
|
| 435 |
+
});
|
| 436 |
+
|
| 437 |
+
it('should allow reading non-ignored files', async () => {
|
| 438 |
+
const allowedFilePath = path.join(tempRootDir, 'allowed.txt');
|
| 439 |
+
await fsp.writeFile(allowedFilePath, 'content', 'utf-8');
|
| 440 |
+
const params: ReadFileToolParams = {
|
| 441 |
+
absolute_path: allowedFilePath,
|
| 442 |
+
};
|
| 443 |
+
const invocation = tool.build(params);
|
| 444 |
+
expect(typeof invocation).not.toBe('string');
|
| 445 |
+
});
|
| 446 |
+
});
|
| 447 |
+
});
|
| 448 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/read-file.ts
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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7 |
+
import path from 'path';
|
| 8 |
+
import { makeRelative, shortenPath } from '../utils/paths.js';
|
| 9 |
+
import {
|
| 10 |
+
BaseDeclarativeTool,
|
| 11 |
+
BaseToolInvocation,
|
| 12 |
+
Kind,
|
| 13 |
+
ToolInvocation,
|
| 14 |
+
ToolLocation,
|
| 15 |
+
ToolResult,
|
| 16 |
+
} from './tools.js';
|
| 17 |
+
import { ToolErrorType } from './tool-error.js';
|
| 18 |
+
import { PartUnion } from '@google/genai';
|
| 19 |
+
import {
|
| 20 |
+
processSingleFileContent,
|
| 21 |
+
getSpecificMimeType,
|
| 22 |
+
} from '../utils/fileUtils.js';
|
| 23 |
+
import { Config } from '../config/config.js';
|
| 24 |
+
import {
|
| 25 |
+
recordFileOperationMetric,
|
| 26 |
+
FileOperation,
|
| 27 |
+
} from '../telemetry/metrics.js';
|
| 28 |
+
|
| 29 |
+
/**
|
| 30 |
+
* Parameters for the ReadFile tool
|
| 31 |
+
*/
|
| 32 |
+
export interface ReadFileToolParams {
|
| 33 |
+
/**
|
| 34 |
+
* The absolute path to the file to read
|
| 35 |
+
*/
|
| 36 |
+
absolute_path: string;
|
| 37 |
+
|
| 38 |
+
/**
|
| 39 |
+
* The line number to start reading from (optional)
|
| 40 |
+
*/
|
| 41 |
+
offset?: number;
|
| 42 |
+
|
| 43 |
+
/**
|
| 44 |
+
* The number of lines to read (optional)
|
| 45 |
+
*/
|
| 46 |
+
limit?: number;
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
class ReadFileToolInvocation extends BaseToolInvocation<
|
| 50 |
+
ReadFileToolParams,
|
| 51 |
+
ToolResult
|
| 52 |
+
> {
|
| 53 |
+
constructor(
|
| 54 |
+
private config: Config,
|
| 55 |
+
params: ReadFileToolParams,
|
| 56 |
+
) {
|
| 57 |
+
super(params);
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
getDescription(): string {
|
| 61 |
+
const relativePath = makeRelative(
|
| 62 |
+
this.params.absolute_path,
|
| 63 |
+
this.config.getTargetDir(),
|
| 64 |
+
);
|
| 65 |
+
return shortenPath(relativePath);
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
override toolLocations(): ToolLocation[] {
|
| 69 |
+
return [{ path: this.params.absolute_path, line: this.params.offset }];
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
async execute(): Promise<ToolResult> {
|
| 73 |
+
const result = await processSingleFileContent(
|
| 74 |
+
this.params.absolute_path,
|
| 75 |
+
this.config.getTargetDir(),
|
| 76 |
+
this.config.getFileSystemService(),
|
| 77 |
+
this.params.offset,
|
| 78 |
+
this.params.limit,
|
| 79 |
+
);
|
| 80 |
+
|
| 81 |
+
if (result.error) {
|
| 82 |
+
// Map error messages to ToolErrorType
|
| 83 |
+
let errorType: ToolErrorType;
|
| 84 |
+
let llmContent: string;
|
| 85 |
+
|
| 86 |
+
// Check error message patterns to determine error type
|
| 87 |
+
if (
|
| 88 |
+
result.error.includes('File not found') ||
|
| 89 |
+
result.error.includes('does not exist') ||
|
| 90 |
+
result.error.includes('ENOENT')
|
| 91 |
+
) {
|
| 92 |
+
errorType = ToolErrorType.FILE_NOT_FOUND;
|
| 93 |
+
llmContent =
|
| 94 |
+
'Could not read file because no file was found at the specified path.';
|
| 95 |
+
} else if (
|
| 96 |
+
result.error.includes('is a directory') ||
|
| 97 |
+
result.error.includes('EISDIR')
|
| 98 |
+
) {
|
| 99 |
+
errorType = ToolErrorType.INVALID_TOOL_PARAMS;
|
| 100 |
+
llmContent =
|
| 101 |
+
'Could not read file because the provided path is a directory, not a file.';
|
| 102 |
+
} else if (
|
| 103 |
+
result.error.includes('too large') ||
|
| 104 |
+
result.error.includes('File size exceeds')
|
| 105 |
+
) {
|
| 106 |
+
errorType = ToolErrorType.FILE_TOO_LARGE;
|
| 107 |
+
llmContent = `Could not read file. ${result.error}`;
|
| 108 |
+
} else {
|
| 109 |
+
// Other read errors map to READ_CONTENT_FAILURE
|
| 110 |
+
errorType = ToolErrorType.READ_CONTENT_FAILURE;
|
| 111 |
+
llmContent = `Could not read file. ${result.error}`;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
return {
|
| 115 |
+
llmContent,
|
| 116 |
+
returnDisplay: result.returnDisplay || 'Error reading file',
|
| 117 |
+
error: {
|
| 118 |
+
message: result.error,
|
| 119 |
+
type: errorType,
|
| 120 |
+
},
|
| 121 |
+
};
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
let llmContent: PartUnion;
|
| 125 |
+
if (result.isTruncated) {
|
| 126 |
+
const [start, end] = result.linesShown!;
|
| 127 |
+
const total = result.originalLineCount!;
|
| 128 |
+
const nextOffset = this.params.offset
|
| 129 |
+
? this.params.offset + end - start + 1
|
| 130 |
+
: end;
|
| 131 |
+
llmContent = `
|
| 132 |
+
IMPORTANT: The file content has been truncated.
|
| 133 |
+
Status: Showing lines ${start}-${end} of ${total} total lines.
|
| 134 |
+
Action: To read more of the file, you can use the 'offset' and 'limit' parameters in a subsequent 'read_file' call. For example, to read the next section of the file, use offset: ${nextOffset}.
|
| 135 |
+
|
| 136 |
+
--- FILE CONTENT (truncated) ---
|
| 137 |
+
${result.llmContent}`;
|
| 138 |
+
} else {
|
| 139 |
+
llmContent = result.llmContent || '';
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
const lines =
|
| 143 |
+
typeof result.llmContent === 'string'
|
| 144 |
+
? result.llmContent.split('\n').length
|
| 145 |
+
: undefined;
|
| 146 |
+
const mimetype = getSpecificMimeType(this.params.absolute_path);
|
| 147 |
+
recordFileOperationMetric(
|
| 148 |
+
this.config,
|
| 149 |
+
FileOperation.READ,
|
| 150 |
+
lines,
|
| 151 |
+
mimetype,
|
| 152 |
+
path.extname(this.params.absolute_path),
|
| 153 |
+
);
|
| 154 |
+
|
| 155 |
+
return {
|
| 156 |
+
llmContent,
|
| 157 |
+
returnDisplay: result.returnDisplay || '',
|
| 158 |
+
};
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
/**
|
| 163 |
+
* Implementation of the ReadFile tool logic
|
| 164 |
+
*/
|
| 165 |
+
export class ReadFileTool extends BaseDeclarativeTool<
|
| 166 |
+
ReadFileToolParams,
|
| 167 |
+
ToolResult
|
| 168 |
+
> {
|
| 169 |
+
static readonly Name: string = 'read_file';
|
| 170 |
+
|
| 171 |
+
constructor(private config: Config) {
|
| 172 |
+
super(
|
| 173 |
+
ReadFileTool.Name,
|
| 174 |
+
'ReadFile',
|
| 175 |
+
`Reads and returns the content of a specified file. If the file is large, the content will be truncated. The tool's response will clearly indicate if truncation has occurred and will provide details on how to read more of the file using the 'offset' and 'limit' parameters. Handles text, images (PNG, JPG, GIF, WEBP, SVG, BMP), and PDF files. For text files, it can read specific line ranges.`,
|
| 176 |
+
Kind.Read,
|
| 177 |
+
{
|
| 178 |
+
properties: {
|
| 179 |
+
absolute_path: {
|
| 180 |
+
description:
|
| 181 |
+
"The absolute path to the file to read (e.g., '/home/user/project/file.txt'). Relative paths are not supported. You must provide an absolute path.",
|
| 182 |
+
type: 'string',
|
| 183 |
+
},
|
| 184 |
+
offset: {
|
| 185 |
+
description:
|
| 186 |
+
"Optional: For text files, the 0-based line number to start reading from. Requires 'limit' to be set. Use for paginating through large files.",
|
| 187 |
+
type: 'number',
|
| 188 |
+
},
|
| 189 |
+
limit: {
|
| 190 |
+
description:
|
| 191 |
+
"Optional: For text files, maximum number of lines to read. Use with 'offset' to paginate through large files. If omitted, reads the entire file (if feasible, up to a default limit).",
|
| 192 |
+
type: 'number',
|
| 193 |
+
},
|
| 194 |
+
},
|
| 195 |
+
required: ['absolute_path'],
|
| 196 |
+
type: 'object',
|
| 197 |
+
},
|
| 198 |
+
);
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
protected override validateToolParamValues(
|
| 202 |
+
params: ReadFileToolParams,
|
| 203 |
+
): string | null {
|
| 204 |
+
const filePath = params.absolute_path;
|
| 205 |
+
if (params.absolute_path.trim() === '') {
|
| 206 |
+
return "The 'absolute_path' parameter must be non-empty.";
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
if (!path.isAbsolute(filePath)) {
|
| 210 |
+
return `File path must be absolute, but was relative: ${filePath}. You must provide an absolute path.`;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 214 |
+
if (!workspaceContext.isPathWithinWorkspace(filePath)) {
|
| 215 |
+
const directories = workspaceContext.getDirectories();
|
| 216 |
+
return `File path must be within one of the workspace directories: ${directories.join(', ')}`;
|
| 217 |
+
}
|
| 218 |
+
if (params.offset !== undefined && params.offset < 0) {
|
| 219 |
+
return 'Offset must be a non-negative number';
|
| 220 |
+
}
|
| 221 |
+
if (params.limit !== undefined && params.limit <= 0) {
|
| 222 |
+
return 'Limit must be a positive number';
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
const fileService = this.config.getFileService();
|
| 226 |
+
if (fileService.shouldGeminiIgnoreFile(params.absolute_path)) {
|
| 227 |
+
return `File path '${filePath}' is ignored by .geminiignore pattern(s).`;
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
return null;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
protected createInvocation(
|
| 234 |
+
params: ReadFileToolParams,
|
| 235 |
+
): ToolInvocation<ReadFileToolParams, ToolResult> {
|
| 236 |
+
return new ReadFileToolInvocation(this.config, params);
|
| 237 |
+
}
|
| 238 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/read-many-files.test.ts
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
import type { Mock } from 'vitest';
|
| 9 |
+
import { mockControl } from '../__mocks__/fs/promises.js';
|
| 10 |
+
import { ReadManyFilesTool } from './read-many-files.js';
|
| 11 |
+
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
|
| 12 |
+
import path from 'path';
|
| 13 |
+
import fs from 'fs'; // Actual fs for setup
|
| 14 |
+
import os from 'os';
|
| 15 |
+
import { Config } from '../config/config.js';
|
| 16 |
+
import { WorkspaceContext } from '../utils/workspaceContext.js';
|
| 17 |
+
import { StandardFileSystemService } from '../services/fileSystemService.js';
|
| 18 |
+
|
| 19 |
+
vi.mock('mime-types', () => {
|
| 20 |
+
const lookup = (filename: string) => {
|
| 21 |
+
if (filename.endsWith('.ts') || filename.endsWith('.js')) {
|
| 22 |
+
return 'text/plain';
|
| 23 |
+
}
|
| 24 |
+
if (filename.endsWith('.png')) {
|
| 25 |
+
return 'image/png';
|
| 26 |
+
}
|
| 27 |
+
if (filename.endsWith('.pdf')) {
|
| 28 |
+
return 'application/pdf';
|
| 29 |
+
}
|
| 30 |
+
if (filename.endsWith('.mp3') || filename.endsWith('.wav')) {
|
| 31 |
+
return 'audio/mpeg';
|
| 32 |
+
}
|
| 33 |
+
if (filename.endsWith('.mp4') || filename.endsWith('.mov')) {
|
| 34 |
+
return 'video/mp4';
|
| 35 |
+
}
|
| 36 |
+
return false;
|
| 37 |
+
};
|
| 38 |
+
return {
|
| 39 |
+
default: {
|
| 40 |
+
lookup,
|
| 41 |
+
},
|
| 42 |
+
lookup,
|
| 43 |
+
};
|
| 44 |
+
});
|
| 45 |
+
|
| 46 |
+
describe('ReadManyFilesTool', () => {
|
| 47 |
+
let tool: ReadManyFilesTool;
|
| 48 |
+
let tempRootDir: string;
|
| 49 |
+
let tempDirOutsideRoot: string;
|
| 50 |
+
let mockReadFileFn: Mock;
|
| 51 |
+
|
| 52 |
+
beforeEach(async () => {
|
| 53 |
+
tempRootDir = fs.realpathSync(
|
| 54 |
+
fs.mkdtempSync(path.join(os.tmpdir(), 'read-many-files-root-')),
|
| 55 |
+
);
|
| 56 |
+
tempDirOutsideRoot = fs.realpathSync(
|
| 57 |
+
fs.mkdtempSync(path.join(os.tmpdir(), 'read-many-files-external-')),
|
| 58 |
+
);
|
| 59 |
+
fs.writeFileSync(path.join(tempRootDir, '.geminiignore'), 'foo.*');
|
| 60 |
+
const fileService = new FileDiscoveryService(tempRootDir);
|
| 61 |
+
const mockConfig = {
|
| 62 |
+
getFileService: () => fileService,
|
| 63 |
+
getFileSystemService: () => new StandardFileSystemService(),
|
| 64 |
+
|
| 65 |
+
getFileFilteringOptions: () => ({
|
| 66 |
+
respectGitIgnore: true,
|
| 67 |
+
respectGeminiIgnore: true,
|
| 68 |
+
}),
|
| 69 |
+
getTargetDir: () => tempRootDir,
|
| 70 |
+
getWorkspaceDirs: () => [tempRootDir],
|
| 71 |
+
getWorkspaceContext: () => new WorkspaceContext(tempRootDir),
|
| 72 |
+
} as Partial<Config> as Config;
|
| 73 |
+
tool = new ReadManyFilesTool(mockConfig);
|
| 74 |
+
|
| 75 |
+
mockReadFileFn = mockControl.mockReadFile;
|
| 76 |
+
mockReadFileFn.mockReset();
|
| 77 |
+
|
| 78 |
+
mockReadFileFn.mockImplementation(
|
| 79 |
+
async (filePath: fs.PathLike, options?: Record<string, unknown>) => {
|
| 80 |
+
const fp =
|
| 81 |
+
typeof filePath === 'string'
|
| 82 |
+
? filePath
|
| 83 |
+
: (filePath as Buffer).toString();
|
| 84 |
+
|
| 85 |
+
if (fs.existsSync(fp)) {
|
| 86 |
+
const originalFs = await vi.importActual<typeof fs>('fs');
|
| 87 |
+
return originalFs.promises.readFile(fp, options);
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
if (fp.endsWith('nonexistent-file.txt')) {
|
| 91 |
+
const err = new Error(
|
| 92 |
+
`ENOENT: no such file or directory, open '${fp}'`,
|
| 93 |
+
);
|
| 94 |
+
(err as NodeJS.ErrnoException).code = 'ENOENT';
|
| 95 |
+
throw err;
|
| 96 |
+
}
|
| 97 |
+
if (fp.endsWith('unreadable.txt')) {
|
| 98 |
+
const err = new Error(`EACCES: permission denied, open '${fp}'`);
|
| 99 |
+
(err as NodeJS.ErrnoException).code = 'EACCES';
|
| 100 |
+
throw err;
|
| 101 |
+
}
|
| 102 |
+
if (fp.endsWith('.png'))
|
| 103 |
+
return Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); // PNG header
|
| 104 |
+
if (fp.endsWith('.pdf')) return Buffer.from('%PDF-1.4...'); // PDF start
|
| 105 |
+
if (fp.endsWith('binary.bin'))
|
| 106 |
+
return Buffer.from([0x00, 0x01, 0x02, 0x00, 0x03]);
|
| 107 |
+
|
| 108 |
+
const err = new Error(
|
| 109 |
+
`ENOENT: no such file or directory, open '${fp}' (unmocked path)`,
|
| 110 |
+
);
|
| 111 |
+
(err as NodeJS.ErrnoException).code = 'ENOENT';
|
| 112 |
+
throw err;
|
| 113 |
+
},
|
| 114 |
+
);
|
| 115 |
+
});
|
| 116 |
+
|
| 117 |
+
afterEach(() => {
|
| 118 |
+
if (fs.existsSync(tempRootDir)) {
|
| 119 |
+
fs.rmSync(tempRootDir, { recursive: true, force: true });
|
| 120 |
+
}
|
| 121 |
+
if (fs.existsSync(tempDirOutsideRoot)) {
|
| 122 |
+
fs.rmSync(tempDirOutsideRoot, { recursive: true, force: true });
|
| 123 |
+
}
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
describe('build', () => {
|
| 127 |
+
it('should return an invocation for valid relative paths within root', () => {
|
| 128 |
+
const params = { paths: ['file1.txt', 'subdir/file2.txt'] };
|
| 129 |
+
const invocation = tool.build(params);
|
| 130 |
+
expect(invocation).toBeDefined();
|
| 131 |
+
});
|
| 132 |
+
|
| 133 |
+
it('should return an invocation for valid glob patterns within root', () => {
|
| 134 |
+
const params = { paths: ['*.txt', 'subdir/**/*.js'] };
|
| 135 |
+
const invocation = tool.build(params);
|
| 136 |
+
expect(invocation).toBeDefined();
|
| 137 |
+
});
|
| 138 |
+
|
| 139 |
+
it('should return an invocation for paths trying to escape the root (e.g., ../) as execute handles this', () => {
|
| 140 |
+
const params = { paths: ['../outside.txt'] };
|
| 141 |
+
const invocation = tool.build(params);
|
| 142 |
+
expect(invocation).toBeDefined();
|
| 143 |
+
});
|
| 144 |
+
|
| 145 |
+
it('should return an invocation for absolute paths as execute handles this', () => {
|
| 146 |
+
const params = { paths: [path.join(tempDirOutsideRoot, 'absolute.txt')] };
|
| 147 |
+
const invocation = tool.build(params);
|
| 148 |
+
expect(invocation).toBeDefined();
|
| 149 |
+
});
|
| 150 |
+
|
| 151 |
+
it('should throw error if paths array is empty', () => {
|
| 152 |
+
const params = { paths: [] };
|
| 153 |
+
expect(() => tool.build(params)).toThrow(
|
| 154 |
+
'params/paths must NOT have fewer than 1 items',
|
| 155 |
+
);
|
| 156 |
+
});
|
| 157 |
+
|
| 158 |
+
it('should return an invocation for valid exclude and include patterns', () => {
|
| 159 |
+
const params = {
|
| 160 |
+
paths: ['src/**/*.ts'],
|
| 161 |
+
exclude: ['**/*.test.ts'],
|
| 162 |
+
include: ['src/utils/*.ts'],
|
| 163 |
+
};
|
| 164 |
+
const invocation = tool.build(params);
|
| 165 |
+
expect(invocation).toBeDefined();
|
| 166 |
+
});
|
| 167 |
+
|
| 168 |
+
it('should throw error if paths array contains an empty string', () => {
|
| 169 |
+
const params = { paths: ['file1.txt', ''] };
|
| 170 |
+
expect(() => tool.build(params)).toThrow(
|
| 171 |
+
'params/paths/1 must NOT have fewer than 1 characters',
|
| 172 |
+
);
|
| 173 |
+
});
|
| 174 |
+
|
| 175 |
+
it('should throw error if include array contains non-string elements', () => {
|
| 176 |
+
const params = {
|
| 177 |
+
paths: ['file1.txt'],
|
| 178 |
+
include: ['*.ts', 123] as string[],
|
| 179 |
+
};
|
| 180 |
+
expect(() => tool.build(params)).toThrow(
|
| 181 |
+
'params/include/1 must be string',
|
| 182 |
+
);
|
| 183 |
+
});
|
| 184 |
+
|
| 185 |
+
it('should throw error if exclude array contains non-string elements', () => {
|
| 186 |
+
const params = {
|
| 187 |
+
paths: ['file1.txt'],
|
| 188 |
+
exclude: ['*.log', {}] as string[],
|
| 189 |
+
};
|
| 190 |
+
expect(() => tool.build(params)).toThrow(
|
| 191 |
+
'params/exclude/1 must be string',
|
| 192 |
+
);
|
| 193 |
+
});
|
| 194 |
+
});
|
| 195 |
+
|
| 196 |
+
describe('execute', () => {
|
| 197 |
+
const createFile = (filePath: string, content = '') => {
|
| 198 |
+
const fullPath = path.join(tempRootDir, filePath);
|
| 199 |
+
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
| 200 |
+
fs.writeFileSync(fullPath, content);
|
| 201 |
+
};
|
| 202 |
+
const createBinaryFile = (filePath: string, data: Uint8Array) => {
|
| 203 |
+
const fullPath = path.join(tempRootDir, filePath);
|
| 204 |
+
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
| 205 |
+
fs.writeFileSync(fullPath, data);
|
| 206 |
+
};
|
| 207 |
+
|
| 208 |
+
it('should read a single specified file', async () => {
|
| 209 |
+
createFile('file1.txt', 'Content of file1');
|
| 210 |
+
const params = { paths: ['file1.txt'] };
|
| 211 |
+
const invocation = tool.build(params);
|
| 212 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 213 |
+
const expectedPath = path.join(tempRootDir, 'file1.txt');
|
| 214 |
+
expect(result.llmContent).toEqual([
|
| 215 |
+
`--- ${expectedPath} ---\n\nContent of file1\n\n`,
|
| 216 |
+
]);
|
| 217 |
+
expect(result.returnDisplay).toContain(
|
| 218 |
+
'Successfully read and concatenated content from **1 file(s)**',
|
| 219 |
+
);
|
| 220 |
+
});
|
| 221 |
+
|
| 222 |
+
it('should read multiple specified files', async () => {
|
| 223 |
+
createFile('file1.txt', 'Content1');
|
| 224 |
+
createFile('subdir/file2.js', 'Content2');
|
| 225 |
+
const params = { paths: ['file1.txt', 'subdir/file2.js'] };
|
| 226 |
+
const invocation = tool.build(params);
|
| 227 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 228 |
+
const content = result.llmContent as string[];
|
| 229 |
+
const expectedPath1 = path.join(tempRootDir, 'file1.txt');
|
| 230 |
+
const expectedPath2 = path.join(tempRootDir, 'subdir/file2.js');
|
| 231 |
+
expect(
|
| 232 |
+
content.some((c) =>
|
| 233 |
+
c.includes(`--- ${expectedPath1} ---\n\nContent1\n\n`),
|
| 234 |
+
),
|
| 235 |
+
).toBe(true);
|
| 236 |
+
expect(
|
| 237 |
+
content.some((c) =>
|
| 238 |
+
c.includes(`--- ${expectedPath2} ---\n\nContent2\n\n`),
|
| 239 |
+
),
|
| 240 |
+
).toBe(true);
|
| 241 |
+
expect(result.returnDisplay).toContain(
|
| 242 |
+
'Successfully read and concatenated content from **2 file(s)**',
|
| 243 |
+
);
|
| 244 |
+
});
|
| 245 |
+
|
| 246 |
+
it('should handle glob patterns', async () => {
|
| 247 |
+
createFile('file.txt', 'Text file');
|
| 248 |
+
createFile('another.txt', 'Another text');
|
| 249 |
+
createFile('sub/data.json', '{}');
|
| 250 |
+
const params = { paths: ['*.txt'] };
|
| 251 |
+
const invocation = tool.build(params);
|
| 252 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 253 |
+
const content = result.llmContent as string[];
|
| 254 |
+
const expectedPath1 = path.join(tempRootDir, 'file.txt');
|
| 255 |
+
const expectedPath2 = path.join(tempRootDir, 'another.txt');
|
| 256 |
+
expect(
|
| 257 |
+
content.some((c) =>
|
| 258 |
+
c.includes(`--- ${expectedPath1} ---\n\nText file\n\n`),
|
| 259 |
+
),
|
| 260 |
+
).toBe(true);
|
| 261 |
+
expect(
|
| 262 |
+
content.some((c) =>
|
| 263 |
+
c.includes(`--- ${expectedPath2} ---\n\nAnother text\n\n`),
|
| 264 |
+
),
|
| 265 |
+
).toBe(true);
|
| 266 |
+
expect(content.find((c) => c.includes('sub/data.json'))).toBeUndefined();
|
| 267 |
+
expect(result.returnDisplay).toContain(
|
| 268 |
+
'Successfully read and concatenated content from **2 file(s)**',
|
| 269 |
+
);
|
| 270 |
+
});
|
| 271 |
+
|
| 272 |
+
it('should respect exclude patterns', async () => {
|
| 273 |
+
createFile('src/main.ts', 'Main content');
|
| 274 |
+
createFile('src/main.test.ts', 'Test content');
|
| 275 |
+
const params = { paths: ['src/**/*.ts'], exclude: ['**/*.test.ts'] };
|
| 276 |
+
const invocation = tool.build(params);
|
| 277 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 278 |
+
const content = result.llmContent as string[];
|
| 279 |
+
const expectedPath = path.join(tempRootDir, 'src/main.ts');
|
| 280 |
+
expect(content).toEqual([`--- ${expectedPath} ---\n\nMain content\n\n`]);
|
| 281 |
+
expect(
|
| 282 |
+
content.find((c) => c.includes('src/main.test.ts')),
|
| 283 |
+
).toBeUndefined();
|
| 284 |
+
expect(result.returnDisplay).toContain(
|
| 285 |
+
'Successfully read and concatenated content from **1 file(s)**',
|
| 286 |
+
);
|
| 287 |
+
});
|
| 288 |
+
|
| 289 |
+
it('should handle nonexistent specific files gracefully', async () => {
|
| 290 |
+
const params = { paths: ['nonexistent-file.txt'] };
|
| 291 |
+
const invocation = tool.build(params);
|
| 292 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 293 |
+
expect(result.llmContent).toEqual([
|
| 294 |
+
'No files matching the criteria were found or all were skipped.',
|
| 295 |
+
]);
|
| 296 |
+
expect(result.returnDisplay).toContain(
|
| 297 |
+
'No files were read and concatenated based on the criteria.',
|
| 298 |
+
);
|
| 299 |
+
});
|
| 300 |
+
|
| 301 |
+
it('should use default excludes', async () => {
|
| 302 |
+
createFile('node_modules/some-lib/index.js', 'lib code');
|
| 303 |
+
createFile('src/app.js', 'app code');
|
| 304 |
+
const params = { paths: ['**/*.js'] };
|
| 305 |
+
const invocation = tool.build(params);
|
| 306 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 307 |
+
const content = result.llmContent as string[];
|
| 308 |
+
const expectedPath = path.join(tempRootDir, 'src/app.js');
|
| 309 |
+
expect(content).toEqual([`--- ${expectedPath} ---\n\napp code\n\n`]);
|
| 310 |
+
expect(
|
| 311 |
+
content.find((c) => c.includes('node_modules/some-lib/index.js')),
|
| 312 |
+
).toBeUndefined();
|
| 313 |
+
expect(result.returnDisplay).toContain(
|
| 314 |
+
'Successfully read and concatenated content from **1 file(s)**',
|
| 315 |
+
);
|
| 316 |
+
});
|
| 317 |
+
|
| 318 |
+
it('should NOT use default excludes if useDefaultExcludes is false', async () => {
|
| 319 |
+
createFile('node_modules/some-lib/index.js', 'lib code');
|
| 320 |
+
createFile('src/app.js', 'app code');
|
| 321 |
+
const params = { paths: ['**/*.js'], useDefaultExcludes: false };
|
| 322 |
+
const invocation = tool.build(params);
|
| 323 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 324 |
+
const content = result.llmContent as string[];
|
| 325 |
+
const expectedPath1 = path.join(
|
| 326 |
+
tempRootDir,
|
| 327 |
+
'node_modules/some-lib/index.js',
|
| 328 |
+
);
|
| 329 |
+
const expectedPath2 = path.join(tempRootDir, 'src/app.js');
|
| 330 |
+
expect(
|
| 331 |
+
content.some((c) =>
|
| 332 |
+
c.includes(`--- ${expectedPath1} ---\n\nlib code\n\n`),
|
| 333 |
+
),
|
| 334 |
+
).toBe(true);
|
| 335 |
+
expect(
|
| 336 |
+
content.some((c) =>
|
| 337 |
+
c.includes(`--- ${expectedPath2} ---\n\napp code\n\n`),
|
| 338 |
+
),
|
| 339 |
+
).toBe(true);
|
| 340 |
+
expect(result.returnDisplay).toContain(
|
| 341 |
+
'Successfully read and concatenated content from **2 file(s)**',
|
| 342 |
+
);
|
| 343 |
+
});
|
| 344 |
+
|
| 345 |
+
it('should include images as inlineData parts if explicitly requested by extension', async () => {
|
| 346 |
+
createBinaryFile(
|
| 347 |
+
'image.png',
|
| 348 |
+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
| 349 |
+
);
|
| 350 |
+
const params = { paths: ['*.png'] }; // Explicitly requesting .png
|
| 351 |
+
const invocation = tool.build(params);
|
| 352 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 353 |
+
expect(result.llmContent).toEqual([
|
| 354 |
+
{
|
| 355 |
+
inlineData: {
|
| 356 |
+
data: Buffer.from([
|
| 357 |
+
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
| 358 |
+
]).toString('base64'),
|
| 359 |
+
mimeType: 'image/png',
|
| 360 |
+
},
|
| 361 |
+
},
|
| 362 |
+
]);
|
| 363 |
+
expect(result.returnDisplay).toContain(
|
| 364 |
+
'Successfully read and concatenated content from **1 file(s)**',
|
| 365 |
+
);
|
| 366 |
+
});
|
| 367 |
+
|
| 368 |
+
it('should include images as inlineData parts if explicitly requested by name', async () => {
|
| 369 |
+
createBinaryFile(
|
| 370 |
+
'myExactImage.png',
|
| 371 |
+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
| 372 |
+
);
|
| 373 |
+
const params = { paths: ['myExactImage.png'] }; // Explicitly requesting by full name
|
| 374 |
+
const invocation = tool.build(params);
|
| 375 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 376 |
+
expect(result.llmContent).toEqual([
|
| 377 |
+
{
|
| 378 |
+
inlineData: {
|
| 379 |
+
data: Buffer.from([
|
| 380 |
+
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
| 381 |
+
]).toString('base64'),
|
| 382 |
+
mimeType: 'image/png',
|
| 383 |
+
},
|
| 384 |
+
},
|
| 385 |
+
]);
|
| 386 |
+
});
|
| 387 |
+
|
| 388 |
+
it('should skip PDF files if not explicitly requested by extension or name', async () => {
|
| 389 |
+
createBinaryFile('document.pdf', Buffer.from('%PDF-1.4...'));
|
| 390 |
+
createFile('notes.txt', 'text notes');
|
| 391 |
+
const params = { paths: ['*'] }; // Generic glob, not specific to .pdf
|
| 392 |
+
const invocation = tool.build(params);
|
| 393 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 394 |
+
const content = result.llmContent as string[];
|
| 395 |
+
const expectedPath = path.join(tempRootDir, 'notes.txt');
|
| 396 |
+
expect(
|
| 397 |
+
content.some(
|
| 398 |
+
(c) =>
|
| 399 |
+
typeof c === 'string' &&
|
| 400 |
+
c.includes(`--- ${expectedPath} ---\n\ntext notes\n\n`),
|
| 401 |
+
),
|
| 402 |
+
).toBe(true);
|
| 403 |
+
expect(result.returnDisplay).toContain('**Skipped 1 item(s):**');
|
| 404 |
+
expect(result.returnDisplay).toContain(
|
| 405 |
+
'- `document.pdf` (Reason: asset file (image/pdf) was not explicitly requested by name or extension)',
|
| 406 |
+
);
|
| 407 |
+
});
|
| 408 |
+
|
| 409 |
+
it('should include PDF files as inlineData parts if explicitly requested by extension', async () => {
|
| 410 |
+
createBinaryFile('important.pdf', Buffer.from('%PDF-1.4...'));
|
| 411 |
+
const params = { paths: ['*.pdf'] }; // Explicitly requesting .pdf files
|
| 412 |
+
const invocation = tool.build(params);
|
| 413 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 414 |
+
expect(result.llmContent).toEqual([
|
| 415 |
+
{
|
| 416 |
+
inlineData: {
|
| 417 |
+
data: Buffer.from('%PDF-1.4...').toString('base64'),
|
| 418 |
+
mimeType: 'application/pdf',
|
| 419 |
+
},
|
| 420 |
+
},
|
| 421 |
+
]);
|
| 422 |
+
});
|
| 423 |
+
|
| 424 |
+
it('should include PDF files as inlineData parts if explicitly requested by name', async () => {
|
| 425 |
+
createBinaryFile('report-final.pdf', Buffer.from('%PDF-1.4...'));
|
| 426 |
+
const params = { paths: ['report-final.pdf'] };
|
| 427 |
+
const invocation = tool.build(params);
|
| 428 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 429 |
+
expect(result.llmContent).toEqual([
|
| 430 |
+
{
|
| 431 |
+
inlineData: {
|
| 432 |
+
data: Buffer.from('%PDF-1.4...').toString('base64'),
|
| 433 |
+
mimeType: 'application/pdf',
|
| 434 |
+
},
|
| 435 |
+
},
|
| 436 |
+
]);
|
| 437 |
+
});
|
| 438 |
+
|
| 439 |
+
it('should return error if path is ignored by a .geminiignore pattern', async () => {
|
| 440 |
+
createFile('foo.bar', '');
|
| 441 |
+
createFile('bar.ts', '');
|
| 442 |
+
createFile('foo.quux', '');
|
| 443 |
+
const params = { paths: ['foo.bar', 'bar.ts', 'foo.quux'] };
|
| 444 |
+
const invocation = tool.build(params);
|
| 445 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 446 |
+
expect(result.returnDisplay).not.toContain('foo.bar');
|
| 447 |
+
expect(result.returnDisplay).not.toContain('foo.quux');
|
| 448 |
+
expect(result.returnDisplay).toContain('bar.ts');
|
| 449 |
+
});
|
| 450 |
+
|
| 451 |
+
it('should read files from multiple workspace directories', async () => {
|
| 452 |
+
const tempDir1 = fs.realpathSync(
|
| 453 |
+
fs.mkdtempSync(path.join(os.tmpdir(), 'multi-dir-1-')),
|
| 454 |
+
);
|
| 455 |
+
const tempDir2 = fs.realpathSync(
|
| 456 |
+
fs.mkdtempSync(path.join(os.tmpdir(), 'multi-dir-2-')),
|
| 457 |
+
);
|
| 458 |
+
const fileService = new FileDiscoveryService(tempDir1);
|
| 459 |
+
const mockConfig = {
|
| 460 |
+
getFileService: () => fileService,
|
| 461 |
+
getFileSystemService: () => new StandardFileSystemService(),
|
| 462 |
+
getFileFilteringOptions: () => ({
|
| 463 |
+
respectGitIgnore: true,
|
| 464 |
+
respectGeminiIgnore: true,
|
| 465 |
+
}),
|
| 466 |
+
getWorkspaceContext: () => new WorkspaceContext(tempDir1, [tempDir2]),
|
| 467 |
+
getTargetDir: () => tempDir1,
|
| 468 |
+
} as Partial<Config> as Config;
|
| 469 |
+
tool = new ReadManyFilesTool(mockConfig);
|
| 470 |
+
|
| 471 |
+
fs.writeFileSync(path.join(tempDir1, 'file1.txt'), 'Content1');
|
| 472 |
+
fs.writeFileSync(path.join(tempDir2, 'file2.txt'), 'Content2');
|
| 473 |
+
|
| 474 |
+
const params = { paths: ['*.txt'] };
|
| 475 |
+
const invocation = tool.build(params);
|
| 476 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 477 |
+
const content = result.llmContent as string[];
|
| 478 |
+
if (!Array.isArray(content)) {
|
| 479 |
+
throw new Error(`llmContent is not an array: ${content}`);
|
| 480 |
+
}
|
| 481 |
+
const expectedPath1 = path.join(tempDir1, 'file1.txt');
|
| 482 |
+
const expectedPath2 = path.join(tempDir2, 'file2.txt');
|
| 483 |
+
|
| 484 |
+
expect(
|
| 485 |
+
content.some((c) =>
|
| 486 |
+
c.includes(`--- ${expectedPath1} ---\n\nContent1\n\n`),
|
| 487 |
+
),
|
| 488 |
+
).toBe(true);
|
| 489 |
+
expect(
|
| 490 |
+
content.some((c) =>
|
| 491 |
+
c.includes(`--- ${expectedPath2} ---\n\nContent2\n\n`),
|
| 492 |
+
),
|
| 493 |
+
).toBe(true);
|
| 494 |
+
expect(result.returnDisplay).toContain(
|
| 495 |
+
'Successfully read and concatenated content from **2 file(s)**',
|
| 496 |
+
);
|
| 497 |
+
|
| 498 |
+
fs.rmSync(tempDir1, { recursive: true, force: true });
|
| 499 |
+
fs.rmSync(tempDir2, { recursive: true, force: true });
|
| 500 |
+
});
|
| 501 |
+
|
| 502 |
+
it('should add a warning for truncated files', async () => {
|
| 503 |
+
createFile('file1.txt', 'Content1');
|
| 504 |
+
// Create a file that will be "truncated" by making it long
|
| 505 |
+
const longContent = Array.from({ length: 2500 }, (_, i) => `L${i}`).join(
|
| 506 |
+
'\n',
|
| 507 |
+
);
|
| 508 |
+
createFile('large-file.txt', longContent);
|
| 509 |
+
|
| 510 |
+
const params = { paths: ['*.txt'] };
|
| 511 |
+
const invocation = tool.build(params);
|
| 512 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 513 |
+
const content = result.llmContent as string[];
|
| 514 |
+
|
| 515 |
+
const normalFileContent = content.find((c) => c.includes('file1.txt'));
|
| 516 |
+
const truncatedFileContent = content.find((c) =>
|
| 517 |
+
c.includes('large-file.txt'),
|
| 518 |
+
);
|
| 519 |
+
|
| 520 |
+
expect(normalFileContent).not.toContain(
|
| 521 |
+
'[WARNING: This file was truncated.',
|
| 522 |
+
);
|
| 523 |
+
expect(truncatedFileContent).toContain(
|
| 524 |
+
"[WARNING: This file was truncated. To view the full content, use the 'read_file' tool on this specific file.]",
|
| 525 |
+
);
|
| 526 |
+
// Check that the actual content is still there but truncated
|
| 527 |
+
expect(truncatedFileContent).toContain('L200');
|
| 528 |
+
expect(truncatedFileContent).not.toContain('L2400');
|
| 529 |
+
});
|
| 530 |
+
|
| 531 |
+
it('should read files with special characters like [] and () in the path', async () => {
|
| 532 |
+
const filePath = 'src/app/[test]/(dashboard)/testing/components/code.tsx';
|
| 533 |
+
createFile(filePath, 'Content of receive-detail');
|
| 534 |
+
const params = { paths: [filePath] };
|
| 535 |
+
const invocation = tool.build(params);
|
| 536 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 537 |
+
const expectedPath = path.join(tempRootDir, filePath);
|
| 538 |
+
expect(result.llmContent).toEqual([
|
| 539 |
+
`--- ${expectedPath} ---
|
| 540 |
+
|
| 541 |
+
Content of receive-detail
|
| 542 |
+
|
| 543 |
+
`,
|
| 544 |
+
]);
|
| 545 |
+
expect(result.returnDisplay).toContain(
|
| 546 |
+
'Successfully read and concatenated content from **1 file(s)**',
|
| 547 |
+
);
|
| 548 |
+
});
|
| 549 |
+
|
| 550 |
+
it('should read files with special characters in the name', async () => {
|
| 551 |
+
createFile('file[1].txt', 'Content of file[1]');
|
| 552 |
+
const params = { paths: ['file[1].txt'] };
|
| 553 |
+
const invocation = tool.build(params);
|
| 554 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 555 |
+
const expectedPath = path.join(tempRootDir, 'file[1].txt');
|
| 556 |
+
expect(result.llmContent).toEqual([
|
| 557 |
+
`--- ${expectedPath} ---
|
| 558 |
+
|
| 559 |
+
Content of file[1]
|
| 560 |
+
|
| 561 |
+
`,
|
| 562 |
+
]);
|
| 563 |
+
expect(result.returnDisplay).toContain(
|
| 564 |
+
'Successfully read and concatenated content from **1 file(s)**',
|
| 565 |
+
);
|
| 566 |
+
});
|
| 567 |
+
});
|
| 568 |
+
|
| 569 |
+
describe('Batch Processing', () => {
|
| 570 |
+
const createMultipleFiles = (count: number, contentPrefix = 'Content') => {
|
| 571 |
+
const files: string[] = [];
|
| 572 |
+
for (let i = 0; i < count; i++) {
|
| 573 |
+
const fileName = `file${i}.txt`;
|
| 574 |
+
createFile(fileName, `${contentPrefix} ${i}`);
|
| 575 |
+
files.push(fileName);
|
| 576 |
+
}
|
| 577 |
+
return files;
|
| 578 |
+
};
|
| 579 |
+
|
| 580 |
+
const createFile = (filePath: string, content = '') => {
|
| 581 |
+
const fullPath = path.join(tempRootDir, filePath);
|
| 582 |
+
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
| 583 |
+
fs.writeFileSync(fullPath, content);
|
| 584 |
+
};
|
| 585 |
+
|
| 586 |
+
it('should process files in parallel', async () => {
|
| 587 |
+
// Mock detectFileType to add artificial delay to simulate I/O
|
| 588 |
+
const detectFileTypeSpy = vi.spyOn(
|
| 589 |
+
await import('../utils/fileUtils.js'),
|
| 590 |
+
'detectFileType',
|
| 591 |
+
);
|
| 592 |
+
|
| 593 |
+
// Create files
|
| 594 |
+
const fileCount = 4;
|
| 595 |
+
const files = createMultipleFiles(fileCount, 'Batch test');
|
| 596 |
+
|
| 597 |
+
// Mock with 10ms delay per file to simulate I/O operations
|
| 598 |
+
detectFileTypeSpy.mockImplementation(async (_filePath: string) => {
|
| 599 |
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
| 600 |
+
return 'text';
|
| 601 |
+
});
|
| 602 |
+
|
| 603 |
+
const params = { paths: files };
|
| 604 |
+
const invocation = tool.build(params);
|
| 605 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 606 |
+
|
| 607 |
+
// Verify all files were processed
|
| 608 |
+
const content = result.llmContent as string[];
|
| 609 |
+
expect(content).toHaveLength(fileCount);
|
| 610 |
+
for (let i = 0; i < fileCount; i++) {
|
| 611 |
+
expect(content.join('')).toContain(`Batch test ${i}`);
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
// Cleanup mock
|
| 615 |
+
detectFileTypeSpy.mockRestore();
|
| 616 |
+
});
|
| 617 |
+
|
| 618 |
+
it('should handle batch processing errors gracefully', async () => {
|
| 619 |
+
// Create mix of valid and problematic files
|
| 620 |
+
createFile('valid1.txt', 'Valid content 1');
|
| 621 |
+
createFile('valid2.txt', 'Valid content 2');
|
| 622 |
+
createFile('valid3.txt', 'Valid content 3');
|
| 623 |
+
|
| 624 |
+
const params = {
|
| 625 |
+
paths: [
|
| 626 |
+
'valid1.txt',
|
| 627 |
+
'valid2.txt',
|
| 628 |
+
'nonexistent-file.txt', // This will fail
|
| 629 |
+
'valid3.txt',
|
| 630 |
+
],
|
| 631 |
+
};
|
| 632 |
+
|
| 633 |
+
const invocation = tool.build(params);
|
| 634 |
+
const result = await invocation.execute(new AbortController().signal);
|
| 635 |
+
const content = result.llmContent as string[];
|
| 636 |
+
|
| 637 |
+
// Should successfully process valid files despite one failure
|
| 638 |
+
expect(content.length).toBeGreaterThanOrEqual(3);
|
| 639 |
+
expect(result.returnDisplay).toContain('Successfully read');
|
| 640 |
+
|
| 641 |
+
// Verify valid files were processed
|
| 642 |
+
const expectedPath1 = path.join(tempRootDir, 'valid1.txt');
|
| 643 |
+
const expectedPath3 = path.join(tempRootDir, 'valid3.txt');
|
| 644 |
+
expect(content.some((c) => c.includes(expectedPath1))).toBe(true);
|
| 645 |
+
expect(content.some((c) => c.includes(expectedPath3))).toBe(true);
|
| 646 |
+
});
|
| 647 |
+
|
| 648 |
+
it('should execute file operations concurrently', async () => {
|
| 649 |
+
// Track execution order to verify concurrency
|
| 650 |
+
const executionOrder: string[] = [];
|
| 651 |
+
const detectFileTypeSpy = vi.spyOn(
|
| 652 |
+
await import('../utils/fileUtils.js'),
|
| 653 |
+
'detectFileType',
|
| 654 |
+
);
|
| 655 |
+
|
| 656 |
+
const files = ['file1.txt', 'file2.txt', 'file3.txt'];
|
| 657 |
+
files.forEach((file) => createFile(file, 'test content'));
|
| 658 |
+
|
| 659 |
+
// Mock to track concurrent vs sequential execution
|
| 660 |
+
detectFileTypeSpy.mockImplementation(async (filePath: string) => {
|
| 661 |
+
const fileName = filePath.split('/').pop() || '';
|
| 662 |
+
executionOrder.push(`start:${fileName}`);
|
| 663 |
+
|
| 664 |
+
// Add delay to make timing differences visible
|
| 665 |
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
| 666 |
+
|
| 667 |
+
executionOrder.push(`end:${fileName}`);
|
| 668 |
+
return 'text';
|
| 669 |
+
});
|
| 670 |
+
|
| 671 |
+
const invocation = tool.build({ paths: files });
|
| 672 |
+
await invocation.execute(new AbortController().signal);
|
| 673 |
+
|
| 674 |
+
console.log('Execution order:', executionOrder);
|
| 675 |
+
|
| 676 |
+
// Verify concurrent execution pattern
|
| 677 |
+
// In parallel execution: all "start:" events should come before all "end:" events
|
| 678 |
+
// In sequential execution: "start:file1", "end:file1", "start:file2", "end:file2", etc.
|
| 679 |
+
|
| 680 |
+
const startEvents = executionOrder.filter((e) =>
|
| 681 |
+
e.startsWith('start:'),
|
| 682 |
+
).length;
|
| 683 |
+
const firstEndIndex = executionOrder.findIndex((e) =>
|
| 684 |
+
e.startsWith('end:'),
|
| 685 |
+
);
|
| 686 |
+
const startsBeforeFirstEnd = executionOrder
|
| 687 |
+
.slice(0, firstEndIndex)
|
| 688 |
+
.filter((e) => e.startsWith('start:')).length;
|
| 689 |
+
|
| 690 |
+
// For parallel processing, ALL start events should happen before the first end event
|
| 691 |
+
expect(startsBeforeFirstEnd).toBe(startEvents); // Should PASS with parallel implementation
|
| 692 |
+
|
| 693 |
+
detectFileTypeSpy.mockRestore();
|
| 694 |
+
});
|
| 695 |
+
});
|
| 696 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/read-many-files.ts
ADDED
|
@@ -0,0 +1,644 @@
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'./tools.js';
|
| 14 |
+
import { getErrorMessage } from '../utils/errors.js';
|
| 15 |
+
import * as fs from 'fs';
|
| 16 |
+
import * as path from 'path';
|
| 17 |
+
import { glob, escape } from 'glob';
|
| 18 |
+
import { getCurrentGeminiMdFilename } from './memoryTool.js';
|
| 19 |
+
import {
|
| 20 |
+
detectFileType,
|
| 21 |
+
processSingleFileContent,
|
| 22 |
+
DEFAULT_ENCODING,
|
| 23 |
+
getSpecificMimeType,
|
| 24 |
+
} from '../utils/fileUtils.js';
|
| 25 |
+
import { PartListUnion } from '@google/genai';
|
| 26 |
+
import { Config, DEFAULT_FILE_FILTERING_OPTIONS } from '../config/config.js';
|
| 27 |
+
import {
|
| 28 |
+
recordFileOperationMetric,
|
| 29 |
+
FileOperation,
|
| 30 |
+
} from '../telemetry/metrics.js';
|
| 31 |
+
|
| 32 |
+
/**
|
| 33 |
+
* Parameters for the ReadManyFilesTool.
|
| 34 |
+
*/
|
| 35 |
+
export interface ReadManyFilesParams {
|
| 36 |
+
/**
|
| 37 |
+
* An array of file paths or directory paths to search within.
|
| 38 |
+
* Paths are relative to the tool's configured target directory.
|
| 39 |
+
* Glob patterns can be used directly in these paths.
|
| 40 |
+
*/
|
| 41 |
+
paths: string[];
|
| 42 |
+
|
| 43 |
+
/**
|
| 44 |
+
* Optional. Glob patterns for files to include.
|
| 45 |
+
* These are effectively combined with the `paths`.
|
| 46 |
+
* Example: ["*.ts", "src/** /*.md"]
|
| 47 |
+
*/
|
| 48 |
+
include?: string[];
|
| 49 |
+
|
| 50 |
+
/**
|
| 51 |
+
* Optional. Glob patterns for files/directories to exclude.
|
| 52 |
+
* Applied as ignore patterns.
|
| 53 |
+
* Example: ["*.log", "dist/**"]
|
| 54 |
+
*/
|
| 55 |
+
exclude?: string[];
|
| 56 |
+
|
| 57 |
+
/**
|
| 58 |
+
* Optional. Search directories recursively.
|
| 59 |
+
* This is generally controlled by glob patterns (e.g., `**`).
|
| 60 |
+
* The glob implementation is recursive by default for `**`.
|
| 61 |
+
* For simplicity, we'll rely on `**` for recursion.
|
| 62 |
+
*/
|
| 63 |
+
recursive?: boolean;
|
| 64 |
+
|
| 65 |
+
/**
|
| 66 |
+
* Optional. Apply default exclusion patterns. Defaults to true.
|
| 67 |
+
*/
|
| 68 |
+
useDefaultExcludes?: boolean;
|
| 69 |
+
|
| 70 |
+
/**
|
| 71 |
+
* Whether to respect .gitignore and .geminiignore patterns (optional, defaults to true)
|
| 72 |
+
*/
|
| 73 |
+
file_filtering_options?: {
|
| 74 |
+
respect_git_ignore?: boolean;
|
| 75 |
+
respect_gemini_ignore?: boolean;
|
| 76 |
+
};
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
/**
|
| 80 |
+
* Result type for file processing operations
|
| 81 |
+
*/
|
| 82 |
+
type FileProcessingResult =
|
| 83 |
+
| {
|
| 84 |
+
success: true;
|
| 85 |
+
filePath: string;
|
| 86 |
+
relativePathForDisplay: string;
|
| 87 |
+
fileReadResult: NonNullable<
|
| 88 |
+
Awaited<ReturnType<typeof processSingleFileContent>>
|
| 89 |
+
>;
|
| 90 |
+
reason?: undefined;
|
| 91 |
+
}
|
| 92 |
+
| {
|
| 93 |
+
success: false;
|
| 94 |
+
filePath: string;
|
| 95 |
+
relativePathForDisplay: string;
|
| 96 |
+
fileReadResult?: undefined;
|
| 97 |
+
reason: string;
|
| 98 |
+
};
|
| 99 |
+
|
| 100 |
+
/**
|
| 101 |
+
* Default exclusion patterns for commonly ignored directories and binary file types.
|
| 102 |
+
* These are compatible with glob ignore patterns.
|
| 103 |
+
* TODO(adh): Consider making this configurable or extendable through a command line argument.
|
| 104 |
+
* TODO(adh): Look into sharing this list with the glob tool.
|
| 105 |
+
*/
|
| 106 |
+
const DEFAULT_EXCLUDES: string[] = [
|
| 107 |
+
'**/node_modules/**',
|
| 108 |
+
'**/.git/**',
|
| 109 |
+
'**/.vscode/**',
|
| 110 |
+
'**/.idea/**',
|
| 111 |
+
'**/dist/**',
|
| 112 |
+
'**/build/**',
|
| 113 |
+
'**/coverage/**',
|
| 114 |
+
'**/__pycache__/**',
|
| 115 |
+
'**/*.pyc',
|
| 116 |
+
'**/*.pyo',
|
| 117 |
+
'**/*.bin',
|
| 118 |
+
'**/*.exe',
|
| 119 |
+
'**/*.dll',
|
| 120 |
+
'**/*.so',
|
| 121 |
+
'**/*.dylib',
|
| 122 |
+
'**/*.class',
|
| 123 |
+
'**/*.jar',
|
| 124 |
+
'**/*.war',
|
| 125 |
+
'**/*.zip',
|
| 126 |
+
'**/*.tar',
|
| 127 |
+
'**/*.gz',
|
| 128 |
+
'**/*.bz2',
|
| 129 |
+
'**/*.rar',
|
| 130 |
+
'**/*.7z',
|
| 131 |
+
'**/*.doc',
|
| 132 |
+
'**/*.docx',
|
| 133 |
+
'**/*.xls',
|
| 134 |
+
'**/*.xlsx',
|
| 135 |
+
'**/*.ppt',
|
| 136 |
+
'**/*.pptx',
|
| 137 |
+
'**/*.odt',
|
| 138 |
+
'**/*.ods',
|
| 139 |
+
'**/*.odp',
|
| 140 |
+
'**/*.DS_Store',
|
| 141 |
+
'**/.env',
|
| 142 |
+
`**/${getCurrentGeminiMdFilename()}`,
|
| 143 |
+
];
|
| 144 |
+
|
| 145 |
+
const DEFAULT_OUTPUT_SEPARATOR_FORMAT = '--- {filePath} ---';
|
| 146 |
+
|
| 147 |
+
class ReadManyFilesToolInvocation extends BaseToolInvocation<
|
| 148 |
+
ReadManyFilesParams,
|
| 149 |
+
ToolResult
|
| 150 |
+
> {
|
| 151 |
+
constructor(
|
| 152 |
+
private readonly config: Config,
|
| 153 |
+
params: ReadManyFilesParams,
|
| 154 |
+
) {
|
| 155 |
+
super(params);
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
getDescription(): string {
|
| 159 |
+
const allPatterns = [...this.params.paths, ...(this.params.include || [])];
|
| 160 |
+
const pathDesc = `using patterns:
|
| 161 |
+
${allPatterns.join('`, `')}
|
| 162 |
+
(within target directory:
|
| 163 |
+
${this.config.getTargetDir()}
|
| 164 |
+
) `;
|
| 165 |
+
|
| 166 |
+
// Determine the final list of exclusion patterns exactly as in execute method
|
| 167 |
+
const paramExcludes = this.params.exclude || [];
|
| 168 |
+
const paramUseDefaultExcludes = this.params.useDefaultExcludes !== false;
|
| 169 |
+
const geminiIgnorePatterns = this.config
|
| 170 |
+
.getFileService()
|
| 171 |
+
.getGeminiIgnorePatterns();
|
| 172 |
+
const finalExclusionPatternsForDescription: string[] =
|
| 173 |
+
paramUseDefaultExcludes
|
| 174 |
+
? [...DEFAULT_EXCLUDES, ...paramExcludes, ...geminiIgnorePatterns]
|
| 175 |
+
: [...paramExcludes, ...geminiIgnorePatterns];
|
| 176 |
+
|
| 177 |
+
let excludeDesc = `Excluding: ${
|
| 178 |
+
finalExclusionPatternsForDescription.length > 0
|
| 179 |
+
? `patterns like
|
| 180 |
+
${finalExclusionPatternsForDescription
|
| 181 |
+
.slice(0, 2)
|
| 182 |
+
.join(
|
| 183 |
+
'`, `',
|
| 184 |
+
)}${finalExclusionPatternsForDescription.length > 2 ? '...`' : '`'}`
|
| 185 |
+
: 'none specified'
|
| 186 |
+
}`;
|
| 187 |
+
|
| 188 |
+
// Add a note if .geminiignore patterns contributed to the final list of exclusions
|
| 189 |
+
if (geminiIgnorePatterns.length > 0) {
|
| 190 |
+
const geminiPatternsInEffect = geminiIgnorePatterns.filter((p) =>
|
| 191 |
+
finalExclusionPatternsForDescription.includes(p),
|
| 192 |
+
).length;
|
| 193 |
+
if (geminiPatternsInEffect > 0) {
|
| 194 |
+
excludeDesc += ` (includes ${geminiPatternsInEffect} from .geminiignore)`;
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
return `Will attempt to read and concatenate files ${pathDesc}. ${excludeDesc}. File encoding: ${DEFAULT_ENCODING}. Separator: "${DEFAULT_OUTPUT_SEPARATOR_FORMAT.replace(
|
| 199 |
+
'{filePath}',
|
| 200 |
+
'path/to/file.ext',
|
| 201 |
+
)}".`;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
async execute(signal: AbortSignal): Promise<ToolResult> {
|
| 205 |
+
const {
|
| 206 |
+
paths: inputPatterns,
|
| 207 |
+
include = [],
|
| 208 |
+
exclude = [],
|
| 209 |
+
useDefaultExcludes = true,
|
| 210 |
+
} = this.params;
|
| 211 |
+
|
| 212 |
+
const defaultFileIgnores =
|
| 213 |
+
this.config.getFileFilteringOptions() ?? DEFAULT_FILE_FILTERING_OPTIONS;
|
| 214 |
+
|
| 215 |
+
const fileFilteringOptions = {
|
| 216 |
+
respectGitIgnore:
|
| 217 |
+
this.params.file_filtering_options?.respect_git_ignore ??
|
| 218 |
+
defaultFileIgnores.respectGitIgnore, // Use the property from the returned object
|
| 219 |
+
respectGeminiIgnore:
|
| 220 |
+
this.params.file_filtering_options?.respect_gemini_ignore ??
|
| 221 |
+
defaultFileIgnores.respectGeminiIgnore, // Use the property from the returned object
|
| 222 |
+
};
|
| 223 |
+
// Get centralized file discovery service
|
| 224 |
+
const fileDiscovery = this.config.getFileService();
|
| 225 |
+
|
| 226 |
+
const filesToConsider = new Set<string>();
|
| 227 |
+
const skippedFiles: Array<{ path: string; reason: string }> = [];
|
| 228 |
+
const processedFilesRelativePaths: string[] = [];
|
| 229 |
+
const contentParts: PartListUnion = [];
|
| 230 |
+
|
| 231 |
+
const effectiveExcludes = useDefaultExcludes
|
| 232 |
+
? [...DEFAULT_EXCLUDES, ...exclude]
|
| 233 |
+
: [...exclude];
|
| 234 |
+
|
| 235 |
+
const searchPatterns = [...inputPatterns, ...include];
|
| 236 |
+
if (searchPatterns.length === 0) {
|
| 237 |
+
return {
|
| 238 |
+
llmContent: 'No search paths or include patterns provided.',
|
| 239 |
+
returnDisplay: `## Information\n\nNo search paths or include patterns were specified. Nothing to read or concatenate.`,
|
| 240 |
+
};
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
try {
|
| 244 |
+
const allEntries = new Set<string>();
|
| 245 |
+
const workspaceDirs = this.config.getWorkspaceContext().getDirectories();
|
| 246 |
+
|
| 247 |
+
for (const dir of workspaceDirs) {
|
| 248 |
+
const processedPatterns = [];
|
| 249 |
+
for (const p of searchPatterns) {
|
| 250 |
+
const normalizedP = p.replace(/\\/g, '/');
|
| 251 |
+
const fullPath = path.join(dir, normalizedP);
|
| 252 |
+
if (fs.existsSync(fullPath)) {
|
| 253 |
+
processedPatterns.push(escape(normalizedP));
|
| 254 |
+
} else {
|
| 255 |
+
// The path does not exist or is not a file, so we treat it as a glob pattern.
|
| 256 |
+
processedPatterns.push(normalizedP);
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
const entriesInDir = await glob(processedPatterns, {
|
| 261 |
+
cwd: dir,
|
| 262 |
+
ignore: effectiveExcludes,
|
| 263 |
+
nodir: true,
|
| 264 |
+
dot: true,
|
| 265 |
+
absolute: true,
|
| 266 |
+
nocase: true,
|
| 267 |
+
signal,
|
| 268 |
+
});
|
| 269 |
+
for (const entry of entriesInDir) {
|
| 270 |
+
allEntries.add(entry);
|
| 271 |
+
}
|
| 272 |
+
}
|
| 273 |
+
const entries = Array.from(allEntries);
|
| 274 |
+
|
| 275 |
+
const gitFilteredEntries = fileFilteringOptions.respectGitIgnore
|
| 276 |
+
? fileDiscovery
|
| 277 |
+
.filterFiles(
|
| 278 |
+
entries.map((p) => path.relative(this.config.getTargetDir(), p)),
|
| 279 |
+
{
|
| 280 |
+
respectGitIgnore: true,
|
| 281 |
+
respectGeminiIgnore: false,
|
| 282 |
+
},
|
| 283 |
+
)
|
| 284 |
+
.map((p) => path.resolve(this.config.getTargetDir(), p))
|
| 285 |
+
: entries;
|
| 286 |
+
|
| 287 |
+
// Apply gemini ignore filtering if enabled
|
| 288 |
+
const finalFilteredEntries = fileFilteringOptions.respectGeminiIgnore
|
| 289 |
+
? fileDiscovery
|
| 290 |
+
.filterFiles(
|
| 291 |
+
gitFilteredEntries.map((p) =>
|
| 292 |
+
path.relative(this.config.getTargetDir(), p),
|
| 293 |
+
),
|
| 294 |
+
{
|
| 295 |
+
respectGitIgnore: false,
|
| 296 |
+
respectGeminiIgnore: true,
|
| 297 |
+
},
|
| 298 |
+
)
|
| 299 |
+
.map((p) => path.resolve(this.config.getTargetDir(), p))
|
| 300 |
+
: gitFilteredEntries;
|
| 301 |
+
|
| 302 |
+
let gitIgnoredCount = 0;
|
| 303 |
+
let geminiIgnoredCount = 0;
|
| 304 |
+
|
| 305 |
+
for (const absoluteFilePath of entries) {
|
| 306 |
+
// Security check: ensure the glob library didn't return something outside the workspace.
|
| 307 |
+
if (
|
| 308 |
+
!this.config
|
| 309 |
+
.getWorkspaceContext()
|
| 310 |
+
.isPathWithinWorkspace(absoluteFilePath)
|
| 311 |
+
) {
|
| 312 |
+
skippedFiles.push({
|
| 313 |
+
path: absoluteFilePath,
|
| 314 |
+
reason: `Security: Glob library returned path outside workspace. Path: ${absoluteFilePath}`,
|
| 315 |
+
});
|
| 316 |
+
continue;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
// Check if this file was filtered out by git ignore
|
| 320 |
+
if (
|
| 321 |
+
fileFilteringOptions.respectGitIgnore &&
|
| 322 |
+
!gitFilteredEntries.includes(absoluteFilePath)
|
| 323 |
+
) {
|
| 324 |
+
gitIgnoredCount++;
|
| 325 |
+
continue;
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
// Check if this file was filtered out by gemini ignore
|
| 329 |
+
if (
|
| 330 |
+
fileFilteringOptions.respectGeminiIgnore &&
|
| 331 |
+
!finalFilteredEntries.includes(absoluteFilePath)
|
| 332 |
+
) {
|
| 333 |
+
geminiIgnoredCount++;
|
| 334 |
+
continue;
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
filesToConsider.add(absoluteFilePath);
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
// Add info about git-ignored files if any were filtered
|
| 341 |
+
if (gitIgnoredCount > 0) {
|
| 342 |
+
skippedFiles.push({
|
| 343 |
+
path: `${gitIgnoredCount} file(s)`,
|
| 344 |
+
reason: 'git ignored',
|
| 345 |
+
});
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
// Add info about gemini-ignored files if any were filtered
|
| 349 |
+
if (geminiIgnoredCount > 0) {
|
| 350 |
+
skippedFiles.push({
|
| 351 |
+
path: `${geminiIgnoredCount} file(s)`,
|
| 352 |
+
reason: 'gemini ignored',
|
| 353 |
+
});
|
| 354 |
+
}
|
| 355 |
+
} catch (error) {
|
| 356 |
+
return {
|
| 357 |
+
llmContent: `Error during file search: ${getErrorMessage(error)}`,
|
| 358 |
+
returnDisplay: `## File Search Error\n\nAn error occurred while searching for files:\n\`\`\`\n${getErrorMessage(error)}\n\`\`\``,
|
| 359 |
+
};
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
const sortedFiles = Array.from(filesToConsider).sort();
|
| 363 |
+
|
| 364 |
+
const fileProcessingPromises = sortedFiles.map(
|
| 365 |
+
async (filePath): Promise<FileProcessingResult> => {
|
| 366 |
+
try {
|
| 367 |
+
const relativePathForDisplay = path
|
| 368 |
+
.relative(this.config.getTargetDir(), filePath)
|
| 369 |
+
.replace(/\\/g, '/');
|
| 370 |
+
|
| 371 |
+
const fileType = await detectFileType(filePath);
|
| 372 |
+
|
| 373 |
+
if (fileType === 'image' || fileType === 'pdf') {
|
| 374 |
+
const fileExtension = path.extname(filePath).toLowerCase();
|
| 375 |
+
const fileNameWithoutExtension = path.basename(
|
| 376 |
+
filePath,
|
| 377 |
+
fileExtension,
|
| 378 |
+
);
|
| 379 |
+
const requestedExplicitly = inputPatterns.some(
|
| 380 |
+
(pattern: string) =>
|
| 381 |
+
pattern.toLowerCase().includes(fileExtension) ||
|
| 382 |
+
pattern.includes(fileNameWithoutExtension),
|
| 383 |
+
);
|
| 384 |
+
|
| 385 |
+
if (!requestedExplicitly) {
|
| 386 |
+
return {
|
| 387 |
+
success: false,
|
| 388 |
+
filePath,
|
| 389 |
+
relativePathForDisplay,
|
| 390 |
+
reason:
|
| 391 |
+
'asset file (image/pdf) was not explicitly requested by name or extension',
|
| 392 |
+
};
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
// Use processSingleFileContent for all file types now
|
| 397 |
+
const fileReadResult = await processSingleFileContent(
|
| 398 |
+
filePath,
|
| 399 |
+
this.config.getTargetDir(),
|
| 400 |
+
this.config.getFileSystemService(),
|
| 401 |
+
);
|
| 402 |
+
|
| 403 |
+
if (fileReadResult.error) {
|
| 404 |
+
return {
|
| 405 |
+
success: false,
|
| 406 |
+
filePath,
|
| 407 |
+
relativePathForDisplay,
|
| 408 |
+
reason: `Read error: ${fileReadResult.error}`,
|
| 409 |
+
};
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
return {
|
| 413 |
+
success: true,
|
| 414 |
+
filePath,
|
| 415 |
+
relativePathForDisplay,
|
| 416 |
+
fileReadResult,
|
| 417 |
+
};
|
| 418 |
+
} catch (error) {
|
| 419 |
+
const relativePathForDisplay = path
|
| 420 |
+
.relative(this.config.getTargetDir(), filePath)
|
| 421 |
+
.replace(/\\/g, '/');
|
| 422 |
+
|
| 423 |
+
return {
|
| 424 |
+
success: false,
|
| 425 |
+
filePath,
|
| 426 |
+
relativePathForDisplay,
|
| 427 |
+
reason: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`,
|
| 428 |
+
};
|
| 429 |
+
}
|
| 430 |
+
},
|
| 431 |
+
);
|
| 432 |
+
|
| 433 |
+
const results = await Promise.allSettled(fileProcessingPromises);
|
| 434 |
+
|
| 435 |
+
for (const result of results) {
|
| 436 |
+
if (result.status === 'fulfilled') {
|
| 437 |
+
const fileResult = result.value;
|
| 438 |
+
|
| 439 |
+
if (!fileResult.success) {
|
| 440 |
+
// Handle skipped files (images/PDFs not requested or read errors)
|
| 441 |
+
skippedFiles.push({
|
| 442 |
+
path: fileResult.relativePathForDisplay,
|
| 443 |
+
reason: fileResult.reason,
|
| 444 |
+
});
|
| 445 |
+
} else {
|
| 446 |
+
// Handle successfully processed files
|
| 447 |
+
const { filePath, relativePathForDisplay, fileReadResult } =
|
| 448 |
+
fileResult;
|
| 449 |
+
|
| 450 |
+
if (typeof fileReadResult.llmContent === 'string') {
|
| 451 |
+
const separator = DEFAULT_OUTPUT_SEPARATOR_FORMAT.replace(
|
| 452 |
+
'{filePath}',
|
| 453 |
+
filePath,
|
| 454 |
+
);
|
| 455 |
+
let fileContentForLlm = '';
|
| 456 |
+
if (fileReadResult.isTruncated) {
|
| 457 |
+
fileContentForLlm += `[WARNING: This file was truncated. To view the full content, use the 'read_file' tool on this specific file.]\n\n`;
|
| 458 |
+
}
|
| 459 |
+
fileContentForLlm += fileReadResult.llmContent;
|
| 460 |
+
contentParts.push(`${separator}\n\n${fileContentForLlm}\n\n`);
|
| 461 |
+
} else {
|
| 462 |
+
// This is a Part for image/pdf, which we don't add the separator to.
|
| 463 |
+
contentParts.push(fileReadResult.llmContent);
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
processedFilesRelativePaths.push(relativePathForDisplay);
|
| 467 |
+
|
| 468 |
+
const lines =
|
| 469 |
+
typeof fileReadResult.llmContent === 'string'
|
| 470 |
+
? fileReadResult.llmContent.split('\n').length
|
| 471 |
+
: undefined;
|
| 472 |
+
const mimetype = getSpecificMimeType(filePath);
|
| 473 |
+
recordFileOperationMetric(
|
| 474 |
+
this.config,
|
| 475 |
+
FileOperation.READ,
|
| 476 |
+
lines,
|
| 477 |
+
mimetype,
|
| 478 |
+
path.extname(filePath),
|
| 479 |
+
);
|
| 480 |
+
}
|
| 481 |
+
} else {
|
| 482 |
+
// Handle Promise rejection (unexpected errors)
|
| 483 |
+
skippedFiles.push({
|
| 484 |
+
path: 'unknown',
|
| 485 |
+
reason: `Unexpected error: ${result.reason}`,
|
| 486 |
+
});
|
| 487 |
+
}
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
let displayMessage = `### ReadManyFiles Result (Target Dir: \`${this.config.getTargetDir()}\`)\n\n`;
|
| 491 |
+
if (processedFilesRelativePaths.length > 0) {
|
| 492 |
+
displayMessage += `Successfully read and concatenated content from **${processedFilesRelativePaths.length} file(s)**.\n`;
|
| 493 |
+
if (processedFilesRelativePaths.length <= 10) {
|
| 494 |
+
displayMessage += `\n**Processed Files:**\n`;
|
| 495 |
+
processedFilesRelativePaths.forEach(
|
| 496 |
+
(p) => (displayMessage += `- \`${p}\`\n`),
|
| 497 |
+
);
|
| 498 |
+
} else {
|
| 499 |
+
displayMessage += `\n**Processed Files (first 10 shown):**\n`;
|
| 500 |
+
processedFilesRelativePaths
|
| 501 |
+
.slice(0, 10)
|
| 502 |
+
.forEach((p) => (displayMessage += `- \`${p}\`\n`));
|
| 503 |
+
displayMessage += `- ...and ${processedFilesRelativePaths.length - 10} more.\n`;
|
| 504 |
+
}
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
if (skippedFiles.length > 0) {
|
| 508 |
+
if (processedFilesRelativePaths.length === 0) {
|
| 509 |
+
displayMessage += `No files were read and concatenated based on the criteria.\n`;
|
| 510 |
+
}
|
| 511 |
+
if (skippedFiles.length <= 5) {
|
| 512 |
+
displayMessage += `\n**Skipped ${skippedFiles.length} item(s):**\n`;
|
| 513 |
+
} else {
|
| 514 |
+
displayMessage += `\n**Skipped ${skippedFiles.length} item(s) (first 5 shown):**\n`;
|
| 515 |
+
}
|
| 516 |
+
skippedFiles
|
| 517 |
+
.slice(0, 5)
|
| 518 |
+
.forEach(
|
| 519 |
+
(f) => (displayMessage += `- \`${f.path}\` (Reason: ${f.reason})\n`),
|
| 520 |
+
);
|
| 521 |
+
if (skippedFiles.length > 5) {
|
| 522 |
+
displayMessage += `- ...and ${skippedFiles.length - 5} more.\n`;
|
| 523 |
+
}
|
| 524 |
+
} else if (
|
| 525 |
+
processedFilesRelativePaths.length === 0 &&
|
| 526 |
+
skippedFiles.length === 0
|
| 527 |
+
) {
|
| 528 |
+
displayMessage += `No files were read and concatenated based on the criteria.\n`;
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
if (contentParts.length === 0) {
|
| 532 |
+
contentParts.push(
|
| 533 |
+
'No files matching the criteria were found or all were skipped.',
|
| 534 |
+
);
|
| 535 |
+
}
|
| 536 |
+
return {
|
| 537 |
+
llmContent: contentParts,
|
| 538 |
+
returnDisplay: displayMessage.trim(),
|
| 539 |
+
};
|
| 540 |
+
}
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
/**
|
| 544 |
+
* Tool implementation for finding and reading multiple text files from the local filesystem
|
| 545 |
+
* within a specified target directory. The content is concatenated.
|
| 546 |
+
* It is intended to run in an environment with access to the local file system (e.g., a Node.js backend).
|
| 547 |
+
*/
|
| 548 |
+
export class ReadManyFilesTool extends BaseDeclarativeTool<
|
| 549 |
+
ReadManyFilesParams,
|
| 550 |
+
ToolResult
|
| 551 |
+
> {
|
| 552 |
+
static readonly Name: string = 'read_many_files';
|
| 553 |
+
|
| 554 |
+
constructor(private config: Config) {
|
| 555 |
+
const parameterSchema = {
|
| 556 |
+
type: 'object',
|
| 557 |
+
properties: {
|
| 558 |
+
paths: {
|
| 559 |
+
type: 'array',
|
| 560 |
+
items: {
|
| 561 |
+
type: 'string',
|
| 562 |
+
minLength: 1,
|
| 563 |
+
},
|
| 564 |
+
minItems: 1,
|
| 565 |
+
description:
|
| 566 |
+
"Required. An array of glob patterns or paths relative to the tool's target directory. Examples: ['src/**/*.ts'], ['README.md', 'docs/']",
|
| 567 |
+
},
|
| 568 |
+
include: {
|
| 569 |
+
type: 'array',
|
| 570 |
+
items: {
|
| 571 |
+
type: 'string',
|
| 572 |
+
minLength: 1,
|
| 573 |
+
},
|
| 574 |
+
description:
|
| 575 |
+
'Optional. Additional glob patterns to include. These are merged with `paths`. Example: "*.test.ts" to specifically add test files if they were broadly excluded.',
|
| 576 |
+
default: [],
|
| 577 |
+
},
|
| 578 |
+
exclude: {
|
| 579 |
+
type: 'array',
|
| 580 |
+
items: {
|
| 581 |
+
type: 'string',
|
| 582 |
+
minLength: 1,
|
| 583 |
+
},
|
| 584 |
+
description:
|
| 585 |
+
'Optional. Glob patterns for files/directories to exclude. Added to default excludes if useDefaultExcludes is true. Example: "**/*.log", "temp/"',
|
| 586 |
+
default: [],
|
| 587 |
+
},
|
| 588 |
+
recursive: {
|
| 589 |
+
type: 'boolean',
|
| 590 |
+
description:
|
| 591 |
+
'Optional. Whether to search recursively (primarily controlled by `**` in glob patterns). Defaults to true.',
|
| 592 |
+
default: true,
|
| 593 |
+
},
|
| 594 |
+
useDefaultExcludes: {
|
| 595 |
+
type: 'boolean',
|
| 596 |
+
description:
|
| 597 |
+
'Optional. Whether to apply a list of default exclusion patterns (e.g., node_modules, .git, binary files). Defaults to true.',
|
| 598 |
+
default: true,
|
| 599 |
+
},
|
| 600 |
+
file_filtering_options: {
|
| 601 |
+
description:
|
| 602 |
+
'Whether to respect ignore patterns from .gitignore or .geminiignore',
|
| 603 |
+
type: 'object',
|
| 604 |
+
properties: {
|
| 605 |
+
respect_git_ignore: {
|
| 606 |
+
description:
|
| 607 |
+
'Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true.',
|
| 608 |
+
type: 'boolean',
|
| 609 |
+
},
|
| 610 |
+
respect_gemini_ignore: {
|
| 611 |
+
description:
|
| 612 |
+
'Optional: Whether to respect .geminiignore patterns when listing files. Defaults to true.',
|
| 613 |
+
type: 'boolean',
|
| 614 |
+
},
|
| 615 |
+
},
|
| 616 |
+
},
|
| 617 |
+
},
|
| 618 |
+
required: ['paths'],
|
| 619 |
+
};
|
| 620 |
+
|
| 621 |
+
super(
|
| 622 |
+
ReadManyFilesTool.Name,
|
| 623 |
+
'ReadManyFiles',
|
| 624 |
+
`Reads content from multiple files specified by paths or glob patterns within a configured target directory. For text files, it concatenates their content into a single string. It is primarily designed for text-based files. However, it can also process image (e.g., .png, .jpg) and PDF (.pdf) files if their file names or extensions are explicitly included in the 'paths' argument. For these explicitly requested non-text files, their data is read and included in a format suitable for model consumption (e.g., base64 encoded).
|
| 625 |
+
|
| 626 |
+
This tool is useful when you need to understand or analyze a collection of files, such as:
|
| 627 |
+
- Getting an overview of a codebase or parts of it (e.g., all TypeScript files in the 'src' directory).
|
| 628 |
+
- Finding where specific functionality is implemented if the user asks broad questions about code.
|
| 629 |
+
- Reviewing documentation files (e.g., all Markdown files in the 'docs' directory).
|
| 630 |
+
- Gathering context from multiple configuration files.
|
| 631 |
+
- When the user asks to "read all files in X directory" or "show me the content of all Y files".
|
| 632 |
+
|
| 633 |
+
Use this tool when the user's query implies needing the content of several files simultaneously for context, analysis, or summarization. For text files, it uses default UTF-8 encoding and a '--- {filePath} ---' separator between file contents. Ensure paths are relative to the target directory. Glob patterns like 'src/**/*.js' are supported. Avoid using for single files if a more specific single-file reading tool is available, unless the user specifically requests to process a list containing just one file via this tool. Other binary files (not explicitly requested as image/PDF) are generally skipped. Default excludes apply to common non-text files (except for explicitly requested images/PDFs) and large dependency directories unless 'useDefaultExcludes' is false.`,
|
| 634 |
+
Kind.Read,
|
| 635 |
+
parameterSchema,
|
| 636 |
+
);
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
protected createInvocation(
|
| 640 |
+
params: ReadManyFilesParams,
|
| 641 |
+
): ToolInvocation<ReadManyFilesParams, ToolResult> {
|
| 642 |
+
return new ReadManyFilesToolInvocation(this.config, params);
|
| 643 |
+
}
|
| 644 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/shell.test.ts
ADDED
|
@@ -0,0 +1,878 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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,
|
| 10 |
+
it,
|
| 11 |
+
expect,
|
| 12 |
+
beforeEach,
|
| 13 |
+
afterEach,
|
| 14 |
+
type Mock,
|
| 15 |
+
} from 'vitest';
|
| 16 |
+
|
| 17 |
+
const mockShellExecutionService = vi.hoisted(() => vi.fn());
|
| 18 |
+
vi.mock('../services/shellExecutionService.js', () => ({
|
| 19 |
+
ShellExecutionService: { execute: mockShellExecutionService },
|
| 20 |
+
}));
|
| 21 |
+
vi.mock('fs');
|
| 22 |
+
vi.mock('os');
|
| 23 |
+
vi.mock('crypto');
|
| 24 |
+
vi.mock('../utils/summarizer.js');
|
| 25 |
+
|
| 26 |
+
import { isCommandAllowed } from '../utils/shell-utils.js';
|
| 27 |
+
import { ShellTool } from './shell.js';
|
| 28 |
+
import { type Config } from '../config/config.js';
|
| 29 |
+
import {
|
| 30 |
+
type ShellExecutionResult,
|
| 31 |
+
type ShellOutputEvent,
|
| 32 |
+
} from '../services/shellExecutionService.js';
|
| 33 |
+
import * as fs from 'fs';
|
| 34 |
+
import * as os from 'os';
|
| 35 |
+
import * as path from 'path';
|
| 36 |
+
import * as crypto from 'crypto';
|
| 37 |
+
import * as summarizer from '../utils/summarizer.js';
|
| 38 |
+
import { ToolConfirmationOutcome } from './tools.js';
|
| 39 |
+
import { OUTPUT_UPDATE_INTERVAL_MS } from './shell.js';
|
| 40 |
+
import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js';
|
| 41 |
+
|
| 42 |
+
describe('ShellTool', () => {
|
| 43 |
+
let shellTool: ShellTool;
|
| 44 |
+
let mockConfig: Config;
|
| 45 |
+
let mockShellOutputCallback: (event: ShellOutputEvent) => void;
|
| 46 |
+
let resolveExecutionPromise: (result: ShellExecutionResult) => void;
|
| 47 |
+
|
| 48 |
+
beforeEach(() => {
|
| 49 |
+
vi.clearAllMocks();
|
| 50 |
+
|
| 51 |
+
mockConfig = {
|
| 52 |
+
getCoreTools: vi.fn().mockReturnValue([]),
|
| 53 |
+
getExcludeTools: vi.fn().mockReturnValue([]),
|
| 54 |
+
getDebugMode: vi.fn().mockReturnValue(false),
|
| 55 |
+
getTargetDir: vi.fn().mockReturnValue('/test/dir'),
|
| 56 |
+
getSummarizeToolOutputConfig: vi.fn().mockReturnValue(undefined),
|
| 57 |
+
getWorkspaceContext: () => createMockWorkspaceContext('.'),
|
| 58 |
+
getGeminiClient: vi.fn(),
|
| 59 |
+
getGitCoAuthor: vi.fn().mockReturnValue({
|
| 60 |
+
enabled: true,
|
| 61 |
+
name: 'Qwen-Coder',
|
| 62 |
+
email: 'qwen-coder@alibabacloud.com',
|
| 63 |
+
}),
|
| 64 |
+
getShouldUseNodePtyShell: vi.fn().mockReturnValue(false),
|
| 65 |
+
} as unknown as Config;
|
| 66 |
+
|
| 67 |
+
shellTool = new ShellTool(mockConfig);
|
| 68 |
+
|
| 69 |
+
vi.mocked(os.platform).mockReturnValue('linux');
|
| 70 |
+
vi.mocked(os.tmpdir).mockReturnValue('/tmp');
|
| 71 |
+
(vi.mocked(crypto.randomBytes) as Mock).mockReturnValue(
|
| 72 |
+
Buffer.from('abcdef', 'hex'),
|
| 73 |
+
);
|
| 74 |
+
|
| 75 |
+
// Capture the output callback to simulate streaming events from the service
|
| 76 |
+
mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
|
| 77 |
+
mockShellOutputCallback = callback;
|
| 78 |
+
return {
|
| 79 |
+
pid: 12345,
|
| 80 |
+
result: new Promise((resolve) => {
|
| 81 |
+
resolveExecutionPromise = resolve;
|
| 82 |
+
}),
|
| 83 |
+
};
|
| 84 |
+
});
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
describe('isCommandAllowed', () => {
|
| 88 |
+
it('should allow a command if no restrictions are provided', () => {
|
| 89 |
+
(mockConfig.getCoreTools as Mock).mockReturnValue(undefined);
|
| 90 |
+
(mockConfig.getExcludeTools as Mock).mockReturnValue(undefined);
|
| 91 |
+
expect(isCommandAllowed('ls -l', mockConfig).allowed).toBe(true);
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it('should block a command with command substitution using $()', () => {
|
| 95 |
+
expect(isCommandAllowed('echo $(rm -rf /)', mockConfig).allowed).toBe(
|
| 96 |
+
false,
|
| 97 |
+
);
|
| 98 |
+
});
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
describe('build', () => {
|
| 102 |
+
it('should return an invocation for a valid command', () => {
|
| 103 |
+
const invocation = shellTool.build({
|
| 104 |
+
command: 'ls -l',
|
| 105 |
+
is_background: false,
|
| 106 |
+
});
|
| 107 |
+
expect(invocation).toBeDefined();
|
| 108 |
+
});
|
| 109 |
+
|
| 110 |
+
it('should throw an error for an empty command', () => {
|
| 111 |
+
expect(() =>
|
| 112 |
+
shellTool.build({ command: ' ', is_background: false }),
|
| 113 |
+
).toThrow('Command cannot be empty.');
|
| 114 |
+
});
|
| 115 |
+
|
| 116 |
+
it('should throw an error for a non-existent directory', () => {
|
| 117 |
+
vi.mocked(fs.existsSync).mockReturnValue(false);
|
| 118 |
+
expect(() =>
|
| 119 |
+
shellTool.build({
|
| 120 |
+
command: 'ls',
|
| 121 |
+
directory: 'rel/path',
|
| 122 |
+
is_background: false,
|
| 123 |
+
}),
|
| 124 |
+
).toThrow(
|
| 125 |
+
"Directory 'rel/path' is not a registered workspace directory.",
|
| 126 |
+
);
|
| 127 |
+
});
|
| 128 |
+
|
| 129 |
+
it('should include background indicator in description when is_background is true', () => {
|
| 130 |
+
const invocation = shellTool.build({
|
| 131 |
+
command: 'npm start',
|
| 132 |
+
is_background: true,
|
| 133 |
+
});
|
| 134 |
+
expect(invocation.getDescription()).toContain('[background]');
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
it('should not include background indicator in description when is_background is false', () => {
|
| 138 |
+
const invocation = shellTool.build({
|
| 139 |
+
command: 'npm test',
|
| 140 |
+
is_background: false,
|
| 141 |
+
});
|
| 142 |
+
expect(invocation.getDescription()).not.toContain('[background]');
|
| 143 |
+
});
|
| 144 |
+
});
|
| 145 |
+
|
| 146 |
+
describe('execute', () => {
|
| 147 |
+
const mockAbortSignal = new AbortController().signal;
|
| 148 |
+
|
| 149 |
+
const resolveShellExecution = (
|
| 150 |
+
result: Partial<ShellExecutionResult> = {},
|
| 151 |
+
) => {
|
| 152 |
+
const fullResult: ShellExecutionResult = {
|
| 153 |
+
rawOutput: Buffer.from(result.output || ''),
|
| 154 |
+
output: 'Success',
|
| 155 |
+
exitCode: 0,
|
| 156 |
+
signal: null,
|
| 157 |
+
error: null,
|
| 158 |
+
aborted: false,
|
| 159 |
+
pid: 12345,
|
| 160 |
+
executionMethod: 'child_process',
|
| 161 |
+
...result,
|
| 162 |
+
};
|
| 163 |
+
resolveExecutionPromise(fullResult);
|
| 164 |
+
};
|
| 165 |
+
|
| 166 |
+
it('should wrap command on linux and parse pgrep output', async () => {
|
| 167 |
+
const invocation = shellTool.build({
|
| 168 |
+
command: 'my-command &',
|
| 169 |
+
is_background: false,
|
| 170 |
+
});
|
| 171 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 172 |
+
resolveShellExecution({ pid: 54321 });
|
| 173 |
+
|
| 174 |
+
vi.mocked(fs.existsSync).mockReturnValue(true);
|
| 175 |
+
vi.mocked(fs.readFileSync).mockReturnValue('54321\n54322\n'); // Service PID and background PID
|
| 176 |
+
|
| 177 |
+
const result = await promise;
|
| 178 |
+
|
| 179 |
+
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
|
| 180 |
+
const wrappedCommand = `{ my-command & }; __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
|
| 181 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 182 |
+
wrappedCommand,
|
| 183 |
+
expect.any(String),
|
| 184 |
+
expect.any(Function),
|
| 185 |
+
mockAbortSignal,
|
| 186 |
+
false,
|
| 187 |
+
undefined,
|
| 188 |
+
undefined,
|
| 189 |
+
);
|
| 190 |
+
expect(result.llmContent).toContain('Background PIDs: 54322');
|
| 191 |
+
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
|
| 192 |
+
});
|
| 193 |
+
|
| 194 |
+
it('should add ampersand to command when is_background is true and command does not end with &', async () => {
|
| 195 |
+
const invocation = shellTool.build({
|
| 196 |
+
command: 'npm start',
|
| 197 |
+
is_background: true,
|
| 198 |
+
});
|
| 199 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 200 |
+
resolveShellExecution({ pid: 54321 });
|
| 201 |
+
|
| 202 |
+
vi.mocked(fs.existsSync).mockReturnValue(true);
|
| 203 |
+
vi.mocked(fs.readFileSync).mockReturnValue('54321\n54322\n');
|
| 204 |
+
|
| 205 |
+
await promise;
|
| 206 |
+
|
| 207 |
+
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
|
| 208 |
+
const wrappedCommand = `{ npm start & }; __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
|
| 209 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 210 |
+
wrappedCommand,
|
| 211 |
+
expect.any(String),
|
| 212 |
+
expect.any(Function),
|
| 213 |
+
mockAbortSignal,
|
| 214 |
+
false,
|
| 215 |
+
undefined,
|
| 216 |
+
undefined,
|
| 217 |
+
);
|
| 218 |
+
});
|
| 219 |
+
|
| 220 |
+
it('should not add extra ampersand when is_background is true and command already ends with &', async () => {
|
| 221 |
+
const invocation = shellTool.build({
|
| 222 |
+
command: 'npm start &',
|
| 223 |
+
is_background: true,
|
| 224 |
+
});
|
| 225 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 226 |
+
resolveShellExecution({ pid: 54321 });
|
| 227 |
+
|
| 228 |
+
vi.mocked(fs.existsSync).mockReturnValue(true);
|
| 229 |
+
vi.mocked(fs.readFileSync).mockReturnValue('54321\n54322\n');
|
| 230 |
+
|
| 231 |
+
await promise;
|
| 232 |
+
|
| 233 |
+
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
|
| 234 |
+
const wrappedCommand = `{ npm start & }; __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
|
| 235 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 236 |
+
wrappedCommand,
|
| 237 |
+
expect.any(String),
|
| 238 |
+
expect.any(Function),
|
| 239 |
+
mockAbortSignal,
|
| 240 |
+
false,
|
| 241 |
+
undefined,
|
| 242 |
+
undefined,
|
| 243 |
+
);
|
| 244 |
+
});
|
| 245 |
+
|
| 246 |
+
it('should not add ampersand when is_background is false', async () => {
|
| 247 |
+
const invocation = shellTool.build({
|
| 248 |
+
command: 'npm test',
|
| 249 |
+
is_background: false,
|
| 250 |
+
});
|
| 251 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 252 |
+
resolveShellExecution({ pid: 54321 });
|
| 253 |
+
|
| 254 |
+
vi.mocked(fs.existsSync).mockReturnValue(true);
|
| 255 |
+
vi.mocked(fs.readFileSync).mockReturnValue('54321\n54322\n');
|
| 256 |
+
|
| 257 |
+
await promise;
|
| 258 |
+
|
| 259 |
+
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
|
| 260 |
+
const wrappedCommand = `{ npm test; }; __code=$?; pgrep -g 0 >${tmpFile} 2>&1; exit $__code;`;
|
| 261 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 262 |
+
wrappedCommand,
|
| 263 |
+
expect.any(String),
|
| 264 |
+
expect.any(Function),
|
| 265 |
+
mockAbortSignal,
|
| 266 |
+
false,
|
| 267 |
+
undefined,
|
| 268 |
+
undefined,
|
| 269 |
+
);
|
| 270 |
+
});
|
| 271 |
+
|
| 272 |
+
it('should not wrap command on windows', async () => {
|
| 273 |
+
vi.mocked(os.platform).mockReturnValue('win32');
|
| 274 |
+
const invocation = shellTool.build({
|
| 275 |
+
command: 'dir',
|
| 276 |
+
is_background: false,
|
| 277 |
+
});
|
| 278 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 279 |
+
resolveShellExecution({
|
| 280 |
+
rawOutput: Buffer.from(''),
|
| 281 |
+
output: '',
|
| 282 |
+
exitCode: 0,
|
| 283 |
+
signal: null,
|
| 284 |
+
error: null,
|
| 285 |
+
aborted: false,
|
| 286 |
+
pid: 12345,
|
| 287 |
+
executionMethod: 'child_process',
|
| 288 |
+
});
|
| 289 |
+
await promise;
|
| 290 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 291 |
+
'dir',
|
| 292 |
+
expect.any(String),
|
| 293 |
+
expect.any(Function),
|
| 294 |
+
mockAbortSignal,
|
| 295 |
+
false,
|
| 296 |
+
undefined,
|
| 297 |
+
undefined,
|
| 298 |
+
);
|
| 299 |
+
});
|
| 300 |
+
|
| 301 |
+
it('should format error messages correctly', async () => {
|
| 302 |
+
const error = new Error('wrapped command failed');
|
| 303 |
+
const invocation = shellTool.build({
|
| 304 |
+
command: 'user-command',
|
| 305 |
+
is_background: false,
|
| 306 |
+
});
|
| 307 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 308 |
+
resolveShellExecution({
|
| 309 |
+
error,
|
| 310 |
+
exitCode: 1,
|
| 311 |
+
output: 'err',
|
| 312 |
+
rawOutput: Buffer.from('err'),
|
| 313 |
+
signal: null,
|
| 314 |
+
aborted: false,
|
| 315 |
+
pid: 12345,
|
| 316 |
+
executionMethod: 'child_process',
|
| 317 |
+
});
|
| 318 |
+
|
| 319 |
+
const result = await promise;
|
| 320 |
+
expect(result.llmContent).toContain('Error: wrapped command failed');
|
| 321 |
+
expect(result.llmContent).not.toContain('pgrep');
|
| 322 |
+
});
|
| 323 |
+
|
| 324 |
+
it('should throw an error for invalid parameters', () => {
|
| 325 |
+
expect(() =>
|
| 326 |
+
shellTool.build({ command: '', is_background: false }),
|
| 327 |
+
).toThrow('Command cannot be empty.');
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
it('should throw an error for invalid directory', () => {
|
| 331 |
+
vi.mocked(fs.existsSync).mockReturnValue(false);
|
| 332 |
+
expect(() =>
|
| 333 |
+
shellTool.build({
|
| 334 |
+
command: 'ls',
|
| 335 |
+
directory: 'nonexistent',
|
| 336 |
+
is_background: false,
|
| 337 |
+
}),
|
| 338 |
+
).toThrow(
|
| 339 |
+
`Directory 'nonexistent' is not a registered workspace directory.`,
|
| 340 |
+
);
|
| 341 |
+
});
|
| 342 |
+
|
| 343 |
+
it('should summarize output when configured', async () => {
|
| 344 |
+
(mockConfig.getSummarizeToolOutputConfig as Mock).mockReturnValue({
|
| 345 |
+
[shellTool.name]: { tokenBudget: 1000 },
|
| 346 |
+
});
|
| 347 |
+
vi.mocked(summarizer.summarizeToolOutput).mockResolvedValue(
|
| 348 |
+
'summarized output',
|
| 349 |
+
);
|
| 350 |
+
|
| 351 |
+
const invocation = shellTool.build({
|
| 352 |
+
command: 'ls',
|
| 353 |
+
is_background: false,
|
| 354 |
+
});
|
| 355 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 356 |
+
resolveExecutionPromise({
|
| 357 |
+
output: 'long output',
|
| 358 |
+
rawOutput: Buffer.from('long output'),
|
| 359 |
+
exitCode: 0,
|
| 360 |
+
signal: null,
|
| 361 |
+
error: null,
|
| 362 |
+
aborted: false,
|
| 363 |
+
pid: 12345,
|
| 364 |
+
executionMethod: 'child_process',
|
| 365 |
+
});
|
| 366 |
+
|
| 367 |
+
const result = await promise;
|
| 368 |
+
|
| 369 |
+
expect(summarizer.summarizeToolOutput).toHaveBeenCalledWith(
|
| 370 |
+
expect.any(String),
|
| 371 |
+
mockConfig.getGeminiClient(),
|
| 372 |
+
mockAbortSignal,
|
| 373 |
+
1000,
|
| 374 |
+
);
|
| 375 |
+
expect(result.llmContent).toBe('summarized output');
|
| 376 |
+
expect(result.returnDisplay).toBe('long output');
|
| 377 |
+
});
|
| 378 |
+
|
| 379 |
+
it('should clean up the temp file on synchronous execution error', async () => {
|
| 380 |
+
const error = new Error('sync spawn error');
|
| 381 |
+
mockShellExecutionService.mockImplementation(() => {
|
| 382 |
+
throw error;
|
| 383 |
+
});
|
| 384 |
+
vi.mocked(fs.existsSync).mockReturnValue(true); // Pretend the file exists
|
| 385 |
+
|
| 386 |
+
const invocation = shellTool.build({
|
| 387 |
+
command: 'a-command',
|
| 388 |
+
is_background: false,
|
| 389 |
+
});
|
| 390 |
+
await expect(invocation.execute(mockAbortSignal)).rejects.toThrow(error);
|
| 391 |
+
|
| 392 |
+
const tmpFile = path.join(os.tmpdir(), 'shell_pgrep_abcdef.tmp');
|
| 393 |
+
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
|
| 394 |
+
});
|
| 395 |
+
|
| 396 |
+
describe('Streaming to `updateOutput`', () => {
|
| 397 |
+
let updateOutputMock: Mock;
|
| 398 |
+
beforeEach(() => {
|
| 399 |
+
vi.useFakeTimers({ toFake: ['Date'] });
|
| 400 |
+
updateOutputMock = vi.fn();
|
| 401 |
+
});
|
| 402 |
+
afterEach(() => {
|
| 403 |
+
vi.useRealTimers();
|
| 404 |
+
});
|
| 405 |
+
|
| 406 |
+
it('should throttle text output updates', async () => {
|
| 407 |
+
const invocation = shellTool.build({
|
| 408 |
+
command: 'stream',
|
| 409 |
+
is_background: false,
|
| 410 |
+
});
|
| 411 |
+
const promise = invocation.execute(mockAbortSignal, updateOutputMock);
|
| 412 |
+
|
| 413 |
+
// First chunk, should be throttled.
|
| 414 |
+
mockShellOutputCallback({
|
| 415 |
+
type: 'data',
|
| 416 |
+
chunk: 'hello ',
|
| 417 |
+
});
|
| 418 |
+
expect(updateOutputMock).not.toHaveBeenCalled();
|
| 419 |
+
|
| 420 |
+
// Advance time past the throttle interval.
|
| 421 |
+
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
|
| 422 |
+
|
| 423 |
+
// Send a second chunk. THIS event triggers the update with the CUMULATIVE content.
|
| 424 |
+
mockShellOutputCallback({
|
| 425 |
+
type: 'data',
|
| 426 |
+
chunk: 'hello world',
|
| 427 |
+
});
|
| 428 |
+
|
| 429 |
+
// It should have been called once now with the combined output.
|
| 430 |
+
expect(updateOutputMock).toHaveBeenCalledOnce();
|
| 431 |
+
expect(updateOutputMock).toHaveBeenCalledWith('hello world');
|
| 432 |
+
|
| 433 |
+
resolveExecutionPromise({
|
| 434 |
+
rawOutput: Buffer.from(''),
|
| 435 |
+
output: '',
|
| 436 |
+
exitCode: 0,
|
| 437 |
+
signal: null,
|
| 438 |
+
error: null,
|
| 439 |
+
aborted: false,
|
| 440 |
+
pid: 12345,
|
| 441 |
+
executionMethod: 'child_process',
|
| 442 |
+
});
|
| 443 |
+
await promise;
|
| 444 |
+
});
|
| 445 |
+
|
| 446 |
+
it('should immediately show binary detection message and throttle progress', async () => {
|
| 447 |
+
const invocation = shellTool.build({
|
| 448 |
+
command: 'cat img',
|
| 449 |
+
is_background: false,
|
| 450 |
+
});
|
| 451 |
+
const promise = invocation.execute(mockAbortSignal, updateOutputMock);
|
| 452 |
+
|
| 453 |
+
mockShellOutputCallback({ type: 'binary_detected' });
|
| 454 |
+
expect(updateOutputMock).toHaveBeenCalledOnce();
|
| 455 |
+
expect(updateOutputMock).toHaveBeenCalledWith(
|
| 456 |
+
'[Binary output detected. Halting stream...]',
|
| 457 |
+
);
|
| 458 |
+
|
| 459 |
+
mockShellOutputCallback({
|
| 460 |
+
type: 'binary_progress',
|
| 461 |
+
bytesReceived: 1024,
|
| 462 |
+
});
|
| 463 |
+
expect(updateOutputMock).toHaveBeenCalledOnce();
|
| 464 |
+
|
| 465 |
+
// Advance time past the throttle interval.
|
| 466 |
+
await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
|
| 467 |
+
|
| 468 |
+
// Send a SECOND progress event. This one will trigger the flush.
|
| 469 |
+
mockShellOutputCallback({
|
| 470 |
+
type: 'binary_progress',
|
| 471 |
+
bytesReceived: 2048,
|
| 472 |
+
});
|
| 473 |
+
|
| 474 |
+
// Now it should be called a second time with the latest progress.
|
| 475 |
+
expect(updateOutputMock).toHaveBeenCalledTimes(2);
|
| 476 |
+
expect(updateOutputMock).toHaveBeenLastCalledWith(
|
| 477 |
+
'[Receiving binary output... 2.0 KB received]',
|
| 478 |
+
);
|
| 479 |
+
|
| 480 |
+
resolveExecutionPromise({
|
| 481 |
+
rawOutput: Buffer.from(''),
|
| 482 |
+
output: '',
|
| 483 |
+
exitCode: 0,
|
| 484 |
+
signal: null,
|
| 485 |
+
error: null,
|
| 486 |
+
aborted: false,
|
| 487 |
+
pid: 12345,
|
| 488 |
+
executionMethod: 'child_process',
|
| 489 |
+
});
|
| 490 |
+
await promise;
|
| 491 |
+
});
|
| 492 |
+
});
|
| 493 |
+
|
| 494 |
+
describe('addCoAuthorToGitCommit', () => {
|
| 495 |
+
it('should add co-author to git commit with double quotes', async () => {
|
| 496 |
+
const command = 'git commit -m "Initial commit"';
|
| 497 |
+
const invocation = shellTool.build({ command, is_background: false });
|
| 498 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 499 |
+
|
| 500 |
+
// Mock the shell execution to return success
|
| 501 |
+
resolveExecutionPromise({
|
| 502 |
+
rawOutput: Buffer.from(''),
|
| 503 |
+
output: '',
|
| 504 |
+
exitCode: 0,
|
| 505 |
+
signal: null,
|
| 506 |
+
error: null,
|
| 507 |
+
aborted: false,
|
| 508 |
+
pid: 12345,
|
| 509 |
+
executionMethod: 'child_process',
|
| 510 |
+
});
|
| 511 |
+
|
| 512 |
+
await promise;
|
| 513 |
+
|
| 514 |
+
// Verify that the command was executed with co-author added
|
| 515 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 516 |
+
expect.stringContaining(
|
| 517 |
+
'Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>',
|
| 518 |
+
),
|
| 519 |
+
expect.any(String),
|
| 520 |
+
expect.any(Function),
|
| 521 |
+
mockAbortSignal,
|
| 522 |
+
false,
|
| 523 |
+
undefined,
|
| 524 |
+
undefined,
|
| 525 |
+
);
|
| 526 |
+
});
|
| 527 |
+
|
| 528 |
+
it('should add co-author to git commit with single quotes', async () => {
|
| 529 |
+
const command = "git commit -m 'Fix bug'";
|
| 530 |
+
const invocation = shellTool.build({ command, is_background: false });
|
| 531 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 532 |
+
|
| 533 |
+
resolveExecutionPromise({
|
| 534 |
+
rawOutput: Buffer.from(''),
|
| 535 |
+
output: '',
|
| 536 |
+
exitCode: 0,
|
| 537 |
+
signal: null,
|
| 538 |
+
error: null,
|
| 539 |
+
aborted: false,
|
| 540 |
+
pid: 12345,
|
| 541 |
+
executionMethod: 'child_process',
|
| 542 |
+
});
|
| 543 |
+
|
| 544 |
+
await promise;
|
| 545 |
+
|
| 546 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 547 |
+
expect.stringContaining(
|
| 548 |
+
'Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>',
|
| 549 |
+
),
|
| 550 |
+
expect.any(String),
|
| 551 |
+
expect.any(Function),
|
| 552 |
+
mockAbortSignal,
|
| 553 |
+
false,
|
| 554 |
+
undefined,
|
| 555 |
+
undefined,
|
| 556 |
+
);
|
| 557 |
+
});
|
| 558 |
+
|
| 559 |
+
it('should handle git commit with additional flags', async () => {
|
| 560 |
+
const command = 'git commit -a -m "Add feature"';
|
| 561 |
+
const invocation = shellTool.build({ command, is_background: false });
|
| 562 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 563 |
+
|
| 564 |
+
resolveExecutionPromise({
|
| 565 |
+
rawOutput: Buffer.from(''),
|
| 566 |
+
output: '',
|
| 567 |
+
exitCode: 0,
|
| 568 |
+
signal: null,
|
| 569 |
+
error: null,
|
| 570 |
+
aborted: false,
|
| 571 |
+
pid: 12345,
|
| 572 |
+
executionMethod: 'child_process',
|
| 573 |
+
});
|
| 574 |
+
|
| 575 |
+
await promise;
|
| 576 |
+
|
| 577 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 578 |
+
expect.stringContaining(
|
| 579 |
+
'Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>',
|
| 580 |
+
),
|
| 581 |
+
expect.any(String),
|
| 582 |
+
expect.any(Function),
|
| 583 |
+
mockAbortSignal,
|
| 584 |
+
false,
|
| 585 |
+
undefined,
|
| 586 |
+
undefined,
|
| 587 |
+
);
|
| 588 |
+
});
|
| 589 |
+
|
| 590 |
+
it('should not modify non-git commands', async () => {
|
| 591 |
+
const command = 'npm install';
|
| 592 |
+
const invocation = shellTool.build({ command, is_background: false });
|
| 593 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 594 |
+
|
| 595 |
+
resolveExecutionPromise({
|
| 596 |
+
rawOutput: Buffer.from(''),
|
| 597 |
+
output: '',
|
| 598 |
+
exitCode: 0,
|
| 599 |
+
signal: null,
|
| 600 |
+
error: null,
|
| 601 |
+
aborted: false,
|
| 602 |
+
pid: 12345,
|
| 603 |
+
executionMethod: 'child_process',
|
| 604 |
+
});
|
| 605 |
+
|
| 606 |
+
await promise;
|
| 607 |
+
|
| 608 |
+
// On Linux, commands are wrapped with pgrep functionality
|
| 609 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 610 |
+
expect.stringContaining('npm install'),
|
| 611 |
+
expect.any(String),
|
| 612 |
+
expect.any(Function),
|
| 613 |
+
mockAbortSignal,
|
| 614 |
+
false,
|
| 615 |
+
undefined,
|
| 616 |
+
undefined,
|
| 617 |
+
);
|
| 618 |
+
});
|
| 619 |
+
|
| 620 |
+
it('should not modify git commands without -m flag', async () => {
|
| 621 |
+
const command = 'git commit';
|
| 622 |
+
const invocation = shellTool.build({ command, is_background: false });
|
| 623 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 624 |
+
|
| 625 |
+
resolveExecutionPromise({
|
| 626 |
+
rawOutput: Buffer.from(''),
|
| 627 |
+
output: '',
|
| 628 |
+
exitCode: 0,
|
| 629 |
+
signal: null,
|
| 630 |
+
error: null,
|
| 631 |
+
aborted: false,
|
| 632 |
+
pid: 12345,
|
| 633 |
+
executionMethod: 'child_process',
|
| 634 |
+
});
|
| 635 |
+
|
| 636 |
+
await promise;
|
| 637 |
+
|
| 638 |
+
// On Linux, commands are wrapped with pgrep functionality
|
| 639 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 640 |
+
expect.stringContaining('git commit'),
|
| 641 |
+
expect.any(String),
|
| 642 |
+
expect.any(Function),
|
| 643 |
+
mockAbortSignal,
|
| 644 |
+
false,
|
| 645 |
+
undefined,
|
| 646 |
+
undefined,
|
| 647 |
+
);
|
| 648 |
+
});
|
| 649 |
+
|
| 650 |
+
it('should handle git commit with escaped quotes in message', async () => {
|
| 651 |
+
const command = 'git commit -m "Fix \\"quoted\\" text"';
|
| 652 |
+
const invocation = shellTool.build({ command, is_background: false });
|
| 653 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 654 |
+
|
| 655 |
+
resolveExecutionPromise({
|
| 656 |
+
rawOutput: Buffer.from(''),
|
| 657 |
+
output: '',
|
| 658 |
+
exitCode: 0,
|
| 659 |
+
signal: null,
|
| 660 |
+
error: null,
|
| 661 |
+
aborted: false,
|
| 662 |
+
pid: 12345,
|
| 663 |
+
executionMethod: 'child_process',
|
| 664 |
+
});
|
| 665 |
+
|
| 666 |
+
await promise;
|
| 667 |
+
|
| 668 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 669 |
+
expect.stringContaining(
|
| 670 |
+
'Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>',
|
| 671 |
+
),
|
| 672 |
+
expect.any(String),
|
| 673 |
+
expect.any(Function),
|
| 674 |
+
mockAbortSignal,
|
| 675 |
+
false,
|
| 676 |
+
undefined,
|
| 677 |
+
undefined,
|
| 678 |
+
);
|
| 679 |
+
});
|
| 680 |
+
|
| 681 |
+
it('should not add co-author when disabled in config', async () => {
|
| 682 |
+
// Mock config with disabled co-author
|
| 683 |
+
(mockConfig.getGitCoAuthor as Mock).mockReturnValue({
|
| 684 |
+
enabled: false,
|
| 685 |
+
name: 'Qwen-Coder',
|
| 686 |
+
email: 'qwen-coder@alibabacloud.com',
|
| 687 |
+
});
|
| 688 |
+
|
| 689 |
+
const command = 'git commit -m "Initial commit"';
|
| 690 |
+
const invocation = shellTool.build({ command, is_background: false });
|
| 691 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 692 |
+
|
| 693 |
+
resolveExecutionPromise({
|
| 694 |
+
rawOutput: Buffer.from(''),
|
| 695 |
+
output: '',
|
| 696 |
+
exitCode: 0,
|
| 697 |
+
signal: null,
|
| 698 |
+
error: null,
|
| 699 |
+
aborted: false,
|
| 700 |
+
pid: 12345,
|
| 701 |
+
executionMethod: 'child_process',
|
| 702 |
+
});
|
| 703 |
+
|
| 704 |
+
await promise;
|
| 705 |
+
|
| 706 |
+
// On Linux, commands are wrapped with pgrep functionality
|
| 707 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 708 |
+
expect.stringContaining('git commit -m "Initial commit"'),
|
| 709 |
+
expect.any(String),
|
| 710 |
+
expect.any(Function),
|
| 711 |
+
mockAbortSignal,
|
| 712 |
+
false,
|
| 713 |
+
undefined,
|
| 714 |
+
undefined,
|
| 715 |
+
);
|
| 716 |
+
});
|
| 717 |
+
|
| 718 |
+
it('should use custom name and email from config', async () => {
|
| 719 |
+
// Mock config with custom co-author details
|
| 720 |
+
(mockConfig.getGitCoAuthor as Mock).mockReturnValue({
|
| 721 |
+
enabled: true,
|
| 722 |
+
name: 'Custom Bot',
|
| 723 |
+
email: 'custom@example.com',
|
| 724 |
+
});
|
| 725 |
+
|
| 726 |
+
const command = 'git commit -m "Test commit"';
|
| 727 |
+
const invocation = shellTool.build({ command, is_background: false });
|
| 728 |
+
const promise = invocation.execute(mockAbortSignal);
|
| 729 |
+
|
| 730 |
+
resolveExecutionPromise({
|
| 731 |
+
rawOutput: Buffer.from(''),
|
| 732 |
+
output: '',
|
| 733 |
+
exitCode: 0,
|
| 734 |
+
signal: null,
|
| 735 |
+
error: null,
|
| 736 |
+
aborted: false,
|
| 737 |
+
pid: 12345,
|
| 738 |
+
executionMethod: 'child_process',
|
| 739 |
+
});
|
| 740 |
+
|
| 741 |
+
await promise;
|
| 742 |
+
|
| 743 |
+
expect(mockShellExecutionService).toHaveBeenCalledWith(
|
| 744 |
+
expect.stringContaining(
|
| 745 |
+
'Co-authored-by: Custom Bot <custom@example.com>',
|
| 746 |
+
),
|
| 747 |
+
expect.any(String),
|
| 748 |
+
expect.any(Function),
|
| 749 |
+
mockAbortSignal,
|
| 750 |
+
false,
|
| 751 |
+
undefined,
|
| 752 |
+
undefined,
|
| 753 |
+
);
|
| 754 |
+
});
|
| 755 |
+
});
|
| 756 |
+
});
|
| 757 |
+
|
| 758 |
+
describe('shouldConfirmExecute', () => {
|
| 759 |
+
it('should request confirmation for a new command and whitelist it on "Always"', async () => {
|
| 760 |
+
const params = { command: 'npm install', is_background: false };
|
| 761 |
+
const invocation = shellTool.build(params);
|
| 762 |
+
const confirmation = await invocation.shouldConfirmExecute(
|
| 763 |
+
new AbortController().signal,
|
| 764 |
+
);
|
| 765 |
+
|
| 766 |
+
expect(confirmation).not.toBe(false);
|
| 767 |
+
expect(confirmation && confirmation.type).toBe('exec');
|
| 768 |
+
|
| 769 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 770 |
+
await (confirmation as any).onConfirm(
|
| 771 |
+
ToolConfirmationOutcome.ProceedAlways,
|
| 772 |
+
);
|
| 773 |
+
|
| 774 |
+
// Should now be whitelisted
|
| 775 |
+
const secondInvocation = shellTool.build({
|
| 776 |
+
command: 'npm test',
|
| 777 |
+
is_background: false,
|
| 778 |
+
});
|
| 779 |
+
const secondConfirmation = await secondInvocation.shouldConfirmExecute(
|
| 780 |
+
new AbortController().signal,
|
| 781 |
+
);
|
| 782 |
+
expect(secondConfirmation).toBe(false);
|
| 783 |
+
});
|
| 784 |
+
|
| 785 |
+
it('should throw an error if validation fails', () => {
|
| 786 |
+
expect(() =>
|
| 787 |
+
shellTool.build({ command: '', is_background: false }),
|
| 788 |
+
).toThrow();
|
| 789 |
+
});
|
| 790 |
+
});
|
| 791 |
+
|
| 792 |
+
describe('getDescription', () => {
|
| 793 |
+
it('should return the windows description when on windows', () => {
|
| 794 |
+
vi.mocked(os.platform).mockReturnValue('win32');
|
| 795 |
+
const shellTool = new ShellTool(mockConfig);
|
| 796 |
+
expect(shellTool.description).toMatchSnapshot();
|
| 797 |
+
});
|
| 798 |
+
|
| 799 |
+
it('should return the non-windows description when not on windows', () => {
|
| 800 |
+
vi.mocked(os.platform).mockReturnValue('linux');
|
| 801 |
+
const shellTool = new ShellTool(mockConfig);
|
| 802 |
+
expect(shellTool.description).toMatchSnapshot();
|
| 803 |
+
});
|
| 804 |
+
});
|
| 805 |
+
});
|
| 806 |
+
|
| 807 |
+
describe('validateToolParams', () => {
|
| 808 |
+
it('should return null for valid directory', () => {
|
| 809 |
+
const config = {
|
| 810 |
+
getCoreTools: () => undefined,
|
| 811 |
+
getExcludeTools: () => undefined,
|
| 812 |
+
getTargetDir: () => '/root',
|
| 813 |
+
getWorkspaceContext: () =>
|
| 814 |
+
createMockWorkspaceContext('/root', ['/users/test']),
|
| 815 |
+
} as unknown as Config;
|
| 816 |
+
const shellTool = new ShellTool(config);
|
| 817 |
+
const result = shellTool.validateToolParams({
|
| 818 |
+
command: 'ls',
|
| 819 |
+
directory: 'test',
|
| 820 |
+
is_background: false,
|
| 821 |
+
});
|
| 822 |
+
expect(result).toBeNull();
|
| 823 |
+
});
|
| 824 |
+
|
| 825 |
+
it('should return error for directory outside workspace', () => {
|
| 826 |
+
const config = {
|
| 827 |
+
getCoreTools: () => undefined,
|
| 828 |
+
getExcludeTools: () => undefined,
|
| 829 |
+
getTargetDir: () => '/root',
|
| 830 |
+
getWorkspaceContext: () =>
|
| 831 |
+
createMockWorkspaceContext('/root', ['/users/test']),
|
| 832 |
+
} as unknown as Config;
|
| 833 |
+
const shellTool = new ShellTool(config);
|
| 834 |
+
const result = shellTool.validateToolParams({
|
| 835 |
+
command: 'ls',
|
| 836 |
+
directory: 'test2',
|
| 837 |
+
is_background: false,
|
| 838 |
+
});
|
| 839 |
+
expect(result).toContain('is not a registered workspace directory');
|
| 840 |
+
});
|
| 841 |
+
});
|
| 842 |
+
|
| 843 |
+
describe('build', () => {
|
| 844 |
+
it('should return an invocation for valid directory', () => {
|
| 845 |
+
const config = {
|
| 846 |
+
getCoreTools: () => undefined,
|
| 847 |
+
getExcludeTools: () => undefined,
|
| 848 |
+
getTargetDir: () => '/root',
|
| 849 |
+
getWorkspaceContext: () =>
|
| 850 |
+
createMockWorkspaceContext('/root', ['/users/test']),
|
| 851 |
+
} as unknown as Config;
|
| 852 |
+
const shellTool = new ShellTool(config);
|
| 853 |
+
const invocation = shellTool.build({
|
| 854 |
+
command: 'ls',
|
| 855 |
+
directory: 'test',
|
| 856 |
+
is_background: false,
|
| 857 |
+
});
|
| 858 |
+
expect(invocation).toBeDefined();
|
| 859 |
+
});
|
| 860 |
+
|
| 861 |
+
it('should throw an error for directory outside workspace', () => {
|
| 862 |
+
const config = {
|
| 863 |
+
getCoreTools: () => undefined,
|
| 864 |
+
getExcludeTools: () => undefined,
|
| 865 |
+
getTargetDir: () => '/root',
|
| 866 |
+
getWorkspaceContext: () =>
|
| 867 |
+
createMockWorkspaceContext('/root', ['/users/test']),
|
| 868 |
+
} as unknown as Config;
|
| 869 |
+
const shellTool = new ShellTool(config);
|
| 870 |
+
expect(() =>
|
| 871 |
+
shellTool.build({
|
| 872 |
+
command: 'ls',
|
| 873 |
+
directory: 'test2',
|
| 874 |
+
is_background: false,
|
| 875 |
+
}),
|
| 876 |
+
).toThrow('is not a registered workspace directory');
|
| 877 |
+
});
|
| 878 |
+
});
|