Add files using upload-large-folder tool
Browse files- projects/ui/qwen-code/packages/core/src/tools/shell.ts +477 -0
- projects/ui/qwen-code/packages/core/src/tools/todoWrite.test.ts +287 -0
- projects/ui/qwen-code/packages/core/src/tools/todoWrite.ts +458 -0
- projects/ui/qwen-code/packages/core/src/tools/tool-error.ts +33 -0
- projects/ui/qwen-code/packages/core/src/tools/tool-registry.test.ts +334 -0
- projects/ui/qwen-code/packages/core/src/tools/tool-registry.ts +464 -0
- projects/ui/qwen-code/packages/core/src/tools/tools.test.ts +236 -0
- projects/ui/qwen-code/packages/core/src/tools/tools.ts +529 -0
- projects/ui/qwen-code/packages/core/src/tools/web-fetch.test.ts +107 -0
- projects/ui/qwen-code/packages/core/src/tools/web-fetch.ts +236 -0
- projects/ui/qwen-code/packages/core/src/tools/web-search.test.ts +166 -0
- projects/ui/qwen-code/packages/core/src/tools/web-search.ts +195 -0
- projects/ui/qwen-code/packages/core/src/tools/write-file.test.ts +783 -0
- projects/ui/qwen-code/packages/core/src/tools/write-file.ts +500 -0
- projects/ui/qwen-code/packages/core/src/utils/LruCache.ts +41 -0
- projects/ui/qwen-code/packages/core/src/utils/bfsFileSearch.test.ts +232 -0
- projects/ui/qwen-code/packages/core/src/utils/bfsFileSearch.ts +124 -0
- projects/ui/qwen-code/packages/core/src/utils/browser.ts +56 -0
- projects/ui/qwen-code/packages/core/src/utils/editCorrector.test.ts +767 -0
- projects/ui/qwen-code/packages/core/src/utils/editCorrector.ts +750 -0
projects/ui/qwen-code/packages/core/src/tools/shell.ts
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 os from 'os';
|
| 10 |
+
import crypto from 'crypto';
|
| 11 |
+
import { Config } from '../config/config.js';
|
| 12 |
+
import {
|
| 13 |
+
BaseDeclarativeTool,
|
| 14 |
+
BaseToolInvocation,
|
| 15 |
+
ToolInvocation,
|
| 16 |
+
ToolResult,
|
| 17 |
+
ToolCallConfirmationDetails,
|
| 18 |
+
ToolExecuteConfirmationDetails,
|
| 19 |
+
ToolConfirmationOutcome,
|
| 20 |
+
Kind,
|
| 21 |
+
} from './tools.js';
|
| 22 |
+
import { getErrorMessage } from '../utils/errors.js';
|
| 23 |
+
import { summarizeToolOutput } from '../utils/summarizer.js';
|
| 24 |
+
import {
|
| 25 |
+
ShellExecutionService,
|
| 26 |
+
ShellOutputEvent,
|
| 27 |
+
} from '../services/shellExecutionService.js';
|
| 28 |
+
import { formatMemoryUsage } from '../utils/formatters.js';
|
| 29 |
+
import {
|
| 30 |
+
getCommandRoots,
|
| 31 |
+
isCommandAllowed,
|
| 32 |
+
stripShellWrapper,
|
| 33 |
+
} from '../utils/shell-utils.js';
|
| 34 |
+
|
| 35 |
+
export const OUTPUT_UPDATE_INTERVAL_MS = 1000;
|
| 36 |
+
|
| 37 |
+
export interface ShellToolParams {
|
| 38 |
+
command: string;
|
| 39 |
+
is_background: boolean;
|
| 40 |
+
description?: string;
|
| 41 |
+
directory?: string;
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
class ShellToolInvocation extends BaseToolInvocation<
|
| 45 |
+
ShellToolParams,
|
| 46 |
+
ToolResult
|
| 47 |
+
> {
|
| 48 |
+
constructor(
|
| 49 |
+
private readonly config: Config,
|
| 50 |
+
params: ShellToolParams,
|
| 51 |
+
private readonly allowlist: Set<string>,
|
| 52 |
+
) {
|
| 53 |
+
super(params);
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
getDescription(): string {
|
| 57 |
+
let description = `${this.params.command}`;
|
| 58 |
+
// append optional [in directory]
|
| 59 |
+
// note description is needed even if validation fails due to absolute path
|
| 60 |
+
if (this.params.directory) {
|
| 61 |
+
description += ` [in ${this.params.directory}]`;
|
| 62 |
+
}
|
| 63 |
+
// append background indicator
|
| 64 |
+
if (this.params.is_background) {
|
| 65 |
+
description += ` [background]`;
|
| 66 |
+
}
|
| 67 |
+
// append optional (description), replacing any line breaks with spaces
|
| 68 |
+
if (this.params.description) {
|
| 69 |
+
description += ` (${this.params.description.replace(/\n/g, ' ')})`;
|
| 70 |
+
}
|
| 71 |
+
return description;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
override async shouldConfirmExecute(
|
| 75 |
+
_abortSignal: AbortSignal,
|
| 76 |
+
): Promise<ToolCallConfirmationDetails | false> {
|
| 77 |
+
const command = stripShellWrapper(this.params.command);
|
| 78 |
+
const rootCommands = [...new Set(getCommandRoots(command))];
|
| 79 |
+
const commandsToConfirm = rootCommands.filter(
|
| 80 |
+
(command) => !this.allowlist.has(command),
|
| 81 |
+
);
|
| 82 |
+
|
| 83 |
+
if (commandsToConfirm.length === 0) {
|
| 84 |
+
return false; // already approved and whitelisted
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
const confirmationDetails: ToolExecuteConfirmationDetails = {
|
| 88 |
+
type: 'exec',
|
| 89 |
+
title: 'Confirm Shell Command',
|
| 90 |
+
command: this.params.command,
|
| 91 |
+
rootCommand: commandsToConfirm.join(', '),
|
| 92 |
+
onConfirm: async (outcome: ToolConfirmationOutcome) => {
|
| 93 |
+
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
| 94 |
+
commandsToConfirm.forEach((command) => this.allowlist.add(command));
|
| 95 |
+
}
|
| 96 |
+
},
|
| 97 |
+
};
|
| 98 |
+
return confirmationDetails;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
async execute(
|
| 102 |
+
signal: AbortSignal,
|
| 103 |
+
updateOutput?: (output: string) => void,
|
| 104 |
+
terminalColumns?: number,
|
| 105 |
+
terminalRows?: number,
|
| 106 |
+
): Promise<ToolResult> {
|
| 107 |
+
const strippedCommand = stripShellWrapper(this.params.command);
|
| 108 |
+
|
| 109 |
+
if (signal.aborted) {
|
| 110 |
+
return {
|
| 111 |
+
llmContent: 'Command was cancelled by user before it could start.',
|
| 112 |
+
returnDisplay: 'Command cancelled by user.',
|
| 113 |
+
};
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
const isWindows = os.platform() === 'win32';
|
| 117 |
+
const tempFileName = `shell_pgrep_${crypto
|
| 118 |
+
.randomBytes(6)
|
| 119 |
+
.toString('hex')}.tmp`;
|
| 120 |
+
const tempFilePath = path.join(os.tmpdir(), tempFileName);
|
| 121 |
+
|
| 122 |
+
try {
|
| 123 |
+
// Add co-author to git commit commands
|
| 124 |
+
const processedCommand = this.addCoAuthorToGitCommit(strippedCommand);
|
| 125 |
+
|
| 126 |
+
const shouldRunInBackground = this.params.is_background;
|
| 127 |
+
let finalCommand = processedCommand;
|
| 128 |
+
|
| 129 |
+
// If explicitly marked as background and doesn't already end with &, add it
|
| 130 |
+
if (shouldRunInBackground && !finalCommand.trim().endsWith('&')) {
|
| 131 |
+
finalCommand = finalCommand.trim() + ' &';
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// pgrep is not available on Windows, so we can't get background PIDs
|
| 135 |
+
const commandToExecute = isWindows
|
| 136 |
+
? finalCommand
|
| 137 |
+
: (() => {
|
| 138 |
+
// wrap command to append subprocess pids (via pgrep) to temporary file
|
| 139 |
+
let command = finalCommand.trim();
|
| 140 |
+
if (!command.endsWith('&')) command += ';';
|
| 141 |
+
return `{ ${command} }; __code=$?; pgrep -g 0 >${tempFilePath} 2>&1; exit $__code;`;
|
| 142 |
+
})();
|
| 143 |
+
|
| 144 |
+
const cwd = path.resolve(
|
| 145 |
+
this.config.getTargetDir(),
|
| 146 |
+
this.params.directory || '',
|
| 147 |
+
);
|
| 148 |
+
|
| 149 |
+
let cumulativeOutput = '';
|
| 150 |
+
let lastUpdateTime = Date.now();
|
| 151 |
+
let isBinaryStream = false;
|
| 152 |
+
|
| 153 |
+
const { result: resultPromise } = await ShellExecutionService.execute(
|
| 154 |
+
commandToExecute,
|
| 155 |
+
cwd,
|
| 156 |
+
(event: ShellOutputEvent) => {
|
| 157 |
+
if (!updateOutput) {
|
| 158 |
+
return;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
let currentDisplayOutput = '';
|
| 162 |
+
let shouldUpdate = false;
|
| 163 |
+
|
| 164 |
+
switch (event.type) {
|
| 165 |
+
case 'data':
|
| 166 |
+
if (isBinaryStream) break;
|
| 167 |
+
cumulativeOutput = event.chunk;
|
| 168 |
+
currentDisplayOutput = cumulativeOutput;
|
| 169 |
+
if (Date.now() - lastUpdateTime > OUTPUT_UPDATE_INTERVAL_MS) {
|
| 170 |
+
shouldUpdate = true;
|
| 171 |
+
}
|
| 172 |
+
break;
|
| 173 |
+
case 'binary_detected':
|
| 174 |
+
isBinaryStream = true;
|
| 175 |
+
currentDisplayOutput =
|
| 176 |
+
'[Binary output detected. Halting stream...]';
|
| 177 |
+
shouldUpdate = true;
|
| 178 |
+
break;
|
| 179 |
+
case 'binary_progress':
|
| 180 |
+
isBinaryStream = true;
|
| 181 |
+
currentDisplayOutput = `[Receiving binary output... ${formatMemoryUsage(
|
| 182 |
+
event.bytesReceived,
|
| 183 |
+
)} received]`;
|
| 184 |
+
if (Date.now() - lastUpdateTime > OUTPUT_UPDATE_INTERVAL_MS) {
|
| 185 |
+
shouldUpdate = true;
|
| 186 |
+
}
|
| 187 |
+
break;
|
| 188 |
+
default: {
|
| 189 |
+
throw new Error('An unhandled ShellOutputEvent was found.');
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
if (shouldUpdate) {
|
| 194 |
+
updateOutput(currentDisplayOutput);
|
| 195 |
+
lastUpdateTime = Date.now();
|
| 196 |
+
}
|
| 197 |
+
},
|
| 198 |
+
signal,
|
| 199 |
+
this.config.getShouldUseNodePtyShell(),
|
| 200 |
+
terminalColumns,
|
| 201 |
+
terminalRows,
|
| 202 |
+
);
|
| 203 |
+
|
| 204 |
+
const result = await resultPromise;
|
| 205 |
+
|
| 206 |
+
const backgroundPIDs: number[] = [];
|
| 207 |
+
if (os.platform() !== 'win32') {
|
| 208 |
+
if (fs.existsSync(tempFilePath)) {
|
| 209 |
+
const pgrepLines = fs
|
| 210 |
+
.readFileSync(tempFilePath, 'utf8')
|
| 211 |
+
.split('\n')
|
| 212 |
+
.filter(Boolean);
|
| 213 |
+
for (const line of pgrepLines) {
|
| 214 |
+
if (!/^\d+$/.test(line)) {
|
| 215 |
+
console.error(`pgrep: ${line}`);
|
| 216 |
+
}
|
| 217 |
+
const pid = Number(line);
|
| 218 |
+
if (pid !== result.pid) {
|
| 219 |
+
backgroundPIDs.push(pid);
|
| 220 |
+
}
|
| 221 |
+
}
|
| 222 |
+
} else {
|
| 223 |
+
if (!signal.aborted) {
|
| 224 |
+
console.error('missing pgrep output');
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
let llmContent = '';
|
| 230 |
+
if (result.aborted) {
|
| 231 |
+
llmContent = 'Command was cancelled by user before it could complete.';
|
| 232 |
+
if (result.output.trim()) {
|
| 233 |
+
llmContent += ` Below is the output before it was cancelled:\n${result.output}`;
|
| 234 |
+
} else {
|
| 235 |
+
llmContent += ' There was no output before it was cancelled.';
|
| 236 |
+
}
|
| 237 |
+
} else {
|
| 238 |
+
// Create a formatted error string for display, replacing the wrapper command
|
| 239 |
+
// with the user-facing command.
|
| 240 |
+
const finalError = result.error
|
| 241 |
+
? result.error.message.replace(commandToExecute, this.params.command)
|
| 242 |
+
: '(none)';
|
| 243 |
+
|
| 244 |
+
llmContent = [
|
| 245 |
+
`Command: ${this.params.command}`,
|
| 246 |
+
`Directory: ${this.params.directory || '(root)'}`,
|
| 247 |
+
`Output: ${result.output || '(empty)'}`,
|
| 248 |
+
`Error: ${finalError}`, // Use the cleaned error string.
|
| 249 |
+
`Exit Code: ${result.exitCode ?? '(none)'}`,
|
| 250 |
+
`Signal: ${result.signal ?? '(none)'}`,
|
| 251 |
+
`Background PIDs: ${
|
| 252 |
+
backgroundPIDs.length ? backgroundPIDs.join(', ') : '(none)'
|
| 253 |
+
}`,
|
| 254 |
+
`Process Group PGID: ${result.pid ?? '(none)'}`,
|
| 255 |
+
].join('\n');
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
let returnDisplayMessage = '';
|
| 259 |
+
if (this.config.getDebugMode()) {
|
| 260 |
+
returnDisplayMessage = llmContent;
|
| 261 |
+
} else {
|
| 262 |
+
if (result.output.trim()) {
|
| 263 |
+
returnDisplayMessage = result.output;
|
| 264 |
+
} else {
|
| 265 |
+
if (result.aborted) {
|
| 266 |
+
returnDisplayMessage = 'Command cancelled by user.';
|
| 267 |
+
} else if (result.signal) {
|
| 268 |
+
returnDisplayMessage = `Command terminated by signal: ${result.signal}`;
|
| 269 |
+
} else if (result.error) {
|
| 270 |
+
returnDisplayMessage = `Command failed: ${getErrorMessage(
|
| 271 |
+
result.error,
|
| 272 |
+
)}`;
|
| 273 |
+
} else if (result.exitCode !== null && result.exitCode !== 0) {
|
| 274 |
+
returnDisplayMessage = `Command exited with code: ${result.exitCode}`;
|
| 275 |
+
}
|
| 276 |
+
// If output is empty and command succeeded (code 0, no error/signal/abort),
|
| 277 |
+
// returnDisplayMessage will remain empty, which is fine.
|
| 278 |
+
}
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
const summarizeConfig = this.config.getSummarizeToolOutputConfig();
|
| 282 |
+
if (summarizeConfig && summarizeConfig[ShellTool.Name]) {
|
| 283 |
+
const summary = await summarizeToolOutput(
|
| 284 |
+
llmContent,
|
| 285 |
+
this.config.getGeminiClient(),
|
| 286 |
+
signal,
|
| 287 |
+
summarizeConfig[ShellTool.Name].tokenBudget,
|
| 288 |
+
);
|
| 289 |
+
return {
|
| 290 |
+
llmContent: summary,
|
| 291 |
+
returnDisplay: returnDisplayMessage,
|
| 292 |
+
};
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
return {
|
| 296 |
+
llmContent,
|
| 297 |
+
returnDisplay: returnDisplayMessage,
|
| 298 |
+
};
|
| 299 |
+
} finally {
|
| 300 |
+
if (fs.existsSync(tempFilePath)) {
|
| 301 |
+
fs.unlinkSync(tempFilePath);
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
private addCoAuthorToGitCommit(command: string): string {
|
| 307 |
+
// Check if co-author feature is enabled
|
| 308 |
+
const gitCoAuthorSettings = this.config.getGitCoAuthor();
|
| 309 |
+
if (!gitCoAuthorSettings.enabled) {
|
| 310 |
+
return command;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
// Check if this is a git commit command
|
| 314 |
+
const gitCommitPattern = /^git\s+commit/;
|
| 315 |
+
if (!gitCommitPattern.test(command.trim())) {
|
| 316 |
+
return command;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
// Define the co-author line using configuration
|
| 320 |
+
const coAuthor = `
|
| 321 |
+
|
| 322 |
+
Co-authored-by: ${gitCoAuthorSettings.name} <${gitCoAuthorSettings.email}>`;
|
| 323 |
+
|
| 324 |
+
// Handle different git commit patterns
|
| 325 |
+
// Match -m "message" or -m 'message'
|
| 326 |
+
const messagePattern = /(-m\s+)(['"])((?:\\.|[^\\])*?)(\2)/;
|
| 327 |
+
const match = command.match(messagePattern);
|
| 328 |
+
|
| 329 |
+
if (match) {
|
| 330 |
+
const [fullMatch, prefix, quote, existingMessage, closingQuote] = match;
|
| 331 |
+
const newMessage = existingMessage + coAuthor;
|
| 332 |
+
const replacement = prefix + quote + newMessage + closingQuote;
|
| 333 |
+
|
| 334 |
+
return command.replace(fullMatch, replacement);
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
// If no -m flag found, the command might open an editor
|
| 338 |
+
// In this case, we can't easily modify it, so return as-is
|
| 339 |
+
return command;
|
| 340 |
+
}
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
function getShellToolDescription(): string {
|
| 344 |
+
const platform = os.platform();
|
| 345 |
+
const toolDescription = `
|
| 346 |
+
${platform === 'win32' ? 'This tool executes a given shell command as `cmd.exe /c <command>`.' : 'This tool executes a given shell command as `bash -c <command>`. '}
|
| 347 |
+
|
| 348 |
+
**Background vs Foreground Execution:**
|
| 349 |
+
You should decide whether commands should run in background or foreground based on their nature:
|
| 350 |
+
|
| 351 |
+
**Use background execution (is_background: true) for:**
|
| 352 |
+
- Long-running development servers: \`npm run start\`, \`npm run dev\`, \`yarn dev\`, \`bun run start\`
|
| 353 |
+
- Build watchers: \`npm run watch\`, \`webpack --watch\`
|
| 354 |
+
- Database servers: \`mongod\`, \`mysql\`, \`redis-server\`
|
| 355 |
+
- Web servers: \`python -m http.server\`, \`php -S localhost:8000\`
|
| 356 |
+
- Any command expected to run indefinitely until manually stopped
|
| 357 |
+
|
| 358 |
+
**Use foreground execution (is_background: false) for:**
|
| 359 |
+
- One-time commands: \`ls\`, \`cat\`, \`grep\`
|
| 360 |
+
- Build commands: \`npm run build\`, \`make\`
|
| 361 |
+
- Installation commands: \`npm install\`, \`pip install\`
|
| 362 |
+
- Git operations: \`git commit\`, \`git push\`
|
| 363 |
+
- Test runs: \`npm test\`, \`pytest\`
|
| 364 |
+
|
| 365 |
+
${platform === 'win32' ? '' : 'Command is executed as a subprocess that leads its own process group. Command process group can be terminated as `kill -- -PGID` or signaled as `kill -s SIGNAL -- -PGID`.'}
|
| 366 |
+
|
| 367 |
+
The following information is returned:
|
| 368 |
+
|
| 369 |
+
Command: Executed command.
|
| 370 |
+
Directory: Directory (relative to project root) where command was executed, or \`(root)\`.
|
| 371 |
+
Stdout: Output on stdout stream. Can be \`(empty)\` or partial on error and for any unwaited background processes.
|
| 372 |
+
Stderr: Output on stderr stream. Can be \`(empty)\` or partial on error and for any unwaited background processes.
|
| 373 |
+
Error: Error or \`(none)\` if no error was reported for the subprocess.
|
| 374 |
+
Exit Code: Exit code or \`(none)\` if terminated by signal.
|
| 375 |
+
Signal: Signal number or \`(none)\` if no signal was received.
|
| 376 |
+
Background PIDs: List of background processes started or \`(none)\`.
|
| 377 |
+
Process Group PGID: Process group started or \`(none)\``;
|
| 378 |
+
|
| 379 |
+
return toolDescription;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
function getCommandDescription(): string {
|
| 383 |
+
if (os.platform() === 'win32') {
|
| 384 |
+
return 'Exact command to execute as `cmd.exe /c <command>`';
|
| 385 |
+
} else {
|
| 386 |
+
return 'Exact bash command to execute as `bash -c <command>`';
|
| 387 |
+
}
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
export class ShellTool extends BaseDeclarativeTool<
|
| 391 |
+
ShellToolParams,
|
| 392 |
+
ToolResult
|
| 393 |
+
> {
|
| 394 |
+
static Name: string = 'run_shell_command';
|
| 395 |
+
private allowlist: Set<string> = new Set();
|
| 396 |
+
|
| 397 |
+
constructor(private readonly config: Config) {
|
| 398 |
+
super(
|
| 399 |
+
ShellTool.Name,
|
| 400 |
+
'Shell',
|
| 401 |
+
getShellToolDescription(),
|
| 402 |
+
Kind.Execute,
|
| 403 |
+
{
|
| 404 |
+
type: 'object',
|
| 405 |
+
properties: {
|
| 406 |
+
command: {
|
| 407 |
+
type: 'string',
|
| 408 |
+
description: getCommandDescription(),
|
| 409 |
+
},
|
| 410 |
+
is_background: {
|
| 411 |
+
type: 'boolean',
|
| 412 |
+
description:
|
| 413 |
+
'Whether to run the command in background. Default is false. Set to true for long-running processes like development servers, watchers, or daemons that should continue running without blocking further commands.',
|
| 414 |
+
},
|
| 415 |
+
description: {
|
| 416 |
+
type: 'string',
|
| 417 |
+
description:
|
| 418 |
+
'Brief description of the command for the user. Be specific and concise. Ideally a single sentence. Can be up to 3 sentences for clarity. No line breaks.',
|
| 419 |
+
},
|
| 420 |
+
directory: {
|
| 421 |
+
type: 'string',
|
| 422 |
+
description:
|
| 423 |
+
'(OPTIONAL) Directory to run the command in, if not the project root directory. Must be relative to the project root directory and must already exist.',
|
| 424 |
+
},
|
| 425 |
+
},
|
| 426 |
+
required: ['command', 'is_background'],
|
| 427 |
+
},
|
| 428 |
+
false, // output is not markdown
|
| 429 |
+
true, // output can be updated
|
| 430 |
+
);
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
protected override validateToolParamValues(
|
| 434 |
+
params: ShellToolParams,
|
| 435 |
+
): string | null {
|
| 436 |
+
const commandCheck = isCommandAllowed(params.command, this.config);
|
| 437 |
+
if (!commandCheck.allowed) {
|
| 438 |
+
if (!commandCheck.reason) {
|
| 439 |
+
console.error(
|
| 440 |
+
'Unexpected: isCommandAllowed returned false without a reason',
|
| 441 |
+
);
|
| 442 |
+
return `Command is not allowed: ${params.command}`;
|
| 443 |
+
}
|
| 444 |
+
return commandCheck.reason;
|
| 445 |
+
}
|
| 446 |
+
if (!params.command.trim()) {
|
| 447 |
+
return 'Command cannot be empty.';
|
| 448 |
+
}
|
| 449 |
+
if (getCommandRoots(params.command).length === 0) {
|
| 450 |
+
return 'Could not identify command root to obtain permission from user.';
|
| 451 |
+
}
|
| 452 |
+
if (params.directory) {
|
| 453 |
+
if (path.isAbsolute(params.directory)) {
|
| 454 |
+
return 'Directory cannot be absolute. Please refer to workspace directories by their name.';
|
| 455 |
+
}
|
| 456 |
+
const workspaceDirs = this.config.getWorkspaceContext().getDirectories();
|
| 457 |
+
const matchingDirs = workspaceDirs.filter(
|
| 458 |
+
(dir) => path.basename(dir) === params.directory,
|
| 459 |
+
);
|
| 460 |
+
|
| 461 |
+
if (matchingDirs.length === 0) {
|
| 462 |
+
return `Directory '${params.directory}' is not a registered workspace directory.`;
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
if (matchingDirs.length > 1) {
|
| 466 |
+
return `Directory name '${params.directory}' is ambiguous as it matches multiple workspace directories.`;
|
| 467 |
+
}
|
| 468 |
+
}
|
| 469 |
+
return null;
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
protected createInvocation(
|
| 473 |
+
params: ShellToolParams,
|
| 474 |
+
): ToolInvocation<ShellToolParams, ToolResult> {
|
| 475 |
+
return new ShellToolInvocation(this.config, params, this.allowlist);
|
| 476 |
+
}
|
| 477 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/todoWrite.test.ts
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 { TodoWriteTool, TodoWriteParams, TodoItem } from './todoWrite.js';
|
| 9 |
+
import * as fs from 'fs/promises';
|
| 10 |
+
import * as fsSync from 'fs';
|
| 11 |
+
import { Config } from '../config/config.js';
|
| 12 |
+
|
| 13 |
+
// Mock fs modules
|
| 14 |
+
vi.mock('fs/promises');
|
| 15 |
+
vi.mock('fs');
|
| 16 |
+
|
| 17 |
+
const mockFs = vi.mocked(fs);
|
| 18 |
+
const mockFsSync = vi.mocked(fsSync);
|
| 19 |
+
|
| 20 |
+
describe('TodoWriteTool', () => {
|
| 21 |
+
let tool: TodoWriteTool;
|
| 22 |
+
let mockAbortSignal: AbortSignal;
|
| 23 |
+
let mockConfig: Config;
|
| 24 |
+
|
| 25 |
+
beforeEach(() => {
|
| 26 |
+
mockConfig = {
|
| 27 |
+
getSessionId: () => 'test-session-123',
|
| 28 |
+
} as Config;
|
| 29 |
+
tool = new TodoWriteTool(mockConfig);
|
| 30 |
+
mockAbortSignal = new AbortController().signal;
|
| 31 |
+
vi.clearAllMocks();
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
afterEach(() => {
|
| 35 |
+
vi.restoreAllMocks();
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
describe('validateToolParams', () => {
|
| 39 |
+
it('should validate correct parameters', () => {
|
| 40 |
+
const params: TodoWriteParams = {
|
| 41 |
+
todos: [
|
| 42 |
+
{ id: '1', content: 'Task 1', status: 'pending' },
|
| 43 |
+
{ id: '2', content: 'Task 2', status: 'in_progress' },
|
| 44 |
+
],
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
const result = tool.validateToolParams(params);
|
| 48 |
+
expect(result).toBeNull();
|
| 49 |
+
});
|
| 50 |
+
|
| 51 |
+
it('should accept empty todos array', () => {
|
| 52 |
+
const params: TodoWriteParams = {
|
| 53 |
+
todos: [],
|
| 54 |
+
};
|
| 55 |
+
|
| 56 |
+
const result = tool.validateToolParams(params);
|
| 57 |
+
expect(result).toBeNull();
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
it('should accept single todo', () => {
|
| 61 |
+
const params: TodoWriteParams = {
|
| 62 |
+
todos: [{ id: '1', content: 'Task 1', status: 'pending' }],
|
| 63 |
+
};
|
| 64 |
+
|
| 65 |
+
const result = tool.validateToolParams(params);
|
| 66 |
+
expect(result).toBeNull();
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
it('should reject todos with empty content', () => {
|
| 70 |
+
const params: TodoWriteParams = {
|
| 71 |
+
todos: [
|
| 72 |
+
{ id: '1', content: '', status: 'pending' },
|
| 73 |
+
{ id: '2', content: 'Task 2', status: 'pending' },
|
| 74 |
+
],
|
| 75 |
+
};
|
| 76 |
+
|
| 77 |
+
const result = tool.validateToolParams(params);
|
| 78 |
+
expect(result).toContain(
|
| 79 |
+
'Each todo must have a non-empty "content" string',
|
| 80 |
+
);
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
it('should reject todos with empty id', () => {
|
| 84 |
+
const params: TodoWriteParams = {
|
| 85 |
+
todos: [
|
| 86 |
+
{ id: '', content: 'Task 1', status: 'pending' },
|
| 87 |
+
{ id: '2', content: 'Task 2', status: 'pending' },
|
| 88 |
+
],
|
| 89 |
+
};
|
| 90 |
+
|
| 91 |
+
const result = tool.validateToolParams(params);
|
| 92 |
+
expect(result).toContain('non-empty "id" string');
|
| 93 |
+
});
|
| 94 |
+
|
| 95 |
+
it('should reject todos with invalid status', () => {
|
| 96 |
+
const params: TodoWriteParams = {
|
| 97 |
+
todos: [
|
| 98 |
+
{
|
| 99 |
+
id: '1',
|
| 100 |
+
content: 'Task 1',
|
| 101 |
+
status: 'invalid' as TodoItem['status'],
|
| 102 |
+
},
|
| 103 |
+
{ id: '2', content: 'Task 2', status: 'pending' },
|
| 104 |
+
],
|
| 105 |
+
};
|
| 106 |
+
|
| 107 |
+
const result = tool.validateToolParams(params);
|
| 108 |
+
expect(result).toContain(
|
| 109 |
+
'Each todo must have a valid "status" (pending, in_progress, completed)',
|
| 110 |
+
);
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
it('should reject todos with duplicate IDs', () => {
|
| 114 |
+
const params: TodoWriteParams = {
|
| 115 |
+
todos: [
|
| 116 |
+
{ id: '1', content: 'Task 1', status: 'pending' },
|
| 117 |
+
{ id: '1', content: 'Task 2', status: 'pending' },
|
| 118 |
+
],
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
const result = tool.validateToolParams(params);
|
| 122 |
+
expect(result).toContain('unique');
|
| 123 |
+
});
|
| 124 |
+
});
|
| 125 |
+
|
| 126 |
+
describe('execute', () => {
|
| 127 |
+
it('should create new todos file when none exists', async () => {
|
| 128 |
+
const params: TodoWriteParams = {
|
| 129 |
+
todos: [
|
| 130 |
+
{ id: '1', content: 'Task 1', status: 'pending' },
|
| 131 |
+
{ id: '2', content: 'Task 2', status: 'in_progress' },
|
| 132 |
+
],
|
| 133 |
+
};
|
| 134 |
+
|
| 135 |
+
// Mock file not existing
|
| 136 |
+
mockFs.readFile.mockRejectedValue({ code: 'ENOENT' });
|
| 137 |
+
mockFs.mkdir.mockResolvedValue(undefined);
|
| 138 |
+
mockFs.writeFile.mockResolvedValue(undefined);
|
| 139 |
+
|
| 140 |
+
const invocation = tool.build(params);
|
| 141 |
+
const result = await invocation.execute(mockAbortSignal);
|
| 142 |
+
|
| 143 |
+
expect(result.llmContent).toContain('success');
|
| 144 |
+
expect(result.returnDisplay).toEqual({
|
| 145 |
+
type: 'todo_list',
|
| 146 |
+
todos: [
|
| 147 |
+
{ id: '1', content: 'Task 1', status: 'pending' },
|
| 148 |
+
{ id: '2', content: 'Task 2', status: 'in_progress' },
|
| 149 |
+
],
|
| 150 |
+
});
|
| 151 |
+
expect(mockFs.writeFile).toHaveBeenCalledWith(
|
| 152 |
+
expect.stringContaining('test-session-123.json'),
|
| 153 |
+
expect.stringContaining('"todos"'),
|
| 154 |
+
'utf-8',
|
| 155 |
+
);
|
| 156 |
+
});
|
| 157 |
+
|
| 158 |
+
it('should replace todos with new ones', async () => {
|
| 159 |
+
const existingTodos = [
|
| 160 |
+
{ id: '1', content: 'Existing Task', status: 'completed' },
|
| 161 |
+
];
|
| 162 |
+
|
| 163 |
+
const params: TodoWriteParams = {
|
| 164 |
+
todos: [
|
| 165 |
+
{ id: '1', content: 'Updated Task', status: 'completed' },
|
| 166 |
+
{ id: '2', content: 'New Task', status: 'pending' },
|
| 167 |
+
],
|
| 168 |
+
};
|
| 169 |
+
|
| 170 |
+
// Mock existing file
|
| 171 |
+
mockFs.readFile.mockResolvedValue(
|
| 172 |
+
JSON.stringify({ todos: existingTodos }),
|
| 173 |
+
);
|
| 174 |
+
mockFs.mkdir.mockResolvedValue(undefined);
|
| 175 |
+
mockFs.writeFile.mockResolvedValue(undefined);
|
| 176 |
+
|
| 177 |
+
const invocation = tool.build(params);
|
| 178 |
+
const result = await invocation.execute(mockAbortSignal);
|
| 179 |
+
|
| 180 |
+
expect(result.llmContent).toContain('success');
|
| 181 |
+
expect(result.returnDisplay).toEqual({
|
| 182 |
+
type: 'todo_list',
|
| 183 |
+
todos: [
|
| 184 |
+
{ id: '1', content: 'Updated Task', status: 'completed' },
|
| 185 |
+
{ id: '2', content: 'New Task', status: 'pending' },
|
| 186 |
+
],
|
| 187 |
+
});
|
| 188 |
+
expect(mockFs.writeFile).toHaveBeenCalledWith(
|
| 189 |
+
expect.stringContaining('test-session-123.json'),
|
| 190 |
+
expect.stringMatching(/"Updated Task"/),
|
| 191 |
+
'utf-8',
|
| 192 |
+
);
|
| 193 |
+
});
|
| 194 |
+
|
| 195 |
+
it('should handle file write errors', async () => {
|
| 196 |
+
const params: TodoWriteParams = {
|
| 197 |
+
todos: [
|
| 198 |
+
{ id: '1', content: 'Task 1', status: 'pending' },
|
| 199 |
+
{ id: '2', content: 'Task 2', status: 'pending' },
|
| 200 |
+
],
|
| 201 |
+
};
|
| 202 |
+
|
| 203 |
+
mockFs.readFile.mockRejectedValue({ code: 'ENOENT' });
|
| 204 |
+
mockFs.mkdir.mockResolvedValue(undefined);
|
| 205 |
+
mockFs.writeFile.mockRejectedValue(new Error('Write failed'));
|
| 206 |
+
|
| 207 |
+
const invocation = tool.build(params);
|
| 208 |
+
const result = await invocation.execute(mockAbortSignal);
|
| 209 |
+
|
| 210 |
+
expect(result.llmContent).toContain('"success":false');
|
| 211 |
+
expect(result.returnDisplay).toContain('Error writing todos');
|
| 212 |
+
});
|
| 213 |
+
|
| 214 |
+
it('should handle empty todos array', async () => {
|
| 215 |
+
const params: TodoWriteParams = {
|
| 216 |
+
todos: [],
|
| 217 |
+
};
|
| 218 |
+
|
| 219 |
+
mockFs.mkdir.mockResolvedValue(undefined);
|
| 220 |
+
mockFs.writeFile.mockResolvedValue(undefined);
|
| 221 |
+
|
| 222 |
+
const invocation = tool.build(params);
|
| 223 |
+
const result = await invocation.execute(mockAbortSignal);
|
| 224 |
+
|
| 225 |
+
expect(result.llmContent).toContain('success');
|
| 226 |
+
expect(result.returnDisplay).toEqual({
|
| 227 |
+
type: 'todo_list',
|
| 228 |
+
todos: [],
|
| 229 |
+
});
|
| 230 |
+
expect(mockFs.writeFile).toHaveBeenCalledWith(
|
| 231 |
+
expect.stringContaining('test-session-123.json'),
|
| 232 |
+
expect.stringContaining('"todos"'),
|
| 233 |
+
'utf-8',
|
| 234 |
+
);
|
| 235 |
+
});
|
| 236 |
+
});
|
| 237 |
+
|
| 238 |
+
describe('tool properties', () => {
|
| 239 |
+
it('should have correct tool name', () => {
|
| 240 |
+
expect(TodoWriteTool.Name).toBe('todo_write');
|
| 241 |
+
expect(tool.name).toBe('todo_write');
|
| 242 |
+
});
|
| 243 |
+
|
| 244 |
+
it('should have correct display name', () => {
|
| 245 |
+
expect(tool.displayName).toBe('Todo Write');
|
| 246 |
+
});
|
| 247 |
+
|
| 248 |
+
it('should have correct kind', () => {
|
| 249 |
+
expect(tool.kind).toBe('think');
|
| 250 |
+
});
|
| 251 |
+
|
| 252 |
+
it('should have schema with required properties', () => {
|
| 253 |
+
const schema = tool.schema;
|
| 254 |
+
expect(schema.name).toBe('todo_write');
|
| 255 |
+
expect(schema.parametersJsonSchema).toHaveProperty('properties.todos');
|
| 256 |
+
expect(schema.parametersJsonSchema).not.toHaveProperty(
|
| 257 |
+
'properties.merge',
|
| 258 |
+
);
|
| 259 |
+
});
|
| 260 |
+
});
|
| 261 |
+
|
| 262 |
+
describe('getDescription', () => {
|
| 263 |
+
it('should return "Create todos" when no todos file exists', () => {
|
| 264 |
+
// Mock existsSync to return false (file doesn't exist)
|
| 265 |
+
mockFsSync.existsSync.mockReturnValue(false);
|
| 266 |
+
|
| 267 |
+
const params = {
|
| 268 |
+
todos: [{ id: '1', content: 'Test todo', status: 'pending' as const }],
|
| 269 |
+
};
|
| 270 |
+
const invocation = tool.build(params);
|
| 271 |
+
expect(invocation.getDescription()).toBe('Create todos');
|
| 272 |
+
});
|
| 273 |
+
|
| 274 |
+
it('should return "Update todos" when todos file exists', () => {
|
| 275 |
+
// Mock existsSync to return true (file exists)
|
| 276 |
+
mockFsSync.existsSync.mockReturnValue(true);
|
| 277 |
+
|
| 278 |
+
const params = {
|
| 279 |
+
todos: [
|
| 280 |
+
{ id: '1', content: 'Updated todo', status: 'completed' as const },
|
| 281 |
+
],
|
| 282 |
+
};
|
| 283 |
+
const invocation = tool.build(params);
|
| 284 |
+
expect(invocation.getDescription()).toBe('Update todos');
|
| 285 |
+
});
|
| 286 |
+
});
|
| 287 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/todoWrite.ts
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
} from './tools.js';
|
| 13 |
+
import { FunctionDeclaration } from '@google/genai';
|
| 14 |
+
import * as fs from 'fs/promises';
|
| 15 |
+
import * as fsSync from 'fs';
|
| 16 |
+
import * as path from 'path';
|
| 17 |
+
import * as process from 'process';
|
| 18 |
+
|
| 19 |
+
import { QWEN_DIR } from '../utils/paths.js';
|
| 20 |
+
import { Config } from '../config/config.js';
|
| 21 |
+
|
| 22 |
+
export interface TodoItem {
|
| 23 |
+
id: string;
|
| 24 |
+
content: string;
|
| 25 |
+
status: 'pending' | 'in_progress' | 'completed';
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
export interface TodoWriteParams {
|
| 29 |
+
todos: TodoItem[];
|
| 30 |
+
modified_by_user?: boolean;
|
| 31 |
+
modified_content?: string;
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
const todoWriteToolSchemaData: FunctionDeclaration = {
|
| 35 |
+
name: 'todo_write',
|
| 36 |
+
description:
|
| 37 |
+
'Creates and manages a structured task list for your current coding session. This helps track progress, organize complex tasks, and demonstrate thoroughness.',
|
| 38 |
+
parametersJsonSchema: {
|
| 39 |
+
type: 'object',
|
| 40 |
+
properties: {
|
| 41 |
+
todos: {
|
| 42 |
+
type: 'array',
|
| 43 |
+
items: {
|
| 44 |
+
type: 'object',
|
| 45 |
+
properties: {
|
| 46 |
+
content: {
|
| 47 |
+
type: 'string',
|
| 48 |
+
minLength: 1,
|
| 49 |
+
},
|
| 50 |
+
status: {
|
| 51 |
+
type: 'string',
|
| 52 |
+
enum: ['pending', 'in_progress', 'completed'],
|
| 53 |
+
},
|
| 54 |
+
id: {
|
| 55 |
+
type: 'string',
|
| 56 |
+
},
|
| 57 |
+
},
|
| 58 |
+
required: ['content', 'status', 'id'],
|
| 59 |
+
additionalProperties: false,
|
| 60 |
+
},
|
| 61 |
+
description: 'The updated todo list',
|
| 62 |
+
},
|
| 63 |
+
},
|
| 64 |
+
required: ['todos'],
|
| 65 |
+
$schema: 'http://json-schema.org/draft-07/schema#',
|
| 66 |
+
},
|
| 67 |
+
};
|
| 68 |
+
|
| 69 |
+
const todoWriteToolDescription = `
|
| 70 |
+
Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
| 71 |
+
It also helps the user understand the progress of the task and overall progress of their requests.
|
| 72 |
+
|
| 73 |
+
## When to Use This Tool
|
| 74 |
+
Use this tool proactively in these scenarios:
|
| 75 |
+
|
| 76 |
+
1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
|
| 77 |
+
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
|
| 78 |
+
3. User explicitly requests todo list - When the user directly asks you to use the todo list
|
| 79 |
+
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
|
| 80 |
+
5. After receiving new instructions - Immediately capture user requirements as todos
|
| 81 |
+
6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
|
| 82 |
+
7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
|
| 83 |
+
|
| 84 |
+
## When NOT to Use This Tool
|
| 85 |
+
|
| 86 |
+
Skip using this tool when:
|
| 87 |
+
1. There is only a single, straightforward task
|
| 88 |
+
2. The task is trivial and tracking it provides no organizational benefit
|
| 89 |
+
3. The task can be completed in less than 3 trivial steps
|
| 90 |
+
4. The task is purely conversational or informational
|
| 91 |
+
|
| 92 |
+
NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
|
| 93 |
+
|
| 94 |
+
## Examples of When to Use the Todo List
|
| 95 |
+
|
| 96 |
+
<example>
|
| 97 |
+
User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
|
| 98 |
+
Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
|
| 99 |
+
*Creates todo list with the following items:*
|
| 100 |
+
1. Create dark mode toggle component in Settings page
|
| 101 |
+
2. Add dark mode state management (context/store)
|
| 102 |
+
3. Implement CSS-in-JS styles for dark theme
|
| 103 |
+
4. Update existing components to support theme switching
|
| 104 |
+
5. Run tests and build process, addressing any failures or errors that occur
|
| 105 |
+
*Begins working on the first task*
|
| 106 |
+
|
| 107 |
+
<reasoning>
|
| 108 |
+
The assistant used the todo list because:
|
| 109 |
+
1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
|
| 110 |
+
2. The user explicitly requested tests and build be run afterward
|
| 111 |
+
3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
|
| 112 |
+
</reasoning>
|
| 113 |
+
</example>
|
| 114 |
+
|
| 115 |
+
<example>
|
| 116 |
+
User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
|
| 117 |
+
Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
|
| 118 |
+
*Uses grep or search tools to locate all instances of getCwd in the codebase*
|
| 119 |
+
Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
|
| 120 |
+
*Creates todo list with specific items for each file that needs updating*
|
| 121 |
+
|
| 122 |
+
<reasoning>
|
| 123 |
+
The assistant used the todo list because:
|
| 124 |
+
1. First, the assistant searched to understand the scope of the task
|
| 125 |
+
2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
|
| 126 |
+
3. The todo list helps ensure every instance is tracked and updated systematically
|
| 127 |
+
4. This approach prevents missing any occurrences and maintains code consistency
|
| 128 |
+
</reasoning>
|
| 129 |
+
</example>
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
<example>
|
| 133 |
+
User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
|
| 134 |
+
Assistant: I'll help implement these features. First, let's add all the features to the todo list.
|
| 135 |
+
*Creates a todo list breaking down each feature into specific tasks based on the project architecture*
|
| 136 |
+
Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
|
| 137 |
+
|
| 138 |
+
<reasoning>
|
| 139 |
+
The assistant used the todo list because:
|
| 140 |
+
1. The user provided multiple complex features to implement in a comma separated list
|
| 141 |
+
2. The todo list helps organize these large features into manageable tasks
|
| 142 |
+
3. This approach allows for tracking progress across the entire implementation
|
| 143 |
+
</reasoning>
|
| 144 |
+
</example>
|
| 145 |
+
|
| 146 |
+
<example>
|
| 147 |
+
User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
|
| 148 |
+
Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
|
| 149 |
+
*Reviews component structure, render patterns, state management, and data fetching*
|
| 150 |
+
Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
|
| 151 |
+
*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
|
| 152 |
+
Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
|
| 153 |
+
|
| 154 |
+
<reasoning>
|
| 155 |
+
The assistant used the todo list because:
|
| 156 |
+
1. First, the assistant examined the codebase to identify specific performance issues
|
| 157 |
+
2. Based on this analysis, it identified multiple optimization opportunities
|
| 158 |
+
3. Performance optimization is a non-trivial task requiring multiple steps
|
| 159 |
+
4. The todo list helps methodically track improvements across different components
|
| 160 |
+
5. This systematic approach ensures all performance bottlenecks are addressed
|
| 161 |
+
</reasoning>
|
| 162 |
+
</example>
|
| 163 |
+
|
| 164 |
+
## Examples of When NOT to Use the Todo List
|
| 165 |
+
|
| 166 |
+
<example>
|
| 167 |
+
User: How do I print 'Hello World' in Python?
|
| 168 |
+
Assistant: In Python, you can print "Hello World" with this simple code:
|
| 169 |
+
|
| 170 |
+
python
|
| 171 |
+
print("Hello World")
|
| 172 |
+
|
| 173 |
+
This will output the text "Hello World" to the console when executed.</assistant>
|
| 174 |
+
|
| 175 |
+
<reasoning>
|
| 176 |
+
The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
|
| 177 |
+
</reasoning>
|
| 178 |
+
</example>
|
| 179 |
+
|
| 180 |
+
<example>
|
| 181 |
+
User: What does the git status command do?
|
| 182 |
+
Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
|
| 183 |
+
|
| 184 |
+
<reasoning>
|
| 185 |
+
The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
|
| 186 |
+
</reasoning>
|
| 187 |
+
</example>
|
| 188 |
+
|
| 189 |
+
<example>
|
| 190 |
+
User: Can you add a comment to the calculateTotal function to explain what it does?
|
| 191 |
+
Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
|
| 192 |
+
* Uses the Edit tool to add a comment to the calculateTotal function *
|
| 193 |
+
|
| 194 |
+
<reasoning>
|
| 195 |
+
The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
|
| 196 |
+
</reasoning>
|
| 197 |
+
</example>
|
| 198 |
+
|
| 199 |
+
<example>
|
| 200 |
+
User: Run npm install for me and tell me what happens.
|
| 201 |
+
Assistant: I'll run the npm install command for you.
|
| 202 |
+
|
| 203 |
+
*Executes: npm install*
|
| 204 |
+
|
| 205 |
+
The command completed successfully. Here's the output:
|
| 206 |
+
[Output of npm install command]
|
| 207 |
+
|
| 208 |
+
All dependencies have been installed according to your package.json file.
|
| 209 |
+
|
| 210 |
+
<reasoning>
|
| 211 |
+
The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
|
| 212 |
+
</reasoning>
|
| 213 |
+
</example>
|
| 214 |
+
|
| 215 |
+
## Task States and Management
|
| 216 |
+
|
| 217 |
+
1. **Task States**: Use these states to track progress:
|
| 218 |
+
- pending: Task not yet started
|
| 219 |
+
- in_progress: Currently working on (limit to ONE task at a time)
|
| 220 |
+
- completed: Task finished successfully
|
| 221 |
+
|
| 222 |
+
2. **Task Management**:
|
| 223 |
+
- Update task status in real-time as you work
|
| 224 |
+
- Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
|
| 225 |
+
- Only have ONE task in_progress at any time
|
| 226 |
+
- Complete current tasks before starting new ones
|
| 227 |
+
- Remove tasks that are no longer relevant from the list entirely
|
| 228 |
+
|
| 229 |
+
3. **Task Completion Requirements**:
|
| 230 |
+
- ONLY mark a task as completed when you have FULLY accomplished it
|
| 231 |
+
- If you encounter errors, blockers, or cannot finish, keep the task as in_progress
|
| 232 |
+
- When blocked, create a new task describing what needs to be resolved
|
| 233 |
+
- Never mark a task as completed if:
|
| 234 |
+
- Tests are failing
|
| 235 |
+
- Implementation is partial
|
| 236 |
+
- You encountered unresolved errors
|
| 237 |
+
- You couldn't find necessary files or dependencies
|
| 238 |
+
|
| 239 |
+
4. **Task Breakdown**:
|
| 240 |
+
- Create specific, actionable items
|
| 241 |
+
- Break complex tasks into smaller, manageable steps
|
| 242 |
+
- Use clear, descriptive task names
|
| 243 |
+
|
| 244 |
+
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
|
| 245 |
+
`;
|
| 246 |
+
|
| 247 |
+
const TODO_SUBDIR = 'todos';
|
| 248 |
+
|
| 249 |
+
function getTodoFilePath(sessionId?: string): string {
|
| 250 |
+
const homeDir =
|
| 251 |
+
process.env['HOME'] || process.env['USERPROFILE'] || process.cwd();
|
| 252 |
+
const todoDir = path.join(homeDir, QWEN_DIR, TODO_SUBDIR);
|
| 253 |
+
|
| 254 |
+
// Use sessionId if provided, otherwise fall back to 'default'
|
| 255 |
+
const filename = `${sessionId || 'default'}.json`;
|
| 256 |
+
return path.join(todoDir, filename);
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
/**
|
| 260 |
+
* Reads the current todos from the file system
|
| 261 |
+
*/
|
| 262 |
+
async function readTodosFromFile(sessionId?: string): Promise<TodoItem[]> {
|
| 263 |
+
try {
|
| 264 |
+
const todoFilePath = getTodoFilePath(sessionId);
|
| 265 |
+
const content = await fs.readFile(todoFilePath, 'utf-8');
|
| 266 |
+
const data = JSON.parse(content);
|
| 267 |
+
return Array.isArray(data.todos) ? data.todos : [];
|
| 268 |
+
} catch (err) {
|
| 269 |
+
const error = err as Error & { code?: string };
|
| 270 |
+
if (!(error instanceof Error) || error.code !== 'ENOENT') {
|
| 271 |
+
throw err;
|
| 272 |
+
}
|
| 273 |
+
return [];
|
| 274 |
+
}
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
/**
|
| 278 |
+
* Writes todos to the file system
|
| 279 |
+
*/
|
| 280 |
+
async function writeTodosToFile(
|
| 281 |
+
todos: TodoItem[],
|
| 282 |
+
sessionId?: string,
|
| 283 |
+
): Promise<void> {
|
| 284 |
+
const todoFilePath = getTodoFilePath(sessionId);
|
| 285 |
+
const todoDir = path.dirname(todoFilePath);
|
| 286 |
+
|
| 287 |
+
await fs.mkdir(todoDir, { recursive: true });
|
| 288 |
+
|
| 289 |
+
const data = {
|
| 290 |
+
todos,
|
| 291 |
+
sessionId: sessionId || 'default',
|
| 292 |
+
};
|
| 293 |
+
|
| 294 |
+
await fs.writeFile(todoFilePath, JSON.stringify(data, null, 2), 'utf-8');
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
class TodoWriteToolInvocation extends BaseToolInvocation<
|
| 298 |
+
TodoWriteParams,
|
| 299 |
+
ToolResult
|
| 300 |
+
> {
|
| 301 |
+
private operationType: 'create' | 'update';
|
| 302 |
+
|
| 303 |
+
constructor(
|
| 304 |
+
private readonly config: Config,
|
| 305 |
+
params: TodoWriteParams,
|
| 306 |
+
operationType: 'create' | 'update' = 'update',
|
| 307 |
+
) {
|
| 308 |
+
super(params);
|
| 309 |
+
this.operationType = operationType;
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
getDescription(): string {
|
| 313 |
+
return this.operationType === 'create' ? 'Create todos' : 'Update todos';
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
override async shouldConfirmExecute(
|
| 317 |
+
_abortSignal: AbortSignal,
|
| 318 |
+
): Promise<false> {
|
| 319 |
+
// Todo operations should execute automatically without user confirmation
|
| 320 |
+
return false;
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
async execute(_signal: AbortSignal): Promise<ToolResult> {
|
| 324 |
+
const { todos, modified_by_user, modified_content } = this.params;
|
| 325 |
+
const sessionId = this.config.getSessionId();
|
| 326 |
+
|
| 327 |
+
try {
|
| 328 |
+
let finalTodos: TodoItem[];
|
| 329 |
+
|
| 330 |
+
if (modified_by_user && modified_content !== undefined) {
|
| 331 |
+
// User modified the content in external editor, parse it directly
|
| 332 |
+
const data = JSON.parse(modified_content);
|
| 333 |
+
finalTodos = Array.isArray(data.todos) ? data.todos : [];
|
| 334 |
+
} else {
|
| 335 |
+
// Use the normal todo logic - simply replace with new todos
|
| 336 |
+
finalTodos = todos;
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
await writeTodosToFile(finalTodos, sessionId);
|
| 340 |
+
|
| 341 |
+
// Create structured display object for rich UI rendering
|
| 342 |
+
const todoResultDisplay = {
|
| 343 |
+
type: 'todo_list' as const,
|
| 344 |
+
todos: finalTodos,
|
| 345 |
+
};
|
| 346 |
+
|
| 347 |
+
return {
|
| 348 |
+
llmContent: JSON.stringify({
|
| 349 |
+
success: true,
|
| 350 |
+
todos: finalTodos,
|
| 351 |
+
}),
|
| 352 |
+
returnDisplay: todoResultDisplay,
|
| 353 |
+
};
|
| 354 |
+
} catch (error) {
|
| 355 |
+
const errorMessage =
|
| 356 |
+
error instanceof Error ? error.message : String(error);
|
| 357 |
+
console.error(
|
| 358 |
+
`[TodoWriteTool] Error executing todo_write: ${errorMessage}`,
|
| 359 |
+
);
|
| 360 |
+
return {
|
| 361 |
+
llmContent: JSON.stringify({
|
| 362 |
+
success: false,
|
| 363 |
+
error: `Failed to write todos. Detail: ${errorMessage}`,
|
| 364 |
+
}),
|
| 365 |
+
returnDisplay: `Error writing todos: ${errorMessage}`,
|
| 366 |
+
};
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
/**
|
| 372 |
+
* Utility function to read todos for a specific session (useful for session recovery)
|
| 373 |
+
*/
|
| 374 |
+
export async function readTodosForSession(
|
| 375 |
+
sessionId?: string,
|
| 376 |
+
): Promise<TodoItem[]> {
|
| 377 |
+
return readTodosFromFile(sessionId);
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
/**
|
| 381 |
+
* Utility function to list all todo files in the todos directory
|
| 382 |
+
*/
|
| 383 |
+
export async function listTodoSessions(): Promise<string[]> {
|
| 384 |
+
try {
|
| 385 |
+
const homeDir =
|
| 386 |
+
process.env['HOME'] || process.env['USERPROFILE'] || process.cwd();
|
| 387 |
+
const todoDir = path.join(homeDir, QWEN_DIR, TODO_SUBDIR);
|
| 388 |
+
const files = await fs.readdir(todoDir);
|
| 389 |
+
return files
|
| 390 |
+
.filter((file: string) => file.endsWith('.json'))
|
| 391 |
+
.map((file: string) => file.replace('.json', ''));
|
| 392 |
+
} catch (err) {
|
| 393 |
+
const error = err as Error & { code?: string };
|
| 394 |
+
if (!(error instanceof Error) || error.code !== 'ENOENT') {
|
| 395 |
+
throw err;
|
| 396 |
+
}
|
| 397 |
+
return [];
|
| 398 |
+
}
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
export class TodoWriteTool extends BaseDeclarativeTool<
|
| 402 |
+
TodoWriteParams,
|
| 403 |
+
ToolResult
|
| 404 |
+
> {
|
| 405 |
+
static readonly Name: string = todoWriteToolSchemaData.name!;
|
| 406 |
+
|
| 407 |
+
constructor(private readonly config: Config) {
|
| 408 |
+
super(
|
| 409 |
+
TodoWriteTool.Name,
|
| 410 |
+
'Todo Write',
|
| 411 |
+
todoWriteToolDescription,
|
| 412 |
+
Kind.Think,
|
| 413 |
+
todoWriteToolSchemaData.parametersJsonSchema as Record<string, unknown>,
|
| 414 |
+
);
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
override validateToolParams(params: TodoWriteParams): string | null {
|
| 418 |
+
// Validate todos array
|
| 419 |
+
if (!Array.isArray(params.todos)) {
|
| 420 |
+
return 'Parameter "todos" must be an array.';
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
// Validate individual todos
|
| 424 |
+
for (const todo of params.todos) {
|
| 425 |
+
if (!todo.id || typeof todo.id !== 'string' || todo.id.trim() === '') {
|
| 426 |
+
return 'Each todo must have a non-empty "id" string.';
|
| 427 |
+
}
|
| 428 |
+
if (
|
| 429 |
+
!todo.content ||
|
| 430 |
+
typeof todo.content !== 'string' ||
|
| 431 |
+
todo.content.trim() === ''
|
| 432 |
+
) {
|
| 433 |
+
return 'Each todo must have a non-empty "content" string.';
|
| 434 |
+
}
|
| 435 |
+
if (!['pending', 'in_progress', 'completed'].includes(todo.status)) {
|
| 436 |
+
return 'Each todo must have a valid "status" (pending, in_progress, completed).';
|
| 437 |
+
}
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
// Check for duplicate IDs
|
| 441 |
+
const ids = params.todos.map((todo) => todo.id);
|
| 442 |
+
const uniqueIds = new Set(ids);
|
| 443 |
+
if (ids.length !== uniqueIds.size) {
|
| 444 |
+
return 'Todo IDs must be unique within the array.';
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
return null;
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
protected createInvocation(params: TodoWriteParams) {
|
| 451 |
+
// Determine if this is a create or update operation by checking if todos file exists
|
| 452 |
+
const sessionId = this.config.getSessionId();
|
| 453 |
+
const todoFilePath = getTodoFilePath(sessionId);
|
| 454 |
+
const operationType = fsSync.existsSync(todoFilePath) ? 'update' : 'create';
|
| 455 |
+
|
| 456 |
+
return new TodoWriteToolInvocation(this.config, params, operationType);
|
| 457 |
+
}
|
| 458 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/tool-error.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* A type-safe enum for tool-related errors.
|
| 9 |
+
*/
|
| 10 |
+
export enum ToolErrorType {
|
| 11 |
+
// General Errors
|
| 12 |
+
INVALID_TOOL_PARAMS = 'invalid_tool_params',
|
| 13 |
+
UNKNOWN = 'unknown',
|
| 14 |
+
UNHANDLED_EXCEPTION = 'unhandled_exception',
|
| 15 |
+
TOOL_NOT_REGISTERED = 'tool_not_registered',
|
| 16 |
+
EXECUTION_FAILED = 'execution_failed',
|
| 17 |
+
|
| 18 |
+
// File System Errors
|
| 19 |
+
FILE_NOT_FOUND = 'file_not_found',
|
| 20 |
+
FILE_WRITE_FAILURE = 'file_write_failure',
|
| 21 |
+
READ_CONTENT_FAILURE = 'read_content_failure',
|
| 22 |
+
ATTEMPT_TO_CREATE_EXISTING_FILE = 'attempt_to_create_existing_file',
|
| 23 |
+
FILE_TOO_LARGE = 'file_too_large',
|
| 24 |
+
PERMISSION_DENIED = 'permission_denied',
|
| 25 |
+
NO_SPACE_LEFT = 'no_space_left',
|
| 26 |
+
TARGET_IS_DIRECTORY = 'target_is_directory',
|
| 27 |
+
|
| 28 |
+
// Edit-specific Errors
|
| 29 |
+
EDIT_PREPARATION_FAILURE = 'edit_preparation_failure',
|
| 30 |
+
EDIT_NO_OCCURRENCE_FOUND = 'edit_no_occurrence_found',
|
| 31 |
+
EDIT_EXPECTED_OCCURRENCE_MISMATCH = 'edit_expected_occurrence_mismatch',
|
| 32 |
+
EDIT_NO_CHANGE = 'edit_no_change',
|
| 33 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/tool-registry.test.ts
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 { Config, ConfigParameters, ApprovalMode } from '../config/config.js';
|
| 18 |
+
import { ToolRegistry, DiscoveredTool } from './tool-registry.js';
|
| 19 |
+
import { DiscoveredMCPTool } from './mcp-tool.js';
|
| 20 |
+
import { FunctionDeclaration, CallableTool, mcpToTool } from '@google/genai';
|
| 21 |
+
import { spawn } from 'node:child_process';
|
| 22 |
+
import fs from 'node:fs';
|
| 23 |
+
import { MockTool } from '../test-utils/tools.js';
|
| 24 |
+
|
| 25 |
+
import { McpClientManager } from './mcp-client-manager.js';
|
| 26 |
+
|
| 27 |
+
vi.mock('node:fs');
|
| 28 |
+
|
| 29 |
+
// Mock ./mcp-client.js to control its behavior within tool-registry tests
|
| 30 |
+
vi.mock('./mcp-client.js', async () => {
|
| 31 |
+
const originalModule = await vi.importActual('./mcp-client.js');
|
| 32 |
+
return {
|
| 33 |
+
...originalModule,
|
| 34 |
+
};
|
| 35 |
+
});
|
| 36 |
+
|
| 37 |
+
// Mock node:child_process
|
| 38 |
+
vi.mock('node:child_process', async () => {
|
| 39 |
+
const actual = await vi.importActual('node:child_process');
|
| 40 |
+
return {
|
| 41 |
+
...actual,
|
| 42 |
+
execSync: vi.fn(),
|
| 43 |
+
spawn: vi.fn(),
|
| 44 |
+
};
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
// Mock MCP SDK Client and Transports
|
| 48 |
+
const mockMcpClientConnect = vi.fn();
|
| 49 |
+
const mockMcpClientOnError = vi.fn();
|
| 50 |
+
const mockStdioTransportClose = vi.fn();
|
| 51 |
+
const mockSseTransportClose = vi.fn();
|
| 52 |
+
|
| 53 |
+
vi.mock('@modelcontextprotocol/sdk/client/index.js', () => {
|
| 54 |
+
const MockClient = vi.fn().mockImplementation(() => ({
|
| 55 |
+
connect: mockMcpClientConnect,
|
| 56 |
+
set onerror(handler: any) {
|
| 57 |
+
mockMcpClientOnError(handler);
|
| 58 |
+
},
|
| 59 |
+
}));
|
| 60 |
+
return { Client: MockClient };
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
vi.mock('@modelcontextprotocol/sdk/client/stdio.js', () => {
|
| 64 |
+
const MockStdioClientTransport = vi.fn().mockImplementation(() => ({
|
| 65 |
+
stderr: {
|
| 66 |
+
on: vi.fn(),
|
| 67 |
+
},
|
| 68 |
+
close: mockStdioTransportClose,
|
| 69 |
+
}));
|
| 70 |
+
return { StdioClientTransport: MockStdioClientTransport };
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => {
|
| 74 |
+
const MockSSEClientTransport = vi.fn().mockImplementation(() => ({
|
| 75 |
+
close: mockSseTransportClose,
|
| 76 |
+
}));
|
| 77 |
+
return { SSEClientTransport: MockSSEClientTransport };
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
// Mock @google/genai mcpToTool
|
| 81 |
+
vi.mock('@google/genai', async () => {
|
| 82 |
+
const actualGenai =
|
| 83 |
+
await vi.importActual<typeof import('@google/genai')>('@google/genai');
|
| 84 |
+
return {
|
| 85 |
+
...actualGenai,
|
| 86 |
+
mcpToTool: vi.fn().mockImplementation(() => ({
|
| 87 |
+
tool: vi.fn().mockResolvedValue({ functionDeclarations: [] }),
|
| 88 |
+
callTool: vi.fn(),
|
| 89 |
+
})),
|
| 90 |
+
};
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
// Helper to create a mock CallableTool for specific test needs
|
| 94 |
+
const createMockCallableTool = (
|
| 95 |
+
toolDeclarations: FunctionDeclaration[],
|
| 96 |
+
): Mocked<CallableTool> => ({
|
| 97 |
+
tool: vi.fn().mockResolvedValue({ functionDeclarations: toolDeclarations }),
|
| 98 |
+
callTool: vi.fn(),
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
const baseConfigParams: ConfigParameters = {
|
| 102 |
+
cwd: '/tmp',
|
| 103 |
+
model: 'test-model',
|
| 104 |
+
embeddingModel: 'test-embedding-model',
|
| 105 |
+
sandbox: undefined,
|
| 106 |
+
targetDir: '/test/dir',
|
| 107 |
+
debugMode: false,
|
| 108 |
+
userMemory: '',
|
| 109 |
+
geminiMdFileCount: 0,
|
| 110 |
+
approvalMode: ApprovalMode.DEFAULT,
|
| 111 |
+
sessionId: 'test-session-id',
|
| 112 |
+
};
|
| 113 |
+
|
| 114 |
+
describe('ToolRegistry', () => {
|
| 115 |
+
let config: Config;
|
| 116 |
+
let toolRegistry: ToolRegistry;
|
| 117 |
+
let mockConfigGetToolDiscoveryCommand: ReturnType<typeof vi.spyOn>;
|
| 118 |
+
|
| 119 |
+
beforeEach(() => {
|
| 120 |
+
vi.mocked(fs.existsSync).mockReturnValue(true);
|
| 121 |
+
vi.mocked(fs.statSync).mockReturnValue({
|
| 122 |
+
isDirectory: () => true,
|
| 123 |
+
} as fs.Stats);
|
| 124 |
+
config = new Config(baseConfigParams);
|
| 125 |
+
toolRegistry = new ToolRegistry(config);
|
| 126 |
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
| 127 |
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
| 128 |
+
vi.spyOn(console, 'debug').mockImplementation(() => {});
|
| 129 |
+
vi.spyOn(console, 'log').mockImplementation(() => {});
|
| 130 |
+
|
| 131 |
+
mockMcpClientConnect.mockReset().mockResolvedValue(undefined);
|
| 132 |
+
mockStdioTransportClose.mockReset();
|
| 133 |
+
mockSseTransportClose.mockReset();
|
| 134 |
+
vi.mocked(mcpToTool).mockClear();
|
| 135 |
+
vi.mocked(mcpToTool).mockReturnValue(createMockCallableTool([]));
|
| 136 |
+
|
| 137 |
+
mockConfigGetToolDiscoveryCommand = vi.spyOn(
|
| 138 |
+
config,
|
| 139 |
+
'getToolDiscoveryCommand',
|
| 140 |
+
);
|
| 141 |
+
vi.spyOn(config, 'getMcpServers');
|
| 142 |
+
vi.spyOn(config, 'getMcpServerCommand');
|
| 143 |
+
vi.spyOn(config, 'getPromptRegistry').mockReturnValue({
|
| 144 |
+
clear: vi.fn(),
|
| 145 |
+
removePromptsByServer: vi.fn(),
|
| 146 |
+
} as any);
|
| 147 |
+
});
|
| 148 |
+
|
| 149 |
+
afterEach(() => {
|
| 150 |
+
vi.restoreAllMocks();
|
| 151 |
+
});
|
| 152 |
+
|
| 153 |
+
describe('registerTool', () => {
|
| 154 |
+
it('should register a new tool', () => {
|
| 155 |
+
const tool = new MockTool();
|
| 156 |
+
toolRegistry.registerTool(tool);
|
| 157 |
+
expect(toolRegistry.getTool('mock-tool')).toBe(tool);
|
| 158 |
+
});
|
| 159 |
+
});
|
| 160 |
+
|
| 161 |
+
describe('getAllTools', () => {
|
| 162 |
+
it('should return all registered tools sorted alphabetically by displayName', () => {
|
| 163 |
+
// Register tools with displayNames in non-alphabetical order
|
| 164 |
+
const toolC = new MockTool('c-tool', 'Tool C');
|
| 165 |
+
const toolA = new MockTool('a-tool', 'Tool A');
|
| 166 |
+
const toolB = new MockTool('b-tool', 'Tool B');
|
| 167 |
+
|
| 168 |
+
toolRegistry.registerTool(toolC);
|
| 169 |
+
toolRegistry.registerTool(toolA);
|
| 170 |
+
toolRegistry.registerTool(toolB);
|
| 171 |
+
|
| 172 |
+
const allTools = toolRegistry.getAllTools();
|
| 173 |
+
const displayNames = allTools.map((t) => t.displayName);
|
| 174 |
+
|
| 175 |
+
// Assert that the returned array is sorted by displayName
|
| 176 |
+
expect(displayNames).toEqual(['Tool A', 'Tool B', 'Tool C']);
|
| 177 |
+
});
|
| 178 |
+
});
|
| 179 |
+
|
| 180 |
+
describe('getToolsByServer', () => {
|
| 181 |
+
it('should return an empty array if no tools match the server name', () => {
|
| 182 |
+
toolRegistry.registerTool(new MockTool());
|
| 183 |
+
expect(toolRegistry.getToolsByServer('any-mcp-server')).toEqual([]);
|
| 184 |
+
});
|
| 185 |
+
|
| 186 |
+
it('should return only tools matching the server name, sorted by name', async () => {
|
| 187 |
+
const server1Name = 'mcp-server-uno';
|
| 188 |
+
const server2Name = 'mcp-server-dos';
|
| 189 |
+
const mockCallable = {} as CallableTool;
|
| 190 |
+
const mcpTool1_c = new DiscoveredMCPTool(
|
| 191 |
+
mockCallable,
|
| 192 |
+
server1Name,
|
| 193 |
+
'zebra-tool',
|
| 194 |
+
'd1',
|
| 195 |
+
{},
|
| 196 |
+
);
|
| 197 |
+
const mcpTool1_a = new DiscoveredMCPTool(
|
| 198 |
+
mockCallable,
|
| 199 |
+
server1Name,
|
| 200 |
+
'apple-tool',
|
| 201 |
+
'd2',
|
| 202 |
+
{},
|
| 203 |
+
);
|
| 204 |
+
const mcpTool1_b = new DiscoveredMCPTool(
|
| 205 |
+
mockCallable,
|
| 206 |
+
server1Name,
|
| 207 |
+
'banana-tool',
|
| 208 |
+
'd3',
|
| 209 |
+
{},
|
| 210 |
+
);
|
| 211 |
+
|
| 212 |
+
const mcpTool2 = new DiscoveredMCPTool(
|
| 213 |
+
mockCallable,
|
| 214 |
+
server2Name,
|
| 215 |
+
'tool-on-server2',
|
| 216 |
+
'd4',
|
| 217 |
+
{},
|
| 218 |
+
);
|
| 219 |
+
const nonMcpTool = new MockTool('regular-tool');
|
| 220 |
+
|
| 221 |
+
toolRegistry.registerTool(mcpTool1_c);
|
| 222 |
+
toolRegistry.registerTool(mcpTool1_a);
|
| 223 |
+
toolRegistry.registerTool(mcpTool1_b);
|
| 224 |
+
toolRegistry.registerTool(mcpTool2);
|
| 225 |
+
toolRegistry.registerTool(nonMcpTool);
|
| 226 |
+
|
| 227 |
+
const toolsFromServer1 = toolRegistry.getToolsByServer(server1Name);
|
| 228 |
+
const toolNames = toolsFromServer1.map((t) => t.name);
|
| 229 |
+
|
| 230 |
+
// Assert that the array has the correct tools and is sorted by name
|
| 231 |
+
expect(toolsFromServer1).toHaveLength(3);
|
| 232 |
+
expect(toolNames).toEqual(['apple-tool', 'banana-tool', 'zebra-tool']);
|
| 233 |
+
|
| 234 |
+
// Assert that all returned tools are indeed from the correct server
|
| 235 |
+
for (const tool of toolsFromServer1) {
|
| 236 |
+
expect((tool as DiscoveredMCPTool).serverName).toBe(server1Name);
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
// Assert that the other server's tools are returned correctly
|
| 240 |
+
const toolsFromServer2 = toolRegistry.getToolsByServer(server2Name);
|
| 241 |
+
expect(toolsFromServer2).toHaveLength(1);
|
| 242 |
+
expect(toolsFromServer2[0].name).toBe(mcpTool2.name);
|
| 243 |
+
});
|
| 244 |
+
});
|
| 245 |
+
|
| 246 |
+
describe('discoverTools', () => {
|
| 247 |
+
it('should will preserve tool parametersJsonSchema during discovery from command', async () => {
|
| 248 |
+
const discoveryCommand = 'my-discovery-command';
|
| 249 |
+
mockConfigGetToolDiscoveryCommand.mockReturnValue(discoveryCommand);
|
| 250 |
+
|
| 251 |
+
const unsanitizedToolDeclaration: FunctionDeclaration = {
|
| 252 |
+
name: 'tool-with-bad-format',
|
| 253 |
+
description: 'A tool with an invalid format property',
|
| 254 |
+
parametersJsonSchema: {
|
| 255 |
+
type: 'object',
|
| 256 |
+
properties: {
|
| 257 |
+
some_string: {
|
| 258 |
+
type: 'string',
|
| 259 |
+
format: 'uuid', // This is an unsupported format
|
| 260 |
+
},
|
| 261 |
+
},
|
| 262 |
+
},
|
| 263 |
+
};
|
| 264 |
+
|
| 265 |
+
const mockSpawn = vi.mocked(spawn);
|
| 266 |
+
const mockChildProcess = {
|
| 267 |
+
stdout: { on: vi.fn() },
|
| 268 |
+
stderr: { on: vi.fn() },
|
| 269 |
+
on: vi.fn(),
|
| 270 |
+
};
|
| 271 |
+
mockSpawn.mockReturnValue(mockChildProcess as any);
|
| 272 |
+
|
| 273 |
+
// Simulate stdout data
|
| 274 |
+
mockChildProcess.stdout.on.mockImplementation((event, callback) => {
|
| 275 |
+
if (event === 'data') {
|
| 276 |
+
callback(
|
| 277 |
+
Buffer.from(
|
| 278 |
+
JSON.stringify([
|
| 279 |
+
{ function_declarations: [unsanitizedToolDeclaration] },
|
| 280 |
+
]),
|
| 281 |
+
),
|
| 282 |
+
);
|
| 283 |
+
}
|
| 284 |
+
return mockChildProcess as any;
|
| 285 |
+
});
|
| 286 |
+
|
| 287 |
+
// Simulate process close
|
| 288 |
+
mockChildProcess.on.mockImplementation((event, callback) => {
|
| 289 |
+
if (event === 'close') {
|
| 290 |
+
callback(0);
|
| 291 |
+
}
|
| 292 |
+
return mockChildProcess as any;
|
| 293 |
+
});
|
| 294 |
+
|
| 295 |
+
await toolRegistry.discoverAllTools();
|
| 296 |
+
|
| 297 |
+
const discoveredTool = toolRegistry.getTool('tool-with-bad-format');
|
| 298 |
+
expect(discoveredTool).toBeDefined();
|
| 299 |
+
|
| 300 |
+
const registeredParams = (discoveredTool as DiscoveredTool).schema
|
| 301 |
+
.parametersJsonSchema;
|
| 302 |
+
expect(registeredParams).toStrictEqual({
|
| 303 |
+
type: 'object',
|
| 304 |
+
properties: {
|
| 305 |
+
some_string: {
|
| 306 |
+
type: 'string',
|
| 307 |
+
format: 'uuid',
|
| 308 |
+
},
|
| 309 |
+
},
|
| 310 |
+
});
|
| 311 |
+
});
|
| 312 |
+
|
| 313 |
+
it('should discover tools using MCP servers defined in getMcpServers', async () => {
|
| 314 |
+
const discoverSpy = vi.spyOn(
|
| 315 |
+
McpClientManager.prototype,
|
| 316 |
+
'discoverAllMcpTools',
|
| 317 |
+
);
|
| 318 |
+
mockConfigGetToolDiscoveryCommand.mockReturnValue(undefined);
|
| 319 |
+
vi.spyOn(config, 'getMcpServerCommand').mockReturnValue(undefined);
|
| 320 |
+
const mcpServerConfigVal = {
|
| 321 |
+
'my-mcp-server': {
|
| 322 |
+
command: 'mcp-server-cmd',
|
| 323 |
+
args: ['--port', '1234'],
|
| 324 |
+
trust: true,
|
| 325 |
+
},
|
| 326 |
+
};
|
| 327 |
+
vi.spyOn(config, 'getMcpServers').mockReturnValue(mcpServerConfigVal);
|
| 328 |
+
|
| 329 |
+
await toolRegistry.discoverAllTools();
|
| 330 |
+
|
| 331 |
+
expect(discoverSpy).toHaveBeenCalled();
|
| 332 |
+
});
|
| 333 |
+
});
|
| 334 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/tool-registry.ts
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { FunctionDeclaration } from '@google/genai';
|
| 8 |
+
import {
|
| 9 |
+
AnyDeclarativeTool,
|
| 10 |
+
Kind,
|
| 11 |
+
ToolResult,
|
| 12 |
+
BaseDeclarativeTool,
|
| 13 |
+
BaseToolInvocation,
|
| 14 |
+
ToolInvocation,
|
| 15 |
+
} from './tools.js';
|
| 16 |
+
import { Config } from '../config/config.js';
|
| 17 |
+
import { spawn } from 'node:child_process';
|
| 18 |
+
import { StringDecoder } from 'node:string_decoder';
|
| 19 |
+
import { connectAndDiscover } from './mcp-client.js';
|
| 20 |
+
import { McpClientManager } from './mcp-client-manager.js';
|
| 21 |
+
import { DiscoveredMCPTool } from './mcp-tool.js';
|
| 22 |
+
import { parse } from 'shell-quote';
|
| 23 |
+
|
| 24 |
+
type ToolParams = Record<string, unknown>;
|
| 25 |
+
|
| 26 |
+
class DiscoveredToolInvocation extends BaseToolInvocation<
|
| 27 |
+
ToolParams,
|
| 28 |
+
ToolResult
|
| 29 |
+
> {
|
| 30 |
+
constructor(
|
| 31 |
+
private readonly config: Config,
|
| 32 |
+
private readonly toolName: string,
|
| 33 |
+
params: ToolParams,
|
| 34 |
+
) {
|
| 35 |
+
super(params);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
getDescription(): string {
|
| 39 |
+
return `Calling discovered tool: ${this.toolName}`;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
async execute(
|
| 43 |
+
_signal: AbortSignal,
|
| 44 |
+
_updateOutput?: (output: string) => void,
|
| 45 |
+
): Promise<ToolResult> {
|
| 46 |
+
const callCommand = this.config.getToolCallCommand()!;
|
| 47 |
+
const child = spawn(callCommand, [this.toolName]);
|
| 48 |
+
child.stdin.write(JSON.stringify(this.params));
|
| 49 |
+
child.stdin.end();
|
| 50 |
+
|
| 51 |
+
let stdout = '';
|
| 52 |
+
let stderr = '';
|
| 53 |
+
let error: Error | null = null;
|
| 54 |
+
let code: number | null = null;
|
| 55 |
+
let signal: NodeJS.Signals | null = null;
|
| 56 |
+
|
| 57 |
+
await new Promise<void>((resolve) => {
|
| 58 |
+
const onStdout = (data: Buffer) => {
|
| 59 |
+
stdout += data?.toString();
|
| 60 |
+
};
|
| 61 |
+
|
| 62 |
+
const onStderr = (data: Buffer) => {
|
| 63 |
+
stderr += data?.toString();
|
| 64 |
+
};
|
| 65 |
+
|
| 66 |
+
const onError = (err: Error) => {
|
| 67 |
+
error = err;
|
| 68 |
+
};
|
| 69 |
+
|
| 70 |
+
const onClose = (
|
| 71 |
+
_code: number | null,
|
| 72 |
+
_signal: NodeJS.Signals | null,
|
| 73 |
+
) => {
|
| 74 |
+
code = _code;
|
| 75 |
+
signal = _signal;
|
| 76 |
+
cleanup();
|
| 77 |
+
resolve();
|
| 78 |
+
};
|
| 79 |
+
|
| 80 |
+
const cleanup = () => {
|
| 81 |
+
child.stdout.removeListener('data', onStdout);
|
| 82 |
+
child.stderr.removeListener('data', onStderr);
|
| 83 |
+
child.removeListener('error', onError);
|
| 84 |
+
child.removeListener('close', onClose);
|
| 85 |
+
if (child.connected) {
|
| 86 |
+
child.disconnect();
|
| 87 |
+
}
|
| 88 |
+
};
|
| 89 |
+
|
| 90 |
+
child.stdout.on('data', onStdout);
|
| 91 |
+
child.stderr.on('data', onStderr);
|
| 92 |
+
child.on('error', onError);
|
| 93 |
+
child.on('close', onClose);
|
| 94 |
+
});
|
| 95 |
+
|
| 96 |
+
// if there is any error, non-zero exit code, signal, or stderr, return error details instead of stdout
|
| 97 |
+
if (error || code !== 0 || signal || stderr) {
|
| 98 |
+
const llmContent = [
|
| 99 |
+
`Stdout: ${stdout || '(empty)'}`,
|
| 100 |
+
`Stderr: ${stderr || '(empty)'}`,
|
| 101 |
+
`Error: ${error ?? '(none)'}`,
|
| 102 |
+
`Exit Code: ${code ?? '(none)'}`,
|
| 103 |
+
`Signal: ${signal ?? '(none)'}`,
|
| 104 |
+
].join('\n');
|
| 105 |
+
return {
|
| 106 |
+
llmContent,
|
| 107 |
+
returnDisplay: llmContent,
|
| 108 |
+
};
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
return {
|
| 112 |
+
llmContent: stdout,
|
| 113 |
+
returnDisplay: stdout,
|
| 114 |
+
};
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
export class DiscoveredTool extends BaseDeclarativeTool<
|
| 119 |
+
ToolParams,
|
| 120 |
+
ToolResult
|
| 121 |
+
> {
|
| 122 |
+
constructor(
|
| 123 |
+
private readonly config: Config,
|
| 124 |
+
name: string,
|
| 125 |
+
override readonly description: string,
|
| 126 |
+
override readonly parameterSchema: Record<string, unknown>,
|
| 127 |
+
) {
|
| 128 |
+
const discoveryCmd = config.getToolDiscoveryCommand()!;
|
| 129 |
+
const callCommand = config.getToolCallCommand()!;
|
| 130 |
+
description += `
|
| 131 |
+
|
| 132 |
+
This tool was discovered from the project by executing the command \`${discoveryCmd}\` on project root.
|
| 133 |
+
When called, this tool will execute the command \`${callCommand} ${name}\` on project root.
|
| 134 |
+
Tool discovery and call commands can be configured in project or user settings.
|
| 135 |
+
|
| 136 |
+
When called, the tool call command is executed as a subprocess.
|
| 137 |
+
On success, tool output is returned as a json string.
|
| 138 |
+
Otherwise, the following information is returned:
|
| 139 |
+
|
| 140 |
+
Stdout: Output on stdout stream. Can be \`(empty)\` or partial.
|
| 141 |
+
Stderr: Output on stderr stream. Can be \`(empty)\` or partial.
|
| 142 |
+
Error: Error or \`(none)\` if no error was reported for the subprocess.
|
| 143 |
+
Exit Code: Exit code or \`(none)\` if terminated by signal.
|
| 144 |
+
Signal: Signal number or \`(none)\` if no signal was received.
|
| 145 |
+
`;
|
| 146 |
+
super(
|
| 147 |
+
name,
|
| 148 |
+
name,
|
| 149 |
+
description,
|
| 150 |
+
Kind.Other,
|
| 151 |
+
parameterSchema,
|
| 152 |
+
false, // isOutputMarkdown
|
| 153 |
+
false, // canUpdateOutput
|
| 154 |
+
);
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
protected createInvocation(
|
| 158 |
+
params: ToolParams,
|
| 159 |
+
): ToolInvocation<ToolParams, ToolResult> {
|
| 160 |
+
return new DiscoveredToolInvocation(this.config, this.name, params);
|
| 161 |
+
}
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
export class ToolRegistry {
|
| 165 |
+
private tools: Map<string, AnyDeclarativeTool> = new Map();
|
| 166 |
+
private config: Config;
|
| 167 |
+
private mcpClientManager: McpClientManager;
|
| 168 |
+
|
| 169 |
+
constructor(config: Config) {
|
| 170 |
+
this.config = config;
|
| 171 |
+
this.mcpClientManager = new McpClientManager(
|
| 172 |
+
this.config.getMcpServers() ?? {},
|
| 173 |
+
this.config.getMcpServerCommand(),
|
| 174 |
+
this,
|
| 175 |
+
this.config.getPromptRegistry(),
|
| 176 |
+
this.config.getDebugMode(),
|
| 177 |
+
this.config.getWorkspaceContext(),
|
| 178 |
+
);
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
/**
|
| 182 |
+
* Registers a tool definition.
|
| 183 |
+
* @param tool - The tool object containing schema and execution logic.
|
| 184 |
+
*/
|
| 185 |
+
registerTool(tool: AnyDeclarativeTool): void {
|
| 186 |
+
if (this.tools.has(tool.name)) {
|
| 187 |
+
if (tool instanceof DiscoveredMCPTool) {
|
| 188 |
+
tool = tool.asFullyQualifiedTool();
|
| 189 |
+
} else {
|
| 190 |
+
// Decide on behavior: throw error, log warning, or allow overwrite
|
| 191 |
+
console.warn(
|
| 192 |
+
`Tool with name "${tool.name}" is already registered. Overwriting.`,
|
| 193 |
+
);
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
this.tools.set(tool.name, tool);
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
private removeDiscoveredTools(): void {
|
| 200 |
+
for (const tool of this.tools.values()) {
|
| 201 |
+
if (tool instanceof DiscoveredTool || tool instanceof DiscoveredMCPTool) {
|
| 202 |
+
this.tools.delete(tool.name);
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
/**
|
| 208 |
+
* Removes all tools from a specific MCP server.
|
| 209 |
+
* @param serverName The name of the server to remove tools from.
|
| 210 |
+
*/
|
| 211 |
+
removeMcpToolsByServer(serverName: string): void {
|
| 212 |
+
for (const [name, tool] of this.tools.entries()) {
|
| 213 |
+
if (tool instanceof DiscoveredMCPTool && tool.serverName === serverName) {
|
| 214 |
+
this.tools.delete(name);
|
| 215 |
+
}
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
/**
|
| 220 |
+
* Discovers tools from project (if available and configured).
|
| 221 |
+
* Can be called multiple times to update discovered tools.
|
| 222 |
+
* This will discover tools from the command line and from MCP servers.
|
| 223 |
+
*/
|
| 224 |
+
async discoverAllTools(): Promise<void> {
|
| 225 |
+
// remove any previously discovered tools
|
| 226 |
+
this.removeDiscoveredTools();
|
| 227 |
+
|
| 228 |
+
this.config.getPromptRegistry().clear();
|
| 229 |
+
|
| 230 |
+
await this.discoverAndRegisterToolsFromCommand();
|
| 231 |
+
|
| 232 |
+
// discover tools using MCP servers, if configured
|
| 233 |
+
await this.mcpClientManager.discoverAllMcpTools();
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
/**
|
| 237 |
+
* Discovers tools from project (if available and configured).
|
| 238 |
+
* Can be called multiple times to update discovered tools.
|
| 239 |
+
* This will NOT discover tools from the command line, only from MCP servers.
|
| 240 |
+
*/
|
| 241 |
+
async discoverMcpTools(): Promise<void> {
|
| 242 |
+
// remove any previously discovered tools
|
| 243 |
+
this.removeDiscoveredTools();
|
| 244 |
+
|
| 245 |
+
this.config.getPromptRegistry().clear();
|
| 246 |
+
|
| 247 |
+
// discover tools using MCP servers, if configured
|
| 248 |
+
await this.mcpClientManager.discoverAllMcpTools();
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
/**
|
| 252 |
+
* Restarts all MCP servers and re-discovers tools.
|
| 253 |
+
*/
|
| 254 |
+
async restartMcpServers(): Promise<void> {
|
| 255 |
+
await this.discoverMcpTools();
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
/**
|
| 259 |
+
* Discover or re-discover tools for a single MCP server.
|
| 260 |
+
* @param serverName - The name of the server to discover tools from.
|
| 261 |
+
*/
|
| 262 |
+
async discoverToolsForServer(serverName: string): Promise<void> {
|
| 263 |
+
// Remove any previously discovered tools from this server
|
| 264 |
+
for (const [name, tool] of this.tools.entries()) {
|
| 265 |
+
if (tool instanceof DiscoveredMCPTool && tool.serverName === serverName) {
|
| 266 |
+
this.tools.delete(name);
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
this.config.getPromptRegistry().removePromptsByServer(serverName);
|
| 271 |
+
|
| 272 |
+
const mcpServers = this.config.getMcpServers() ?? {};
|
| 273 |
+
const serverConfig = mcpServers[serverName];
|
| 274 |
+
if (serverConfig) {
|
| 275 |
+
await connectAndDiscover(
|
| 276 |
+
serverName,
|
| 277 |
+
serverConfig,
|
| 278 |
+
this,
|
| 279 |
+
this.config.getPromptRegistry(),
|
| 280 |
+
this.config.getDebugMode(),
|
| 281 |
+
this.config.getWorkspaceContext(),
|
| 282 |
+
);
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
private async discoverAndRegisterToolsFromCommand(): Promise<void> {
|
| 287 |
+
const discoveryCmd = this.config.getToolDiscoveryCommand();
|
| 288 |
+
if (!discoveryCmd) {
|
| 289 |
+
return;
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
try {
|
| 293 |
+
const cmdParts = parse(discoveryCmd);
|
| 294 |
+
if (cmdParts.length === 0) {
|
| 295 |
+
throw new Error(
|
| 296 |
+
'Tool discovery command is empty or contains only whitespace.',
|
| 297 |
+
);
|
| 298 |
+
}
|
| 299 |
+
const proc = spawn(cmdParts[0] as string, cmdParts.slice(1) as string[]);
|
| 300 |
+
let stdout = '';
|
| 301 |
+
const stdoutDecoder = new StringDecoder('utf8');
|
| 302 |
+
let stderr = '';
|
| 303 |
+
const stderrDecoder = new StringDecoder('utf8');
|
| 304 |
+
let sizeLimitExceeded = false;
|
| 305 |
+
const MAX_STDOUT_SIZE = 10 * 1024 * 1024; // 10MB limit
|
| 306 |
+
const MAX_STDERR_SIZE = 10 * 1024 * 1024; // 10MB limit
|
| 307 |
+
|
| 308 |
+
let stdoutByteLength = 0;
|
| 309 |
+
let stderrByteLength = 0;
|
| 310 |
+
|
| 311 |
+
proc.stdout.on('data', (data) => {
|
| 312 |
+
if (sizeLimitExceeded) return;
|
| 313 |
+
if (stdoutByteLength + data.length > MAX_STDOUT_SIZE) {
|
| 314 |
+
sizeLimitExceeded = true;
|
| 315 |
+
proc.kill();
|
| 316 |
+
return;
|
| 317 |
+
}
|
| 318 |
+
stdoutByteLength += data.length;
|
| 319 |
+
stdout += stdoutDecoder.write(data);
|
| 320 |
+
});
|
| 321 |
+
|
| 322 |
+
proc.stderr.on('data', (data) => {
|
| 323 |
+
if (sizeLimitExceeded) return;
|
| 324 |
+
if (stderrByteLength + data.length > MAX_STDERR_SIZE) {
|
| 325 |
+
sizeLimitExceeded = true;
|
| 326 |
+
proc.kill();
|
| 327 |
+
return;
|
| 328 |
+
}
|
| 329 |
+
stderrByteLength += data.length;
|
| 330 |
+
stderr += stderrDecoder.write(data);
|
| 331 |
+
});
|
| 332 |
+
|
| 333 |
+
await new Promise<void>((resolve, reject) => {
|
| 334 |
+
proc.on('error', reject);
|
| 335 |
+
proc.on('close', (code) => {
|
| 336 |
+
stdout += stdoutDecoder.end();
|
| 337 |
+
stderr += stderrDecoder.end();
|
| 338 |
+
|
| 339 |
+
if (sizeLimitExceeded) {
|
| 340 |
+
return reject(
|
| 341 |
+
new Error(
|
| 342 |
+
`Tool discovery command output exceeded size limit of ${MAX_STDOUT_SIZE} bytes.`,
|
| 343 |
+
),
|
| 344 |
+
);
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
if (code !== 0) {
|
| 348 |
+
console.error(`Command failed with code ${code}`);
|
| 349 |
+
console.error(stderr);
|
| 350 |
+
return reject(
|
| 351 |
+
new Error(`Tool discovery command failed with exit code ${code}`),
|
| 352 |
+
);
|
| 353 |
+
}
|
| 354 |
+
resolve();
|
| 355 |
+
});
|
| 356 |
+
});
|
| 357 |
+
|
| 358 |
+
// execute discovery command and extract function declarations (w/ or w/o "tool" wrappers)
|
| 359 |
+
const functions: FunctionDeclaration[] = [];
|
| 360 |
+
const discoveredItems = JSON.parse(stdout.trim());
|
| 361 |
+
|
| 362 |
+
if (!discoveredItems || !Array.isArray(discoveredItems)) {
|
| 363 |
+
throw new Error(
|
| 364 |
+
'Tool discovery command did not return a JSON array of tools.',
|
| 365 |
+
);
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
for (const tool of discoveredItems) {
|
| 369 |
+
if (tool && typeof tool === 'object') {
|
| 370 |
+
if (Array.isArray(tool['function_declarations'])) {
|
| 371 |
+
functions.push(...tool['function_declarations']);
|
| 372 |
+
} else if (Array.isArray(tool['functionDeclarations'])) {
|
| 373 |
+
functions.push(...tool['functionDeclarations']);
|
| 374 |
+
} else if (tool['name']) {
|
| 375 |
+
functions.push(tool as FunctionDeclaration);
|
| 376 |
+
}
|
| 377 |
+
}
|
| 378 |
+
}
|
| 379 |
+
// register each function as a tool
|
| 380 |
+
for (const func of functions) {
|
| 381 |
+
if (!func.name) {
|
| 382 |
+
console.warn('Discovered a tool with no name. Skipping.');
|
| 383 |
+
continue;
|
| 384 |
+
}
|
| 385 |
+
const parameters =
|
| 386 |
+
func.parametersJsonSchema &&
|
| 387 |
+
typeof func.parametersJsonSchema === 'object' &&
|
| 388 |
+
!Array.isArray(func.parametersJsonSchema)
|
| 389 |
+
? func.parametersJsonSchema
|
| 390 |
+
: {};
|
| 391 |
+
this.registerTool(
|
| 392 |
+
new DiscoveredTool(
|
| 393 |
+
this.config,
|
| 394 |
+
func.name,
|
| 395 |
+
func.description ?? '',
|
| 396 |
+
parameters as Record<string, unknown>,
|
| 397 |
+
),
|
| 398 |
+
);
|
| 399 |
+
}
|
| 400 |
+
} catch (e) {
|
| 401 |
+
console.error(`Tool discovery command "${discoveryCmd}" failed:`, e);
|
| 402 |
+
throw e;
|
| 403 |
+
}
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
/**
|
| 407 |
+
* Retrieves the list of tool schemas (FunctionDeclaration array).
|
| 408 |
+
* Extracts the declarations from the ToolListUnion structure.
|
| 409 |
+
* Includes discovered (vs registered) tools if configured.
|
| 410 |
+
* @returns An array of FunctionDeclarations.
|
| 411 |
+
*/
|
| 412 |
+
getFunctionDeclarations(): FunctionDeclaration[] {
|
| 413 |
+
const declarations: FunctionDeclaration[] = [];
|
| 414 |
+
this.tools.forEach((tool) => {
|
| 415 |
+
declarations.push(tool.schema);
|
| 416 |
+
});
|
| 417 |
+
return declarations;
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
/**
|
| 421 |
+
* Retrieves a filtered list of tool schemas based on a list of tool names.
|
| 422 |
+
* @param toolNames - An array of tool names to include.
|
| 423 |
+
* @returns An array of FunctionDeclarations for the specified tools.
|
| 424 |
+
*/
|
| 425 |
+
getFunctionDeclarationsFiltered(toolNames: string[]): FunctionDeclaration[] {
|
| 426 |
+
const declarations: FunctionDeclaration[] = [];
|
| 427 |
+
for (const name of toolNames) {
|
| 428 |
+
const tool = this.tools.get(name);
|
| 429 |
+
if (tool) {
|
| 430 |
+
declarations.push(tool.schema);
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
return declarations;
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
/**
|
| 437 |
+
* Returns an array of all registered and discovered tool instances.
|
| 438 |
+
*/
|
| 439 |
+
getAllTools(): AnyDeclarativeTool[] {
|
| 440 |
+
return Array.from(this.tools.values()).sort((a, b) =>
|
| 441 |
+
a.displayName.localeCompare(b.displayName),
|
| 442 |
+
);
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
/**
|
| 446 |
+
* Returns an array of tools registered from a specific MCP server.
|
| 447 |
+
*/
|
| 448 |
+
getToolsByServer(serverName: string): AnyDeclarativeTool[] {
|
| 449 |
+
const serverTools: AnyDeclarativeTool[] = [];
|
| 450 |
+
for (const tool of this.tools.values()) {
|
| 451 |
+
if ((tool as DiscoveredMCPTool)?.serverName === serverName) {
|
| 452 |
+
serverTools.push(tool);
|
| 453 |
+
}
|
| 454 |
+
}
|
| 455 |
+
return serverTools.sort((a, b) => a.name.localeCompare(b.name));
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
/**
|
| 459 |
+
* Get the definition of a specific tool.
|
| 460 |
+
*/
|
| 461 |
+
getTool(name: string): AnyDeclarativeTool | undefined {
|
| 462 |
+
return this.tools.get(name);
|
| 463 |
+
}
|
| 464 |
+
}
|
projects/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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, vi } from 'vitest';
|
| 8 |
+
import {
|
| 9 |
+
DeclarativeTool,
|
| 10 |
+
hasCycleInSchema,
|
| 11 |
+
Kind,
|
| 12 |
+
ToolInvocation,
|
| 13 |
+
ToolResult,
|
| 14 |
+
} from './tools.js';
|
| 15 |
+
import { ToolErrorType } from './tool-error.js';
|
| 16 |
+
|
| 17 |
+
class TestToolInvocation implements ToolInvocation<object, ToolResult> {
|
| 18 |
+
constructor(
|
| 19 |
+
readonly params: object,
|
| 20 |
+
private readonly executeFn: () => Promise<ToolResult>,
|
| 21 |
+
) {}
|
| 22 |
+
|
| 23 |
+
getDescription(): string {
|
| 24 |
+
return 'A test invocation';
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
toolLocations() {
|
| 28 |
+
return [];
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
shouldConfirmExecute(): Promise<false> {
|
| 32 |
+
return Promise.resolve(false);
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
execute(): Promise<ToolResult> {
|
| 36 |
+
return this.executeFn();
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
class TestTool extends DeclarativeTool<object, ToolResult> {
|
| 41 |
+
private readonly buildFn: (params: object) => TestToolInvocation;
|
| 42 |
+
|
| 43 |
+
constructor(buildFn: (params: object) => TestToolInvocation) {
|
| 44 |
+
super('test-tool', 'Test Tool', 'A tool for testing', Kind.Other, {});
|
| 45 |
+
this.buildFn = buildFn;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
build(params: object): ToolInvocation<object, ToolResult> {
|
| 49 |
+
return this.buildFn(params);
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
describe('DeclarativeTool', () => {
|
| 54 |
+
describe('validateBuildAndExecute', () => {
|
| 55 |
+
const abortSignal = new AbortController().signal;
|
| 56 |
+
|
| 57 |
+
it('should return INVALID_TOOL_PARAMS error if build fails', async () => {
|
| 58 |
+
const buildError = new Error('Invalid build parameters');
|
| 59 |
+
const buildFn = vi.fn().mockImplementation(() => {
|
| 60 |
+
throw buildError;
|
| 61 |
+
});
|
| 62 |
+
const tool = new TestTool(buildFn);
|
| 63 |
+
const params = { foo: 'bar' };
|
| 64 |
+
|
| 65 |
+
const result = await tool.validateBuildAndExecute(params, abortSignal);
|
| 66 |
+
|
| 67 |
+
expect(buildFn).toHaveBeenCalledWith(params);
|
| 68 |
+
expect(result).toEqual({
|
| 69 |
+
llmContent: `Error: Invalid parameters provided. Reason: ${buildError.message}`,
|
| 70 |
+
returnDisplay: buildError.message,
|
| 71 |
+
error: {
|
| 72 |
+
message: buildError.message,
|
| 73 |
+
type: ToolErrorType.INVALID_TOOL_PARAMS,
|
| 74 |
+
},
|
| 75 |
+
});
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
it('should return EXECUTION_FAILED error if execute fails', async () => {
|
| 79 |
+
const executeError = new Error('Execution failed');
|
| 80 |
+
const executeFn = vi.fn().mockRejectedValue(executeError);
|
| 81 |
+
const invocation = new TestToolInvocation({}, executeFn);
|
| 82 |
+
const buildFn = vi.fn().mockReturnValue(invocation);
|
| 83 |
+
const tool = new TestTool(buildFn);
|
| 84 |
+
const params = { foo: 'bar' };
|
| 85 |
+
|
| 86 |
+
const result = await tool.validateBuildAndExecute(params, abortSignal);
|
| 87 |
+
|
| 88 |
+
expect(buildFn).toHaveBeenCalledWith(params);
|
| 89 |
+
expect(executeFn).toHaveBeenCalled();
|
| 90 |
+
expect(result).toEqual({
|
| 91 |
+
llmContent: `Error: Tool call execution failed. Reason: ${executeError.message}`,
|
| 92 |
+
returnDisplay: executeError.message,
|
| 93 |
+
error: {
|
| 94 |
+
message: executeError.message,
|
| 95 |
+
type: ToolErrorType.EXECUTION_FAILED,
|
| 96 |
+
},
|
| 97 |
+
});
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
it('should return the result of execute on success', async () => {
|
| 101 |
+
const successResult: ToolResult = {
|
| 102 |
+
llmContent: 'Success!',
|
| 103 |
+
returnDisplay: 'Success!',
|
| 104 |
+
summary: 'Tool executed successfully',
|
| 105 |
+
};
|
| 106 |
+
const executeFn = vi.fn().mockResolvedValue(successResult);
|
| 107 |
+
const invocation = new TestToolInvocation({}, executeFn);
|
| 108 |
+
const buildFn = vi.fn().mockReturnValue(invocation);
|
| 109 |
+
const tool = new TestTool(buildFn);
|
| 110 |
+
const params = { foo: 'bar' };
|
| 111 |
+
|
| 112 |
+
const result = await tool.validateBuildAndExecute(params, abortSignal);
|
| 113 |
+
|
| 114 |
+
expect(buildFn).toHaveBeenCalledWith(params);
|
| 115 |
+
expect(executeFn).toHaveBeenCalled();
|
| 116 |
+
expect(result).toEqual(successResult);
|
| 117 |
+
});
|
| 118 |
+
});
|
| 119 |
+
});
|
| 120 |
+
|
| 121 |
+
describe('hasCycleInSchema', () => {
|
| 122 |
+
it('should detect a simple direct cycle', () => {
|
| 123 |
+
const schema = {
|
| 124 |
+
properties: {
|
| 125 |
+
data: {
|
| 126 |
+
$ref: '#/properties/data',
|
| 127 |
+
},
|
| 128 |
+
},
|
| 129 |
+
};
|
| 130 |
+
expect(hasCycleInSchema(schema)).toBe(true);
|
| 131 |
+
});
|
| 132 |
+
|
| 133 |
+
it('should detect a cycle from object properties referencing parent properties', () => {
|
| 134 |
+
const schema = {
|
| 135 |
+
type: 'object',
|
| 136 |
+
properties: {
|
| 137 |
+
data: {
|
| 138 |
+
type: 'object',
|
| 139 |
+
properties: {
|
| 140 |
+
child: { $ref: '#/properties/data' },
|
| 141 |
+
},
|
| 142 |
+
},
|
| 143 |
+
},
|
| 144 |
+
};
|
| 145 |
+
expect(hasCycleInSchema(schema)).toBe(true);
|
| 146 |
+
});
|
| 147 |
+
|
| 148 |
+
it('should detect a cycle from array items referencing parent properties', () => {
|
| 149 |
+
const schema = {
|
| 150 |
+
type: 'object',
|
| 151 |
+
properties: {
|
| 152 |
+
data: {
|
| 153 |
+
type: 'array',
|
| 154 |
+
items: {
|
| 155 |
+
type: 'object',
|
| 156 |
+
properties: {
|
| 157 |
+
child: { $ref: '#/properties/data/items' },
|
| 158 |
+
},
|
| 159 |
+
},
|
| 160 |
+
},
|
| 161 |
+
},
|
| 162 |
+
};
|
| 163 |
+
expect(hasCycleInSchema(schema)).toBe(true);
|
| 164 |
+
});
|
| 165 |
+
|
| 166 |
+
it('should detect a cycle between sibling properties', () => {
|
| 167 |
+
const schema = {
|
| 168 |
+
type: 'object',
|
| 169 |
+
properties: {
|
| 170 |
+
a: {
|
| 171 |
+
type: 'object',
|
| 172 |
+
properties: {
|
| 173 |
+
child: { $ref: '#/properties/b' },
|
| 174 |
+
},
|
| 175 |
+
},
|
| 176 |
+
b: {
|
| 177 |
+
type: 'object',
|
| 178 |
+
properties: {
|
| 179 |
+
child: { $ref: '#/properties/a' },
|
| 180 |
+
},
|
| 181 |
+
},
|
| 182 |
+
},
|
| 183 |
+
};
|
| 184 |
+
expect(hasCycleInSchema(schema)).toBe(true);
|
| 185 |
+
});
|
| 186 |
+
|
| 187 |
+
it('should not detect a cycle in a valid schema', () => {
|
| 188 |
+
const schema = {
|
| 189 |
+
type: 'object',
|
| 190 |
+
properties: {
|
| 191 |
+
name: { type: 'string' },
|
| 192 |
+
address: { $ref: '#/definitions/address' },
|
| 193 |
+
},
|
| 194 |
+
definitions: {
|
| 195 |
+
address: {
|
| 196 |
+
type: 'object',
|
| 197 |
+
properties: {
|
| 198 |
+
street: { type: 'string' },
|
| 199 |
+
city: { type: 'string' },
|
| 200 |
+
},
|
| 201 |
+
},
|
| 202 |
+
},
|
| 203 |
+
};
|
| 204 |
+
expect(hasCycleInSchema(schema)).toBe(false);
|
| 205 |
+
});
|
| 206 |
+
|
| 207 |
+
it('should handle non-cyclic sibling refs', () => {
|
| 208 |
+
const schema = {
|
| 209 |
+
properties: {
|
| 210 |
+
a: { $ref: '#/definitions/stringDef' },
|
| 211 |
+
b: { $ref: '#/definitions/stringDef' },
|
| 212 |
+
},
|
| 213 |
+
definitions: {
|
| 214 |
+
stringDef: { type: 'string' },
|
| 215 |
+
},
|
| 216 |
+
};
|
| 217 |
+
expect(hasCycleInSchema(schema)).toBe(false);
|
| 218 |
+
});
|
| 219 |
+
|
| 220 |
+
it('should handle nested but not cyclic refs', () => {
|
| 221 |
+
const schema = {
|
| 222 |
+
properties: {
|
| 223 |
+
a: { $ref: '#/definitions/defA' },
|
| 224 |
+
},
|
| 225 |
+
definitions: {
|
| 226 |
+
defA: { properties: { b: { $ref: '#/definitions/defB' } } },
|
| 227 |
+
defB: { type: 'string' },
|
| 228 |
+
},
|
| 229 |
+
};
|
| 230 |
+
expect(hasCycleInSchema(schema)).toBe(false);
|
| 231 |
+
});
|
| 232 |
+
|
| 233 |
+
it('should return false for an empty schema', () => {
|
| 234 |
+
expect(hasCycleInSchema({})).toBe(false);
|
| 235 |
+
});
|
| 236 |
+
});
|
projects/ui/qwen-code/packages/core/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { FunctionDeclaration, PartListUnion } from '@google/genai';
|
| 8 |
+
import { ToolErrorType } from './tool-error.js';
|
| 9 |
+
import { DiffUpdateResult } from '../ide/ideContext.js';
|
| 10 |
+
import { SchemaValidator } from '../utils/schemaValidator.js';
|
| 11 |
+
|
| 12 |
+
/**
|
| 13 |
+
* Represents a validated and ready-to-execute tool call.
|
| 14 |
+
* An instance of this is created by a `ToolBuilder`.
|
| 15 |
+
*/
|
| 16 |
+
export interface ToolInvocation<
|
| 17 |
+
TParams extends object,
|
| 18 |
+
TResult extends ToolResult,
|
| 19 |
+
> {
|
| 20 |
+
/**
|
| 21 |
+
* The validated parameters for this specific invocation.
|
| 22 |
+
*/
|
| 23 |
+
params: TParams;
|
| 24 |
+
|
| 25 |
+
/**
|
| 26 |
+
* Gets a pre-execution description of the tool operation.
|
| 27 |
+
* @returns A markdown string describing what the tool will do.
|
| 28 |
+
*/
|
| 29 |
+
getDescription(): string;
|
| 30 |
+
|
| 31 |
+
/**
|
| 32 |
+
* Determines what file system paths the tool will affect.
|
| 33 |
+
* @returns A list of such paths.
|
| 34 |
+
*/
|
| 35 |
+
toolLocations(): ToolLocation[];
|
| 36 |
+
|
| 37 |
+
/**
|
| 38 |
+
* Determines if the tool should prompt for confirmation before execution.
|
| 39 |
+
* @returns Confirmation details or false if no confirmation is needed.
|
| 40 |
+
*/
|
| 41 |
+
shouldConfirmExecute(
|
| 42 |
+
abortSignal: AbortSignal,
|
| 43 |
+
): Promise<ToolCallConfirmationDetails | false>;
|
| 44 |
+
|
| 45 |
+
/**
|
| 46 |
+
* Executes the tool with the validated parameters.
|
| 47 |
+
* @param signal AbortSignal for tool cancellation.
|
| 48 |
+
* @param updateOutput Optional callback to stream output.
|
| 49 |
+
* @returns Result of the tool execution.
|
| 50 |
+
*/
|
| 51 |
+
execute(
|
| 52 |
+
signal: AbortSignal,
|
| 53 |
+
updateOutput?: (output: string) => void,
|
| 54 |
+
): Promise<TResult>;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/**
|
| 58 |
+
* A convenience base class for ToolInvocation.
|
| 59 |
+
*/
|
| 60 |
+
export abstract class BaseToolInvocation<
|
| 61 |
+
TParams extends object,
|
| 62 |
+
TResult extends ToolResult,
|
| 63 |
+
> implements ToolInvocation<TParams, TResult>
|
| 64 |
+
{
|
| 65 |
+
constructor(readonly params: TParams) {}
|
| 66 |
+
|
| 67 |
+
abstract getDescription(): string;
|
| 68 |
+
|
| 69 |
+
toolLocations(): ToolLocation[] {
|
| 70 |
+
return [];
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
shouldConfirmExecute(
|
| 74 |
+
_abortSignal: AbortSignal,
|
| 75 |
+
): Promise<ToolCallConfirmationDetails | false> {
|
| 76 |
+
return Promise.resolve(false);
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
abstract execute(
|
| 80 |
+
signal: AbortSignal,
|
| 81 |
+
updateOutput?: (output: string) => void,
|
| 82 |
+
): Promise<TResult>;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
/**
|
| 86 |
+
* A type alias for a tool invocation where the specific parameter and result types are not known.
|
| 87 |
+
*/
|
| 88 |
+
export type AnyToolInvocation = ToolInvocation<object, ToolResult>;
|
| 89 |
+
|
| 90 |
+
/**
|
| 91 |
+
* Interface for a tool builder that validates parameters and creates invocations.
|
| 92 |
+
*/
|
| 93 |
+
export interface ToolBuilder<
|
| 94 |
+
TParams extends object,
|
| 95 |
+
TResult extends ToolResult,
|
| 96 |
+
> {
|
| 97 |
+
/**
|
| 98 |
+
* The internal name of the tool (used for API calls).
|
| 99 |
+
*/
|
| 100 |
+
name: string;
|
| 101 |
+
|
| 102 |
+
/**
|
| 103 |
+
* The user-friendly display name of the tool.
|
| 104 |
+
*/
|
| 105 |
+
displayName: string;
|
| 106 |
+
|
| 107 |
+
/**
|
| 108 |
+
* Description of what the tool does.
|
| 109 |
+
*/
|
| 110 |
+
description: string;
|
| 111 |
+
|
| 112 |
+
/**
|
| 113 |
+
* The kind of tool for categorization and permissions
|
| 114 |
+
*/
|
| 115 |
+
kind: Kind;
|
| 116 |
+
|
| 117 |
+
/**
|
| 118 |
+
* Function declaration schema from @google/genai.
|
| 119 |
+
*/
|
| 120 |
+
schema: FunctionDeclaration;
|
| 121 |
+
|
| 122 |
+
/**
|
| 123 |
+
* Whether the tool's output should be rendered as markdown.
|
| 124 |
+
*/
|
| 125 |
+
isOutputMarkdown: boolean;
|
| 126 |
+
|
| 127 |
+
/**
|
| 128 |
+
* Whether the tool supports live (streaming) output.
|
| 129 |
+
*/
|
| 130 |
+
canUpdateOutput: boolean;
|
| 131 |
+
|
| 132 |
+
/**
|
| 133 |
+
* Validates raw parameters and builds a ready-to-execute invocation.
|
| 134 |
+
* @param params The raw, untrusted parameters from the model.
|
| 135 |
+
* @returns A valid `ToolInvocation` if successful. Throws an error if validation fails.
|
| 136 |
+
*/
|
| 137 |
+
build(params: TParams): ToolInvocation<TParams, TResult>;
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
/**
|
| 141 |
+
* New base class for tools that separates validation from execution.
|
| 142 |
+
* New tools should extend this class.
|
| 143 |
+
*/
|
| 144 |
+
export abstract class DeclarativeTool<
|
| 145 |
+
TParams extends object,
|
| 146 |
+
TResult extends ToolResult,
|
| 147 |
+
> implements ToolBuilder<TParams, TResult>
|
| 148 |
+
{
|
| 149 |
+
constructor(
|
| 150 |
+
readonly name: string,
|
| 151 |
+
readonly displayName: string,
|
| 152 |
+
readonly description: string,
|
| 153 |
+
readonly kind: Kind,
|
| 154 |
+
readonly parameterSchema: unknown,
|
| 155 |
+
readonly isOutputMarkdown: boolean = true,
|
| 156 |
+
readonly canUpdateOutput: boolean = false,
|
| 157 |
+
) {}
|
| 158 |
+
|
| 159 |
+
get schema(): FunctionDeclaration {
|
| 160 |
+
return {
|
| 161 |
+
name: this.name,
|
| 162 |
+
description: this.description,
|
| 163 |
+
parametersJsonSchema: this.parameterSchema,
|
| 164 |
+
};
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
/**
|
| 168 |
+
* Validates the raw tool parameters.
|
| 169 |
+
* Subclasses should override this to add custom validation logic
|
| 170 |
+
* beyond the JSON schema check.
|
| 171 |
+
* @param params The raw parameters from the model.
|
| 172 |
+
* @returns An error message string if invalid, null otherwise.
|
| 173 |
+
*/
|
| 174 |
+
validateToolParams(_params: TParams): string | null {
|
| 175 |
+
// Base implementation can be extended by subclasses.
|
| 176 |
+
return null;
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
/**
|
| 180 |
+
* The core of the new pattern. It validates parameters and, if successful,
|
| 181 |
+
* returns a `ToolInvocation` object that encapsulates the logic for the
|
| 182 |
+
* specific, validated call.
|
| 183 |
+
* @param params The raw, untrusted parameters from the model.
|
| 184 |
+
* @returns A `ToolInvocation` instance.
|
| 185 |
+
*/
|
| 186 |
+
abstract build(params: TParams): ToolInvocation<TParams, TResult>;
|
| 187 |
+
|
| 188 |
+
/**
|
| 189 |
+
* A convenience method that builds and executes the tool in one step.
|
| 190 |
+
* Throws an error if validation fails.
|
| 191 |
+
* @param params The raw, untrusted parameters from the model.
|
| 192 |
+
* @param signal AbortSignal for tool cancellation.
|
| 193 |
+
* @param updateOutput Optional callback to stream output.
|
| 194 |
+
* @returns The result of the tool execution.
|
| 195 |
+
*/
|
| 196 |
+
async buildAndExecute(
|
| 197 |
+
params: TParams,
|
| 198 |
+
signal: AbortSignal,
|
| 199 |
+
updateOutput?: (output: string) => void,
|
| 200 |
+
): Promise<TResult> {
|
| 201 |
+
const invocation = this.build(params);
|
| 202 |
+
return invocation.execute(signal, updateOutput);
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
/**
|
| 206 |
+
* Similar to `build` but never throws.
|
| 207 |
+
* @param params The raw, untrusted parameters from the model.
|
| 208 |
+
* @returns A `ToolInvocation` instance.
|
| 209 |
+
*/
|
| 210 |
+
private silentBuild(
|
| 211 |
+
params: TParams,
|
| 212 |
+
): ToolInvocation<TParams, TResult> | Error {
|
| 213 |
+
try {
|
| 214 |
+
return this.build(params);
|
| 215 |
+
} catch (e) {
|
| 216 |
+
if (e instanceof Error) {
|
| 217 |
+
return e;
|
| 218 |
+
}
|
| 219 |
+
return new Error(String(e));
|
| 220 |
+
}
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
/**
|
| 224 |
+
* A convenience method that builds and executes the tool in one step.
|
| 225 |
+
* Never throws.
|
| 226 |
+
* @param params The raw, untrusted parameters from the model.
|
| 227 |
+
* @params abortSignal a signal to abort.
|
| 228 |
+
* @returns The result of the tool execution.
|
| 229 |
+
*/
|
| 230 |
+
async validateBuildAndExecute(
|
| 231 |
+
params: TParams,
|
| 232 |
+
abortSignal: AbortSignal,
|
| 233 |
+
): Promise<ToolResult> {
|
| 234 |
+
const invocationOrError = this.silentBuild(params);
|
| 235 |
+
if (invocationOrError instanceof Error) {
|
| 236 |
+
const errorMessage = invocationOrError.message;
|
| 237 |
+
return {
|
| 238 |
+
llmContent: `Error: Invalid parameters provided. Reason: ${errorMessage}`,
|
| 239 |
+
returnDisplay: errorMessage,
|
| 240 |
+
error: {
|
| 241 |
+
message: errorMessage,
|
| 242 |
+
type: ToolErrorType.INVALID_TOOL_PARAMS,
|
| 243 |
+
},
|
| 244 |
+
};
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
try {
|
| 248 |
+
return await invocationOrError.execute(abortSignal);
|
| 249 |
+
} catch (error) {
|
| 250 |
+
const errorMessage =
|
| 251 |
+
error instanceof Error ? error.message : String(error);
|
| 252 |
+
return {
|
| 253 |
+
llmContent: `Error: Tool call execution failed. Reason: ${errorMessage}`,
|
| 254 |
+
returnDisplay: errorMessage,
|
| 255 |
+
error: {
|
| 256 |
+
message: errorMessage,
|
| 257 |
+
type: ToolErrorType.EXECUTION_FAILED,
|
| 258 |
+
},
|
| 259 |
+
};
|
| 260 |
+
}
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
/**
|
| 265 |
+
* New base class for declarative tools that separates validation from execution.
|
| 266 |
+
* New tools should extend this class, which provides a `build` method that
|
| 267 |
+
* validates parameters before deferring to a `createInvocation` method for
|
| 268 |
+
* the final `ToolInvocation` object instantiation.
|
| 269 |
+
*/
|
| 270 |
+
export abstract class BaseDeclarativeTool<
|
| 271 |
+
TParams extends object,
|
| 272 |
+
TResult extends ToolResult,
|
| 273 |
+
> extends DeclarativeTool<TParams, TResult> {
|
| 274 |
+
build(params: TParams): ToolInvocation<TParams, TResult> {
|
| 275 |
+
const validationError = this.validateToolParams(params);
|
| 276 |
+
if (validationError) {
|
| 277 |
+
throw new Error(validationError);
|
| 278 |
+
}
|
| 279 |
+
return this.createInvocation(params);
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
override validateToolParams(params: TParams): string | null {
|
| 283 |
+
const errors = SchemaValidator.validate(
|
| 284 |
+
this.schema.parametersJsonSchema,
|
| 285 |
+
params,
|
| 286 |
+
);
|
| 287 |
+
|
| 288 |
+
if (errors) {
|
| 289 |
+
return errors;
|
| 290 |
+
}
|
| 291 |
+
return this.validateToolParamValues(params);
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
protected validateToolParamValues(_params: TParams): string | null {
|
| 295 |
+
// Base implementation can be extended by subclasses.
|
| 296 |
+
return null;
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
protected abstract createInvocation(
|
| 300 |
+
params: TParams,
|
| 301 |
+
): ToolInvocation<TParams, TResult>;
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
/**
|
| 305 |
+
* A type alias for a declarative tool where the specific parameter and result types are not known.
|
| 306 |
+
*/
|
| 307 |
+
export type AnyDeclarativeTool = DeclarativeTool<object, ToolResult>;
|
| 308 |
+
|
| 309 |
+
export interface ToolResult {
|
| 310 |
+
/**
|
| 311 |
+
* A short, one-line summary of the tool's action and result.
|
| 312 |
+
* e.g., "Read 5 files", "Wrote 256 bytes to foo.txt"
|
| 313 |
+
*/
|
| 314 |
+
summary?: string;
|
| 315 |
+
/**
|
| 316 |
+
* Content meant to be included in LLM history.
|
| 317 |
+
* This should represent the factual outcome of the tool execution.
|
| 318 |
+
*/
|
| 319 |
+
llmContent: PartListUnion;
|
| 320 |
+
|
| 321 |
+
/**
|
| 322 |
+
* Markdown string for user display.
|
| 323 |
+
* This provides a user-friendly summary or visualization of the result.
|
| 324 |
+
* NOTE: This might also be considered UI-specific and could potentially be
|
| 325 |
+
* removed or modified in a further refactor if the server becomes purely API-driven.
|
| 326 |
+
* For now, we keep it as the core logic in ReadFileTool currently produces it.
|
| 327 |
+
*/
|
| 328 |
+
returnDisplay: ToolResultDisplay;
|
| 329 |
+
|
| 330 |
+
/**
|
| 331 |
+
* If this property is present, the tool call is considered a failure.
|
| 332 |
+
*/
|
| 333 |
+
error?: {
|
| 334 |
+
message: string; // raw error message
|
| 335 |
+
type?: ToolErrorType; // An optional machine-readable error type (e.g., 'FILE_NOT_FOUND').
|
| 336 |
+
};
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
/**
|
| 340 |
+
* Detects cycles in a JSON schemas due to `$ref`s.
|
| 341 |
+
* @param schema The root of the JSON schema.
|
| 342 |
+
* @returns `true` if a cycle is detected, `false` otherwise.
|
| 343 |
+
*/
|
| 344 |
+
export function hasCycleInSchema(schema: object): boolean {
|
| 345 |
+
function resolveRef(ref: string): object | null {
|
| 346 |
+
if (!ref.startsWith('#/')) {
|
| 347 |
+
return null;
|
| 348 |
+
}
|
| 349 |
+
const path = ref.substring(2).split('/');
|
| 350 |
+
let current: unknown = schema;
|
| 351 |
+
for (const segment of path) {
|
| 352 |
+
if (
|
| 353 |
+
typeof current !== 'object' ||
|
| 354 |
+
current === null ||
|
| 355 |
+
!Object.prototype.hasOwnProperty.call(current, segment)
|
| 356 |
+
) {
|
| 357 |
+
return null;
|
| 358 |
+
}
|
| 359 |
+
current = (current as Record<string, unknown>)[segment];
|
| 360 |
+
}
|
| 361 |
+
return current as object;
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
function traverse(
|
| 365 |
+
node: unknown,
|
| 366 |
+
visitedRefs: Set<string>,
|
| 367 |
+
pathRefs: Set<string>,
|
| 368 |
+
): boolean {
|
| 369 |
+
if (typeof node !== 'object' || node === null) {
|
| 370 |
+
return false;
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
if (Array.isArray(node)) {
|
| 374 |
+
for (const item of node) {
|
| 375 |
+
if (traverse(item, visitedRefs, pathRefs)) {
|
| 376 |
+
return true;
|
| 377 |
+
}
|
| 378 |
+
}
|
| 379 |
+
return false;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
if ('$ref' in node && typeof node.$ref === 'string') {
|
| 383 |
+
const ref = node.$ref;
|
| 384 |
+
if (ref === '#/' || pathRefs.has(ref)) {
|
| 385 |
+
// A ref to just '#/' is always a cycle.
|
| 386 |
+
return true; // Cycle detected!
|
| 387 |
+
}
|
| 388 |
+
if (visitedRefs.has(ref)) {
|
| 389 |
+
return false; // Bail early, we have checked this ref before.
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
const resolvedNode = resolveRef(ref);
|
| 393 |
+
if (resolvedNode) {
|
| 394 |
+
// Add it to both visited and the current path
|
| 395 |
+
visitedRefs.add(ref);
|
| 396 |
+
pathRefs.add(ref);
|
| 397 |
+
const hasCycle = traverse(resolvedNode, visitedRefs, pathRefs);
|
| 398 |
+
pathRefs.delete(ref); // Backtrack, leaving it in visited
|
| 399 |
+
return hasCycle;
|
| 400 |
+
}
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
// Crawl all the properties of node
|
| 404 |
+
for (const key in node) {
|
| 405 |
+
if (Object.prototype.hasOwnProperty.call(node, key)) {
|
| 406 |
+
if (
|
| 407 |
+
traverse(
|
| 408 |
+
(node as Record<string, unknown>)[key],
|
| 409 |
+
visitedRefs,
|
| 410 |
+
pathRefs,
|
| 411 |
+
)
|
| 412 |
+
) {
|
| 413 |
+
return true;
|
| 414 |
+
}
|
| 415 |
+
}
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
return false;
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
return traverse(schema, new Set<string>(), new Set<string>());
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
export type ToolResultDisplay = string | FileDiff | TodoResultDisplay;
|
| 425 |
+
|
| 426 |
+
export interface FileDiff {
|
| 427 |
+
fileDiff: string;
|
| 428 |
+
fileName: string;
|
| 429 |
+
originalContent: string | null;
|
| 430 |
+
newContent: string;
|
| 431 |
+
diffStat?: DiffStat;
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
export interface DiffStat {
|
| 435 |
+
ai_removed_lines: number;
|
| 436 |
+
ai_added_lines: number;
|
| 437 |
+
user_added_lines: number;
|
| 438 |
+
user_removed_lines: number;
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
export interface TodoResultDisplay {
|
| 442 |
+
type: 'todo_list';
|
| 443 |
+
todos: Array<{
|
| 444 |
+
id: string;
|
| 445 |
+
content: string;
|
| 446 |
+
status: 'pending' | 'in_progress' | 'completed';
|
| 447 |
+
}>;
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
export interface ToolEditConfirmationDetails {
|
| 451 |
+
type: 'edit';
|
| 452 |
+
title: string;
|
| 453 |
+
onConfirm: (
|
| 454 |
+
outcome: ToolConfirmationOutcome,
|
| 455 |
+
payload?: ToolConfirmationPayload,
|
| 456 |
+
) => Promise<void>;
|
| 457 |
+
fileName: string;
|
| 458 |
+
filePath: string;
|
| 459 |
+
fileDiff: string;
|
| 460 |
+
originalContent: string | null;
|
| 461 |
+
newContent: string;
|
| 462 |
+
isModifying?: boolean;
|
| 463 |
+
ideConfirmation?: Promise<DiffUpdateResult>;
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
export interface ToolConfirmationPayload {
|
| 467 |
+
// used to override `modifiedProposedContent` for modifiable tools in the
|
| 468 |
+
// inline modify flow
|
| 469 |
+
newContent: string;
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
export interface ToolExecuteConfirmationDetails {
|
| 473 |
+
type: 'exec';
|
| 474 |
+
title: string;
|
| 475 |
+
onConfirm: (outcome: ToolConfirmationOutcome) => Promise<void>;
|
| 476 |
+
command: string;
|
| 477 |
+
rootCommand: string;
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
export interface ToolMcpConfirmationDetails {
|
| 481 |
+
type: 'mcp';
|
| 482 |
+
title: string;
|
| 483 |
+
serverName: string;
|
| 484 |
+
toolName: string;
|
| 485 |
+
toolDisplayName: string;
|
| 486 |
+
onConfirm: (outcome: ToolConfirmationOutcome) => Promise<void>;
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
export interface ToolInfoConfirmationDetails {
|
| 490 |
+
type: 'info';
|
| 491 |
+
title: string;
|
| 492 |
+
onConfirm: (outcome: ToolConfirmationOutcome) => Promise<void>;
|
| 493 |
+
prompt: string;
|
| 494 |
+
urls?: string[];
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
export type ToolCallConfirmationDetails =
|
| 498 |
+
| ToolEditConfirmationDetails
|
| 499 |
+
| ToolExecuteConfirmationDetails
|
| 500 |
+
| ToolMcpConfirmationDetails
|
| 501 |
+
| ToolInfoConfirmationDetails;
|
| 502 |
+
|
| 503 |
+
export enum ToolConfirmationOutcome {
|
| 504 |
+
ProceedOnce = 'proceed_once',
|
| 505 |
+
ProceedAlways = 'proceed_always',
|
| 506 |
+
ProceedAlwaysServer = 'proceed_always_server',
|
| 507 |
+
ProceedAlwaysTool = 'proceed_always_tool',
|
| 508 |
+
ModifyWithEditor = 'modify_with_editor',
|
| 509 |
+
Cancel = 'cancel',
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
export enum Kind {
|
| 513 |
+
Read = 'read',
|
| 514 |
+
Edit = 'edit',
|
| 515 |
+
Delete = 'delete',
|
| 516 |
+
Move = 'move',
|
| 517 |
+
Search = 'search',
|
| 518 |
+
Execute = 'execute',
|
| 519 |
+
Think = 'think',
|
| 520 |
+
Fetch = 'fetch',
|
| 521 |
+
Other = 'other',
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
export interface ToolLocation {
|
| 525 |
+
// Absolute path to the file
|
| 526 |
+
path: string;
|
| 527 |
+
// Which line (if known)
|
| 528 |
+
line?: number;
|
| 529 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/web-fetch.test.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { describe, it, expect, vi } from 'vitest';
|
| 8 |
+
import { WebFetchTool } from './web-fetch.js';
|
| 9 |
+
import { Config, ApprovalMode } from '../config/config.js';
|
| 10 |
+
import { ToolConfirmationOutcome } from './tools.js';
|
| 11 |
+
|
| 12 |
+
describe('WebFetchTool', () => {
|
| 13 |
+
const mockConfig = {
|
| 14 |
+
getApprovalMode: vi.fn(),
|
| 15 |
+
setApprovalMode: vi.fn(),
|
| 16 |
+
getProxy: vi.fn(),
|
| 17 |
+
} as unknown as Config;
|
| 18 |
+
|
| 19 |
+
describe('shouldConfirmExecute', () => {
|
| 20 |
+
it('should return confirmation details with the correct prompt and urls', async () => {
|
| 21 |
+
const tool = new WebFetchTool(mockConfig);
|
| 22 |
+
const params = {
|
| 23 |
+
url: 'https://example.com',
|
| 24 |
+
prompt: 'summarize this page',
|
| 25 |
+
};
|
| 26 |
+
const invocation = tool.build(params);
|
| 27 |
+
const confirmationDetails = await invocation.shouldConfirmExecute(
|
| 28 |
+
new AbortController().signal,
|
| 29 |
+
);
|
| 30 |
+
|
| 31 |
+
expect(confirmationDetails).toEqual({
|
| 32 |
+
type: 'info',
|
| 33 |
+
title: 'Confirm Web Fetch',
|
| 34 |
+
prompt:
|
| 35 |
+
'Fetch content from https://example.com and process with: summarize this page',
|
| 36 |
+
urls: ['https://example.com'],
|
| 37 |
+
onConfirm: expect.any(Function),
|
| 38 |
+
});
|
| 39 |
+
});
|
| 40 |
+
|
| 41 |
+
it('should return github urls as-is in confirmation details', async () => {
|
| 42 |
+
const tool = new WebFetchTool(mockConfig);
|
| 43 |
+
const params = {
|
| 44 |
+
url: 'https://github.com/google/gemini-react/blob/main/README.md',
|
| 45 |
+
prompt: 'summarize the README',
|
| 46 |
+
};
|
| 47 |
+
const invocation = tool.build(params);
|
| 48 |
+
const confirmationDetails = await invocation.shouldConfirmExecute(
|
| 49 |
+
new AbortController().signal,
|
| 50 |
+
);
|
| 51 |
+
|
| 52 |
+
expect(confirmationDetails).toEqual({
|
| 53 |
+
type: 'info',
|
| 54 |
+
title: 'Confirm Web Fetch',
|
| 55 |
+
prompt:
|
| 56 |
+
'Fetch content from https://github.com/google/gemini-react/blob/main/README.md and process with: summarize the README',
|
| 57 |
+
urls: ['https://github.com/google/gemini-react/blob/main/README.md'],
|
| 58 |
+
onConfirm: expect.any(Function),
|
| 59 |
+
});
|
| 60 |
+
});
|
| 61 |
+
|
| 62 |
+
it('should return false if approval mode is AUTO_EDIT', async () => {
|
| 63 |
+
const tool = new WebFetchTool({
|
| 64 |
+
...mockConfig,
|
| 65 |
+
getApprovalMode: () => ApprovalMode.AUTO_EDIT,
|
| 66 |
+
} as unknown as Config);
|
| 67 |
+
const params = {
|
| 68 |
+
url: 'https://example.com',
|
| 69 |
+
prompt: 'summarize this page',
|
| 70 |
+
};
|
| 71 |
+
const invocation = tool.build(params);
|
| 72 |
+
const confirmationDetails = await invocation.shouldConfirmExecute(
|
| 73 |
+
new AbortController().signal,
|
| 74 |
+
);
|
| 75 |
+
|
| 76 |
+
expect(confirmationDetails).toBe(false);
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
it('should call setApprovalMode when onConfirm is called with ProceedAlways', async () => {
|
| 80 |
+
const setApprovalMode = vi.fn();
|
| 81 |
+
const tool = new WebFetchTool({
|
| 82 |
+
...mockConfig,
|
| 83 |
+
setApprovalMode,
|
| 84 |
+
} as unknown as Config);
|
| 85 |
+
const params = {
|
| 86 |
+
url: 'https://example.com',
|
| 87 |
+
prompt: 'summarize this page',
|
| 88 |
+
};
|
| 89 |
+
const invocation = tool.build(params);
|
| 90 |
+
const confirmationDetails = await invocation.shouldConfirmExecute(
|
| 91 |
+
new AbortController().signal,
|
| 92 |
+
);
|
| 93 |
+
|
| 94 |
+
if (
|
| 95 |
+
confirmationDetails &&
|
| 96 |
+
typeof confirmationDetails === 'object' &&
|
| 97 |
+
'onConfirm' in confirmationDetails
|
| 98 |
+
) {
|
| 99 |
+
await confirmationDetails.onConfirm(
|
| 100 |
+
ToolConfirmationOutcome.ProceedAlways,
|
| 101 |
+
);
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
expect(setApprovalMode).toHaveBeenCalledWith(ApprovalMode.AUTO_EDIT);
|
| 105 |
+
});
|
| 106 |
+
});
|
| 107 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/web-fetch.ts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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,
|
| 13 |
+
ToolInvocation,
|
| 14 |
+
ToolResult,
|
| 15 |
+
} from './tools.js';
|
| 16 |
+
|
| 17 |
+
import { Config, ApprovalMode } from '../config/config.js';
|
| 18 |
+
import { getResponseText } from '../utils/generateContentResponseUtilities.js';
|
| 19 |
+
import { fetchWithTimeout, isPrivateIp } from '../utils/fetch.js';
|
| 20 |
+
import { convert } from 'html-to-text';
|
| 21 |
+
import { ProxyAgent, setGlobalDispatcher } from 'undici';
|
| 22 |
+
|
| 23 |
+
const URL_FETCH_TIMEOUT_MS = 10000;
|
| 24 |
+
const MAX_CONTENT_LENGTH = 100000;
|
| 25 |
+
|
| 26 |
+
/**
|
| 27 |
+
* Parameters for the WebFetch tool
|
| 28 |
+
*/
|
| 29 |
+
export interface WebFetchToolParams {
|
| 30 |
+
/**
|
| 31 |
+
* The URL to fetch content from
|
| 32 |
+
*/
|
| 33 |
+
url: string;
|
| 34 |
+
/**
|
| 35 |
+
* The prompt to run on the fetched content
|
| 36 |
+
*/
|
| 37 |
+
prompt: string;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/**
|
| 41 |
+
* Implementation of the WebFetch tool invocation logic
|
| 42 |
+
*/
|
| 43 |
+
class WebFetchToolInvocation extends BaseToolInvocation<
|
| 44 |
+
WebFetchToolParams,
|
| 45 |
+
ToolResult
|
| 46 |
+
> {
|
| 47 |
+
constructor(
|
| 48 |
+
private readonly config: Config,
|
| 49 |
+
params: WebFetchToolParams,
|
| 50 |
+
) {
|
| 51 |
+
super(params);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
private async executeDirectFetch(signal: AbortSignal): Promise<ToolResult> {
|
| 55 |
+
let url = this.params.url;
|
| 56 |
+
|
| 57 |
+
// Convert GitHub blob URL to raw URL
|
| 58 |
+
if (url.includes('github.com') && url.includes('/blob/')) {
|
| 59 |
+
url = url
|
| 60 |
+
.replace('github.com', 'raw.githubusercontent.com')
|
| 61 |
+
.replace('/blob/', '/');
|
| 62 |
+
console.debug(
|
| 63 |
+
`[WebFetchTool] Converted GitHub blob URL to raw URL: ${url}`,
|
| 64 |
+
);
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
try {
|
| 68 |
+
console.debug(`[WebFetchTool] Fetching content from: ${url}`);
|
| 69 |
+
const response = await fetchWithTimeout(url, URL_FETCH_TIMEOUT_MS);
|
| 70 |
+
|
| 71 |
+
if (!response.ok) {
|
| 72 |
+
const errorMessage = `Request failed with status code ${response.status} ${response.statusText}`;
|
| 73 |
+
console.error(`[WebFetchTool] ${errorMessage}`);
|
| 74 |
+
throw new Error(errorMessage);
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
console.debug(`[WebFetchTool] Successfully fetched content from ${url}`);
|
| 78 |
+
const html = await response.text();
|
| 79 |
+
const textContent = convert(html, {
|
| 80 |
+
wordwrap: false,
|
| 81 |
+
selectors: [
|
| 82 |
+
{ selector: 'a', options: { ignoreHref: true } },
|
| 83 |
+
{ selector: 'img', format: 'skip' },
|
| 84 |
+
],
|
| 85 |
+
}).substring(0, MAX_CONTENT_LENGTH);
|
| 86 |
+
|
| 87 |
+
console.debug(
|
| 88 |
+
`[WebFetchTool] Converted HTML to text (${textContent.length} characters)`,
|
| 89 |
+
);
|
| 90 |
+
|
| 91 |
+
const geminiClient = this.config.getGeminiClient();
|
| 92 |
+
const fallbackPrompt = `The user requested the following: "${this.params.prompt}".
|
| 93 |
+
|
| 94 |
+
I have fetched the content from ${this.params.url}. Please use the following content to answer the user's request.
|
| 95 |
+
|
| 96 |
+
---
|
| 97 |
+
${textContent}
|
| 98 |
+
---`;
|
| 99 |
+
|
| 100 |
+
console.debug(
|
| 101 |
+
`[WebFetchTool] Processing content with prompt: "${this.params.prompt}"`,
|
| 102 |
+
);
|
| 103 |
+
|
| 104 |
+
const result = await geminiClient.generateContent(
|
| 105 |
+
[{ role: 'user', parts: [{ text: fallbackPrompt }] }],
|
| 106 |
+
{},
|
| 107 |
+
signal,
|
| 108 |
+
);
|
| 109 |
+
const resultText = getResponseText(result) || '';
|
| 110 |
+
|
| 111 |
+
console.debug(
|
| 112 |
+
`[WebFetchTool] Successfully processed content from ${this.params.url}`,
|
| 113 |
+
);
|
| 114 |
+
|
| 115 |
+
return {
|
| 116 |
+
llmContent: resultText,
|
| 117 |
+
returnDisplay: `Content from ${this.params.url} processed successfully.`,
|
| 118 |
+
};
|
| 119 |
+
} catch (e) {
|
| 120 |
+
const error = e as Error;
|
| 121 |
+
const errorMessage = `Error during fetch for ${url}: ${error.message}`;
|
| 122 |
+
console.error(`[WebFetchTool] ${errorMessage}`, error);
|
| 123 |
+
return {
|
| 124 |
+
llmContent: `Error: ${errorMessage}`,
|
| 125 |
+
returnDisplay: `Error: ${errorMessage}`,
|
| 126 |
+
};
|
| 127 |
+
}
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
override getDescription(): string {
|
| 131 |
+
const displayPrompt =
|
| 132 |
+
this.params.prompt.length > 100
|
| 133 |
+
? this.params.prompt.substring(0, 97) + '...'
|
| 134 |
+
: this.params.prompt;
|
| 135 |
+
return `Fetching content from ${this.params.url} and processing with prompt: "${displayPrompt}"`;
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
override async shouldConfirmExecute(): Promise<
|
| 139 |
+
ToolCallConfirmationDetails | false
|
| 140 |
+
> {
|
| 141 |
+
if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
|
| 142 |
+
return false;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
const confirmationDetails: ToolCallConfirmationDetails = {
|
| 146 |
+
type: 'info',
|
| 147 |
+
title: `Confirm Web Fetch`,
|
| 148 |
+
prompt: `Fetch content from ${this.params.url} and process with: ${this.params.prompt}`,
|
| 149 |
+
urls: [this.params.url],
|
| 150 |
+
onConfirm: async (outcome: ToolConfirmationOutcome) => {
|
| 151 |
+
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
| 152 |
+
this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
|
| 153 |
+
}
|
| 154 |
+
},
|
| 155 |
+
};
|
| 156 |
+
return confirmationDetails;
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
async execute(signal: AbortSignal): Promise<ToolResult> {
|
| 160 |
+
// Check if URL is private/localhost
|
| 161 |
+
const isPrivate = isPrivateIp(this.params.url);
|
| 162 |
+
|
| 163 |
+
if (isPrivate) {
|
| 164 |
+
console.debug(
|
| 165 |
+
`[WebFetchTool] Private IP detected for ${this.params.url}, using direct fetch`,
|
| 166 |
+
);
|
| 167 |
+
} else {
|
| 168 |
+
console.debug(
|
| 169 |
+
`[WebFetchTool] Public URL detected for ${this.params.url}, using direct fetch`,
|
| 170 |
+
);
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
return this.executeDirectFetch(signal);
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
/**
|
| 178 |
+
* Implementation of the WebFetch tool logic
|
| 179 |
+
*/
|
| 180 |
+
export class WebFetchTool extends BaseDeclarativeTool<
|
| 181 |
+
WebFetchToolParams,
|
| 182 |
+
ToolResult
|
| 183 |
+
> {
|
| 184 |
+
static readonly Name: string = 'web_fetch';
|
| 185 |
+
|
| 186 |
+
constructor(private readonly config: Config) {
|
| 187 |
+
super(
|
| 188 |
+
WebFetchTool.Name,
|
| 189 |
+
'WebFetch',
|
| 190 |
+
'Fetches content from a specified URL and processes it using an AI model\n- Takes a URL and a prompt as input\n- Fetches the URL content, converts HTML to markdown\n- Processes the content with the prompt using a small, fast model\n- Returns the model\'s response about the content\n- Use this tool when you need to retrieve and analyze web content\n\nUsage notes:\n - IMPORTANT: If an MCP-provided web fetch tool is available, prefer using that tool instead of this one, as it may have fewer restrictions. All MCP-provided tools start with "mcp__".\n - The URL must be a fully-formed valid URL\n - The prompt should describe what information you want to extract from the page\n - This tool is read-only and does not modify any files\n - Results may be summarized if the content is very large\n - Supports both public and private/localhost URLs using direct fetch',
|
| 191 |
+
Kind.Fetch,
|
| 192 |
+
{
|
| 193 |
+
properties: {
|
| 194 |
+
url: {
|
| 195 |
+
description: 'The URL to fetch content from',
|
| 196 |
+
type: 'string',
|
| 197 |
+
},
|
| 198 |
+
prompt: {
|
| 199 |
+
description: 'The prompt to run on the fetched content',
|
| 200 |
+
type: 'string',
|
| 201 |
+
},
|
| 202 |
+
},
|
| 203 |
+
required: ['url', 'prompt'],
|
| 204 |
+
type: 'object',
|
| 205 |
+
},
|
| 206 |
+
);
|
| 207 |
+
const proxy = config.getProxy();
|
| 208 |
+
if (proxy) {
|
| 209 |
+
setGlobalDispatcher(new ProxyAgent(proxy as string));
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
protected override validateToolParamValues(
|
| 214 |
+
params: WebFetchToolParams,
|
| 215 |
+
): string | null {
|
| 216 |
+
if (!params.url || params.url.trim() === '') {
|
| 217 |
+
return "The 'url' parameter cannot be empty.";
|
| 218 |
+
}
|
| 219 |
+
if (
|
| 220 |
+
!params.url.startsWith('http://') &&
|
| 221 |
+
!params.url.startsWith('https://')
|
| 222 |
+
) {
|
| 223 |
+
return "The 'url' must be a valid URL starting with http:// or https://.";
|
| 224 |
+
}
|
| 225 |
+
if (!params.prompt || params.prompt.trim() === '') {
|
| 226 |
+
return "The 'prompt' parameter cannot be empty.";
|
| 227 |
+
}
|
| 228 |
+
return null;
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
protected createInvocation(
|
| 232 |
+
params: WebFetchToolParams,
|
| 233 |
+
): ToolInvocation<WebFetchToolParams, ToolResult> {
|
| 234 |
+
return new WebFetchToolInvocation(this.config, params);
|
| 235 |
+
}
|
| 236 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/web-search.test.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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est';
|
| 8 |
+
import { WebSearchTool, WebSearchToolParams } from './web-search.js';
|
| 9 |
+
import { Config } from '../config/config.js';
|
| 10 |
+
import { GeminiClient } from '../core/client.js';
|
| 11 |
+
|
| 12 |
+
// Mock GeminiClient and Config constructor
|
| 13 |
+
vi.mock('../core/client.js');
|
| 14 |
+
vi.mock('../config/config.js');
|
| 15 |
+
|
| 16 |
+
// Mock global fetch
|
| 17 |
+
const mockFetch = vi.fn();
|
| 18 |
+
global.fetch = mockFetch;
|
| 19 |
+
|
| 20 |
+
describe('WebSearchTool', () => {
|
| 21 |
+
const abortSignal = new AbortController().signal;
|
| 22 |
+
let mockGeminiClient: GeminiClient;
|
| 23 |
+
let tool: WebSearchTool;
|
| 24 |
+
|
| 25 |
+
beforeEach(() => {
|
| 26 |
+
vi.clearAllMocks();
|
| 27 |
+
const mockConfigInstance = {
|
| 28 |
+
getGeminiClient: () => mockGeminiClient,
|
| 29 |
+
getProxy: () => undefined,
|
| 30 |
+
getTavilyApiKey: () => 'test-api-key', // Add the missing method
|
| 31 |
+
} as unknown as Config;
|
| 32 |
+
mockGeminiClient = new GeminiClient(mockConfigInstance);
|
| 33 |
+
tool = new WebSearchTool(mockConfigInstance);
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
afterEach(() => {
|
| 37 |
+
vi.restoreAllMocks();
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
describe('build', () => {
|
| 41 |
+
it('should return an invocation for a valid query', () => {
|
| 42 |
+
const params: WebSearchToolParams = { query: 'test query' };
|
| 43 |
+
const invocation = tool.build(params);
|
| 44 |
+
expect(invocation).toBeDefined();
|
| 45 |
+
expect(invocation.params).toEqual(params);
|
| 46 |
+
});
|
| 47 |
+
|
| 48 |
+
it('should throw an error for an empty query', () => {
|
| 49 |
+
const params: WebSearchToolParams = { query: '' };
|
| 50 |
+
expect(() => tool.build(params)).toThrow(
|
| 51 |
+
"The 'query' parameter cannot be empty.",
|
| 52 |
+
);
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
it('should throw an error for a query with only whitespace', () => {
|
| 56 |
+
const params: WebSearchToolParams = { query: ' ' };
|
| 57 |
+
expect(() => tool.build(params)).toThrow(
|
| 58 |
+
"The 'query' parameter cannot be empty.",
|
| 59 |
+
);
|
| 60 |
+
});
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
describe('getDescription', () => {
|
| 64 |
+
it('should return a description of the search', () => {
|
| 65 |
+
const params: WebSearchToolParams = { query: 'test query' };
|
| 66 |
+
const invocation = tool.build(params);
|
| 67 |
+
expect(invocation.getDescription()).toBe(
|
| 68 |
+
'Searching the web for: "test query"',
|
| 69 |
+
);
|
| 70 |
+
});
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
describe('execute', () => {
|
| 74 |
+
it('should return search results for a successful query', async () => {
|
| 75 |
+
const params: WebSearchToolParams = { query: 'successful query' };
|
| 76 |
+
|
| 77 |
+
// Mock the fetch response
|
| 78 |
+
mockFetch.mockResolvedValueOnce({
|
| 79 |
+
ok: true,
|
| 80 |
+
json: async () => ({
|
| 81 |
+
answer: 'Here are your results.',
|
| 82 |
+
results: [],
|
| 83 |
+
}),
|
| 84 |
+
} as Response);
|
| 85 |
+
|
| 86 |
+
const invocation = tool.build(params);
|
| 87 |
+
const result = await invocation.execute(abortSignal);
|
| 88 |
+
|
| 89 |
+
expect(result.llmContent).toBe(
|
| 90 |
+
'Web search results for "successful query":\n\nHere are your results.',
|
| 91 |
+
);
|
| 92 |
+
expect(result.returnDisplay).toBe(
|
| 93 |
+
'Search results for "successful query" returned.',
|
| 94 |
+
);
|
| 95 |
+
expect(result.sources).toEqual([]);
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
it('should handle no search results found', async () => {
|
| 99 |
+
const params: WebSearchToolParams = { query: 'no results query' };
|
| 100 |
+
|
| 101 |
+
// Mock the fetch response
|
| 102 |
+
mockFetch.mockResolvedValueOnce({
|
| 103 |
+
ok: true,
|
| 104 |
+
json: async () => ({
|
| 105 |
+
answer: '',
|
| 106 |
+
results: [],
|
| 107 |
+
}),
|
| 108 |
+
} as Response);
|
| 109 |
+
|
| 110 |
+
const invocation = tool.build(params);
|
| 111 |
+
const result = await invocation.execute(abortSignal);
|
| 112 |
+
|
| 113 |
+
expect(result.llmContent).toBe(
|
| 114 |
+
'No search results or information found for query: "no results query"',
|
| 115 |
+
);
|
| 116 |
+
expect(result.returnDisplay).toBe('No information found.');
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
it('should handle API errors gracefully', async () => {
|
| 120 |
+
const params: WebSearchToolParams = { query: 'error query' };
|
| 121 |
+
|
| 122 |
+
// Mock the fetch to reject
|
| 123 |
+
mockFetch.mockRejectedValueOnce(new Error('API Failure'));
|
| 124 |
+
|
| 125 |
+
const invocation = tool.build(params);
|
| 126 |
+
const result = await invocation.execute(abortSignal);
|
| 127 |
+
|
| 128 |
+
expect(result.llmContent).toContain('Error:');
|
| 129 |
+
expect(result.llmContent).toContain('API Failure');
|
| 130 |
+
expect(result.returnDisplay).toBe('Error performing web search.');
|
| 131 |
+
});
|
| 132 |
+
|
| 133 |
+
it('should correctly format results with sources', async () => {
|
| 134 |
+
const params: WebSearchToolParams = { query: 'grounding query' };
|
| 135 |
+
|
| 136 |
+
// Mock the fetch response
|
| 137 |
+
mockFetch.mockResolvedValueOnce({
|
| 138 |
+
ok: true,
|
| 139 |
+
json: async () => ({
|
| 140 |
+
answer: 'This is a test response.',
|
| 141 |
+
results: [
|
| 142 |
+
{ title: 'Example Site', url: 'https://example.com' },
|
| 143 |
+
{ title: 'Google', url: 'https://google.com' },
|
| 144 |
+
],
|
| 145 |
+
}),
|
| 146 |
+
} as Response);
|
| 147 |
+
|
| 148 |
+
const invocation = tool.build(params);
|
| 149 |
+
const result = await invocation.execute(abortSignal);
|
| 150 |
+
|
| 151 |
+
const expectedLlmContent = `Web search results for "grounding query":
|
| 152 |
+
|
| 153 |
+
This is a test response.
|
| 154 |
+
|
| 155 |
+
Sources:
|
| 156 |
+
[1] Example Site (https://example.com)
|
| 157 |
+
[2] Google (https://google.com)`;
|
| 158 |
+
|
| 159 |
+
expect(result.llmContent).toBe(expectedLlmContent);
|
| 160 |
+
expect(result.returnDisplay).toBe(
|
| 161 |
+
'Search results for "grounding query" returned.',
|
| 162 |
+
);
|
| 163 |
+
expect(result.sources).toHaveLength(2);
|
| 164 |
+
});
|
| 165 |
+
});
|
| 166 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/web-search.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
ToolInvocation,
|
| 12 |
+
ToolResult,
|
| 13 |
+
} from './tools.js';
|
| 14 |
+
|
| 15 |
+
import { getErrorMessage } from '../utils/errors.js';
|
| 16 |
+
import { Config } from '../config/config.js';
|
| 17 |
+
|
| 18 |
+
interface TavilyResultItem {
|
| 19 |
+
title: string;
|
| 20 |
+
url: string;
|
| 21 |
+
content?: string;
|
| 22 |
+
score?: number;
|
| 23 |
+
published_date?: string;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
interface TavilySearchResponse {
|
| 27 |
+
query: string;
|
| 28 |
+
answer?: string;
|
| 29 |
+
results: TavilyResultItem[];
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
/**
|
| 33 |
+
* Parameters for the WebSearchTool.
|
| 34 |
+
*/
|
| 35 |
+
export interface WebSearchToolParams {
|
| 36 |
+
/**
|
| 37 |
+
* The search query.
|
| 38 |
+
*/
|
| 39 |
+
query: string;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/**
|
| 43 |
+
* Extends ToolResult to include sources for web search.
|
| 44 |
+
*/
|
| 45 |
+
export interface WebSearchToolResult extends ToolResult {
|
| 46 |
+
sources?: Array<{ title: string; url: string }>;
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
class WebSearchToolInvocation extends BaseToolInvocation<
|
| 50 |
+
WebSearchToolParams,
|
| 51 |
+
WebSearchToolResult
|
| 52 |
+
> {
|
| 53 |
+
constructor(
|
| 54 |
+
private readonly config: Config,
|
| 55 |
+
params: WebSearchToolParams,
|
| 56 |
+
) {
|
| 57 |
+
super(params);
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
override getDescription(): string {
|
| 61 |
+
return `Searching the web for: "${this.params.query}"`;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
async execute(signal: AbortSignal): Promise<WebSearchToolResult> {
|
| 65 |
+
const apiKey =
|
| 66 |
+
this.config.getTavilyApiKey() || process.env['TAVILY_API_KEY'];
|
| 67 |
+
if (!apiKey) {
|
| 68 |
+
return {
|
| 69 |
+
llmContent:
|
| 70 |
+
'Web search is disabled because TAVILY_API_KEY is not configured. Please set it in your settings.json, .env file, or via --tavily-api-key command line argument to enable web search.',
|
| 71 |
+
returnDisplay:
|
| 72 |
+
'Web search disabled. Configure TAVILY_API_KEY to enable Tavily search.',
|
| 73 |
+
};
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
try {
|
| 77 |
+
const response = await fetch('https://api.tavily.com/search', {
|
| 78 |
+
method: 'POST',
|
| 79 |
+
headers: {
|
| 80 |
+
'Content-Type': 'application/json',
|
| 81 |
+
},
|
| 82 |
+
body: JSON.stringify({
|
| 83 |
+
api_key: apiKey,
|
| 84 |
+
query: this.params.query,
|
| 85 |
+
search_depth: 'advanced',
|
| 86 |
+
max_results: 5,
|
| 87 |
+
include_answer: true,
|
| 88 |
+
}),
|
| 89 |
+
signal,
|
| 90 |
+
});
|
| 91 |
+
|
| 92 |
+
if (!response.ok) {
|
| 93 |
+
const text = await response.text().catch(() => '');
|
| 94 |
+
throw new Error(
|
| 95 |
+
`Tavily API error: ${response.status} ${response.statusText}${text ? ` - ${text}` : ''}`,
|
| 96 |
+
);
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
const data = (await response.json()) as TavilySearchResponse;
|
| 100 |
+
|
| 101 |
+
const sources = (data.results || []).map((r) => ({
|
| 102 |
+
title: r.title,
|
| 103 |
+
url: r.url,
|
| 104 |
+
}));
|
| 105 |
+
|
| 106 |
+
const sourceListFormatted = sources.map(
|
| 107 |
+
(s, i) => `[${i + 1}] ${s.title || 'Untitled'} (${s.url})`,
|
| 108 |
+
);
|
| 109 |
+
|
| 110 |
+
let content = data.answer?.trim() || '';
|
| 111 |
+
if (!content) {
|
| 112 |
+
// Fallback: build a concise summary from top results
|
| 113 |
+
content = sources
|
| 114 |
+
.slice(0, 3)
|
| 115 |
+
.map((s, i) => `${i + 1}. ${s.title} - ${s.url}`)
|
| 116 |
+
.join('\n');
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
if (sourceListFormatted.length > 0) {
|
| 120 |
+
content += `\n\nSources:\n${sourceListFormatted.join('\n')}`;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
if (!content.trim()) {
|
| 124 |
+
return {
|
| 125 |
+
llmContent: `No search results or information found for query: "${this.params.query}"`,
|
| 126 |
+
returnDisplay: 'No information found.',
|
| 127 |
+
};
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
return {
|
| 131 |
+
llmContent: `Web search results for "${this.params.query}":\n\n${content}`,
|
| 132 |
+
returnDisplay: `Search results for "${this.params.query}" returned.`,
|
| 133 |
+
sources,
|
| 134 |
+
};
|
| 135 |
+
} catch (error: unknown) {
|
| 136 |
+
const errorMessage = `Error during web search for query "${this.params.query}": ${getErrorMessage(
|
| 137 |
+
error,
|
| 138 |
+
)}`;
|
| 139 |
+
console.error(errorMessage, error);
|
| 140 |
+
return {
|
| 141 |
+
llmContent: `Error: ${errorMessage}`,
|
| 142 |
+
returnDisplay: `Error performing web search.`,
|
| 143 |
+
};
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
/**
|
| 149 |
+
* A tool to perform web searches using Google Search via the Gemini API.
|
| 150 |
+
*/
|
| 151 |
+
export class WebSearchTool extends BaseDeclarativeTool<
|
| 152 |
+
WebSearchToolParams,
|
| 153 |
+
WebSearchToolResult
|
| 154 |
+
> {
|
| 155 |
+
static readonly Name: string = 'web_search';
|
| 156 |
+
|
| 157 |
+
constructor(private readonly config: Config) {
|
| 158 |
+
super(
|
| 159 |
+
WebSearchTool.Name,
|
| 160 |
+
'TavilySearch',
|
| 161 |
+
'Performs a web search using the Tavily API and returns a concise answer with sources. Requires the TAVILY_API_KEY environment variable.',
|
| 162 |
+
Kind.Search,
|
| 163 |
+
{
|
| 164 |
+
type: 'object',
|
| 165 |
+
properties: {
|
| 166 |
+
query: {
|
| 167 |
+
type: 'string',
|
| 168 |
+
description: 'The search query to find information on the web.',
|
| 169 |
+
},
|
| 170 |
+
},
|
| 171 |
+
required: ['query'],
|
| 172 |
+
},
|
| 173 |
+
);
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
/**
|
| 177 |
+
* Validates the parameters for the WebSearchTool.
|
| 178 |
+
* @param params The parameters to validate
|
| 179 |
+
* @returns An error message string if validation fails, null if valid
|
| 180 |
+
*/
|
| 181 |
+
protected override validateToolParamValues(
|
| 182 |
+
params: WebSearchToolParams,
|
| 183 |
+
): string | null {
|
| 184 |
+
if (!params.query || params.query.trim() === '') {
|
| 185 |
+
return "The 'query' parameter cannot be empty.";
|
| 186 |
+
}
|
| 187 |
+
return null;
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
protected createInvocation(
|
| 191 |
+
params: WebSearchToolParams,
|
| 192 |
+
): ToolInvocation<WebSearchToolParams, WebSearchToolResult> {
|
| 193 |
+
return new WebSearchToolInvocation(this.config, params);
|
| 194 |
+
}
|
| 195 |
+
}
|
projects/ui/qwen-code/packages/core/src/tools/write-file.test.ts
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 17 |
+
getCorrectedFileContent,
|
| 18 |
+
WriteFileTool,
|
| 19 |
+
WriteFileToolParams,
|
| 20 |
+
} from './write-file.js';
|
| 21 |
+
import { ToolErrorType } from './tool-error.js';
|
| 22 |
+
import {
|
| 23 |
+
FileDiff,
|
| 24 |
+
ToolConfirmationOutcome,
|
| 25 |
+
ToolEditConfirmationDetails,
|
| 26 |
+
} from './tools.js';
|
| 27 |
+
import { type EditToolParams } from './edit.js';
|
| 28 |
+
import { ApprovalMode, Config } from '../config/config.js';
|
| 29 |
+
import { ToolRegistry } from './tool-registry.js';
|
| 30 |
+
import path from 'path';
|
| 31 |
+
import fs from 'fs';
|
| 32 |
+
import os from 'os';
|
| 33 |
+
import { GeminiClient } from '../core/client.js';
|
| 34 |
+
import {
|
| 35 |
+
ensureCorrectEdit,
|
| 36 |
+
ensureCorrectFileContent,
|
| 37 |
+
CorrectedEditResult,
|
| 38 |
+
} from '../utils/editCorrector.js';
|
| 39 |
+
import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js';
|
| 40 |
+
import { StandardFileSystemService } from '../services/fileSystemService.js';
|
| 41 |
+
|
| 42 |
+
const rootDir = path.resolve(os.tmpdir(), 'qwen-code-test-root');
|
| 43 |
+
|
| 44 |
+
// --- MOCKS ---
|
| 45 |
+
vi.mock('../core/client.js');
|
| 46 |
+
vi.mock('../utils/editCorrector.js');
|
| 47 |
+
|
| 48 |
+
let mockGeminiClientInstance: Mocked<GeminiClient>;
|
| 49 |
+
const mockEnsureCorrectEdit = vi.fn<typeof ensureCorrectEdit>();
|
| 50 |
+
const mockEnsureCorrectFileContent = vi.fn<typeof ensureCorrectFileContent>();
|
| 51 |
+
|
| 52 |
+
// Wire up the mocked functions to be used by the actual module imports
|
| 53 |
+
vi.mocked(ensureCorrectEdit).mockImplementation(mockEnsureCorrectEdit);
|
| 54 |
+
vi.mocked(ensureCorrectFileContent).mockImplementation(
|
| 55 |
+
mockEnsureCorrectFileContent,
|
| 56 |
+
);
|
| 57 |
+
|
| 58 |
+
// Mock Config
|
| 59 |
+
const fsService = new StandardFileSystemService();
|
| 60 |
+
const mockConfigInternal = {
|
| 61 |
+
getTargetDir: () => rootDir,
|
| 62 |
+
getApprovalMode: vi.fn(() => ApprovalMode.DEFAULT),
|
| 63 |
+
setApprovalMode: vi.fn(),
|
| 64 |
+
getGeminiClient: vi.fn(), // Initialize as a plain mock function
|
| 65 |
+
getFileSystemService: () => fsService,
|
| 66 |
+
getIdeClient: vi.fn(),
|
| 67 |
+
getIdeMode: vi.fn(() => false),
|
| 68 |
+
getWorkspaceContext: () => createMockWorkspaceContext(rootDir),
|
| 69 |
+
getApiKey: () => 'test-key',
|
| 70 |
+
getModel: () => 'test-model',
|
| 71 |
+
getSandbox: () => false,
|
| 72 |
+
getDebugMode: () => false,
|
| 73 |
+
getQuestion: () => undefined,
|
| 74 |
+
getFullContext: () => false,
|
| 75 |
+
getToolDiscoveryCommand: () => undefined,
|
| 76 |
+
getToolCallCommand: () => undefined,
|
| 77 |
+
getMcpServerCommand: () => undefined,
|
| 78 |
+
getMcpServers: () => undefined,
|
| 79 |
+
getUserAgent: () => 'test-agent',
|
| 80 |
+
getUserMemory: () => '',
|
| 81 |
+
setUserMemory: vi.fn(),
|
| 82 |
+
getGeminiMdFileCount: () => 0,
|
| 83 |
+
setGeminiMdFileCount: vi.fn(),
|
| 84 |
+
getToolRegistry: () =>
|
| 85 |
+
({
|
| 86 |
+
registerTool: vi.fn(),
|
| 87 |
+
discoverTools: vi.fn(),
|
| 88 |
+
}) as unknown as ToolRegistry,
|
| 89 |
+
};
|
| 90 |
+
const mockConfig = mockConfigInternal as unknown as Config;
|
| 91 |
+
// --- END MOCKS ---
|
| 92 |
+
|
| 93 |
+
describe('WriteFileTool', () => {
|
| 94 |
+
let tool: WriteFileTool;
|
| 95 |
+
let tempDir: string;
|
| 96 |
+
|
| 97 |
+
beforeEach(() => {
|
| 98 |
+
vi.clearAllMocks();
|
| 99 |
+
// Create a unique temporary directory for files created outside the root
|
| 100 |
+
tempDir = fs.mkdtempSync(
|
| 101 |
+
path.join(os.tmpdir(), 'write-file-test-external-'),
|
| 102 |
+
);
|
| 103 |
+
// Ensure the rootDir for the tool exists
|
| 104 |
+
if (!fs.existsSync(rootDir)) {
|
| 105 |
+
fs.mkdirSync(rootDir, { recursive: true });
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// Setup GeminiClient mock
|
| 109 |
+
mockGeminiClientInstance = new (vi.mocked(GeminiClient))(
|
| 110 |
+
mockConfig,
|
| 111 |
+
) as Mocked<GeminiClient>;
|
| 112 |
+
vi.mocked(GeminiClient).mockImplementation(() => mockGeminiClientInstance);
|
| 113 |
+
|
| 114 |
+
vi.mocked(ensureCorrectEdit).mockImplementation(mockEnsureCorrectEdit);
|
| 115 |
+
vi.mocked(ensureCorrectFileContent).mockImplementation(
|
| 116 |
+
mockEnsureCorrectFileContent,
|
| 117 |
+
);
|
| 118 |
+
|
| 119 |
+
// Now that mockGeminiClientInstance is initialized, set the mock implementation for getGeminiClient
|
| 120 |
+
mockConfigInternal.getGeminiClient.mockReturnValue(
|
| 121 |
+
mockGeminiClientInstance,
|
| 122 |
+
);
|
| 123 |
+
mockConfigInternal.getIdeClient.mockReturnValue({
|
| 124 |
+
openDiff: vi.fn(),
|
| 125 |
+
closeDiff: vi.fn(),
|
| 126 |
+
getIdeContext: vi.fn(),
|
| 127 |
+
subscribeToIdeContext: vi.fn(),
|
| 128 |
+
isCodeTrackerEnabled: vi.fn(),
|
| 129 |
+
getTrackedCode: vi.fn(),
|
| 130 |
+
});
|
| 131 |
+
|
| 132 |
+
tool = new WriteFileTool(mockConfig);
|
| 133 |
+
|
| 134 |
+
// Reset mocks before each test
|
| 135 |
+
mockConfigInternal.getApprovalMode.mockReturnValue(ApprovalMode.DEFAULT);
|
| 136 |
+
mockConfigInternal.setApprovalMode.mockClear();
|
| 137 |
+
mockEnsureCorrectEdit.mockReset();
|
| 138 |
+
mockEnsureCorrectFileContent.mockReset();
|
| 139 |
+
|
| 140 |
+
// Default mock implementations that return valid structures
|
| 141 |
+
mockEnsureCorrectEdit.mockImplementation(
|
| 142 |
+
async (
|
| 143 |
+
filePath: string,
|
| 144 |
+
_currentContent: string,
|
| 145 |
+
params: EditToolParams,
|
| 146 |
+
_client: GeminiClient,
|
| 147 |
+
signal?: AbortSignal, // Make AbortSignal optional to match usage
|
| 148 |
+
): Promise<CorrectedEditResult> => {
|
| 149 |
+
if (signal?.aborted) {
|
| 150 |
+
return Promise.reject(new Error('Aborted'));
|
| 151 |
+
}
|
| 152 |
+
return Promise.resolve({
|
| 153 |
+
params: { ...params, new_string: params.new_string ?? '' },
|
| 154 |
+
occurrences: 1,
|
| 155 |
+
});
|
| 156 |
+
},
|
| 157 |
+
);
|
| 158 |
+
mockEnsureCorrectFileContent.mockImplementation(
|
| 159 |
+
async (
|
| 160 |
+
content: string,
|
| 161 |
+
_client: GeminiClient,
|
| 162 |
+
signal?: AbortSignal,
|
| 163 |
+
): Promise<string> => {
|
| 164 |
+
// Make AbortSignal optional
|
| 165 |
+
if (signal?.aborted) {
|
| 166 |
+
return Promise.reject(new Error('Aborted'));
|
| 167 |
+
}
|
| 168 |
+
return Promise.resolve(content ?? '');
|
| 169 |
+
},
|
| 170 |
+
);
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
afterEach(() => {
|
| 174 |
+
// Clean up the temporary directories
|
| 175 |
+
if (fs.existsSync(tempDir)) {
|
| 176 |
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
| 177 |
+
}
|
| 178 |
+
if (fs.existsSync(rootDir)) {
|
| 179 |
+
fs.rmSync(rootDir, { recursive: true, force: true });
|
| 180 |
+
}
|
| 181 |
+
vi.clearAllMocks();
|
| 182 |
+
});
|
| 183 |
+
|
| 184 |
+
describe('build', () => {
|
| 185 |
+
it('should return an invocation for a valid absolute path within root', () => {
|
| 186 |
+
const params = {
|
| 187 |
+
file_path: path.join(rootDir, 'test.txt'),
|
| 188 |
+
content: 'hello',
|
| 189 |
+
};
|
| 190 |
+
const invocation = tool.build(params);
|
| 191 |
+
expect(invocation).toBeDefined();
|
| 192 |
+
expect(invocation.params).toEqual(params);
|
| 193 |
+
});
|
| 194 |
+
|
| 195 |
+
it('should throw an error for a relative path', () => {
|
| 196 |
+
const params = { file_path: 'test.txt', content: 'hello' };
|
| 197 |
+
expect(() => tool.build(params)).toThrow(/File path must be absolute/);
|
| 198 |
+
});
|
| 199 |
+
|
| 200 |
+
it('should throw an error for a path outside root', () => {
|
| 201 |
+
const outsidePath = path.resolve(tempDir, 'outside-root.txt');
|
| 202 |
+
const params = {
|
| 203 |
+
file_path: outsidePath,
|
| 204 |
+
content: 'hello',
|
| 205 |
+
};
|
| 206 |
+
expect(() => tool.build(params)).toThrow(
|
| 207 |
+
/File path must be within one of the workspace directories/,
|
| 208 |
+
);
|
| 209 |
+
});
|
| 210 |
+
|
| 211 |
+
it('should throw an error if path is a directory', () => {
|
| 212 |
+
const dirAsFilePath = path.join(rootDir, 'a_directory');
|
| 213 |
+
fs.mkdirSync(dirAsFilePath);
|
| 214 |
+
const params = {
|
| 215 |
+
file_path: dirAsFilePath,
|
| 216 |
+
content: 'hello',
|
| 217 |
+
};
|
| 218 |
+
expect(() => tool.build(params)).toThrow(
|
| 219 |
+
`Path is a directory, not a file: ${dirAsFilePath}`,
|
| 220 |
+
);
|
| 221 |
+
});
|
| 222 |
+
|
| 223 |
+
it('should throw an error if the content is null', () => {
|
| 224 |
+
const dirAsFilePath = path.join(rootDir, 'a_directory');
|
| 225 |
+
fs.mkdirSync(dirAsFilePath);
|
| 226 |
+
const params = {
|
| 227 |
+
file_path: dirAsFilePath,
|
| 228 |
+
content: null,
|
| 229 |
+
} as unknown as WriteFileToolParams; // Intentionally non-conforming
|
| 230 |
+
expect(() => tool.build(params)).toThrow('params/content must be string');
|
| 231 |
+
});
|
| 232 |
+
|
| 233 |
+
it('should throw error if the file_path is empty', () => {
|
| 234 |
+
const dirAsFilePath = path.join(rootDir, 'a_directory');
|
| 235 |
+
fs.mkdirSync(dirAsFilePath);
|
| 236 |
+
const params = {
|
| 237 |
+
file_path: '',
|
| 238 |
+
content: '',
|
| 239 |
+
};
|
| 240 |
+
expect(() => tool.build(params)).toThrow(`Missing or empty "file_path"`);
|
| 241 |
+
});
|
| 242 |
+
});
|
| 243 |
+
|
| 244 |
+
describe('getCorrectedFileContent', () => {
|
| 245 |
+
it('should call ensureCorrectFileContent for a new file', async () => {
|
| 246 |
+
const filePath = path.join(rootDir, 'new_corrected_file.txt');
|
| 247 |
+
const proposedContent = 'Proposed new content.';
|
| 248 |
+
const correctedContent = 'Corrected new content.';
|
| 249 |
+
const abortSignal = new AbortController().signal;
|
| 250 |
+
// Ensure the mock is set for this specific test case if needed, or rely on beforeEach
|
| 251 |
+
mockEnsureCorrectFileContent.mockResolvedValue(correctedContent);
|
| 252 |
+
|
| 253 |
+
const result = await getCorrectedFileContent(
|
| 254 |
+
mockConfig,
|
| 255 |
+
filePath,
|
| 256 |
+
proposedContent,
|
| 257 |
+
abortSignal,
|
| 258 |
+
);
|
| 259 |
+
|
| 260 |
+
expect(mockEnsureCorrectFileContent).toHaveBeenCalledWith(
|
| 261 |
+
proposedContent,
|
| 262 |
+
mockGeminiClientInstance,
|
| 263 |
+
abortSignal,
|
| 264 |
+
);
|
| 265 |
+
expect(mockEnsureCorrectEdit).not.toHaveBeenCalled();
|
| 266 |
+
expect(result.correctedContent).toBe(correctedContent);
|
| 267 |
+
expect(result.originalContent).toBe('');
|
| 268 |
+
expect(result.fileExists).toBe(false);
|
| 269 |
+
expect(result.error).toBeUndefined();
|
| 270 |
+
});
|
| 271 |
+
|
| 272 |
+
it('should call ensureCorrectEdit for an existing file', async () => {
|
| 273 |
+
const filePath = path.join(rootDir, 'existing_corrected_file.txt');
|
| 274 |
+
const originalContent = 'Original existing content.';
|
| 275 |
+
const proposedContent = 'Proposed replacement content.';
|
| 276 |
+
const correctedProposedContent = 'Corrected replacement content.';
|
| 277 |
+
const abortSignal = new AbortController().signal;
|
| 278 |
+
fs.writeFileSync(filePath, originalContent, 'utf8');
|
| 279 |
+
|
| 280 |
+
// Ensure this mock is active and returns the correct structure
|
| 281 |
+
mockEnsureCorrectEdit.mockResolvedValue({
|
| 282 |
+
params: {
|
| 283 |
+
file_path: filePath,
|
| 284 |
+
old_string: originalContent,
|
| 285 |
+
new_string: correctedProposedContent,
|
| 286 |
+
},
|
| 287 |
+
occurrences: 1,
|
| 288 |
+
} as CorrectedEditResult);
|
| 289 |
+
|
| 290 |
+
const result = await getCorrectedFileContent(
|
| 291 |
+
mockConfig,
|
| 292 |
+
filePath,
|
| 293 |
+
proposedContent,
|
| 294 |
+
abortSignal,
|
| 295 |
+
);
|
| 296 |
+
|
| 297 |
+
expect(mockEnsureCorrectEdit).toHaveBeenCalledWith(
|
| 298 |
+
filePath,
|
| 299 |
+
originalContent,
|
| 300 |
+
{
|
| 301 |
+
old_string: originalContent,
|
| 302 |
+
new_string: proposedContent,
|
| 303 |
+
file_path: filePath,
|
| 304 |
+
},
|
| 305 |
+
mockGeminiClientInstance,
|
| 306 |
+
abortSignal,
|
| 307 |
+
);
|
| 308 |
+
expect(mockEnsureCorrectFileContent).not.toHaveBeenCalled();
|
| 309 |
+
expect(result.correctedContent).toBe(correctedProposedContent);
|
| 310 |
+
expect(result.originalContent).toBe(originalContent);
|
| 311 |
+
expect(result.fileExists).toBe(true);
|
| 312 |
+
expect(result.error).toBeUndefined();
|
| 313 |
+
});
|
| 314 |
+
|
| 315 |
+
it('should return error if reading an existing file fails (e.g. permissions)', async () => {
|
| 316 |
+
const filePath = path.join(rootDir, 'unreadable_file.txt');
|
| 317 |
+
const proposedContent = 'some content';
|
| 318 |
+
const abortSignal = new AbortController().signal;
|
| 319 |
+
fs.writeFileSync(filePath, 'content', { mode: 0o000 });
|
| 320 |
+
|
| 321 |
+
const readError = new Error('Permission denied');
|
| 322 |
+
vi.spyOn(fsService, 'readTextFile').mockImplementationOnce(() =>
|
| 323 |
+
Promise.reject(readError),
|
| 324 |
+
);
|
| 325 |
+
|
| 326 |
+
const result = await getCorrectedFileContent(
|
| 327 |
+
mockConfig,
|
| 328 |
+
filePath,
|
| 329 |
+
proposedContent,
|
| 330 |
+
abortSignal,
|
| 331 |
+
);
|
| 332 |
+
|
| 333 |
+
expect(fsService.readTextFile).toHaveBeenCalledWith(filePath);
|
| 334 |
+
expect(mockEnsureCorrectEdit).not.toHaveBeenCalled();
|
| 335 |
+
expect(mockEnsureCorrectFileContent).not.toHaveBeenCalled();
|
| 336 |
+
expect(result.correctedContent).toBe(proposedContent);
|
| 337 |
+
expect(result.originalContent).toBe('');
|
| 338 |
+
expect(result.fileExists).toBe(true);
|
| 339 |
+
expect(result.error).toEqual({
|
| 340 |
+
message: 'Permission denied',
|
| 341 |
+
code: undefined,
|
| 342 |
+
});
|
| 343 |
+
|
| 344 |
+
fs.chmodSync(filePath, 0o600);
|
| 345 |
+
});
|
| 346 |
+
});
|
| 347 |
+
|
| 348 |
+
describe('shouldConfirmExecute', () => {
|
| 349 |
+
const abortSignal = new AbortController().signal;
|
| 350 |
+
|
| 351 |
+
it('should return false if _getCorrectedFileContent returns an error', async () => {
|
| 352 |
+
const filePath = path.join(rootDir, 'confirm_error_file.txt');
|
| 353 |
+
const params = { file_path: filePath, content: 'test content' };
|
| 354 |
+
fs.writeFileSync(filePath, 'original', { mode: 0o000 });
|
| 355 |
+
|
| 356 |
+
const readError = new Error('Simulated read error for confirmation');
|
| 357 |
+
vi.spyOn(fsService, 'readTextFile').mockImplementationOnce(() =>
|
| 358 |
+
Promise.reject(readError),
|
| 359 |
+
);
|
| 360 |
+
|
| 361 |
+
const invocation = tool.build(params);
|
| 362 |
+
const confirmation = await invocation.shouldConfirmExecute(abortSignal);
|
| 363 |
+
expect(confirmation).toBe(false);
|
| 364 |
+
|
| 365 |
+
fs.chmodSync(filePath, 0o600);
|
| 366 |
+
});
|
| 367 |
+
|
| 368 |
+
it('should request confirmation with diff for a new file (with corrected content)', async () => {
|
| 369 |
+
const filePath = path.join(rootDir, 'confirm_new_file.txt');
|
| 370 |
+
const proposedContent = 'Proposed new content for confirmation.';
|
| 371 |
+
const correctedContent = 'Corrected new content for confirmation.';
|
| 372 |
+
mockEnsureCorrectFileContent.mockResolvedValue(correctedContent); // Ensure this mock is active
|
| 373 |
+
|
| 374 |
+
const params = { file_path: filePath, content: proposedContent };
|
| 375 |
+
const invocation = tool.build(params);
|
| 376 |
+
const confirmation = (await invocation.shouldConfirmExecute(
|
| 377 |
+
abortSignal,
|
| 378 |
+
)) as ToolEditConfirmationDetails;
|
| 379 |
+
|
| 380 |
+
expect(mockEnsureCorrectFileContent).toHaveBeenCalledWith(
|
| 381 |
+
proposedContent,
|
| 382 |
+
mockGeminiClientInstance,
|
| 383 |
+
abortSignal,
|
| 384 |
+
);
|
| 385 |
+
expect(confirmation).toEqual(
|
| 386 |
+
expect.objectContaining({
|
| 387 |
+
title: `Confirm Write: ${path.basename(filePath)}`,
|
| 388 |
+
fileName: 'confirm_new_file.txt',
|
| 389 |
+
fileDiff: expect.stringContaining(correctedContent),
|
| 390 |
+
}),
|
| 391 |
+
);
|
| 392 |
+
expect(confirmation.fileDiff).toMatch(
|
| 393 |
+
/--- confirm_new_file.txt\tCurrent/,
|
| 394 |
+
);
|
| 395 |
+
expect(confirmation.fileDiff).toMatch(
|
| 396 |
+
/\+\+\+ confirm_new_file.txt\tProposed/,
|
| 397 |
+
);
|
| 398 |
+
});
|
| 399 |
+
|
| 400 |
+
it('should request confirmation with diff for an existing file (with corrected content)', async () => {
|
| 401 |
+
const filePath = path.join(rootDir, 'confirm_existing_file.txt');
|
| 402 |
+
const originalContent = 'Original content for confirmation.';
|
| 403 |
+
const proposedContent = 'Proposed replacement for confirmation.';
|
| 404 |
+
const correctedProposedContent =
|
| 405 |
+
'Corrected replacement for confirmation.';
|
| 406 |
+
fs.writeFileSync(filePath, originalContent, 'utf8');
|
| 407 |
+
|
| 408 |
+
mockEnsureCorrectEdit.mockResolvedValue({
|
| 409 |
+
params: {
|
| 410 |
+
file_path: filePath,
|
| 411 |
+
old_string: originalContent,
|
| 412 |
+
new_string: correctedProposedContent,
|
| 413 |
+
},
|
| 414 |
+
occurrences: 1,
|
| 415 |
+
});
|
| 416 |
+
|
| 417 |
+
const params = { file_path: filePath, content: proposedContent };
|
| 418 |
+
const invocation = tool.build(params);
|
| 419 |
+
const confirmation = (await invocation.shouldConfirmExecute(
|
| 420 |
+
abortSignal,
|
| 421 |
+
)) as ToolEditConfirmationDetails;
|
| 422 |
+
|
| 423 |
+
expect(mockEnsureCorrectEdit).toHaveBeenCalledWith(
|
| 424 |
+
filePath,
|
| 425 |
+
originalContent,
|
| 426 |
+
{
|
| 427 |
+
old_string: originalContent,
|
| 428 |
+
new_string: proposedContent,
|
| 429 |
+
file_path: filePath,
|
| 430 |
+
},
|
| 431 |
+
mockGeminiClientInstance,
|
| 432 |
+
abortSignal,
|
| 433 |
+
);
|
| 434 |
+
expect(confirmation).toEqual(
|
| 435 |
+
expect.objectContaining({
|
| 436 |
+
title: `Confirm Write: ${path.basename(filePath)}`,
|
| 437 |
+
fileName: 'confirm_existing_file.txt',
|
| 438 |
+
fileDiff: expect.stringContaining(correctedProposedContent),
|
| 439 |
+
}),
|
| 440 |
+
);
|
| 441 |
+
expect(confirmation.fileDiff).toMatch(
|
| 442 |
+
originalContent.replace(/[.*+?^${}()|[\\]\\]/g, '\\$&'),
|
| 443 |
+
);
|
| 444 |
+
});
|
| 445 |
+
});
|
| 446 |
+
|
| 447 |
+
describe('execute', () => {
|
| 448 |
+
const abortSignal = new AbortController().signal;
|
| 449 |
+
|
| 450 |
+
it('should return error if _getCorrectedFileContent returns an error during execute', async () => {
|
| 451 |
+
const filePath = path.join(rootDir, 'execute_error_file.txt');
|
| 452 |
+
const params = { file_path: filePath, content: 'test content' };
|
| 453 |
+
fs.writeFileSync(filePath, 'original', { mode: 0o000 });
|
| 454 |
+
|
| 455 |
+
vi.spyOn(fsService, 'readTextFile').mockImplementationOnce(() => {
|
| 456 |
+
const readError = new Error('Simulated read error for execute');
|
| 457 |
+
return Promise.reject(readError);
|
| 458 |
+
});
|
| 459 |
+
|
| 460 |
+
const invocation = tool.build(params);
|
| 461 |
+
const result = await invocation.execute(abortSignal);
|
| 462 |
+
expect(result.llmContent).toContain('Error checking existing file');
|
| 463 |
+
expect(result.returnDisplay).toMatch(
|
| 464 |
+
/Error checking existing file: Simulated read error for execute/,
|
| 465 |
+
);
|
| 466 |
+
expect(result.error).toEqual({
|
| 467 |
+
message:
|
| 468 |
+
'Error checking existing file: Simulated read error for execute',
|
| 469 |
+
type: ToolErrorType.FILE_WRITE_FAILURE,
|
| 470 |
+
});
|
| 471 |
+
|
| 472 |
+
fs.chmodSync(filePath, 0o600);
|
| 473 |
+
});
|
| 474 |
+
|
| 475 |
+
it('should write a new file with corrected content and return diff', async () => {
|
| 476 |
+
const filePath = path.join(rootDir, 'execute_new_corrected_file.txt');
|
| 477 |
+
const proposedContent = 'Proposed new content for execute.';
|
| 478 |
+
const correctedContent = 'Corrected new content for execute.';
|
| 479 |
+
mockEnsureCorrectFileContent.mockResolvedValue(correctedContent);
|
| 480 |
+
|
| 481 |
+
const params = { file_path: filePath, content: proposedContent };
|
| 482 |
+
const invocation = tool.build(params);
|
| 483 |
+
|
| 484 |
+
const confirmDetails = await invocation.shouldConfirmExecute(abortSignal);
|
| 485 |
+
if (
|
| 486 |
+
typeof confirmDetails === 'object' &&
|
| 487 |
+
'onConfirm' in confirmDetails &&
|
| 488 |
+
confirmDetails.onConfirm
|
| 489 |
+
) {
|
| 490 |
+
await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce);
|
| 491 |
+
}
|
| 492 |
+
|
| 493 |
+
const result = await invocation.execute(abortSignal);
|
| 494 |
+
|
| 495 |
+
expect(mockEnsureCorrectFileContent).toHaveBeenCalledWith(
|
| 496 |
+
proposedContent,
|
| 497 |
+
mockGeminiClientInstance,
|
| 498 |
+
abortSignal,
|
| 499 |
+
);
|
| 500 |
+
expect(result.llmContent).toMatch(
|
| 501 |
+
/Successfully created and wrote to new file/,
|
| 502 |
+
);
|
| 503 |
+
expect(fs.existsSync(filePath)).toBe(true);
|
| 504 |
+
const writtenContent = await fsService.readTextFile(filePath);
|
| 505 |
+
expect(writtenContent).toBe(correctedContent);
|
| 506 |
+
const display = result.returnDisplay as FileDiff;
|
| 507 |
+
expect(display.fileName).toBe('execute_new_corrected_file.txt');
|
| 508 |
+
expect(display.fileDiff).toMatch(
|
| 509 |
+
/--- execute_new_corrected_file.txt\tOriginal/,
|
| 510 |
+
);
|
| 511 |
+
expect(display.fileDiff).toMatch(
|
| 512 |
+
/\+\+\+ execute_new_corrected_file.txt\tWritten/,
|
| 513 |
+
);
|
| 514 |
+
expect(display.fileDiff).toMatch(
|
| 515 |
+
correctedContent.replace(/[.*+?^${}()|[\\]\\]/g, '\\$&'),
|
| 516 |
+
);
|
| 517 |
+
});
|
| 518 |
+
|
| 519 |
+
it('should overwrite an existing file with corrected content and return diff', async () => {
|
| 520 |
+
const filePath = path.join(
|
| 521 |
+
rootDir,
|
| 522 |
+
'execute_existing_corrected_file.txt',
|
| 523 |
+
);
|
| 524 |
+
const initialContent = 'Initial content for execute.';
|
| 525 |
+
const proposedContent = 'Proposed overwrite for execute.';
|
| 526 |
+
const correctedProposedContent = 'Corrected overwrite for execute.';
|
| 527 |
+
fs.writeFileSync(filePath, initialContent, 'utf8');
|
| 528 |
+
|
| 529 |
+
mockEnsureCorrectEdit.mockResolvedValue({
|
| 530 |
+
params: {
|
| 531 |
+
file_path: filePath,
|
| 532 |
+
old_string: initialContent,
|
| 533 |
+
new_string: correctedProposedContent,
|
| 534 |
+
},
|
| 535 |
+
occurrences: 1,
|
| 536 |
+
});
|
| 537 |
+
|
| 538 |
+
const params = { file_path: filePath, content: proposedContent };
|
| 539 |
+
const invocation = tool.build(params);
|
| 540 |
+
|
| 541 |
+
const confirmDetails = await invocation.shouldConfirmExecute(abortSignal);
|
| 542 |
+
if (
|
| 543 |
+
typeof confirmDetails === 'object' &&
|
| 544 |
+
'onConfirm' in confirmDetails &&
|
| 545 |
+
confirmDetails.onConfirm
|
| 546 |
+
) {
|
| 547 |
+
await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce);
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
const result = await invocation.execute(abortSignal);
|
| 551 |
+
|
| 552 |
+
expect(mockEnsureCorrectEdit).toHaveBeenCalledWith(
|
| 553 |
+
filePath,
|
| 554 |
+
initialContent,
|
| 555 |
+
{
|
| 556 |
+
old_string: initialContent,
|
| 557 |
+
new_string: proposedContent,
|
| 558 |
+
file_path: filePath,
|
| 559 |
+
},
|
| 560 |
+
mockGeminiClientInstance,
|
| 561 |
+
abortSignal,
|
| 562 |
+
);
|
| 563 |
+
expect(result.llmContent).toMatch(/Successfully overwrote file/);
|
| 564 |
+
const writtenContent = await fsService.readTextFile(filePath);
|
| 565 |
+
expect(writtenContent).toBe(correctedProposedContent);
|
| 566 |
+
const display = result.returnDisplay as FileDiff;
|
| 567 |
+
expect(display.fileName).toBe('execute_existing_corrected_file.txt');
|
| 568 |
+
expect(display.fileDiff).toMatch(
|
| 569 |
+
initialContent.replace(/[.*+?^${}()|[\\]\\]/g, '\\$&'),
|
| 570 |
+
);
|
| 571 |
+
expect(display.fileDiff).toMatch(
|
| 572 |
+
correctedProposedContent.replace(/[.*+?^${}()|[\\]\\]/g, '\\$&'),
|
| 573 |
+
);
|
| 574 |
+
});
|
| 575 |
+
|
| 576 |
+
it('should create directory if it does not exist', async () => {
|
| 577 |
+
const dirPath = path.join(rootDir, 'new_dir_for_write');
|
| 578 |
+
const filePath = path.join(dirPath, 'file_in_new_dir.txt');
|
| 579 |
+
const content = 'Content in new directory';
|
| 580 |
+
mockEnsureCorrectFileContent.mockResolvedValue(content); // Ensure this mock is active
|
| 581 |
+
|
| 582 |
+
const params = { file_path: filePath, content };
|
| 583 |
+
const invocation = tool.build(params);
|
| 584 |
+
// Simulate confirmation if your logic requires it before execute, or remove if not needed for this path
|
| 585 |
+
const confirmDetails = await invocation.shouldConfirmExecute(abortSignal);
|
| 586 |
+
if (
|
| 587 |
+
typeof confirmDetails === 'object' &&
|
| 588 |
+
'onConfirm' in confirmDetails &&
|
| 589 |
+
confirmDetails.onConfirm
|
| 590 |
+
) {
|
| 591 |
+
await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce);
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
await invocation.execute(abortSignal);
|
| 595 |
+
|
| 596 |
+
expect(fs.existsSync(dirPath)).toBe(true);
|
| 597 |
+
expect(fs.statSync(dirPath).isDirectory()).toBe(true);
|
| 598 |
+
expect(fs.existsSync(filePath)).toBe(true);
|
| 599 |
+
expect(fs.readFileSync(filePath, 'utf8')).toBe(content);
|
| 600 |
+
});
|
| 601 |
+
|
| 602 |
+
it('should include modification message when proposed content is modified', async () => {
|
| 603 |
+
const filePath = path.join(rootDir, 'new_file_modified.txt');
|
| 604 |
+
const content = 'New file content modified by user';
|
| 605 |
+
mockEnsureCorrectFileContent.mockResolvedValue(content);
|
| 606 |
+
|
| 607 |
+
const params = {
|
| 608 |
+
file_path: filePath,
|
| 609 |
+
content,
|
| 610 |
+
modified_by_user: true,
|
| 611 |
+
};
|
| 612 |
+
const invocation = tool.build(params);
|
| 613 |
+
const result = await invocation.execute(abortSignal);
|
| 614 |
+
|
| 615 |
+
expect(result.llmContent).toMatch(/User modified the `content`/);
|
| 616 |
+
});
|
| 617 |
+
|
| 618 |
+
it('should not include modification message when proposed content is not modified', async () => {
|
| 619 |
+
const filePath = path.join(rootDir, 'new_file_unmodified.txt');
|
| 620 |
+
const content = 'New file content not modified';
|
| 621 |
+
mockEnsureCorrectFileContent.mockResolvedValue(content);
|
| 622 |
+
|
| 623 |
+
const params = {
|
| 624 |
+
file_path: filePath,
|
| 625 |
+
content,
|
| 626 |
+
modified_by_user: false,
|
| 627 |
+
};
|
| 628 |
+
const invocation = tool.build(params);
|
| 629 |
+
const result = await invocation.execute(abortSignal);
|
| 630 |
+
|
| 631 |
+
expect(result.llmContent).not.toMatch(/User modified the `content`/);
|
| 632 |
+
});
|
| 633 |
+
|
| 634 |
+
it('should not include modification message when modified_by_user is not provided', async () => {
|
| 635 |
+
const filePath = path.join(rootDir, 'new_file_unmodified.txt');
|
| 636 |
+
const content = 'New file content not modified';
|
| 637 |
+
mockEnsureCorrectFileContent.mockResolvedValue(content);
|
| 638 |
+
|
| 639 |
+
const params = {
|
| 640 |
+
file_path: filePath,
|
| 641 |
+
content,
|
| 642 |
+
};
|
| 643 |
+
const invocation = tool.build(params);
|
| 644 |
+
const result = await invocation.execute(abortSignal);
|
| 645 |
+
|
| 646 |
+
expect(result.llmContent).not.toMatch(/User modified the `content`/);
|
| 647 |
+
});
|
| 648 |
+
});
|
| 649 |
+
|
| 650 |
+
describe('workspace boundary validation', () => {
|
| 651 |
+
it('should validate paths are within workspace root', () => {
|
| 652 |
+
const params = {
|
| 653 |
+
file_path: path.join(rootDir, 'file.txt'),
|
| 654 |
+
content: 'test content',
|
| 655 |
+
};
|
| 656 |
+
expect(() => tool.build(params)).not.toThrow();
|
| 657 |
+
});
|
| 658 |
+
|
| 659 |
+
it('should reject paths outside workspace root', () => {
|
| 660 |
+
const params = {
|
| 661 |
+
file_path: '/etc/passwd',
|
| 662 |
+
content: 'malicious',
|
| 663 |
+
};
|
| 664 |
+
expect(() => tool.build(params)).toThrow(
|
| 665 |
+
/File path must be within one of the workspace directories/,
|
| 666 |
+
);
|
| 667 |
+
});
|
| 668 |
+
});
|
| 669 |
+
|
| 670 |
+
describe('specific error types for write failures', () => {
|
| 671 |
+
const abortSignal = new AbortController().signal;
|
| 672 |
+
|
| 673 |
+
it('should return PERMISSION_DENIED error when write fails with EACCES', async () => {
|
| 674 |
+
const filePath = path.join(rootDir, 'permission_denied_file.txt');
|
| 675 |
+
const content = 'test content';
|
| 676 |
+
|
| 677 |
+
// Mock FileSystemService writeTextFile to throw EACCES error
|
| 678 |
+
vi.spyOn(fsService, 'writeTextFile').mockImplementationOnce(() => {
|
| 679 |
+
const error = new Error('Permission denied') as NodeJS.ErrnoException;
|
| 680 |
+
error.code = 'EACCES';
|
| 681 |
+
return Promise.reject(error);
|
| 682 |
+
});
|
| 683 |
+
|
| 684 |
+
const params = { file_path: filePath, content };
|
| 685 |
+
const invocation = tool.build(params);
|
| 686 |
+
const result = await invocation.execute(abortSignal);
|
| 687 |
+
|
| 688 |
+
expect(result.error?.type).toBe(ToolErrorType.PERMISSION_DENIED);
|
| 689 |
+
expect(result.llmContent).toContain(
|
| 690 |
+
`Permission denied writing to file: ${filePath} (EACCES)`,
|
| 691 |
+
);
|
| 692 |
+
expect(result.returnDisplay).toContain(
|
| 693 |
+
`Permission denied writing to file: ${filePath} (EACCES)`,
|
| 694 |
+
);
|
| 695 |
+
});
|
| 696 |
+
|
| 697 |
+
it('should return NO_SPACE_LEFT error when write fails with ENOSPC', async () => {
|
| 698 |
+
const filePath = path.join(rootDir, 'no_space_file.txt');
|
| 699 |
+
const content = 'test content';
|
| 700 |
+
|
| 701 |
+
// Mock FileSystemService writeTextFile to throw ENOSPC error
|
| 702 |
+
vi.spyOn(fsService, 'writeTextFile').mockImplementationOnce(() => {
|
| 703 |
+
const error = new Error(
|
| 704 |
+
'No space left on device',
|
| 705 |
+
) as NodeJS.ErrnoException;
|
| 706 |
+
error.code = 'ENOSPC';
|
| 707 |
+
return Promise.reject(error);
|
| 708 |
+
});
|
| 709 |
+
|
| 710 |
+
const params = { file_path: filePath, content };
|
| 711 |
+
const invocation = tool.build(params);
|
| 712 |
+
const result = await invocation.execute(abortSignal);
|
| 713 |
+
|
| 714 |
+
expect(result.error?.type).toBe(ToolErrorType.NO_SPACE_LEFT);
|
| 715 |
+
expect(result.llmContent).toContain(
|
| 716 |
+
`No space left on device: ${filePath} (ENOSPC)`,
|
| 717 |
+
);
|
| 718 |
+
expect(result.returnDisplay).toContain(
|
| 719 |
+
`No space left on device: ${filePath} (ENOSPC)`,
|
| 720 |
+
);
|
| 721 |
+
});
|
| 722 |
+
|
| 723 |
+
it('should return TARGET_IS_DIRECTORY error when write fails with EISDIR', async () => {
|
| 724 |
+
const dirPath = path.join(rootDir, 'test_directory');
|
| 725 |
+
const content = 'test content';
|
| 726 |
+
|
| 727 |
+
// Mock fs.existsSync to return false to bypass validation
|
| 728 |
+
const originalExistsSync = fs.existsSync;
|
| 729 |
+
vi.spyOn(fs, 'existsSync').mockImplementation((path) => {
|
| 730 |
+
if (path === dirPath) {
|
| 731 |
+
return false; // Pretend directory doesn't exist to bypass validation
|
| 732 |
+
}
|
| 733 |
+
return originalExistsSync(path as string);
|
| 734 |
+
});
|
| 735 |
+
|
| 736 |
+
// Mock FileSystemService writeTextFile to throw EISDIR error
|
| 737 |
+
vi.spyOn(fsService, 'writeTextFile').mockImplementationOnce(() => {
|
| 738 |
+
const error = new Error('Is a directory') as NodeJS.ErrnoException;
|
| 739 |
+
error.code = 'EISDIR';
|
| 740 |
+
return Promise.reject(error);
|
| 741 |
+
});
|
| 742 |
+
|
| 743 |
+
const params = { file_path: dirPath, content };
|
| 744 |
+
const invocation = tool.build(params);
|
| 745 |
+
const result = await invocation.execute(abortSignal);
|
| 746 |
+
|
| 747 |
+
expect(result.error?.type).toBe(ToolErrorType.TARGET_IS_DIRECTORY);
|
| 748 |
+
expect(result.llmContent).toContain(
|
| 749 |
+
`Target is a directory, not a file: ${dirPath} (EISDIR)`,
|
| 750 |
+
);
|
| 751 |
+
expect(result.returnDisplay).toContain(
|
| 752 |
+
`Target is a directory, not a file: ${dirPath} (EISDIR)`,
|
| 753 |
+
);
|
| 754 |
+
|
| 755 |
+
vi.spyOn(fs, 'existsSync').mockImplementation(originalExistsSync);
|
| 756 |
+
});
|
| 757 |
+
|
| 758 |
+
it('should return FILE_WRITE_FAILURE for generic write errors', async () => {
|
| 759 |
+
const filePath = path.join(rootDir, 'generic_error_file.txt');
|
| 760 |
+
const content = 'test content';
|
| 761 |
+
|
| 762 |
+
// Ensure fs.existsSync is not mocked for this test
|
| 763 |
+
vi.restoreAllMocks();
|
| 764 |
+
|
| 765 |
+
// Mock FileSystemService writeTextFile to throw generic error
|
| 766 |
+
vi.spyOn(fsService, 'writeTextFile').mockImplementationOnce(() =>
|
| 767 |
+
Promise.reject(new Error('Generic write error')),
|
| 768 |
+
);
|
| 769 |
+
|
| 770 |
+
const params = { file_path: filePath, content };
|
| 771 |
+
const invocation = tool.build(params);
|
| 772 |
+
const result = await invocation.execute(abortSignal);
|
| 773 |
+
|
| 774 |
+
expect(result.error?.type).toBe(ToolErrorType.FILE_WRITE_FAILURE);
|
| 775 |
+
expect(result.llmContent).toContain(
|
| 776 |
+
'Error writing to file: Generic write error',
|
| 777 |
+
);
|
| 778 |
+
expect(result.returnDisplay).toContain(
|
| 779 |
+
'Error writing to file: Generic write error',
|
| 780 |
+
);
|
| 781 |
+
});
|
| 782 |
+
});
|
| 783 |
+
});
|
projects/ui/qwen-code/packages/core/src/tools/write-file.ts
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 * as Diff from 'diff';
|
| 10 |
+
import { Config, ApprovalMode } from '../config/config.js';
|
| 11 |
+
import {
|
| 12 |
+
BaseDeclarativeTool,
|
| 13 |
+
BaseToolInvocation,
|
| 14 |
+
FileDiff,
|
| 15 |
+
Kind,
|
| 16 |
+
ToolCallConfirmationDetails,
|
| 17 |
+
ToolConfirmationOutcome,
|
| 18 |
+
ToolEditConfirmationDetails,
|
| 19 |
+
ToolInvocation,
|
| 20 |
+
ToolLocation,
|
| 21 |
+
ToolResult,
|
| 22 |
+
} from './tools.js';
|
| 23 |
+
import { ToolErrorType } from './tool-error.js';
|
| 24 |
+
import { makeRelative, shortenPath } from '../utils/paths.js';
|
| 25 |
+
import { getErrorMessage, isNodeError } from '../utils/errors.js';
|
| 26 |
+
import {
|
| 27 |
+
ensureCorrectEdit,
|
| 28 |
+
ensureCorrectFileContent,
|
| 29 |
+
} from '../utils/editCorrector.js';
|
| 30 |
+
import { DEFAULT_DIFF_OPTIONS, getDiffStat } from './diffOptions.js';
|
| 31 |
+
import { ModifiableDeclarativeTool, ModifyContext } from './modifiable-tool.js';
|
| 32 |
+
import { getSpecificMimeType } from '../utils/fileUtils.js';
|
| 33 |
+
import {
|
| 34 |
+
recordFileOperationMetric,
|
| 35 |
+
FileOperation,
|
| 36 |
+
} from '../telemetry/metrics.js';
|
| 37 |
+
import { IDEConnectionStatus } from '../ide/ide-client.js';
|
| 38 |
+
|
| 39 |
+
/**
|
| 40 |
+
* Parameters for the WriteFile tool
|
| 41 |
+
*/
|
| 42 |
+
export interface WriteFileToolParams {
|
| 43 |
+
/**
|
| 44 |
+
* The absolute path to the file to write to
|
| 45 |
+
*/
|
| 46 |
+
file_path: string;
|
| 47 |
+
|
| 48 |
+
/**
|
| 49 |
+
* The content to write to the file
|
| 50 |
+
*/
|
| 51 |
+
content: string;
|
| 52 |
+
|
| 53 |
+
/**
|
| 54 |
+
* Whether the proposed content was modified by the user.
|
| 55 |
+
*/
|
| 56 |
+
modified_by_user?: boolean;
|
| 57 |
+
|
| 58 |
+
/**
|
| 59 |
+
* Initially proposed content.
|
| 60 |
+
*/
|
| 61 |
+
ai_proposed_content?: string;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
interface GetCorrectedFileContentResult {
|
| 65 |
+
originalContent: string;
|
| 66 |
+
correctedContent: string;
|
| 67 |
+
fileExists: boolean;
|
| 68 |
+
error?: { message: string; code?: string };
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
export async function getCorrectedFileContent(
|
| 72 |
+
config: Config,
|
| 73 |
+
filePath: string,
|
| 74 |
+
proposedContent: string,
|
| 75 |
+
abortSignal: AbortSignal,
|
| 76 |
+
): Promise<GetCorrectedFileContentResult> {
|
| 77 |
+
let originalContent = '';
|
| 78 |
+
let fileExists = false;
|
| 79 |
+
let correctedContent = proposedContent;
|
| 80 |
+
|
| 81 |
+
try {
|
| 82 |
+
originalContent = await config
|
| 83 |
+
.getFileSystemService()
|
| 84 |
+
.readTextFile(filePath);
|
| 85 |
+
fileExists = true; // File exists and was read
|
| 86 |
+
} catch (err) {
|
| 87 |
+
if (isNodeError(err) && err.code === 'ENOENT') {
|
| 88 |
+
fileExists = false;
|
| 89 |
+
originalContent = '';
|
| 90 |
+
} else {
|
| 91 |
+
// File exists but could not be read (permissions, etc.)
|
| 92 |
+
fileExists = true; // Mark as existing but problematic
|
| 93 |
+
originalContent = ''; // Can't use its content
|
| 94 |
+
const error = {
|
| 95 |
+
message: getErrorMessage(err),
|
| 96 |
+
code: isNodeError(err) ? err.code : undefined,
|
| 97 |
+
};
|
| 98 |
+
// Return early as we can't proceed with content correction meaningfully
|
| 99 |
+
return { originalContent, correctedContent, fileExists, error };
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
// If readError is set, we have returned.
|
| 104 |
+
// So, file was either read successfully (fileExists=true, originalContent set)
|
| 105 |
+
// or it was ENOENT (fileExists=false, originalContent='').
|
| 106 |
+
|
| 107 |
+
if (fileExists) {
|
| 108 |
+
// This implies originalContent is available
|
| 109 |
+
const { params: correctedParams } = await ensureCorrectEdit(
|
| 110 |
+
filePath,
|
| 111 |
+
originalContent,
|
| 112 |
+
{
|
| 113 |
+
old_string: originalContent, // Treat entire current content as old_string
|
| 114 |
+
new_string: proposedContent,
|
| 115 |
+
file_path: filePath,
|
| 116 |
+
},
|
| 117 |
+
config.getGeminiClient(),
|
| 118 |
+
abortSignal,
|
| 119 |
+
);
|
| 120 |
+
correctedContent = correctedParams.new_string;
|
| 121 |
+
} else {
|
| 122 |
+
// This implies new file (ENOENT)
|
| 123 |
+
correctedContent = await ensureCorrectFileContent(
|
| 124 |
+
proposedContent,
|
| 125 |
+
config.getGeminiClient(),
|
| 126 |
+
abortSignal,
|
| 127 |
+
);
|
| 128 |
+
}
|
| 129 |
+
return { originalContent, correctedContent, fileExists };
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
class WriteFileToolInvocation extends BaseToolInvocation<
|
| 133 |
+
WriteFileToolParams,
|
| 134 |
+
ToolResult
|
| 135 |
+
> {
|
| 136 |
+
constructor(
|
| 137 |
+
private readonly config: Config,
|
| 138 |
+
params: WriteFileToolParams,
|
| 139 |
+
) {
|
| 140 |
+
super(params);
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
override toolLocations(): ToolLocation[] {
|
| 144 |
+
return [{ path: this.params.file_path }];
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
override getDescription(): string {
|
| 148 |
+
const relativePath = makeRelative(
|
| 149 |
+
this.params.file_path,
|
| 150 |
+
this.config.getTargetDir(),
|
| 151 |
+
);
|
| 152 |
+
return `Writing to ${shortenPath(relativePath)}`;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
override async shouldConfirmExecute(
|
| 156 |
+
abortSignal: AbortSignal,
|
| 157 |
+
): Promise<ToolCallConfirmationDetails | false> {
|
| 158 |
+
if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
|
| 159 |
+
return false;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
const correctedContentResult = await getCorrectedFileContent(
|
| 163 |
+
this.config,
|
| 164 |
+
this.params.file_path,
|
| 165 |
+
this.params.content,
|
| 166 |
+
abortSignal,
|
| 167 |
+
);
|
| 168 |
+
|
| 169 |
+
if (correctedContentResult.error) {
|
| 170 |
+
// If file exists but couldn't be read, we can't show a diff for confirmation.
|
| 171 |
+
return false;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
const { originalContent, correctedContent } = correctedContentResult;
|
| 175 |
+
const relativePath = makeRelative(
|
| 176 |
+
this.params.file_path,
|
| 177 |
+
this.config.getTargetDir(),
|
| 178 |
+
);
|
| 179 |
+
const fileName = path.basename(this.params.file_path);
|
| 180 |
+
|
| 181 |
+
const fileDiff = Diff.createPatch(
|
| 182 |
+
fileName,
|
| 183 |
+
originalContent, // Original content (empty if new file or unreadable)
|
| 184 |
+
correctedContent, // Content after potential correction
|
| 185 |
+
'Current',
|
| 186 |
+
'Proposed',
|
| 187 |
+
DEFAULT_DIFF_OPTIONS,
|
| 188 |
+
);
|
| 189 |
+
|
| 190 |
+
const ideClient = this.config.getIdeClient();
|
| 191 |
+
const ideConfirmation =
|
| 192 |
+
this.config.getIdeMode() &&
|
| 193 |
+
ideClient.getConnectionStatus().status === IDEConnectionStatus.Connected
|
| 194 |
+
? ideClient.openDiff(this.params.file_path, correctedContent)
|
| 195 |
+
: undefined;
|
| 196 |
+
|
| 197 |
+
const confirmationDetails: ToolEditConfirmationDetails = {
|
| 198 |
+
type: 'edit',
|
| 199 |
+
title: `Confirm Write: ${shortenPath(relativePath)}`,
|
| 200 |
+
fileName,
|
| 201 |
+
filePath: this.params.file_path,
|
| 202 |
+
fileDiff,
|
| 203 |
+
originalContent,
|
| 204 |
+
newContent: correctedContent,
|
| 205 |
+
onConfirm: async (outcome: ToolConfirmationOutcome) => {
|
| 206 |
+
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
| 207 |
+
this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
if (ideConfirmation) {
|
| 211 |
+
const result = await ideConfirmation;
|
| 212 |
+
if (result.status === 'accepted' && result.content) {
|
| 213 |
+
this.params.content = result.content;
|
| 214 |
+
}
|
| 215 |
+
}
|
| 216 |
+
},
|
| 217 |
+
ideConfirmation,
|
| 218 |
+
};
|
| 219 |
+
return confirmationDetails;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
async execute(abortSignal: AbortSignal): Promise<ToolResult> {
|
| 223 |
+
const { file_path, content, ai_proposed_content, modified_by_user } =
|
| 224 |
+
this.params;
|
| 225 |
+
const correctedContentResult = await getCorrectedFileContent(
|
| 226 |
+
this.config,
|
| 227 |
+
file_path,
|
| 228 |
+
content,
|
| 229 |
+
abortSignal,
|
| 230 |
+
);
|
| 231 |
+
|
| 232 |
+
if (correctedContentResult.error) {
|
| 233 |
+
const errDetails = correctedContentResult.error;
|
| 234 |
+
const errorMsg = errDetails.code
|
| 235 |
+
? `Error checking existing file '${file_path}': ${errDetails.message} (${errDetails.code})`
|
| 236 |
+
: `Error checking existing file: ${errDetails.message}`;
|
| 237 |
+
return {
|
| 238 |
+
llmContent: errorMsg,
|
| 239 |
+
returnDisplay: errorMsg,
|
| 240 |
+
error: {
|
| 241 |
+
message: errorMsg,
|
| 242 |
+
type: ToolErrorType.FILE_WRITE_FAILURE,
|
| 243 |
+
},
|
| 244 |
+
};
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
const {
|
| 248 |
+
originalContent,
|
| 249 |
+
correctedContent: fileContent,
|
| 250 |
+
fileExists,
|
| 251 |
+
} = correctedContentResult;
|
| 252 |
+
// fileExists is true if the file existed (and was readable or unreadable but caught by readError).
|
| 253 |
+
// fileExists is false if the file did not exist (ENOENT).
|
| 254 |
+
const isNewFile =
|
| 255 |
+
!fileExists ||
|
| 256 |
+
(correctedContentResult.error !== undefined &&
|
| 257 |
+
!correctedContentResult.fileExists);
|
| 258 |
+
|
| 259 |
+
try {
|
| 260 |
+
const dirName = path.dirname(file_path);
|
| 261 |
+
if (!fs.existsSync(dirName)) {
|
| 262 |
+
fs.mkdirSync(dirName, { recursive: true });
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
await this.config
|
| 266 |
+
.getFileSystemService()
|
| 267 |
+
.writeTextFile(file_path, fileContent);
|
| 268 |
+
|
| 269 |
+
// Generate diff for display result
|
| 270 |
+
const fileName = path.basename(file_path);
|
| 271 |
+
// If there was a readError, originalContent in correctedContentResult is '',
|
| 272 |
+
// but for the diff, we want to show the original content as it was before the write if possible.
|
| 273 |
+
// However, if it was unreadable, currentContentForDiff will be empty.
|
| 274 |
+
const currentContentForDiff = correctedContentResult.error
|
| 275 |
+
? '' // Or some indicator of unreadable content
|
| 276 |
+
: originalContent;
|
| 277 |
+
|
| 278 |
+
const fileDiff = Diff.createPatch(
|
| 279 |
+
fileName,
|
| 280 |
+
currentContentForDiff,
|
| 281 |
+
fileContent,
|
| 282 |
+
'Original',
|
| 283 |
+
'Written',
|
| 284 |
+
DEFAULT_DIFF_OPTIONS,
|
| 285 |
+
);
|
| 286 |
+
|
| 287 |
+
const originallyProposedContent = ai_proposed_content || content;
|
| 288 |
+
const diffStat = getDiffStat(
|
| 289 |
+
fileName,
|
| 290 |
+
currentContentForDiff,
|
| 291 |
+
originallyProposedContent,
|
| 292 |
+
content,
|
| 293 |
+
);
|
| 294 |
+
|
| 295 |
+
const llmSuccessMessageParts = [
|
| 296 |
+
isNewFile
|
| 297 |
+
? `Successfully created and wrote to new file: ${file_path}.`
|
| 298 |
+
: `Successfully overwrote file: ${file_path}.`,
|
| 299 |
+
];
|
| 300 |
+
if (modified_by_user) {
|
| 301 |
+
llmSuccessMessageParts.push(
|
| 302 |
+
`User modified the \`content\` to be: ${content}`,
|
| 303 |
+
);
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
const displayResult: FileDiff = {
|
| 307 |
+
fileDiff,
|
| 308 |
+
fileName,
|
| 309 |
+
originalContent: correctedContentResult.originalContent,
|
| 310 |
+
newContent: correctedContentResult.correctedContent,
|
| 311 |
+
diffStat,
|
| 312 |
+
};
|
| 313 |
+
|
| 314 |
+
const lines = fileContent.split('\n').length;
|
| 315 |
+
const mimetype = getSpecificMimeType(file_path);
|
| 316 |
+
const extension = path.extname(file_path); // Get extension
|
| 317 |
+
if (isNewFile) {
|
| 318 |
+
recordFileOperationMetric(
|
| 319 |
+
this.config,
|
| 320 |
+
FileOperation.CREATE,
|
| 321 |
+
lines,
|
| 322 |
+
mimetype,
|
| 323 |
+
extension,
|
| 324 |
+
diffStat,
|
| 325 |
+
);
|
| 326 |
+
} else {
|
| 327 |
+
recordFileOperationMetric(
|
| 328 |
+
this.config,
|
| 329 |
+
FileOperation.UPDATE,
|
| 330 |
+
lines,
|
| 331 |
+
mimetype,
|
| 332 |
+
extension,
|
| 333 |
+
diffStat,
|
| 334 |
+
);
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
return {
|
| 338 |
+
llmContent: llmSuccessMessageParts.join(' '),
|
| 339 |
+
returnDisplay: displayResult,
|
| 340 |
+
};
|
| 341 |
+
} catch (error) {
|
| 342 |
+
// Capture detailed error information for debugging
|
| 343 |
+
let errorMsg: string;
|
| 344 |
+
let errorType = ToolErrorType.FILE_WRITE_FAILURE;
|
| 345 |
+
|
| 346 |
+
if (isNodeError(error)) {
|
| 347 |
+
// Handle specific Node.js errors with their error codes
|
| 348 |
+
errorMsg = `Error writing to file '${file_path}': ${error.message} (${error.code})`;
|
| 349 |
+
|
| 350 |
+
// Log specific error types for better debugging
|
| 351 |
+
if (error.code === 'EACCES') {
|
| 352 |
+
errorMsg = `Permission denied writing to file: ${file_path} (${error.code})`;
|
| 353 |
+
errorType = ToolErrorType.PERMISSION_DENIED;
|
| 354 |
+
} else if (error.code === 'ENOSPC') {
|
| 355 |
+
errorMsg = `No space left on device: ${file_path} (${error.code})`;
|
| 356 |
+
errorType = ToolErrorType.NO_SPACE_LEFT;
|
| 357 |
+
} else if (error.code === 'EISDIR') {
|
| 358 |
+
errorMsg = `Target is a directory, not a file: ${file_path} (${error.code})`;
|
| 359 |
+
errorType = ToolErrorType.TARGET_IS_DIRECTORY;
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
// Include stack trace in debug mode for better troubleshooting
|
| 363 |
+
if (this.config.getDebugMode() && error.stack) {
|
| 364 |
+
console.error('Write file error stack:', error.stack);
|
| 365 |
+
}
|
| 366 |
+
} else if (error instanceof Error) {
|
| 367 |
+
errorMsg = `Error writing to file: ${error.message}`;
|
| 368 |
+
} else {
|
| 369 |
+
errorMsg = `Error writing to file: ${String(error)}`;
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
return {
|
| 373 |
+
llmContent: errorMsg,
|
| 374 |
+
returnDisplay: errorMsg,
|
| 375 |
+
error: {
|
| 376 |
+
message: errorMsg,
|
| 377 |
+
type: errorType,
|
| 378 |
+
},
|
| 379 |
+
};
|
| 380 |
+
}
|
| 381 |
+
}
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
/**
|
| 385 |
+
* Implementation of the WriteFile tool logic
|
| 386 |
+
*/
|
| 387 |
+
export class WriteFileTool
|
| 388 |
+
extends BaseDeclarativeTool<WriteFileToolParams, ToolResult>
|
| 389 |
+
implements ModifiableDeclarativeTool<WriteFileToolParams>
|
| 390 |
+
{
|
| 391 |
+
static readonly Name: string = 'write_file';
|
| 392 |
+
|
| 393 |
+
constructor(private readonly config: Config) {
|
| 394 |
+
super(
|
| 395 |
+
WriteFileTool.Name,
|
| 396 |
+
'WriteFile',
|
| 397 |
+
`Writes content to a specified file in the local filesystem.
|
| 398 |
+
|
| 399 |
+
The user has the ability to modify \`content\`. If modified, this will be stated in the response.`,
|
| 400 |
+
Kind.Edit,
|
| 401 |
+
{
|
| 402 |
+
properties: {
|
| 403 |
+
file_path: {
|
| 404 |
+
description:
|
| 405 |
+
"The absolute path to the file to write to (e.g., '/home/user/project/file.txt'). Relative paths are not supported.",
|
| 406 |
+
type: 'string',
|
| 407 |
+
},
|
| 408 |
+
content: {
|
| 409 |
+
description: 'The content to write to the file.',
|
| 410 |
+
type: 'string',
|
| 411 |
+
},
|
| 412 |
+
},
|
| 413 |
+
required: ['file_path', 'content'],
|
| 414 |
+
type: 'object',
|
| 415 |
+
},
|
| 416 |
+
);
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
protected override validateToolParamValues(
|
| 420 |
+
params: WriteFileToolParams,
|
| 421 |
+
): string | null {
|
| 422 |
+
const filePath = params.file_path;
|
| 423 |
+
|
| 424 |
+
if (!filePath) {
|
| 425 |
+
return `Missing or empty "file_path"`;
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
if (!path.isAbsolute(filePath)) {
|
| 429 |
+
return `File path must be absolute: ${filePath}`;
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
const workspaceContext = this.config.getWorkspaceContext();
|
| 433 |
+
if (!workspaceContext.isPathWithinWorkspace(filePath)) {
|
| 434 |
+
const directories = workspaceContext.getDirectories();
|
| 435 |
+
return `File path must be within one of the workspace directories: ${directories.join(
|
| 436 |
+
', ',
|
| 437 |
+
)}`;
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
try {
|
| 441 |
+
if (fs.existsSync(filePath)) {
|
| 442 |
+
const stats = fs.lstatSync(filePath);
|
| 443 |
+
if (stats.isDirectory()) {
|
| 444 |
+
return `Path is a directory, not a file: ${filePath}`;
|
| 445 |
+
}
|
| 446 |
+
}
|
| 447 |
+
} catch (statError: unknown) {
|
| 448 |
+
return `Error accessing path properties for validation: ${filePath}. Reason: ${
|
| 449 |
+
statError instanceof Error ? statError.message : String(statError)
|
| 450 |
+
}`;
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
return null;
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
protected createInvocation(
|
| 457 |
+
params: WriteFileToolParams,
|
| 458 |
+
): ToolInvocation<WriteFileToolParams, ToolResult> {
|
| 459 |
+
return new WriteFileToolInvocation(this.config, params);
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
getModifyContext(
|
| 463 |
+
abortSignal: AbortSignal,
|
| 464 |
+
): ModifyContext<WriteFileToolParams> {
|
| 465 |
+
return {
|
| 466 |
+
getFilePath: (params: WriteFileToolParams) => params.file_path,
|
| 467 |
+
getCurrentContent: async (params: WriteFileToolParams) => {
|
| 468 |
+
const correctedContentResult = await getCorrectedFileContent(
|
| 469 |
+
this.config,
|
| 470 |
+
params.file_path,
|
| 471 |
+
params.content,
|
| 472 |
+
abortSignal,
|
| 473 |
+
);
|
| 474 |
+
return correctedContentResult.originalContent;
|
| 475 |
+
},
|
| 476 |
+
getProposedContent: async (params: WriteFileToolParams) => {
|
| 477 |
+
const correctedContentResult = await getCorrectedFileContent(
|
| 478 |
+
this.config,
|
| 479 |
+
params.file_path,
|
| 480 |
+
params.content,
|
| 481 |
+
abortSignal,
|
| 482 |
+
);
|
| 483 |
+
return correctedContentResult.correctedContent;
|
| 484 |
+
},
|
| 485 |
+
createUpdatedParams: (
|
| 486 |
+
_oldContent: string,
|
| 487 |
+
modifiedProposedContent: string,
|
| 488 |
+
originalParams: WriteFileToolParams,
|
| 489 |
+
) => {
|
| 490 |
+
const content = originalParams.content;
|
| 491 |
+
return {
|
| 492 |
+
...originalParams,
|
| 493 |
+
ai_proposed_content: content,
|
| 494 |
+
content: modifiedProposedContent,
|
| 495 |
+
modified_by_user: true,
|
| 496 |
+
};
|
| 497 |
+
},
|
| 498 |
+
};
|
| 499 |
+
}
|
| 500 |
+
}
|
projects/ui/qwen-code/packages/core/src/utils/LruCache.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
export class LruCache<K, V> {
|
| 8 |
+
private cache: Map<K, V>;
|
| 9 |
+
private maxSize: number;
|
| 10 |
+
|
| 11 |
+
constructor(maxSize: number) {
|
| 12 |
+
this.cache = new Map<K, V>();
|
| 13 |
+
this.maxSize = maxSize;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
get(key: K): V | undefined {
|
| 17 |
+
const value = this.cache.get(key);
|
| 18 |
+
if (value) {
|
| 19 |
+
// Move to end to mark as recently used
|
| 20 |
+
this.cache.delete(key);
|
| 21 |
+
this.cache.set(key, value);
|
| 22 |
+
}
|
| 23 |
+
return value;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
set(key: K, value: V): void {
|
| 27 |
+
if (this.cache.has(key)) {
|
| 28 |
+
this.cache.delete(key);
|
| 29 |
+
} else if (this.cache.size >= this.maxSize) {
|
| 30 |
+
const firstKey = this.cache.keys().next().value;
|
| 31 |
+
if (firstKey !== undefined) {
|
| 32 |
+
this.cache.delete(firstKey);
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
this.cache.set(key, value);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
clear(): void {
|
| 39 |
+
this.cache.clear();
|
| 40 |
+
}
|
| 41 |
+
}
|
projects/ui/qwen-code/packages/core/src/utils/bfsFileSearch.test.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
import * as fsPromises from 'fs/promises';
|
| 9 |
+
import * as path from 'path';
|
| 10 |
+
import * as os from 'os';
|
| 11 |
+
import { bfsFileSearch } from './bfsFileSearch.js';
|
| 12 |
+
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
|
| 13 |
+
|
| 14 |
+
describe('bfsFileSearch', () => {
|
| 15 |
+
let testRootDir: string;
|
| 16 |
+
|
| 17 |
+
async function createEmptyDir(...pathSegments: string[]) {
|
| 18 |
+
const fullPath = path.join(testRootDir, ...pathSegments);
|
| 19 |
+
await fsPromises.mkdir(fullPath, { recursive: true });
|
| 20 |
+
return fullPath;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
async function createTestFile(content: string, ...pathSegments: string[]) {
|
| 24 |
+
const fullPath = path.join(testRootDir, ...pathSegments);
|
| 25 |
+
await fsPromises.mkdir(path.dirname(fullPath), { recursive: true });
|
| 26 |
+
await fsPromises.writeFile(fullPath, content);
|
| 27 |
+
return fullPath;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
beforeEach(async () => {
|
| 31 |
+
testRootDir = await fsPromises.mkdtemp(
|
| 32 |
+
path.join(os.tmpdir(), 'bfs-file-search-test-'),
|
| 33 |
+
);
|
| 34 |
+
});
|
| 35 |
+
|
| 36 |
+
afterEach(async () => {
|
| 37 |
+
await fsPromises.rm(testRootDir, { recursive: true, force: true });
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
it('should find a file in the root directory', async () => {
|
| 41 |
+
const targetFilePath = await createTestFile('content', 'target.txt');
|
| 42 |
+
const result = await bfsFileSearch(testRootDir, { fileName: 'target.txt' });
|
| 43 |
+
expect(result).toEqual([targetFilePath]);
|
| 44 |
+
});
|
| 45 |
+
|
| 46 |
+
it('should find a file in a nested directory', async () => {
|
| 47 |
+
const targetFilePath = await createTestFile(
|
| 48 |
+
'content',
|
| 49 |
+
'a',
|
| 50 |
+
'b',
|
| 51 |
+
'target.txt',
|
| 52 |
+
);
|
| 53 |
+
const result = await bfsFileSearch(testRootDir, { fileName: 'target.txt' });
|
| 54 |
+
expect(result).toEqual([targetFilePath]);
|
| 55 |
+
});
|
| 56 |
+
|
| 57 |
+
it('should find multiple files with the same name', async () => {
|
| 58 |
+
const targetFilePath1 = await createTestFile('content1', 'a', 'target.txt');
|
| 59 |
+
const targetFilePath2 = await createTestFile('content2', 'b', 'target.txt');
|
| 60 |
+
const result = await bfsFileSearch(testRootDir, { fileName: 'target.txt' });
|
| 61 |
+
result.sort();
|
| 62 |
+
expect(result).toEqual([targetFilePath1, targetFilePath2].sort());
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
it('should return an empty array if no file is found', async () => {
|
| 66 |
+
await createTestFile('content', 'other.txt');
|
| 67 |
+
const result = await bfsFileSearch(testRootDir, { fileName: 'target.txt' });
|
| 68 |
+
expect(result).toEqual([]);
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
it('should ignore directories specified in ignoreDirs', async () => {
|
| 72 |
+
await createTestFile('content', 'ignored', 'target.txt');
|
| 73 |
+
const targetFilePath = await createTestFile(
|
| 74 |
+
'content',
|
| 75 |
+
'not-ignored',
|
| 76 |
+
'target.txt',
|
| 77 |
+
);
|
| 78 |
+
const result = await bfsFileSearch(testRootDir, {
|
| 79 |
+
fileName: 'target.txt',
|
| 80 |
+
ignoreDirs: ['ignored'],
|
| 81 |
+
});
|
| 82 |
+
expect(result).toEqual([targetFilePath]);
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
it('should respect the maxDirs limit and not find the file', async () => {
|
| 86 |
+
await createTestFile('content', 'a', 'b', 'c', 'target.txt');
|
| 87 |
+
const result = await bfsFileSearch(testRootDir, {
|
| 88 |
+
fileName: 'target.txt',
|
| 89 |
+
maxDirs: 3,
|
| 90 |
+
});
|
| 91 |
+
expect(result).toEqual([]);
|
| 92 |
+
});
|
| 93 |
+
|
| 94 |
+
it('should respect the maxDirs limit and find the file', async () => {
|
| 95 |
+
const targetFilePath = await createTestFile(
|
| 96 |
+
'content',
|
| 97 |
+
'a',
|
| 98 |
+
'b',
|
| 99 |
+
'c',
|
| 100 |
+
'target.txt',
|
| 101 |
+
);
|
| 102 |
+
const result = await bfsFileSearch(testRootDir, {
|
| 103 |
+
fileName: 'target.txt',
|
| 104 |
+
maxDirs: 4,
|
| 105 |
+
});
|
| 106 |
+
expect(result).toEqual([targetFilePath]);
|
| 107 |
+
});
|
| 108 |
+
|
| 109 |
+
describe('with FileDiscoveryService', () => {
|
| 110 |
+
let projectRoot: string;
|
| 111 |
+
|
| 112 |
+
beforeEach(async () => {
|
| 113 |
+
projectRoot = await createEmptyDir('project');
|
| 114 |
+
});
|
| 115 |
+
|
| 116 |
+
it('should ignore gitignored files', async () => {
|
| 117 |
+
await createEmptyDir('project', '.git');
|
| 118 |
+
await createTestFile('node_modules/', 'project', '.gitignore');
|
| 119 |
+
await createTestFile('content', 'project', 'node_modules', 'target.txt');
|
| 120 |
+
const targetFilePath = await createTestFile(
|
| 121 |
+
'content',
|
| 122 |
+
'project',
|
| 123 |
+
'not-ignored',
|
| 124 |
+
'target.txt',
|
| 125 |
+
);
|
| 126 |
+
|
| 127 |
+
const fileService = new FileDiscoveryService(projectRoot);
|
| 128 |
+
const result = await bfsFileSearch(projectRoot, {
|
| 129 |
+
fileName: 'target.txt',
|
| 130 |
+
fileService,
|
| 131 |
+
fileFilteringOptions: {
|
| 132 |
+
respectGitIgnore: true,
|
| 133 |
+
respectGeminiIgnore: true,
|
| 134 |
+
},
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
expect(result).toEqual([targetFilePath]);
|
| 138 |
+
});
|
| 139 |
+
|
| 140 |
+
it('should ignore geminiignored files', async () => {
|
| 141 |
+
await createTestFile('node_modules/', 'project', '.geminiignore');
|
| 142 |
+
await createTestFile('content', 'project', 'node_modules', 'target.txt');
|
| 143 |
+
const targetFilePath = await createTestFile(
|
| 144 |
+
'content',
|
| 145 |
+
'project',
|
| 146 |
+
'not-ignored',
|
| 147 |
+
'target.txt',
|
| 148 |
+
);
|
| 149 |
+
|
| 150 |
+
const fileService = new FileDiscoveryService(projectRoot);
|
| 151 |
+
const result = await bfsFileSearch(projectRoot, {
|
| 152 |
+
fileName: 'target.txt',
|
| 153 |
+
fileService,
|
| 154 |
+
fileFilteringOptions: {
|
| 155 |
+
respectGitIgnore: false,
|
| 156 |
+
respectGeminiIgnore: true,
|
| 157 |
+
},
|
| 158 |
+
});
|
| 159 |
+
|
| 160 |
+
expect(result).toEqual([targetFilePath]);
|
| 161 |
+
});
|
| 162 |
+
|
| 163 |
+
it('should not ignore files if respect flags are false', async () => {
|
| 164 |
+
await createEmptyDir('project', '.git');
|
| 165 |
+
await createTestFile('node_modules/', 'project', '.gitignore');
|
| 166 |
+
const target1 = await createTestFile(
|
| 167 |
+
'content',
|
| 168 |
+
'project',
|
| 169 |
+
'node_modules',
|
| 170 |
+
'target.txt',
|
| 171 |
+
);
|
| 172 |
+
const target2 = await createTestFile(
|
| 173 |
+
'content',
|
| 174 |
+
'project',
|
| 175 |
+
'not-ignored',
|
| 176 |
+
'target.txt',
|
| 177 |
+
);
|
| 178 |
+
|
| 179 |
+
const fileService = new FileDiscoveryService(projectRoot);
|
| 180 |
+
const result = await bfsFileSearch(projectRoot, {
|
| 181 |
+
fileName: 'target.txt',
|
| 182 |
+
fileService,
|
| 183 |
+
fileFilteringOptions: {
|
| 184 |
+
respectGitIgnore: false,
|
| 185 |
+
respectGeminiIgnore: false,
|
| 186 |
+
},
|
| 187 |
+
});
|
| 188 |
+
|
| 189 |
+
expect(result.sort()).toEqual([target1, target2].sort());
|
| 190 |
+
});
|
| 191 |
+
});
|
| 192 |
+
|
| 193 |
+
it('should find all files in a complex directory structure', async () => {
|
| 194 |
+
// Create a complex directory structure to test correctness at scale
|
| 195 |
+
// without flaky performance checks.
|
| 196 |
+
const numDirs = 50;
|
| 197 |
+
const numFilesPerDir = 2;
|
| 198 |
+
const numTargetDirs = 10;
|
| 199 |
+
|
| 200 |
+
const dirCreationPromises: Array<Promise<unknown>> = [];
|
| 201 |
+
for (let i = 0; i < numDirs; i++) {
|
| 202 |
+
dirCreationPromises.push(createEmptyDir(`dir${i}`));
|
| 203 |
+
dirCreationPromises.push(createEmptyDir(`dir${i}`, 'subdir1'));
|
| 204 |
+
dirCreationPromises.push(createEmptyDir(`dir${i}`, 'subdir2'));
|
| 205 |
+
dirCreationPromises.push(createEmptyDir(`dir${i}`, 'subdir1', 'deep'));
|
| 206 |
+
}
|
| 207 |
+
await Promise.all(dirCreationPromises);
|
| 208 |
+
|
| 209 |
+
const fileCreationPromises: Array<Promise<string>> = [];
|
| 210 |
+
for (let i = 0; i < numTargetDirs; i++) {
|
| 211 |
+
// Add target files in some directories
|
| 212 |
+
fileCreationPromises.push(
|
| 213 |
+
createTestFile('content', `dir${i}`, 'QWEN.md'),
|
| 214 |
+
);
|
| 215 |
+
fileCreationPromises.push(
|
| 216 |
+
createTestFile('content', `dir${i}`, 'subdir1', 'QWEN.md'),
|
| 217 |
+
);
|
| 218 |
+
}
|
| 219 |
+
const expectedFiles = await Promise.all(fileCreationPromises);
|
| 220 |
+
|
| 221 |
+
const result = await bfsFileSearch(testRootDir, {
|
| 222 |
+
fileName: 'QWEN.md',
|
| 223 |
+
// Provide a generous maxDirs limit to ensure it doesn't prematurely stop
|
| 224 |
+
// in this large test case. Total dirs created is 200.
|
| 225 |
+
maxDirs: 250,
|
| 226 |
+
});
|
| 227 |
+
|
| 228 |
+
// Verify we found the exact files we created
|
| 229 |
+
expect(result.length).toBe(numTargetDirs * numFilesPerDir);
|
| 230 |
+
expect(result.sort()).toEqual(expectedFiles.sort());
|
| 231 |
+
});
|
| 232 |
+
});
|
projects/ui/qwen-code/packages/core/src/utils/bfsFileSearch.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import * as fs from 'fs/promises';
|
| 8 |
+
import * as path from 'path';
|
| 9 |
+
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
|
| 10 |
+
import { FileFilteringOptions } from '../config/config.js';
|
| 11 |
+
// Simple console logger for now.
|
| 12 |
+
// TODO: Integrate with a more robust server-side logger.
|
| 13 |
+
const logger = {
|
| 14 |
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
| 15 |
+
debug: (...args: any[]) => console.debug('[DEBUG] [BfsFileSearch]', ...args),
|
| 16 |
+
};
|
| 17 |
+
|
| 18 |
+
interface BfsFileSearchOptions {
|
| 19 |
+
fileName: string;
|
| 20 |
+
ignoreDirs?: string[];
|
| 21 |
+
maxDirs?: number;
|
| 22 |
+
debug?: boolean;
|
| 23 |
+
fileService?: FileDiscoveryService;
|
| 24 |
+
fileFilteringOptions?: FileFilteringOptions;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
/**
|
| 28 |
+
* Performs a breadth-first search for a specific file within a directory structure.
|
| 29 |
+
*
|
| 30 |
+
* @param rootDir The directory to start the search from.
|
| 31 |
+
* @param options Configuration for the search.
|
| 32 |
+
* @returns A promise that resolves to an array of paths where the file was found.
|
| 33 |
+
*/
|
| 34 |
+
export async function bfsFileSearch(
|
| 35 |
+
rootDir: string,
|
| 36 |
+
options: BfsFileSearchOptions,
|
| 37 |
+
): Promise<string[]> {
|
| 38 |
+
const {
|
| 39 |
+
fileName,
|
| 40 |
+
ignoreDirs = [],
|
| 41 |
+
maxDirs = Infinity,
|
| 42 |
+
debug = false,
|
| 43 |
+
fileService,
|
| 44 |
+
} = options;
|
| 45 |
+
const foundFiles: string[] = [];
|
| 46 |
+
const queue: string[] = [rootDir];
|
| 47 |
+
const visited = new Set<string>();
|
| 48 |
+
let scannedDirCount = 0;
|
| 49 |
+
let queueHead = 0; // Pointer-based queue head to avoid expensive splice operations
|
| 50 |
+
|
| 51 |
+
// Convert ignoreDirs array to Set for O(1) lookup performance
|
| 52 |
+
const ignoreDirsSet = new Set(ignoreDirs);
|
| 53 |
+
|
| 54 |
+
// Process directories in parallel batches for maximum performance
|
| 55 |
+
const PARALLEL_BATCH_SIZE = 15; // Parallel processing batch size for optimal performance
|
| 56 |
+
|
| 57 |
+
while (queueHead < queue.length && scannedDirCount < maxDirs) {
|
| 58 |
+
// Fill batch with unvisited directories up to the desired size
|
| 59 |
+
const batchSize = Math.min(PARALLEL_BATCH_SIZE, maxDirs - scannedDirCount);
|
| 60 |
+
const currentBatch = [];
|
| 61 |
+
while (currentBatch.length < batchSize && queueHead < queue.length) {
|
| 62 |
+
const currentDir = queue[queueHead];
|
| 63 |
+
queueHead++;
|
| 64 |
+
if (!visited.has(currentDir)) {
|
| 65 |
+
visited.add(currentDir);
|
| 66 |
+
currentBatch.push(currentDir);
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
scannedDirCount += currentBatch.length;
|
| 70 |
+
|
| 71 |
+
if (currentBatch.length === 0) continue;
|
| 72 |
+
|
| 73 |
+
if (debug) {
|
| 74 |
+
logger.debug(
|
| 75 |
+
`Scanning [${scannedDirCount}/${maxDirs}]: batch of ${currentBatch.length}`,
|
| 76 |
+
);
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// Read directories in parallel instead of one by one
|
| 80 |
+
const readPromises = currentBatch.map(async (currentDir) => {
|
| 81 |
+
try {
|
| 82 |
+
const entries = await fs.readdir(currentDir, { withFileTypes: true });
|
| 83 |
+
return { currentDir, entries };
|
| 84 |
+
} catch (error) {
|
| 85 |
+
// Warn user that a directory could not be read, as this affects search results.
|
| 86 |
+
const message = (error as Error)?.message ?? 'Unknown error';
|
| 87 |
+
console.warn(
|
| 88 |
+
`[WARN] Skipping unreadable directory: ${currentDir} (${message})`,
|
| 89 |
+
);
|
| 90 |
+
if (debug) {
|
| 91 |
+
logger.debug(`Full error for ${currentDir}:`, error);
|
| 92 |
+
}
|
| 93 |
+
return { currentDir, entries: [] };
|
| 94 |
+
}
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
const results = await Promise.all(readPromises);
|
| 98 |
+
|
| 99 |
+
for (const { currentDir, entries } of results) {
|
| 100 |
+
for (const entry of entries) {
|
| 101 |
+
const fullPath = path.join(currentDir, entry.name);
|
| 102 |
+
if (
|
| 103 |
+
fileService?.shouldIgnoreFile(fullPath, {
|
| 104 |
+
respectGitIgnore: options.fileFilteringOptions?.respectGitIgnore,
|
| 105 |
+
respectGeminiIgnore:
|
| 106 |
+
options.fileFilteringOptions?.respectGeminiIgnore,
|
| 107 |
+
})
|
| 108 |
+
) {
|
| 109 |
+
continue;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
if (entry.isDirectory()) {
|
| 113 |
+
if (!ignoreDirsSet.has(entry.name)) {
|
| 114 |
+
queue.push(fullPath);
|
| 115 |
+
}
|
| 116 |
+
} else if (entry.isFile() && entry.name === fileName) {
|
| 117 |
+
foundFiles.push(fullPath);
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
return foundFiles;
|
| 124 |
+
}
|
projects/ui/qwen-code/packages/core/src/utils/browser.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
/**
|
| 8 |
+
* Determines if we should attempt to launch a browser for authentication
|
| 9 |
+
* based on the user's environment.
|
| 10 |
+
*
|
| 11 |
+
* This is an adaptation of the logic from the Google Cloud SDK.
|
| 12 |
+
* @returns True if the tool should attempt to launch a browser.
|
| 13 |
+
*/
|
| 14 |
+
export function shouldAttemptBrowserLaunch(): boolean {
|
| 15 |
+
// A list of browser names that indicate we should not attempt to open a
|
| 16 |
+
// web browser for the user.
|
| 17 |
+
const browserBlocklist = ['www-browser'];
|
| 18 |
+
const browserEnv = process.env['BROWSER'];
|
| 19 |
+
if (browserEnv && browserBlocklist.includes(browserEnv)) {
|
| 20 |
+
return false;
|
| 21 |
+
}
|
| 22 |
+
// Common environment variables used in CI/CD or other non-interactive shells.
|
| 23 |
+
if (
|
| 24 |
+
process.env['CI'] ||
|
| 25 |
+
process.env['DEBIAN_FRONTEND'] === 'noninteractive'
|
| 26 |
+
) {
|
| 27 |
+
return false;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// The presence of SSH_CONNECTION indicates a remote session.
|
| 31 |
+
// We should not attempt to launch a browser unless a display is explicitly available
|
| 32 |
+
// (checked below for Linux).
|
| 33 |
+
const isSSH = !!process.env['SSH_CONNECTION'];
|
| 34 |
+
|
| 35 |
+
// On Linux, the presence of a display server is a strong indicator of a GUI.
|
| 36 |
+
if (process.platform === 'linux') {
|
| 37 |
+
// These are environment variables that can indicate a running compositor on
|
| 38 |
+
// Linux.
|
| 39 |
+
const displayVariables = ['DISPLAY', 'WAYLAND_DISPLAY', 'MIR_SOCKET'];
|
| 40 |
+
const hasDisplay = displayVariables.some((v) => !!process.env[v]);
|
| 41 |
+
if (!hasDisplay) {
|
| 42 |
+
return false;
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
// If in an SSH session on a non-Linux OS (e.g., macOS), don't launch browser.
|
| 47 |
+
// The Linux case is handled above (it's allowed if DISPLAY is set).
|
| 48 |
+
if (isSSH && process.platform !== 'linux') {
|
| 49 |
+
return false;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
// For non-Linux OSes, we generally assume a GUI is available
|
| 53 |
+
// unless other signals (like SSH) suggest otherwise.
|
| 54 |
+
// The `open` command's error handling will catch final edge cases.
|
| 55 |
+
return true;
|
| 56 |
+
}
|
projects/ui/qwen-code/packages/core/src/utils/editCorrector.test.ts
ADDED
|
@@ -0,0 +1,767 @@
|
|
|
|
|
|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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 |
+
vi,
|
| 10 |
+
describe,
|
| 11 |
+
it,
|
| 12 |
+
expect,
|
| 13 |
+
beforeEach,
|
| 14 |
+
Mock,
|
| 15 |
+
type Mocked,
|
| 16 |
+
} from 'vitest';
|
| 17 |
+
import * as fs from 'fs';
|
| 18 |
+
import { EditTool } from '../tools/edit.js';
|
| 19 |
+
|
| 20 |
+
// MOCKS
|
| 21 |
+
let callCount = 0;
|
| 22 |
+
const mockResponses: any[] = [];
|
| 23 |
+
|
| 24 |
+
let mockGenerateJson: any;
|
| 25 |
+
let mockStartChat: any;
|
| 26 |
+
let mockSendMessageStream: any;
|
| 27 |
+
|
| 28 |
+
vi.mock('fs', () => ({
|
| 29 |
+
statSync: vi.fn(),
|
| 30 |
+
}));
|
| 31 |
+
|
| 32 |
+
vi.mock('../core/client.js', () => ({
|
| 33 |
+
GeminiClient: vi.fn().mockImplementation(function (
|
| 34 |
+
this: any,
|
| 35 |
+
_config: Config,
|
| 36 |
+
) {
|
| 37 |
+
this.generateJson = (...params: any[]) => mockGenerateJson(...params); // Corrected: use mockGenerateJson
|
| 38 |
+
this.startChat = (...params: any[]) => mockStartChat(...params); // Corrected: use mockStartChat
|
| 39 |
+
this.sendMessageStream = (...params: any[]) =>
|
| 40 |
+
mockSendMessageStream(...params); // Corrected: use mockSendMessageStream
|
| 41 |
+
return this;
|
| 42 |
+
}),
|
| 43 |
+
}));
|
| 44 |
+
// END MOCKS
|
| 45 |
+
|
| 46 |
+
import {
|
| 47 |
+
countOccurrences,
|
| 48 |
+
ensureCorrectEdit,
|
| 49 |
+
ensureCorrectFileContent,
|
| 50 |
+
unescapeStringForGeminiBug,
|
| 51 |
+
resetEditCorrectorCaches_TEST_ONLY,
|
| 52 |
+
} from './editCorrector.js';
|
| 53 |
+
import { GeminiClient } from '../core/client.js';
|
| 54 |
+
import type { Config } from '../config/config.js';
|
| 55 |
+
import { ToolRegistry } from '../tools/tool-registry.js';
|
| 56 |
+
|
| 57 |
+
vi.mock('../tools/tool-registry.js');
|
| 58 |
+
|
| 59 |
+
describe('editCorrector', () => {
|
| 60 |
+
describe('countOccurrences', () => {
|
| 61 |
+
it('should return 0 for empty string', () => {
|
| 62 |
+
expect(countOccurrences('', 'a')).toBe(0);
|
| 63 |
+
});
|
| 64 |
+
it('should return 0 for empty substring', () => {
|
| 65 |
+
expect(countOccurrences('abc', '')).toBe(0);
|
| 66 |
+
});
|
| 67 |
+
it('should return 0 if substring is not found', () => {
|
| 68 |
+
expect(countOccurrences('abc', 'd')).toBe(0);
|
| 69 |
+
});
|
| 70 |
+
it('should return 1 if substring is found once', () => {
|
| 71 |
+
expect(countOccurrences('abc', 'b')).toBe(1);
|
| 72 |
+
});
|
| 73 |
+
it('should return correct count for multiple occurrences', () => {
|
| 74 |
+
expect(countOccurrences('ababa', 'a')).toBe(3);
|
| 75 |
+
expect(countOccurrences('ababab', 'ab')).toBe(3);
|
| 76 |
+
});
|
| 77 |
+
it('should count non-overlapping occurrences', () => {
|
| 78 |
+
expect(countOccurrences('aaaaa', 'aa')).toBe(2);
|
| 79 |
+
expect(countOccurrences('ababab', 'aba')).toBe(1);
|
| 80 |
+
});
|
| 81 |
+
it('should correctly count occurrences when substring is longer', () => {
|
| 82 |
+
expect(countOccurrences('abc', 'abcdef')).toBe(0);
|
| 83 |
+
});
|
| 84 |
+
it('should be case-sensitive', () => {
|
| 85 |
+
expect(countOccurrences('abcABC', 'a')).toBe(1);
|
| 86 |
+
expect(countOccurrences('abcABC', 'A')).toBe(1);
|
| 87 |
+
});
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
describe('unescapeStringForGeminiBug', () => {
|
| 91 |
+
it('should unescape common sequences', () => {
|
| 92 |
+
expect(unescapeStringForGeminiBug('\\n')).toBe('\n');
|
| 93 |
+
expect(unescapeStringForGeminiBug('\\t')).toBe('\t');
|
| 94 |
+
expect(unescapeStringForGeminiBug("\\'")).toBe("'");
|
| 95 |
+
expect(unescapeStringForGeminiBug('\\"')).toBe('"');
|
| 96 |
+
expect(unescapeStringForGeminiBug('\\`')).toBe('`');
|
| 97 |
+
});
|
| 98 |
+
it('should handle multiple escaped sequences', () => {
|
| 99 |
+
expect(unescapeStringForGeminiBug('Hello\\nWorld\\tTest')).toBe(
|
| 100 |
+
'Hello\nWorld\tTest',
|
| 101 |
+
);
|
| 102 |
+
});
|
| 103 |
+
it('should not alter already correct sequences', () => {
|
| 104 |
+
expect(unescapeStringForGeminiBug('\n')).toBe('\n');
|
| 105 |
+
expect(unescapeStringForGeminiBug('Correct string')).toBe(
|
| 106 |
+
'Correct string',
|
| 107 |
+
);
|
| 108 |
+
});
|
| 109 |
+
it('should handle mixed correct and incorrect sequences', () => {
|
| 110 |
+
expect(unescapeStringForGeminiBug('\\nCorrect\t\\`')).toBe(
|
| 111 |
+
'\nCorrect\t`',
|
| 112 |
+
);
|
| 113 |
+
});
|
| 114 |
+
it('should handle backslash followed by actual newline character', () => {
|
| 115 |
+
expect(unescapeStringForGeminiBug('\\\n')).toBe('\n');
|
| 116 |
+
expect(unescapeStringForGeminiBug('First line\\\nSecond line')).toBe(
|
| 117 |
+
'First line\nSecond line',
|
| 118 |
+
);
|
| 119 |
+
});
|
| 120 |
+
it('should handle multiple backslashes before an escapable character (aggressive unescaping)', () => {
|
| 121 |
+
expect(unescapeStringForGeminiBug('\\\\n')).toBe('\n');
|
| 122 |
+
expect(unescapeStringForGeminiBug('\\\\\\t')).toBe('\t');
|
| 123 |
+
expect(unescapeStringForGeminiBug('\\\\\\\\`')).toBe('`');
|
| 124 |
+
});
|
| 125 |
+
it('should return empty string for empty input', () => {
|
| 126 |
+
expect(unescapeStringForGeminiBug('')).toBe('');
|
| 127 |
+
});
|
| 128 |
+
it('should not alter strings with no targeted escape sequences', () => {
|
| 129 |
+
expect(unescapeStringForGeminiBug('abc def')).toBe('abc def');
|
| 130 |
+
expect(unescapeStringForGeminiBug('C:\\Folder\\File')).toBe(
|
| 131 |
+
'C:\\Folder\\File',
|
| 132 |
+
);
|
| 133 |
+
});
|
| 134 |
+
it('should correctly process strings with some targeted escapes', () => {
|
| 135 |
+
expect(unescapeStringForGeminiBug('C:\\Users\\name')).toBe(
|
| 136 |
+
'C:\\Users\name',
|
| 137 |
+
);
|
| 138 |
+
});
|
| 139 |
+
it('should handle complex cases with mixed slashes and characters', () => {
|
| 140 |
+
expect(
|
| 141 |
+
unescapeStringForGeminiBug('\\\\\\\nLine1\\\nLine2\\tTab\\\\`Tick\\"'),
|
| 142 |
+
).toBe('\nLine1\nLine2\tTab`Tick"');
|
| 143 |
+
});
|
| 144 |
+
it('should handle escaped backslashes', () => {
|
| 145 |
+
expect(unescapeStringForGeminiBug('\\\\')).toBe('\\');
|
| 146 |
+
expect(unescapeStringForGeminiBug('C:\\\\Users')).toBe('C:\\Users');
|
| 147 |
+
expect(unescapeStringForGeminiBug('path\\\\to\\\\file')).toBe(
|
| 148 |
+
'path\to\\file',
|
| 149 |
+
);
|
| 150 |
+
});
|
| 151 |
+
it('should handle escaped backslashes mixed with other escapes (aggressive unescaping)', () => {
|
| 152 |
+
expect(unescapeStringForGeminiBug('line1\\\\\\nline2')).toBe(
|
| 153 |
+
'line1\nline2',
|
| 154 |
+
);
|
| 155 |
+
expect(unescapeStringForGeminiBug('quote\\\\"text\\\\nline')).toBe(
|
| 156 |
+
'quote"text\nline',
|
| 157 |
+
);
|
| 158 |
+
});
|
| 159 |
+
});
|
| 160 |
+
|
| 161 |
+
describe('ensureCorrectEdit', () => {
|
| 162 |
+
let mockGeminiClientInstance: Mocked<GeminiClient>;
|
| 163 |
+
let mockToolRegistry: Mocked<ToolRegistry>;
|
| 164 |
+
let mockConfigInstance: Config;
|
| 165 |
+
const abortSignal = new AbortController().signal;
|
| 166 |
+
|
| 167 |
+
beforeEach(() => {
|
| 168 |
+
mockToolRegistry = new ToolRegistry({} as Config) as Mocked<ToolRegistry>;
|
| 169 |
+
const configParams = {
|
| 170 |
+
apiKey: 'test-api-key',
|
| 171 |
+
model: 'test-model',
|
| 172 |
+
sandbox: false as boolean | string,
|
| 173 |
+
targetDir: '/test',
|
| 174 |
+
debugMode: false,
|
| 175 |
+
question: undefined as string | undefined,
|
| 176 |
+
fullContext: false,
|
| 177 |
+
coreTools: undefined as string[] | undefined,
|
| 178 |
+
toolDiscoveryCommand: undefined as string | undefined,
|
| 179 |
+
toolCallCommand: undefined as string | undefined,
|
| 180 |
+
mcpServerCommand: undefined as string | undefined,
|
| 181 |
+
mcpServers: undefined as Record<string, any> | undefined,
|
| 182 |
+
userAgent: 'test-agent',
|
| 183 |
+
userMemory: '',
|
| 184 |
+
geminiMdFileCount: 0,
|
| 185 |
+
alwaysSkipModificationConfirmation: false,
|
| 186 |
+
};
|
| 187 |
+
mockConfigInstance = {
|
| 188 |
+
...configParams,
|
| 189 |
+
getApiKey: vi.fn(() => configParams.apiKey),
|
| 190 |
+
getModel: vi.fn(() => configParams.model),
|
| 191 |
+
getSandbox: vi.fn(() => configParams.sandbox),
|
| 192 |
+
getTargetDir: vi.fn(() => configParams.targetDir),
|
| 193 |
+
getToolRegistry: vi.fn(() => mockToolRegistry),
|
| 194 |
+
getDebugMode: vi.fn(() => configParams.debugMode),
|
| 195 |
+
getQuestion: vi.fn(() => configParams.question),
|
| 196 |
+
getFullContext: vi.fn(() => configParams.fullContext),
|
| 197 |
+
getCoreTools: vi.fn(() => configParams.coreTools),
|
| 198 |
+
getToolDiscoveryCommand: vi.fn(() => configParams.toolDiscoveryCommand),
|
| 199 |
+
getToolCallCommand: vi.fn(() => configParams.toolCallCommand),
|
| 200 |
+
getMcpServerCommand: vi.fn(() => configParams.mcpServerCommand),
|
| 201 |
+
getMcpServers: vi.fn(() => configParams.mcpServers),
|
| 202 |
+
getUserAgent: vi.fn(() => configParams.userAgent),
|
| 203 |
+
getUserMemory: vi.fn(() => configParams.userMemory),
|
| 204 |
+
setUserMemory: vi.fn((mem: string) => {
|
| 205 |
+
configParams.userMemory = mem;
|
| 206 |
+
}),
|
| 207 |
+
getGeminiMdFileCount: vi.fn(() => configParams.geminiMdFileCount),
|
| 208 |
+
setGeminiMdFileCount: vi.fn((count: number) => {
|
| 209 |
+
configParams.geminiMdFileCount = count;
|
| 210 |
+
}),
|
| 211 |
+
getAlwaysSkipModificationConfirmation: vi.fn(
|
| 212 |
+
() => configParams.alwaysSkipModificationConfirmation,
|
| 213 |
+
),
|
| 214 |
+
setAlwaysSkipModificationConfirmation: vi.fn((skip: boolean) => {
|
| 215 |
+
configParams.alwaysSkipModificationConfirmation = skip;
|
| 216 |
+
}),
|
| 217 |
+
getQuotaErrorOccurred: vi.fn().mockReturnValue(false),
|
| 218 |
+
setQuotaErrorOccurred: vi.fn(),
|
| 219 |
+
} as unknown as Config;
|
| 220 |
+
|
| 221 |
+
callCount = 0;
|
| 222 |
+
mockResponses.length = 0;
|
| 223 |
+
mockGenerateJson = vi
|
| 224 |
+
.fn()
|
| 225 |
+
.mockImplementation((_contents, _schema, signal) => {
|
| 226 |
+
// Check if the signal is aborted. If so, throw an error or return a specific response.
|
| 227 |
+
if (signal && signal.aborted) {
|
| 228 |
+
return Promise.reject(new Error('Aborted')); // Or some other specific error/response
|
| 229 |
+
}
|
| 230 |
+
const response = mockResponses[callCount];
|
| 231 |
+
callCount++;
|
| 232 |
+
if (response === undefined) return Promise.resolve({});
|
| 233 |
+
return Promise.resolve(response);
|
| 234 |
+
});
|
| 235 |
+
mockStartChat = vi.fn();
|
| 236 |
+
mockSendMessageStream = vi.fn();
|
| 237 |
+
|
| 238 |
+
mockGeminiClientInstance = new GeminiClient(
|
| 239 |
+
mockConfigInstance,
|
| 240 |
+
) as Mocked<GeminiClient>;
|
| 241 |
+
mockGeminiClientInstance.getHistory = vi.fn().mockResolvedValue([]);
|
| 242 |
+
resetEditCorrectorCaches_TEST_ONLY();
|
| 243 |
+
});
|
| 244 |
+
|
| 245 |
+
describe('Scenario Group 1: originalParams.old_string matches currentContent directly', () => {
|
| 246 |
+
it('Test 1.1: old_string (no literal \\), new_string (escaped by Gemini) -> new_string unescaped', async () => {
|
| 247 |
+
const currentContent = 'This is a test string to find me.';
|
| 248 |
+
const originalParams = {
|
| 249 |
+
file_path: '/test/file.txt',
|
| 250 |
+
old_string: 'find me',
|
| 251 |
+
new_string: 'replace with \\"this\\"',
|
| 252 |
+
};
|
| 253 |
+
mockResponses.push({
|
| 254 |
+
corrected_new_string_escaping: 'replace with "this"',
|
| 255 |
+
});
|
| 256 |
+
const result = await ensureCorrectEdit(
|
| 257 |
+
'/test/file.txt',
|
| 258 |
+
currentContent,
|
| 259 |
+
originalParams,
|
| 260 |
+
mockGeminiClientInstance,
|
| 261 |
+
abortSignal,
|
| 262 |
+
);
|
| 263 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 264 |
+
expect(result.params.new_string).toBe('replace with "this"');
|
| 265 |
+
expect(result.params.old_string).toBe('find me');
|
| 266 |
+
expect(result.occurrences).toBe(1);
|
| 267 |
+
});
|
| 268 |
+
it('Test 1.2: old_string (no literal \\), new_string (correctly formatted) -> new_string unchanged', async () => {
|
| 269 |
+
const currentContent = 'This is a test string to find me.';
|
| 270 |
+
const originalParams = {
|
| 271 |
+
file_path: '/test/file.txt',
|
| 272 |
+
old_string: 'find me',
|
| 273 |
+
new_string: 'replace with this',
|
| 274 |
+
};
|
| 275 |
+
const result = await ensureCorrectEdit(
|
| 276 |
+
'/test/file.txt',
|
| 277 |
+
currentContent,
|
| 278 |
+
originalParams,
|
| 279 |
+
mockGeminiClientInstance,
|
| 280 |
+
abortSignal,
|
| 281 |
+
);
|
| 282 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(0);
|
| 283 |
+
expect(result.params.new_string).toBe('replace with this');
|
| 284 |
+
expect(result.params.old_string).toBe('find me');
|
| 285 |
+
expect(result.occurrences).toBe(1);
|
| 286 |
+
});
|
| 287 |
+
it('Test 1.3: old_string (with literal \\), new_string (escaped by Gemini) -> new_string unchanged (still escaped)', async () => {
|
| 288 |
+
const currentContent = 'This is a test string to find\\me.';
|
| 289 |
+
const originalParams = {
|
| 290 |
+
file_path: '/test/file.txt',
|
| 291 |
+
old_string: 'find\\me',
|
| 292 |
+
new_string: 'replace with \\"this\\"',
|
| 293 |
+
};
|
| 294 |
+
mockResponses.push({
|
| 295 |
+
corrected_new_string_escaping: 'replace with "this"',
|
| 296 |
+
});
|
| 297 |
+
const result = await ensureCorrectEdit(
|
| 298 |
+
'/test/file.txt',
|
| 299 |
+
currentContent,
|
| 300 |
+
originalParams,
|
| 301 |
+
mockGeminiClientInstance,
|
| 302 |
+
abortSignal,
|
| 303 |
+
);
|
| 304 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 305 |
+
expect(result.params.new_string).toBe('replace with "this"');
|
| 306 |
+
expect(result.params.old_string).toBe('find\\me');
|
| 307 |
+
expect(result.occurrences).toBe(1);
|
| 308 |
+
});
|
| 309 |
+
it('Test 1.4: old_string (with literal \\), new_string (correctly formatted) -> new_string unchanged', async () => {
|
| 310 |
+
const currentContent = 'This is a test string to find\\me.';
|
| 311 |
+
const originalParams = {
|
| 312 |
+
file_path: '/test/file.txt',
|
| 313 |
+
old_string: 'find\\me',
|
| 314 |
+
new_string: 'replace with this',
|
| 315 |
+
};
|
| 316 |
+
const result = await ensureCorrectEdit(
|
| 317 |
+
'/test/file.txt',
|
| 318 |
+
currentContent,
|
| 319 |
+
originalParams,
|
| 320 |
+
mockGeminiClientInstance,
|
| 321 |
+
abortSignal,
|
| 322 |
+
);
|
| 323 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(0);
|
| 324 |
+
expect(result.params.new_string).toBe('replace with this');
|
| 325 |
+
expect(result.params.old_string).toBe('find\\me');
|
| 326 |
+
expect(result.occurrences).toBe(1);
|
| 327 |
+
});
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
describe('Scenario Group 2: originalParams.old_string does NOT match, but unescapeStringForGeminiBug(originalParams.old_string) DOES match', () => {
|
| 331 |
+
it('Test 2.1: old_string (over-escaped, no intended literal \\), new_string (escaped by Gemini) -> new_string unescaped', async () => {
|
| 332 |
+
const currentContent = 'This is a test string to find "me".';
|
| 333 |
+
const originalParams = {
|
| 334 |
+
file_path: '/test/file.txt',
|
| 335 |
+
old_string: 'find \\"me\\"',
|
| 336 |
+
new_string: 'replace with \\"this\\"',
|
| 337 |
+
};
|
| 338 |
+
mockResponses.push({ corrected_new_string: 'replace with "this"' });
|
| 339 |
+
const result = await ensureCorrectEdit(
|
| 340 |
+
'/test/file.txt',
|
| 341 |
+
currentContent,
|
| 342 |
+
originalParams,
|
| 343 |
+
mockGeminiClientInstance,
|
| 344 |
+
abortSignal,
|
| 345 |
+
);
|
| 346 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 347 |
+
expect(result.params.new_string).toBe('replace with "this"');
|
| 348 |
+
expect(result.params.old_string).toBe('find "me"');
|
| 349 |
+
expect(result.occurrences).toBe(1);
|
| 350 |
+
});
|
| 351 |
+
it('Test 2.2: old_string (over-escaped, no intended literal \\), new_string (correctly formatted) -> new_string unescaped (harmlessly)', async () => {
|
| 352 |
+
const currentContent = 'This is a test string to find "me".';
|
| 353 |
+
const originalParams = {
|
| 354 |
+
file_path: '/test/file.txt',
|
| 355 |
+
old_string: 'find \\"me\\"',
|
| 356 |
+
new_string: 'replace with this',
|
| 357 |
+
};
|
| 358 |
+
const result = await ensureCorrectEdit(
|
| 359 |
+
'/test/file.txt',
|
| 360 |
+
currentContent,
|
| 361 |
+
originalParams,
|
| 362 |
+
mockGeminiClientInstance,
|
| 363 |
+
abortSignal,
|
| 364 |
+
);
|
| 365 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(0);
|
| 366 |
+
expect(result.params.new_string).toBe('replace with this');
|
| 367 |
+
expect(result.params.old_string).toBe('find "me"');
|
| 368 |
+
expect(result.occurrences).toBe(1);
|
| 369 |
+
});
|
| 370 |
+
it('Test 2.3: old_string (over-escaped, with intended literal \\), new_string (simple) -> new_string corrected', async () => {
|
| 371 |
+
const currentContent = 'This is a test string to find \\me.';
|
| 372 |
+
const originalParams = {
|
| 373 |
+
file_path: '/test/file.txt',
|
| 374 |
+
old_string: 'find \\\\me',
|
| 375 |
+
new_string: 'replace with foobar',
|
| 376 |
+
};
|
| 377 |
+
const result = await ensureCorrectEdit(
|
| 378 |
+
'/test/file.txt',
|
| 379 |
+
currentContent,
|
| 380 |
+
originalParams,
|
| 381 |
+
mockGeminiClientInstance,
|
| 382 |
+
abortSignal,
|
| 383 |
+
);
|
| 384 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(0);
|
| 385 |
+
expect(result.params.new_string).toBe('replace with foobar');
|
| 386 |
+
expect(result.params.old_string).toBe('find \\me');
|
| 387 |
+
expect(result.occurrences).toBe(1);
|
| 388 |
+
});
|
| 389 |
+
});
|
| 390 |
+
|
| 391 |
+
describe('Scenario Group 3: LLM Correction Path', () => {
|
| 392 |
+
it('Test 3.1: old_string (no literal \\), new_string (escaped by Gemini), LLM re-escapes new_string -> final new_string is double unescaped', async () => {
|
| 393 |
+
const currentContent = 'This is a test string to corrected find me.';
|
| 394 |
+
const originalParams = {
|
| 395 |
+
file_path: '/test/file.txt',
|
| 396 |
+
old_string: 'find me',
|
| 397 |
+
new_string: 'replace with \\\\"this\\\\"',
|
| 398 |
+
};
|
| 399 |
+
const llmNewString = 'LLM says replace with "that"';
|
| 400 |
+
mockResponses.push({ corrected_new_string_escaping: llmNewString });
|
| 401 |
+
const result = await ensureCorrectEdit(
|
| 402 |
+
'/test/file.txt',
|
| 403 |
+
currentContent,
|
| 404 |
+
originalParams,
|
| 405 |
+
mockGeminiClientInstance,
|
| 406 |
+
abortSignal,
|
| 407 |
+
);
|
| 408 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 409 |
+
expect(result.params.new_string).toBe(llmNewString);
|
| 410 |
+
expect(result.params.old_string).toBe('find me');
|
| 411 |
+
expect(result.occurrences).toBe(1);
|
| 412 |
+
});
|
| 413 |
+
it('Test 3.2: old_string (with literal \\), new_string (escaped by Gemini), LLM re-escapes new_string -> final new_string is unescaped once', async () => {
|
| 414 |
+
const currentContent = 'This is a test string to corrected find me.';
|
| 415 |
+
const originalParams = {
|
| 416 |
+
file_path: '/test/file.txt',
|
| 417 |
+
old_string: 'find\\me',
|
| 418 |
+
new_string: 'replace with \\\\"this\\\\"',
|
| 419 |
+
};
|
| 420 |
+
const llmCorrectedOldString = 'corrected find me';
|
| 421 |
+
const llmNewString = 'LLM says replace with "that"';
|
| 422 |
+
mockResponses.push({ corrected_target_snippet: llmCorrectedOldString });
|
| 423 |
+
mockResponses.push({ corrected_new_string: llmNewString });
|
| 424 |
+
const result = await ensureCorrectEdit(
|
| 425 |
+
'/test/file.txt',
|
| 426 |
+
currentContent,
|
| 427 |
+
originalParams,
|
| 428 |
+
mockGeminiClientInstance,
|
| 429 |
+
abortSignal,
|
| 430 |
+
);
|
| 431 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(2);
|
| 432 |
+
expect(result.params.new_string).toBe(llmNewString);
|
| 433 |
+
expect(result.params.old_string).toBe(llmCorrectedOldString);
|
| 434 |
+
expect(result.occurrences).toBe(1);
|
| 435 |
+
});
|
| 436 |
+
it('Test 3.3: old_string needs LLM, new_string is fine -> old_string corrected, new_string original', async () => {
|
| 437 |
+
const currentContent = 'This is a test string to be corrected.';
|
| 438 |
+
const originalParams = {
|
| 439 |
+
file_path: '/test/file.txt',
|
| 440 |
+
old_string: 'fiiind me',
|
| 441 |
+
new_string: 'replace with "this"',
|
| 442 |
+
};
|
| 443 |
+
const llmCorrectedOldString = 'to be corrected';
|
| 444 |
+
mockResponses.push({ corrected_target_snippet: llmCorrectedOldString });
|
| 445 |
+
const result = await ensureCorrectEdit(
|
| 446 |
+
'/test/file.txt',
|
| 447 |
+
currentContent,
|
| 448 |
+
originalParams,
|
| 449 |
+
mockGeminiClientInstance,
|
| 450 |
+
abortSignal,
|
| 451 |
+
);
|
| 452 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 453 |
+
expect(result.params.new_string).toBe('replace with "this"');
|
| 454 |
+
expect(result.params.old_string).toBe(llmCorrectedOldString);
|
| 455 |
+
expect(result.occurrences).toBe(1);
|
| 456 |
+
});
|
| 457 |
+
it('Test 3.4: LLM correction path, correctNewString returns the originalNewString it was passed (which was unescaped) -> final new_string is unescaped', async () => {
|
| 458 |
+
const currentContent = 'This is a test string to corrected find me.';
|
| 459 |
+
const originalParams = {
|
| 460 |
+
file_path: '/test/file.txt',
|
| 461 |
+
old_string: 'find me',
|
| 462 |
+
new_string: 'replace with \\\\"this\\\\"',
|
| 463 |
+
};
|
| 464 |
+
const newStringForLLMAndReturnedByLLM = 'replace with "this"';
|
| 465 |
+
mockResponses.push({
|
| 466 |
+
corrected_new_string_escaping: newStringForLLMAndReturnedByLLM,
|
| 467 |
+
});
|
| 468 |
+
const result = await ensureCorrectEdit(
|
| 469 |
+
'/test/file.txt',
|
| 470 |
+
currentContent,
|
| 471 |
+
originalParams,
|
| 472 |
+
mockGeminiClientInstance,
|
| 473 |
+
abortSignal,
|
| 474 |
+
);
|
| 475 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 476 |
+
expect(result.params.new_string).toBe(newStringForLLMAndReturnedByLLM);
|
| 477 |
+
expect(result.occurrences).toBe(1);
|
| 478 |
+
});
|
| 479 |
+
});
|
| 480 |
+
|
| 481 |
+
describe('Scenario Group 4: No Match Found / Multiple Matches', () => {
|
| 482 |
+
it('Test 4.1: No version of old_string (original, unescaped, LLM-corrected) matches -> returns original params, 0 occurrences', async () => {
|
| 483 |
+
const currentContent = 'This content has nothing to find.';
|
| 484 |
+
const originalParams = {
|
| 485 |
+
file_path: '/test/file.txt',
|
| 486 |
+
old_string: 'nonexistent string',
|
| 487 |
+
new_string: 'some new string',
|
| 488 |
+
};
|
| 489 |
+
mockResponses.push({ corrected_target_snippet: 'still nonexistent' });
|
| 490 |
+
const result = await ensureCorrectEdit(
|
| 491 |
+
'/test/file.txt',
|
| 492 |
+
currentContent,
|
| 493 |
+
originalParams,
|
| 494 |
+
mockGeminiClientInstance,
|
| 495 |
+
abortSignal,
|
| 496 |
+
);
|
| 497 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 498 |
+
expect(result.params).toEqual(originalParams);
|
| 499 |
+
expect(result.occurrences).toBe(0);
|
| 500 |
+
});
|
| 501 |
+
it('Test 4.2: unescapedOldStringAttempt results in >1 occurrences -> returns original params, count occurrences', async () => {
|
| 502 |
+
const currentContent =
|
| 503 |
+
'This content has find "me" and also find "me" again.';
|
| 504 |
+
const originalParams = {
|
| 505 |
+
file_path: '/test/file.txt',
|
| 506 |
+
old_string: 'find "me"',
|
| 507 |
+
new_string: 'some new string',
|
| 508 |
+
};
|
| 509 |
+
const result = await ensureCorrectEdit(
|
| 510 |
+
'/test/file.txt',
|
| 511 |
+
currentContent,
|
| 512 |
+
originalParams,
|
| 513 |
+
mockGeminiClientInstance,
|
| 514 |
+
abortSignal,
|
| 515 |
+
);
|
| 516 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(0);
|
| 517 |
+
expect(result.params).toEqual(originalParams);
|
| 518 |
+
expect(result.occurrences).toBe(2);
|
| 519 |
+
});
|
| 520 |
+
});
|
| 521 |
+
|
| 522 |
+
describe('Scenario Group 5: Specific unescapeStringForGeminiBug checks (integrated into ensureCorrectEdit)', () => {
|
| 523 |
+
it('Test 5.1: old_string needs LLM to become currentContent, new_string also needs correction', async () => {
|
| 524 |
+
const currentContent = 'const x = "a\nbc\\"def\\"';
|
| 525 |
+
const originalParams = {
|
| 526 |
+
file_path: '/test/file.txt',
|
| 527 |
+
old_string: 'const x = \\"a\\nbc\\\\"def\\\\"',
|
| 528 |
+
new_string: 'const y = \\"new\\nval\\\\"content\\\\"',
|
| 529 |
+
};
|
| 530 |
+
const expectedFinalNewString = 'const y = "new\nval\\"content\\"';
|
| 531 |
+
mockResponses.push({ corrected_target_snippet: currentContent });
|
| 532 |
+
mockResponses.push({ corrected_new_string: expectedFinalNewString });
|
| 533 |
+
const result = await ensureCorrectEdit(
|
| 534 |
+
'/test/file.txt',
|
| 535 |
+
currentContent,
|
| 536 |
+
originalParams,
|
| 537 |
+
mockGeminiClientInstance,
|
| 538 |
+
abortSignal,
|
| 539 |
+
);
|
| 540 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(2);
|
| 541 |
+
expect(result.params.old_string).toBe(currentContent);
|
| 542 |
+
expect(result.params.new_string).toBe(expectedFinalNewString);
|
| 543 |
+
expect(result.occurrences).toBe(1);
|
| 544 |
+
});
|
| 545 |
+
});
|
| 546 |
+
|
| 547 |
+
describe('Scenario Group 6: Concurrent Edits', () => {
|
| 548 |
+
it('Test 6.1: should return early if file was modified by another process', async () => {
|
| 549 |
+
const filePath = '/test/file.txt';
|
| 550 |
+
const currentContent =
|
| 551 |
+
'This content has been modified by someone else.';
|
| 552 |
+
const originalParams = {
|
| 553 |
+
file_path: filePath,
|
| 554 |
+
old_string: 'nonexistent string',
|
| 555 |
+
new_string: 'some new string',
|
| 556 |
+
};
|
| 557 |
+
|
| 558 |
+
const now = Date.now();
|
| 559 |
+
const lastEditTime = now - 5000; // 5 seconds ago
|
| 560 |
+
|
| 561 |
+
// Mock the file's modification time to be recent
|
| 562 |
+
vi.spyOn(fs, 'statSync').mockReturnValue({
|
| 563 |
+
mtimeMs: now,
|
| 564 |
+
} as fs.Stats);
|
| 565 |
+
|
| 566 |
+
// Mock the last edit timestamp from our history to be in the past
|
| 567 |
+
const history = [
|
| 568 |
+
{
|
| 569 |
+
role: 'model',
|
| 570 |
+
parts: [
|
| 571 |
+
{
|
| 572 |
+
functionResponse: {
|
| 573 |
+
name: EditTool.Name,
|
| 574 |
+
id: `${EditTool.Name}-${lastEditTime}-123`,
|
| 575 |
+
response: {
|
| 576 |
+
output: {
|
| 577 |
+
llmContent: `Successfully modified file: ${filePath}`,
|
| 578 |
+
},
|
| 579 |
+
},
|
| 580 |
+
},
|
| 581 |
+
},
|
| 582 |
+
],
|
| 583 |
+
},
|
| 584 |
+
];
|
| 585 |
+
(mockGeminiClientInstance.getHistory as Mock).mockResolvedValue(
|
| 586 |
+
history,
|
| 587 |
+
);
|
| 588 |
+
|
| 589 |
+
const result = await ensureCorrectEdit(
|
| 590 |
+
filePath,
|
| 591 |
+
currentContent,
|
| 592 |
+
originalParams,
|
| 593 |
+
mockGeminiClientInstance,
|
| 594 |
+
abortSignal,
|
| 595 |
+
);
|
| 596 |
+
|
| 597 |
+
expect(result.occurrences).toBe(0);
|
| 598 |
+
expect(result.params).toEqual(originalParams);
|
| 599 |
+
});
|
| 600 |
+
});
|
| 601 |
+
});
|
| 602 |
+
|
| 603 |
+
describe('ensureCorrectFileContent', () => {
|
| 604 |
+
let mockGeminiClientInstance: Mocked<GeminiClient>;
|
| 605 |
+
let mockToolRegistry: Mocked<ToolRegistry>;
|
| 606 |
+
let mockConfigInstance: Config;
|
| 607 |
+
const abortSignal = new AbortController().signal;
|
| 608 |
+
|
| 609 |
+
beforeEach(() => {
|
| 610 |
+
mockToolRegistry = new ToolRegistry({} as Config) as Mocked<ToolRegistry>;
|
| 611 |
+
const configParams = {
|
| 612 |
+
apiKey: 'test-api-key',
|
| 613 |
+
model: 'test-model',
|
| 614 |
+
sandbox: false as boolean | string,
|
| 615 |
+
targetDir: '/test',
|
| 616 |
+
debugMode: false,
|
| 617 |
+
question: undefined as string | undefined,
|
| 618 |
+
fullContext: false,
|
| 619 |
+
coreTools: undefined as string[] | undefined,
|
| 620 |
+
toolDiscoveryCommand: undefined as string | undefined,
|
| 621 |
+
toolCallCommand: undefined as string | undefined,
|
| 622 |
+
mcpServerCommand: undefined as string | undefined,
|
| 623 |
+
mcpServers: undefined as Record<string, any> | undefined,
|
| 624 |
+
userAgent: 'test-agent',
|
| 625 |
+
userMemory: '',
|
| 626 |
+
geminiMdFileCount: 0,
|
| 627 |
+
alwaysSkipModificationConfirmation: false,
|
| 628 |
+
};
|
| 629 |
+
mockConfigInstance = {
|
| 630 |
+
...configParams,
|
| 631 |
+
getApiKey: vi.fn(() => configParams.apiKey),
|
| 632 |
+
getModel: vi.fn(() => configParams.model),
|
| 633 |
+
getSandbox: vi.fn(() => configParams.sandbox),
|
| 634 |
+
getTargetDir: vi.fn(() => configParams.targetDir),
|
| 635 |
+
getToolRegistry: vi.fn(() => mockToolRegistry),
|
| 636 |
+
getDebugMode: vi.fn(() => configParams.debugMode),
|
| 637 |
+
getQuestion: vi.fn(() => configParams.question),
|
| 638 |
+
getFullContext: vi.fn(() => configParams.fullContext),
|
| 639 |
+
getCoreTools: vi.fn(() => configParams.coreTools),
|
| 640 |
+
getToolDiscoveryCommand: vi.fn(() => configParams.toolDiscoveryCommand),
|
| 641 |
+
getToolCallCommand: vi.fn(() => configParams.toolCallCommand),
|
| 642 |
+
getMcpServerCommand: vi.fn(() => configParams.mcpServerCommand),
|
| 643 |
+
getMcpServers: vi.fn(() => configParams.mcpServers),
|
| 644 |
+
getUserAgent: vi.fn(() => configParams.userAgent),
|
| 645 |
+
getUserMemory: vi.fn(() => configParams.userMemory),
|
| 646 |
+
setUserMemory: vi.fn((mem: string) => {
|
| 647 |
+
configParams.userMemory = mem;
|
| 648 |
+
}),
|
| 649 |
+
getGeminiMdFileCount: vi.fn(() => configParams.geminiMdFileCount),
|
| 650 |
+
setGeminiMdFileCount: vi.fn((count: number) => {
|
| 651 |
+
configParams.geminiMdFileCount = count;
|
| 652 |
+
}),
|
| 653 |
+
getAlwaysSkipModificationConfirmation: vi.fn(
|
| 654 |
+
() => configParams.alwaysSkipModificationConfirmation,
|
| 655 |
+
),
|
| 656 |
+
setAlwaysSkipModificationConfirmation: vi.fn((skip: boolean) => {
|
| 657 |
+
configParams.alwaysSkipModificationConfirmation = skip;
|
| 658 |
+
}),
|
| 659 |
+
getQuotaErrorOccurred: vi.fn().mockReturnValue(false),
|
| 660 |
+
setQuotaErrorOccurred: vi.fn(),
|
| 661 |
+
} as unknown as Config;
|
| 662 |
+
|
| 663 |
+
callCount = 0;
|
| 664 |
+
mockResponses.length = 0;
|
| 665 |
+
mockGenerateJson = vi
|
| 666 |
+
.fn()
|
| 667 |
+
.mockImplementation((_contents, _schema, signal) => {
|
| 668 |
+
if (signal && signal.aborted) {
|
| 669 |
+
return Promise.reject(new Error('Aborted'));
|
| 670 |
+
}
|
| 671 |
+
const response = mockResponses[callCount];
|
| 672 |
+
callCount++;
|
| 673 |
+
if (response === undefined) return Promise.resolve({});
|
| 674 |
+
return Promise.resolve(response);
|
| 675 |
+
});
|
| 676 |
+
mockStartChat = vi.fn();
|
| 677 |
+
mockSendMessageStream = vi.fn();
|
| 678 |
+
|
| 679 |
+
mockGeminiClientInstance = new GeminiClient(
|
| 680 |
+
mockConfigInstance,
|
| 681 |
+
) as Mocked<GeminiClient>;
|
| 682 |
+
resetEditCorrectorCaches_TEST_ONLY();
|
| 683 |
+
});
|
| 684 |
+
|
| 685 |
+
it('should return content unchanged if no escaping issues detected', async () => {
|
| 686 |
+
const content = 'This is normal content without escaping issues';
|
| 687 |
+
const result = await ensureCorrectFileContent(
|
| 688 |
+
content,
|
| 689 |
+
mockGeminiClientInstance,
|
| 690 |
+
abortSignal,
|
| 691 |
+
);
|
| 692 |
+
expect(result).toBe(content);
|
| 693 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(0);
|
| 694 |
+
});
|
| 695 |
+
|
| 696 |
+
it('should call correctStringEscaping for potentially escaped content', async () => {
|
| 697 |
+
const content = 'console.log(\\"Hello World\\");';
|
| 698 |
+
const correctedContent = 'console.log("Hello World");';
|
| 699 |
+
mockResponses.push({
|
| 700 |
+
corrected_string_escaping: correctedContent,
|
| 701 |
+
});
|
| 702 |
+
|
| 703 |
+
const result = await ensureCorrectFileContent(
|
| 704 |
+
content,
|
| 705 |
+
mockGeminiClientInstance,
|
| 706 |
+
abortSignal,
|
| 707 |
+
);
|
| 708 |
+
|
| 709 |
+
expect(result).toBe(correctedContent);
|
| 710 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 711 |
+
});
|
| 712 |
+
|
| 713 |
+
it('should handle correctStringEscaping returning corrected content via correct property name', async () => {
|
| 714 |
+
// This test specifically verifies the property name fix
|
| 715 |
+
const content = 'const message = \\"Hello\\nWorld\\";';
|
| 716 |
+
const correctedContent = 'const message = "Hello\nWorld";';
|
| 717 |
+
|
| 718 |
+
// Mock the response with the correct property name
|
| 719 |
+
mockResponses.push({
|
| 720 |
+
corrected_string_escaping: correctedContent,
|
| 721 |
+
});
|
| 722 |
+
|
| 723 |
+
const result = await ensureCorrectFileContent(
|
| 724 |
+
content,
|
| 725 |
+
mockGeminiClientInstance,
|
| 726 |
+
abortSignal,
|
| 727 |
+
);
|
| 728 |
+
|
| 729 |
+
expect(result).toBe(correctedContent);
|
| 730 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 731 |
+
});
|
| 732 |
+
|
| 733 |
+
it('should return original content if LLM correction fails', async () => {
|
| 734 |
+
const content = 'console.log(\\"Hello World\\");';
|
| 735 |
+
// Mock empty response to simulate LLM failure
|
| 736 |
+
mockResponses.push({});
|
| 737 |
+
|
| 738 |
+
const result = await ensureCorrectFileContent(
|
| 739 |
+
content,
|
| 740 |
+
mockGeminiClientInstance,
|
| 741 |
+
abortSignal,
|
| 742 |
+
);
|
| 743 |
+
|
| 744 |
+
expect(result).toBe(content);
|
| 745 |
+
expect(mockGenerateJson).toHaveBeenCalledTimes(1);
|
| 746 |
+
});
|
| 747 |
+
|
| 748 |
+
it('should handle various escape sequences that need correction', async () => {
|
| 749 |
+
const content =
|
| 750 |
+
'const obj = { name: \\"John\\", age: 30, bio: \\"Developer\\nEngineer\\" };';
|
| 751 |
+
const correctedContent =
|
| 752 |
+
'const obj = { name: "John", age: 30, bio: "Developer\nEngineer" };';
|
| 753 |
+
|
| 754 |
+
mockResponses.push({
|
| 755 |
+
corrected_string_escaping: correctedContent,
|
| 756 |
+
});
|
| 757 |
+
|
| 758 |
+
const result = await ensureCorrectFileContent(
|
| 759 |
+
content,
|
| 760 |
+
mockGeminiClientInstance,
|
| 761 |
+
abortSignal,
|
| 762 |
+
);
|
| 763 |
+
|
| 764 |
+
expect(result).toBe(correctedContent);
|
| 765 |
+
});
|
| 766 |
+
});
|
| 767 |
+
});
|
projects/ui/qwen-code/packages/core/src/utils/editCorrector.ts
ADDED
|
@@ -0,0 +1,750 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* @license
|
| 3 |
+
* Copyright 2025 Google LLC
|
| 4 |
+
* SPDX-License-Identifier: Apache-2.0
|
| 5 |
+
*/
|
| 6 |
+
|
| 7 |
+
import { Content, GenerateContentConfig } from '@google/genai';
|
| 8 |
+
import { GeminiClient } from '../core/client.js';
|
| 9 |
+
import { EditToolParams, EditTool } from '../tools/edit.js';
|
| 10 |
+
import { WriteFileTool } from '../tools/write-file.js';
|
| 11 |
+
import { ReadFileTool } from '../tools/read-file.js';
|
| 12 |
+
import { ReadManyFilesTool } from '../tools/read-many-files.js';
|
| 13 |
+
import { GrepTool } from '../tools/grep.js';
|
| 14 |
+
import { LruCache } from './LruCache.js';
|
| 15 |
+
import { DEFAULT_GEMINI_FLASH_LITE_MODEL } from '../config/models.js';
|
| 16 |
+
import {
|
| 17 |
+
isFunctionResponse,
|
| 18 |
+
isFunctionCall,
|
| 19 |
+
} from '../utils/messageInspectors.js';
|
| 20 |
+
import * as fs from 'fs';
|
| 21 |
+
|
| 22 |
+
const EditModel = DEFAULT_GEMINI_FLASH_LITE_MODEL;
|
| 23 |
+
const EditConfig: GenerateContentConfig = {
|
| 24 |
+
thinkingConfig: {
|
| 25 |
+
thinkingBudget: 0,
|
| 26 |
+
},
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
const MAX_CACHE_SIZE = 50;
|
| 30 |
+
|
| 31 |
+
// Cache for ensureCorrectEdit results
|
| 32 |
+
const editCorrectionCache = new LruCache<string, CorrectedEditResult>(
|
| 33 |
+
MAX_CACHE_SIZE,
|
| 34 |
+
);
|
| 35 |
+
|
| 36 |
+
// Cache for ensureCorrectFileContent results
|
| 37 |
+
const fileContentCorrectionCache = new LruCache<string, string>(MAX_CACHE_SIZE);
|
| 38 |
+
|
| 39 |
+
/**
|
| 40 |
+
* Defines the structure of the parameters within CorrectedEditResult
|
| 41 |
+
*/
|
| 42 |
+
interface CorrectedEditParams {
|
| 43 |
+
file_path: string;
|
| 44 |
+
old_string: string;
|
| 45 |
+
new_string: string;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
/**
|
| 49 |
+
* Defines the result structure for ensureCorrectEdit.
|
| 50 |
+
*/
|
| 51 |
+
export interface CorrectedEditResult {
|
| 52 |
+
params: CorrectedEditParams;
|
| 53 |
+
occurrences: number;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/**
|
| 57 |
+
* Extracts the timestamp from the .id value, which is in format
|
| 58 |
+
* <tool.name>-<timestamp>-<uuid>
|
| 59 |
+
* @param fcnId the ID value of a functionCall or functionResponse object
|
| 60 |
+
* @returns -1 if the timestamp could not be extracted, else the timestamp (as a number)
|
| 61 |
+
*/
|
| 62 |
+
function getTimestampFromFunctionId(fcnId: string): number {
|
| 63 |
+
const idParts = fcnId.split('-');
|
| 64 |
+
if (idParts.length > 2) {
|
| 65 |
+
const timestamp = parseInt(idParts[1], 10);
|
| 66 |
+
if (!isNaN(timestamp)) {
|
| 67 |
+
return timestamp;
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
return -1;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
/**
|
| 74 |
+
* Will look through the gemini client history and determine when the most recent
|
| 75 |
+
* edit to a target file occurred. If no edit happened, it will return -1
|
| 76 |
+
* @param filePath the path to the file
|
| 77 |
+
* @param client the geminiClient, so that we can get the history
|
| 78 |
+
* @returns a DateTime (as a number) of when the last edit occurred, or -1 if no edit was found.
|
| 79 |
+
*/
|
| 80 |
+
async function findLastEditTimestamp(
|
| 81 |
+
filePath: string,
|
| 82 |
+
client: GeminiClient,
|
| 83 |
+
): Promise<number> {
|
| 84 |
+
const history = (await client.getHistory()) ?? [];
|
| 85 |
+
|
| 86 |
+
// Tools that may reference the file path in their FunctionResponse `output`.
|
| 87 |
+
const toolsInResp = new Set([
|
| 88 |
+
WriteFileTool.Name,
|
| 89 |
+
EditTool.Name,
|
| 90 |
+
ReadManyFilesTool.Name,
|
| 91 |
+
GrepTool.Name,
|
| 92 |
+
]);
|
| 93 |
+
// Tools that may reference the file path in their FunctionCall `args`.
|
| 94 |
+
const toolsInCall = new Set([...toolsInResp, ReadFileTool.Name]);
|
| 95 |
+
|
| 96 |
+
// Iterate backwards to find the most recent relevant action.
|
| 97 |
+
for (const entry of history.slice().reverse()) {
|
| 98 |
+
if (!entry.parts) continue;
|
| 99 |
+
|
| 100 |
+
for (const part of entry.parts) {
|
| 101 |
+
let id: string | undefined;
|
| 102 |
+
let content: unknown;
|
| 103 |
+
|
| 104 |
+
// Check for a relevant FunctionCall with the file path in its arguments.
|
| 105 |
+
if (
|
| 106 |
+
isFunctionCall(entry) &&
|
| 107 |
+
part.functionCall?.name &&
|
| 108 |
+
toolsInCall.has(part.functionCall.name)
|
| 109 |
+
) {
|
| 110 |
+
id = part.functionCall.id;
|
| 111 |
+
content = part.functionCall.args;
|
| 112 |
+
}
|
| 113 |
+
// Check for a relevant FunctionResponse with the file path in its output.
|
| 114 |
+
else if (
|
| 115 |
+
isFunctionResponse(entry) &&
|
| 116 |
+
part.functionResponse?.name &&
|
| 117 |
+
toolsInResp.has(part.functionResponse.name)
|
| 118 |
+
) {
|
| 119 |
+
const { response } = part.functionResponse;
|
| 120 |
+
if (response && !('error' in response) && 'output' in response) {
|
| 121 |
+
id = part.functionResponse.id;
|
| 122 |
+
content = response['output'];
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
if (!id || content === undefined) continue;
|
| 127 |
+
|
| 128 |
+
// Use the "blunt hammer" approach to find the file path in the content.
|
| 129 |
+
// Note that the tool response data is inconsistent in their formatting
|
| 130 |
+
// with successes and errors - so, we just check for the existence
|
| 131 |
+
// as the best guess to if error/failed occurred with the response.
|
| 132 |
+
const stringified = JSON.stringify(content);
|
| 133 |
+
if (
|
| 134 |
+
!stringified.includes('Error') && // only applicable for functionResponse
|
| 135 |
+
!stringified.includes('Failed') && // only applicable for functionResponse
|
| 136 |
+
stringified.includes(filePath)
|
| 137 |
+
) {
|
| 138 |
+
return getTimestampFromFunctionId(id);
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
return -1;
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
/**
|
| 147 |
+
* Attempts to correct edit parameters if the original old_string is not found.
|
| 148 |
+
* It tries unescaping, and then LLM-based correction.
|
| 149 |
+
* Results are cached to avoid redundant processing.
|
| 150 |
+
*
|
| 151 |
+
* @param currentContent The current content of the file.
|
| 152 |
+
* @param originalParams The original EditToolParams
|
| 153 |
+
* @param client The GeminiClient for LLM calls.
|
| 154 |
+
* @returns A promise resolving to an object containing the (potentially corrected)
|
| 155 |
+
* EditToolParams (as CorrectedEditParams) and the final occurrences count.
|
| 156 |
+
*/
|
| 157 |
+
export async function ensureCorrectEdit(
|
| 158 |
+
filePath: string,
|
| 159 |
+
currentContent: string,
|
| 160 |
+
originalParams: EditToolParams, // This is the EditToolParams from edit.ts, without \'corrected\'
|
| 161 |
+
client: GeminiClient,
|
| 162 |
+
abortSignal: AbortSignal,
|
| 163 |
+
): Promise<CorrectedEditResult> {
|
| 164 |
+
const cacheKey = `${currentContent}---${originalParams.old_string}---${originalParams.new_string}`;
|
| 165 |
+
const cachedResult = editCorrectionCache.get(cacheKey);
|
| 166 |
+
if (cachedResult) {
|
| 167 |
+
return cachedResult;
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
let finalNewString = originalParams.new_string;
|
| 171 |
+
const newStringPotentiallyEscaped =
|
| 172 |
+
unescapeStringForGeminiBug(originalParams.new_string) !==
|
| 173 |
+
originalParams.new_string;
|
| 174 |
+
|
| 175 |
+
const expectedReplacements = originalParams.expected_replacements ?? 1;
|
| 176 |
+
|
| 177 |
+
let finalOldString = originalParams.old_string;
|
| 178 |
+
let occurrences = countOccurrences(currentContent, finalOldString);
|
| 179 |
+
|
| 180 |
+
if (occurrences === expectedReplacements) {
|
| 181 |
+
if (newStringPotentiallyEscaped) {
|
| 182 |
+
finalNewString = await correctNewStringEscaping(
|
| 183 |
+
client,
|
| 184 |
+
finalOldString,
|
| 185 |
+
originalParams.new_string,
|
| 186 |
+
abortSignal,
|
| 187 |
+
);
|
| 188 |
+
}
|
| 189 |
+
} else if (occurrences > expectedReplacements) {
|
| 190 |
+
const expectedReplacements = originalParams.expected_replacements ?? 1;
|
| 191 |
+
|
| 192 |
+
// If user expects multiple replacements, return as-is
|
| 193 |
+
if (occurrences === expectedReplacements) {
|
| 194 |
+
const result: CorrectedEditResult = {
|
| 195 |
+
params: { ...originalParams },
|
| 196 |
+
occurrences,
|
| 197 |
+
};
|
| 198 |
+
editCorrectionCache.set(cacheKey, result);
|
| 199 |
+
return result;
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
// If user expects 1 but found multiple, try to correct (existing behavior)
|
| 203 |
+
if (expectedReplacements === 1) {
|
| 204 |
+
const result: CorrectedEditResult = {
|
| 205 |
+
params: { ...originalParams },
|
| 206 |
+
occurrences,
|
| 207 |
+
};
|
| 208 |
+
editCorrectionCache.set(cacheKey, result);
|
| 209 |
+
return result;
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
// If occurrences don't match expected, return as-is (will fail validation later)
|
| 213 |
+
const result: CorrectedEditResult = {
|
| 214 |
+
params: { ...originalParams },
|
| 215 |
+
occurrences,
|
| 216 |
+
};
|
| 217 |
+
editCorrectionCache.set(cacheKey, result);
|
| 218 |
+
return result;
|
| 219 |
+
} else {
|
| 220 |
+
// occurrences is 0 or some other unexpected state initially
|
| 221 |
+
const unescapedOldStringAttempt = unescapeStringForGeminiBug(
|
| 222 |
+
originalParams.old_string,
|
| 223 |
+
);
|
| 224 |
+
occurrences = countOccurrences(currentContent, unescapedOldStringAttempt);
|
| 225 |
+
|
| 226 |
+
if (occurrences === expectedReplacements) {
|
| 227 |
+
finalOldString = unescapedOldStringAttempt;
|
| 228 |
+
if (newStringPotentiallyEscaped) {
|
| 229 |
+
finalNewString = await correctNewString(
|
| 230 |
+
client,
|
| 231 |
+
originalParams.old_string, // original old
|
| 232 |
+
unescapedOldStringAttempt, // corrected old
|
| 233 |
+
originalParams.new_string, // original new (which is potentially escaped)
|
| 234 |
+
abortSignal,
|
| 235 |
+
);
|
| 236 |
+
}
|
| 237 |
+
} else if (occurrences === 0) {
|
| 238 |
+
if (filePath) {
|
| 239 |
+
// In order to keep from clobbering edits made outside our system,
|
| 240 |
+
// let's check if there was a more recent edit to the file than what
|
| 241 |
+
// our system has done
|
| 242 |
+
const lastEditedByUsTime = await findLastEditTimestamp(
|
| 243 |
+
filePath,
|
| 244 |
+
client,
|
| 245 |
+
);
|
| 246 |
+
|
| 247 |
+
// Add a 1-second buffer to account for timing inaccuracies. If the file
|
| 248 |
+
// was modified more than a second after the last edit tool was run, we
|
| 249 |
+
// can assume it was modified by something else.
|
| 250 |
+
if (lastEditedByUsTime > 0) {
|
| 251 |
+
const stats = fs.statSync(filePath);
|
| 252 |
+
const diff = stats.mtimeMs - lastEditedByUsTime;
|
| 253 |
+
if (diff > 2000) {
|
| 254 |
+
// Hard coded for 2 seconds
|
| 255 |
+
// This file was edited sooner
|
| 256 |
+
const result: CorrectedEditResult = {
|
| 257 |
+
params: { ...originalParams },
|
| 258 |
+
occurrences: 0, // Explicitly 0 as LLM failed
|
| 259 |
+
};
|
| 260 |
+
editCorrectionCache.set(cacheKey, result);
|
| 261 |
+
return result;
|
| 262 |
+
}
|
| 263 |
+
}
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
const llmCorrectedOldString = await correctOldStringMismatch(
|
| 267 |
+
client,
|
| 268 |
+
currentContent,
|
| 269 |
+
unescapedOldStringAttempt,
|
| 270 |
+
abortSignal,
|
| 271 |
+
);
|
| 272 |
+
const llmOldOccurrences = countOccurrences(
|
| 273 |
+
currentContent,
|
| 274 |
+
llmCorrectedOldString,
|
| 275 |
+
);
|
| 276 |
+
|
| 277 |
+
if (llmOldOccurrences === expectedReplacements) {
|
| 278 |
+
finalOldString = llmCorrectedOldString;
|
| 279 |
+
occurrences = llmOldOccurrences;
|
| 280 |
+
|
| 281 |
+
if (newStringPotentiallyEscaped) {
|
| 282 |
+
const baseNewStringForLLMCorrection = unescapeStringForGeminiBug(
|
| 283 |
+
originalParams.new_string,
|
| 284 |
+
);
|
| 285 |
+
finalNewString = await correctNewString(
|
| 286 |
+
client,
|
| 287 |
+
originalParams.old_string, // original old
|
| 288 |
+
llmCorrectedOldString, // corrected old
|
| 289 |
+
baseNewStringForLLMCorrection, // base new for correction
|
| 290 |
+
abortSignal,
|
| 291 |
+
);
|
| 292 |
+
}
|
| 293 |
+
} else {
|
| 294 |
+
// LLM correction also failed for old_string
|
| 295 |
+
const result: CorrectedEditResult = {
|
| 296 |
+
params: { ...originalParams },
|
| 297 |
+
occurrences: 0, // Explicitly 0 as LLM failed
|
| 298 |
+
};
|
| 299 |
+
editCorrectionCache.set(cacheKey, result);
|
| 300 |
+
return result;
|
| 301 |
+
}
|
| 302 |
+
} else {
|
| 303 |
+
// Unescaping old_string resulted in > 1 occurrence
|
| 304 |
+
const result: CorrectedEditResult = {
|
| 305 |
+
params: { ...originalParams },
|
| 306 |
+
occurrences, // This will be > 1
|
| 307 |
+
};
|
| 308 |
+
editCorrectionCache.set(cacheKey, result);
|
| 309 |
+
return result;
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
const { targetString, pair } = trimPairIfPossible(
|
| 314 |
+
finalOldString,
|
| 315 |
+
finalNewString,
|
| 316 |
+
currentContent,
|
| 317 |
+
expectedReplacements,
|
| 318 |
+
);
|
| 319 |
+
finalOldString = targetString;
|
| 320 |
+
finalNewString = pair;
|
| 321 |
+
|
| 322 |
+
// Final result construction
|
| 323 |
+
const result: CorrectedEditResult = {
|
| 324 |
+
params: {
|
| 325 |
+
file_path: originalParams.file_path,
|
| 326 |
+
old_string: finalOldString,
|
| 327 |
+
new_string: finalNewString,
|
| 328 |
+
},
|
| 329 |
+
occurrences: countOccurrences(currentContent, finalOldString), // Recalculate occurrences with the final old_string
|
| 330 |
+
};
|
| 331 |
+
editCorrectionCache.set(cacheKey, result);
|
| 332 |
+
return result;
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
export async function ensureCorrectFileContent(
|
| 336 |
+
content: string,
|
| 337 |
+
client: GeminiClient,
|
| 338 |
+
abortSignal: AbortSignal,
|
| 339 |
+
): Promise<string> {
|
| 340 |
+
const cachedResult = fileContentCorrectionCache.get(content);
|
| 341 |
+
if (cachedResult) {
|
| 342 |
+
return cachedResult;
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
const contentPotentiallyEscaped =
|
| 346 |
+
unescapeStringForGeminiBug(content) !== content;
|
| 347 |
+
if (!contentPotentiallyEscaped) {
|
| 348 |
+
fileContentCorrectionCache.set(content, content);
|
| 349 |
+
return content;
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
const correctedContent = await correctStringEscaping(
|
| 353 |
+
content,
|
| 354 |
+
client,
|
| 355 |
+
abortSignal,
|
| 356 |
+
);
|
| 357 |
+
fileContentCorrectionCache.set(content, correctedContent);
|
| 358 |
+
return correctedContent;
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
// Define the expected JSON schema for the LLM response for old_string correction
|
| 362 |
+
const OLD_STRING_CORRECTION_SCHEMA: Record<string, unknown> = {
|
| 363 |
+
type: 'object',
|
| 364 |
+
properties: {
|
| 365 |
+
corrected_target_snippet: {
|
| 366 |
+
type: 'string',
|
| 367 |
+
description:
|
| 368 |
+
'The corrected version of the target snippet that exactly and uniquely matches a segment within the provided file content.',
|
| 369 |
+
},
|
| 370 |
+
},
|
| 371 |
+
required: ['corrected_target_snippet'],
|
| 372 |
+
};
|
| 373 |
+
|
| 374 |
+
export async function correctOldStringMismatch(
|
| 375 |
+
geminiClient: GeminiClient,
|
| 376 |
+
fileContent: string,
|
| 377 |
+
problematicSnippet: string,
|
| 378 |
+
abortSignal: AbortSignal,
|
| 379 |
+
): Promise<string> {
|
| 380 |
+
const prompt = `
|
| 381 |
+
Context: A process needs to find an exact literal, unique match for a specific text snippet within a file's content. The provided snippet failed to match exactly. This is most likely because it has been overly escaped.
|
| 382 |
+
|
| 383 |
+
Task: Analyze the provided file content and the problematic target snippet. Identify the segment in the file content that the snippet was *most likely* intended to match. Output the *exact*, literal text of that segment from the file content. Focus *only* on removing extra escape characters and correcting formatting, whitespace, or minor differences to achieve a PERFECT literal match. The output must be the exact literal text as it appears in the file.
|
| 384 |
+
|
| 385 |
+
Problematic target snippet:
|
| 386 |
+
\`\`\`
|
| 387 |
+
${problematicSnippet}
|
| 388 |
+
\`\`\`
|
| 389 |
+
|
| 390 |
+
File Content:
|
| 391 |
+
\`\`\`
|
| 392 |
+
${fileContent}
|
| 393 |
+
\`\`\`
|
| 394 |
+
|
| 395 |
+
For example, if the problematic target snippet was "\\\\\\nconst greeting = \`Hello \\\\\`\${name}\\\\\`\`;" and the file content had content that looked like "\nconst greeting = \`Hello ${'\\`'}\${name}${'\\`'}\`;", then corrected_target_snippet should likely be "\nconst greeting = \`Hello ${'\\`'}\${name}${'\\`'}\`;" to fix the incorrect escaping to match the original file content.
|
| 396 |
+
If the differences are only in whitespace or formatting, apply similar whitespace/formatting changes to the corrected_target_snippet.
|
| 397 |
+
|
| 398 |
+
Return ONLY the corrected target snippet in the specified JSON format with the key 'corrected_target_snippet'. If no clear, unique match can be found, return an empty string for 'corrected_target_snippet'.
|
| 399 |
+
`.trim();
|
| 400 |
+
|
| 401 |
+
const contents: Content[] = [{ role: 'user', parts: [{ text: prompt }] }];
|
| 402 |
+
|
| 403 |
+
try {
|
| 404 |
+
const result = await geminiClient.generateJson(
|
| 405 |
+
contents,
|
| 406 |
+
OLD_STRING_CORRECTION_SCHEMA,
|
| 407 |
+
abortSignal,
|
| 408 |
+
EditModel,
|
| 409 |
+
EditConfig,
|
| 410 |
+
);
|
| 411 |
+
|
| 412 |
+
if (
|
| 413 |
+
result &&
|
| 414 |
+
typeof result['corrected_target_snippet'] === 'string' &&
|
| 415 |
+
result['corrected_target_snippet'].length > 0
|
| 416 |
+
) {
|
| 417 |
+
return result['corrected_target_snippet'];
|
| 418 |
+
} else {
|
| 419 |
+
return problematicSnippet;
|
| 420 |
+
}
|
| 421 |
+
} catch (error) {
|
| 422 |
+
if (abortSignal.aborted) {
|
| 423 |
+
throw error;
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
console.error(
|
| 427 |
+
'Error during LLM call for old string snippet correction:',
|
| 428 |
+
error,
|
| 429 |
+
);
|
| 430 |
+
|
| 431 |
+
return problematicSnippet;
|
| 432 |
+
}
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
// Define the expected JSON schema for the new_string correction LLM response
|
| 436 |
+
const NEW_STRING_CORRECTION_SCHEMA: Record<string, unknown> = {
|
| 437 |
+
type: 'object',
|
| 438 |
+
properties: {
|
| 439 |
+
corrected_new_string: {
|
| 440 |
+
type: 'string',
|
| 441 |
+
description:
|
| 442 |
+
'The original_new_string adjusted to be a suitable replacement for the corrected_old_string, while maintaining the original intent of the change.',
|
| 443 |
+
},
|
| 444 |
+
},
|
| 445 |
+
required: ['corrected_new_string'],
|
| 446 |
+
};
|
| 447 |
+
|
| 448 |
+
/**
|
| 449 |
+
* Adjusts the new_string to align with a corrected old_string, maintaining the original intent.
|
| 450 |
+
*/
|
| 451 |
+
export async function correctNewString(
|
| 452 |
+
geminiClient: GeminiClient,
|
| 453 |
+
originalOldString: string,
|
| 454 |
+
correctedOldString: string,
|
| 455 |
+
originalNewString: string,
|
| 456 |
+
abortSignal: AbortSignal,
|
| 457 |
+
): Promise<string> {
|
| 458 |
+
if (originalOldString === correctedOldString) {
|
| 459 |
+
return originalNewString;
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
const prompt = `
|
| 463 |
+
Context: A text replacement operation was planned. The original text to be replaced (original_old_string) was slightly different from the actual text in the file (corrected_old_string). The original_old_string has now been corrected to match the file content.
|
| 464 |
+
We now need to adjust the replacement text (original_new_string) so that it makes sense as a replacement for the corrected_old_string, while preserving the original intent of the change.
|
| 465 |
+
|
| 466 |
+
original_old_string (what was initially intended to be found):
|
| 467 |
+
\`\`\`
|
| 468 |
+
${originalOldString}
|
| 469 |
+
\`\`\`
|
| 470 |
+
|
| 471 |
+
corrected_old_string (what was actually found in the file and will be replaced):
|
| 472 |
+
\`\`\`
|
| 473 |
+
${correctedOldString}
|
| 474 |
+
\`\`\`
|
| 475 |
+
|
| 476 |
+
original_new_string (what was intended to replace original_old_string):
|
| 477 |
+
\`\`\`
|
| 478 |
+
${originalNewString}
|
| 479 |
+
\`\`\`
|
| 480 |
+
|
| 481 |
+
Task: Based on the differences between original_old_string and corrected_old_string, and the content of original_new_string, generate a corrected_new_string. This corrected_new_string should be what original_new_string would have been if it was designed to replace corrected_old_string directly, while maintaining the spirit of the original transformation.
|
| 482 |
+
|
| 483 |
+
For example, if original_old_string was "\\\\\\nconst greeting = \`Hello \\\\\`\${name}\\\\\`\`;" and corrected_old_string is "\nconst greeting = \`Hello ${'\\`'}\${name}${'\\`'}\`;", and original_new_string was "\\\\\\nconst greeting = \`Hello \\\\\`\${name} \${lastName}\\\\\`\`;", then corrected_new_string should likely be "\nconst greeting = \`Hello ${'\\`'}\${name} \${lastName}${'\\`'}\`;" to fix the incorrect escaping.
|
| 484 |
+
If the differences are only in whitespace or formatting, apply similar whitespace/formatting changes to the corrected_new_string.
|
| 485 |
+
|
| 486 |
+
Return ONLY the corrected string in the specified JSON format with the key 'corrected_new_string'. If no adjustment is deemed necessary or possible, return the original_new_string.
|
| 487 |
+
`.trim();
|
| 488 |
+
|
| 489 |
+
const contents: Content[] = [{ role: 'user', parts: [{ text: prompt }] }];
|
| 490 |
+
|
| 491 |
+
try {
|
| 492 |
+
const result = await geminiClient.generateJson(
|
| 493 |
+
contents,
|
| 494 |
+
NEW_STRING_CORRECTION_SCHEMA,
|
| 495 |
+
abortSignal,
|
| 496 |
+
EditModel,
|
| 497 |
+
EditConfig,
|
| 498 |
+
);
|
| 499 |
+
|
| 500 |
+
if (
|
| 501 |
+
result &&
|
| 502 |
+
typeof result['corrected_new_string'] === 'string' &&
|
| 503 |
+
result['corrected_new_string'].length > 0
|
| 504 |
+
) {
|
| 505 |
+
return result['corrected_new_string'];
|
| 506 |
+
} else {
|
| 507 |
+
return originalNewString;
|
| 508 |
+
}
|
| 509 |
+
} catch (error) {
|
| 510 |
+
if (abortSignal.aborted) {
|
| 511 |
+
throw error;
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
console.error('Error during LLM call for new_string correction:', error);
|
| 515 |
+
return originalNewString;
|
| 516 |
+
}
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
const CORRECT_NEW_STRING_ESCAPING_SCHEMA: Record<string, unknown> = {
|
| 520 |
+
type: 'object',
|
| 521 |
+
properties: {
|
| 522 |
+
corrected_new_string_escaping: {
|
| 523 |
+
type: 'string',
|
| 524 |
+
description:
|
| 525 |
+
'The new_string with corrected escaping, ensuring it is a proper replacement for the old_string, especially considering potential over-escaping issues from previous LLM generations.',
|
| 526 |
+
},
|
| 527 |
+
},
|
| 528 |
+
required: ['corrected_new_string_escaping'],
|
| 529 |
+
};
|
| 530 |
+
|
| 531 |
+
export async function correctNewStringEscaping(
|
| 532 |
+
geminiClient: GeminiClient,
|
| 533 |
+
oldString: string,
|
| 534 |
+
potentiallyProblematicNewString: string,
|
| 535 |
+
abortSignal: AbortSignal,
|
| 536 |
+
): Promise<string> {
|
| 537 |
+
const prompt = `
|
| 538 |
+
Context: A text replacement operation is planned. The text to be replaced (old_string) has been correctly identified in the file. However, the replacement text (new_string) might have been improperly escaped by a previous LLM generation (e.g. too many backslashes for newlines like \\n instead of \n, or unnecessarily quotes like \\"Hello\\" instead of "Hello").
|
| 539 |
+
|
| 540 |
+
old_string (this is the exact text that will be replaced):
|
| 541 |
+
\`\`\`
|
| 542 |
+
${oldString}
|
| 543 |
+
\`\`\`
|
| 544 |
+
|
| 545 |
+
potentially_problematic_new_string (this is the text that should replace old_string, but MIGHT have bad escaping, or might be entirely correct):
|
| 546 |
+
\`\`\`
|
| 547 |
+
${potentiallyProblematicNewString}
|
| 548 |
+
\`\`\`
|
| 549 |
+
|
| 550 |
+
Task: Analyze the potentially_problematic_new_string. If it's syntactically invalid due to incorrect escaping (e.g., "\n", "\t", "\\", "\\'", "\\""), correct the invalid syntax. The goal is to ensure the new_string, when inserted into the code, will be a valid and correctly interpreted.
|
| 551 |
+
|
| 552 |
+
For example, if old_string is "foo" and potentially_problematic_new_string is "bar\\nbaz", the corrected_new_string_escaping should be "bar\nbaz".
|
| 553 |
+
If potentially_problematic_new_string is console.log(\\"Hello World\\"), it should be console.log("Hello World").
|
| 554 |
+
|
| 555 |
+
Return ONLY the corrected string in the specified JSON format with the key 'corrected_new_string_escaping'. If no escaping correction is needed, return the original potentially_problematic_new_string.
|
| 556 |
+
`.trim();
|
| 557 |
+
|
| 558 |
+
const contents: Content[] = [{ role: 'user', parts: [{ text: prompt }] }];
|
| 559 |
+
|
| 560 |
+
try {
|
| 561 |
+
const result = await geminiClient.generateJson(
|
| 562 |
+
contents,
|
| 563 |
+
CORRECT_NEW_STRING_ESCAPING_SCHEMA,
|
| 564 |
+
abortSignal,
|
| 565 |
+
EditModel,
|
| 566 |
+
EditConfig,
|
| 567 |
+
);
|
| 568 |
+
|
| 569 |
+
if (
|
| 570 |
+
result &&
|
| 571 |
+
typeof result['corrected_new_string_escaping'] === 'string' &&
|
| 572 |
+
result['corrected_new_string_escaping'].length > 0
|
| 573 |
+
) {
|
| 574 |
+
return result['corrected_new_string_escaping'];
|
| 575 |
+
} else {
|
| 576 |
+
return potentiallyProblematicNewString;
|
| 577 |
+
}
|
| 578 |
+
} catch (error) {
|
| 579 |
+
if (abortSignal.aborted) {
|
| 580 |
+
throw error;
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
console.error(
|
| 584 |
+
'Error during LLM call for new_string escaping correction:',
|
| 585 |
+
error,
|
| 586 |
+
);
|
| 587 |
+
return potentiallyProblematicNewString;
|
| 588 |
+
}
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
const CORRECT_STRING_ESCAPING_SCHEMA: Record<string, unknown> = {
|
| 592 |
+
type: 'object',
|
| 593 |
+
properties: {
|
| 594 |
+
corrected_string_escaping: {
|
| 595 |
+
type: 'string',
|
| 596 |
+
description:
|
| 597 |
+
'The string with corrected escaping, ensuring it is valid, specially considering potential over-escaping issues from previous LLM generations.',
|
| 598 |
+
},
|
| 599 |
+
},
|
| 600 |
+
required: ['corrected_string_escaping'],
|
| 601 |
+
};
|
| 602 |
+
|
| 603 |
+
export async function correctStringEscaping(
|
| 604 |
+
potentiallyProblematicString: string,
|
| 605 |
+
client: GeminiClient,
|
| 606 |
+
abortSignal: AbortSignal,
|
| 607 |
+
): Promise<string> {
|
| 608 |
+
const prompt = `
|
| 609 |
+
Context: An LLM has just generated potentially_problematic_string and the text might have been improperly escaped (e.g. too many backslashes for newlines like \\n instead of \n, or unnecessarily quotes like \\"Hello\\" instead of "Hello").
|
| 610 |
+
|
| 611 |
+
potentially_problematic_string (this text MIGHT have bad escaping, or might be entirely correct):
|
| 612 |
+
\`\`\`
|
| 613 |
+
${potentiallyProblematicString}
|
| 614 |
+
\`\`\`
|
| 615 |
+
|
| 616 |
+
Task: Analyze the potentially_problematic_string. If it's syntactically invalid due to incorrect escaping (e.g., "\n", "\t", "\\", "\\'", "\\""), correct the invalid syntax. The goal is to ensure the text will be a valid and correctly interpreted.
|
| 617 |
+
|
| 618 |
+
For example, if potentially_problematic_string is "bar\\nbaz", the corrected_new_string_escaping should be "bar\nbaz".
|
| 619 |
+
If potentially_problematic_string is console.log(\\"Hello World\\"), it should be console.log("Hello World").
|
| 620 |
+
|
| 621 |
+
Return ONLY the corrected string in the specified JSON format with the key 'corrected_string_escaping'. If no escaping correction is needed, return the original potentially_problematic_string.
|
| 622 |
+
`.trim();
|
| 623 |
+
|
| 624 |
+
const contents: Content[] = [{ role: 'user', parts: [{ text: prompt }] }];
|
| 625 |
+
|
| 626 |
+
try {
|
| 627 |
+
const result = await client.generateJson(
|
| 628 |
+
contents,
|
| 629 |
+
CORRECT_STRING_ESCAPING_SCHEMA,
|
| 630 |
+
abortSignal,
|
| 631 |
+
EditModel,
|
| 632 |
+
EditConfig,
|
| 633 |
+
);
|
| 634 |
+
|
| 635 |
+
if (
|
| 636 |
+
result &&
|
| 637 |
+
typeof result['corrected_string_escaping'] === 'string' &&
|
| 638 |
+
result['corrected_string_escaping'].length > 0
|
| 639 |
+
) {
|
| 640 |
+
return result['corrected_string_escaping'];
|
| 641 |
+
} else {
|
| 642 |
+
return potentiallyProblematicString;
|
| 643 |
+
}
|
| 644 |
+
} catch (error) {
|
| 645 |
+
if (abortSignal.aborted) {
|
| 646 |
+
throw error;
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
console.error(
|
| 650 |
+
'Error during LLM call for string escaping correction:',
|
| 651 |
+
error,
|
| 652 |
+
);
|
| 653 |
+
return potentiallyProblematicString;
|
| 654 |
+
}
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
function trimPairIfPossible(
|
| 658 |
+
target: string,
|
| 659 |
+
trimIfTargetTrims: string,
|
| 660 |
+
currentContent: string,
|
| 661 |
+
expectedReplacements: number,
|
| 662 |
+
) {
|
| 663 |
+
const trimmedTargetString = target.trim();
|
| 664 |
+
if (target.length !== trimmedTargetString.length) {
|
| 665 |
+
const trimmedTargetOccurrences = countOccurrences(
|
| 666 |
+
currentContent,
|
| 667 |
+
trimmedTargetString,
|
| 668 |
+
);
|
| 669 |
+
|
| 670 |
+
if (trimmedTargetOccurrences === expectedReplacements) {
|
| 671 |
+
const trimmedReactiveString = trimIfTargetTrims.trim();
|
| 672 |
+
return {
|
| 673 |
+
targetString: trimmedTargetString,
|
| 674 |
+
pair: trimmedReactiveString,
|
| 675 |
+
};
|
| 676 |
+
}
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
return {
|
| 680 |
+
targetString: target,
|
| 681 |
+
pair: trimIfTargetTrims,
|
| 682 |
+
};
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
/**
|
| 686 |
+
* Unescapes a string that might have been overly escaped by an LLM.
|
| 687 |
+
*/
|
| 688 |
+
export function unescapeStringForGeminiBug(inputString: string): string {
|
| 689 |
+
// Regex explanation:
|
| 690 |
+
// \\ : Matches exactly one literal backslash character.
|
| 691 |
+
// (n|t|r|'|"|`|\\|\n) : This is a capturing group. It matches one of the following:
|
| 692 |
+
// n, t, r, ', ", ` : These match the literal characters 'n', 't', 'r', single quote, double quote, or backtick.
|
| 693 |
+
// This handles cases like "\\n", "\\`", etc.
|
| 694 |
+
// \\ : This matches a literal backslash. This handles cases like "\\\\" (escaped backslash).
|
| 695 |
+
// \n : This matches an actual newline character. This handles cases where the input
|
| 696 |
+
// string might have something like "\\\n" (a literal backslash followed by a newline).
|
| 697 |
+
// g : Global flag, to replace all occurrences.
|
| 698 |
+
|
| 699 |
+
return inputString.replace(
|
| 700 |
+
/\\+(n|t|r|'|"|`|\\|\n)/g,
|
| 701 |
+
(match, capturedChar) => {
|
| 702 |
+
// 'match' is the entire erroneous sequence, e.g., if the input (in memory) was "\\\\`", match is "\\\\`".
|
| 703 |
+
// 'capturedChar' is the character that determines the true meaning, e.g., '`'.
|
| 704 |
+
|
| 705 |
+
switch (capturedChar) {
|
| 706 |
+
case 'n':
|
| 707 |
+
return '\n'; // Correctly escaped: \n (newline character)
|
| 708 |
+
case 't':
|
| 709 |
+
return '\t'; // Correctly escaped: \t (tab character)
|
| 710 |
+
case 'r':
|
| 711 |
+
return '\r'; // Correctly escaped: \r (carriage return character)
|
| 712 |
+
case "'":
|
| 713 |
+
return "'"; // Correctly escaped: ' (apostrophe character)
|
| 714 |
+
case '"':
|
| 715 |
+
return '"'; // Correctly escaped: " (quotation mark character)
|
| 716 |
+
case '`':
|
| 717 |
+
return '`'; // Correctly escaped: ` (backtick character)
|
| 718 |
+
case '\\': // This handles when 'capturedChar' is a literal backslash
|
| 719 |
+
return '\\'; // Replace escaped backslash (e.g., "\\\\") with single backslash
|
| 720 |
+
case '\n': // This handles when 'capturedChar' is an actual newline
|
| 721 |
+
return '\n'; // Replace the whole erroneous sequence (e.g., "\\\n" in memory) with a clean newline
|
| 722 |
+
default:
|
| 723 |
+
// This fallback should ideally not be reached if the regex captures correctly.
|
| 724 |
+
// It would return the original matched sequence if an unexpected character was captured.
|
| 725 |
+
return match;
|
| 726 |
+
}
|
| 727 |
+
},
|
| 728 |
+
);
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
/**
|
| 732 |
+
* Counts occurrences of a substring in a string
|
| 733 |
+
*/
|
| 734 |
+
export function countOccurrences(str: string, substr: string): number {
|
| 735 |
+
if (substr === '') {
|
| 736 |
+
return 0;
|
| 737 |
+
}
|
| 738 |
+
let count = 0;
|
| 739 |
+
let pos = str.indexOf(substr);
|
| 740 |
+
while (pos !== -1) {
|
| 741 |
+
count++;
|
| 742 |
+
pos = str.indexOf(substr, pos + substr.length); // Start search after the current match
|
| 743 |
+
}
|
| 744 |
+
return count;
|
| 745 |
+
}
|
| 746 |
+
|
| 747 |
+
export function resetEditCorrectorCaches_TEST_ONLY() {
|
| 748 |
+
editCorrectionCache.clear();
|
| 749 |
+
fileContentCorrectionCache.clear();
|
| 750 |
+
}
|