Tool improvements

This commit is contained in:
Alex Gleason committed 2026-01-21 21:04:52 -06:00
1 parent 765652ec67
commit 18bdf741d3
8 files changed
+728 -490

No files matched your search

+3
View File
@@ -19,12 +19,14 @@ interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
projectId: string; // Current project ID for path display
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall,
projectId,
}: AIMessageItemProps) => {
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
@@ -71,6 +73,7 @@ export const AIMessageItem = memo(({
toolArgs={toolArgs}
state="completed"
result={content}
projectId={projectId}
/>
);
}
+4
View File
@@ -645,6 +645,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
projectId={projectId}
/>
)}
{/* Show tool call in "calling" state if streaming tool call is in progress */}
@@ -660,6 +661,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="calling"
projectId={projectId}
/>
) : (
<>
@@ -696,6 +698,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="waiting"
projectId={projectId}
/>
);
}
@@ -827,6 +830,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
message={message}
toolCall={toolCall}
projectId={projectId}
/>
);
})}
+144
View File
@@ -0,0 +1,144 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ToolCallDisplay } from './ToolCallDisplay';
describe('ToolCallDisplay', () => {
describe('path stripping', () => {
it('should strip project prefix from absolute paths for read tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: '/projects/mysite/src/index.ts' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
it('should strip project prefix from absolute paths for write tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="write"
toolArgs={{ filePath: '/projects/mysite/src/App.tsx', content: 'code' }}
state="completed"
result="File written"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Wrote src/App.tsx')).toBeInTheDocument();
});
it('should strip project prefix from absolute paths for edit tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="edit"
toolArgs={{
filePath: '/projects/mysite/src/components/Header.tsx',
oldString: 'old',
newString: 'new'
}}
state="completed"
result="File edited"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Edited src/components/Header.tsx')).toBeInTheDocument();
});
it('should handle paths without project prefix', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: 'src/index.ts' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
it('should handle legacy text_editor_view tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_view"
toolArgs={{ path: '/projects/mysite/README.md' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed README.md')).toBeInTheDocument();
});
it('should handle legacy text_editor_write tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_write"
toolArgs={{ path: '/projects/mysite/package.json', file_text: '{}' }}
state="completed"
result="File written"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Wrote package.json')).toBeInTheDocument();
});
it('should handle legacy text_editor_str_replace tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_str_replace"
toolArgs={{
path: '/projects/mysite/src/utils.ts',
old_str: 'old',
new_str: 'new'
}}
state="completed"
result="File edited"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Edited src/utils.ts')).toBeInTheDocument();
});
it('should handle different projects with same relative path', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: '/projects/another-project/src/index.ts' }}
state="completed"
result="File content"
projectId="another-project"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
});
});
+118 -36
View File
@@ -26,12 +26,14 @@ import {
Settings,
TriangleAlert,
X,
Search,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { VFSImage } from '@/components/VFSImage';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ImageModelDialog } from '@/components/ImageModelDialog';
import { ImageLightbox } from '@/components/ImageLightbox';
import { useFSPaths } from '@/hooks/useFSPaths';
interface ToolInfo {
icon: LucideIcon;
@@ -45,6 +47,7 @@ interface ToolCallDisplayProps {
toolArgs: Record<string, unknown>;
state: 'calling' | 'waiting' | 'completed';
result?: string; // The tool result content (only for completed state)
projectId: string; // Current project ID for path display
}
// Component to show image generation errors inline
@@ -77,10 +80,25 @@ function ImageGenerationError() {
);
}
/**
* Strip project path prefix from absolute paths
* e.g., /projects/mysite/src/index.ts -> src/index.ts
*/
function stripProjectPrefix(path: string, projectId?: string, projectsPath = '/projects'): string {
if (!projectId) return path;
const projectPrefix = `${projectsPath}/${projectId}/`;
if (path.startsWith(projectPrefix)) {
return path.slice(projectPrefix.length);
}
return path;
}
/**
* Get tool information including icon, title, and calling title
*/
function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo {
function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?: string, projectsPath?: string): ToolInfo {
switch (toolName) {
case 'shell':
return {
@@ -92,56 +110,63 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
// New tools (OpenCode-compatible names)
case 'read': {
const path = args.filePath ? String(args.filePath) : 'File';
const rawPath = args.filePath ? String(args.filePath) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const offset = typeof args.offset === 'number' ? args.offset : 0;
const limit = typeof args.limit === 'number' ? args.limit : 2000;
const hasLineRange = args.offset || args.limit;
const lineInfo = hasLineRange
? ` (lines ${offset}-${offset + limit})`
const limit = typeof args.limit === 'number' ? args.limit : undefined;
const lineInfo = (typeof offset === 'number' && typeof limit === 'number')
? ` (lines ${(offset || 0) + 1}-${limit ? offset + limit : ''})`
: '';
return {
icon: Eye,
title: `Read ${path}${lineInfo}`,
callingTitle: `Reading ${path}${lineInfo}`,
errorTitle: `Failed to read ${path}${lineInfo}`,
title: `Viewed ${path}${lineInfo}`,
callingTitle: `Viewing ${path}${lineInfo}`,
errorTitle: `Failed to view ${path}${lineInfo}`,
};
}
case 'write':
case 'write': {
const rawPath = args.filePath ? String(args.filePath) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: args.filePath ? `Wrote ${args.filePath}` : 'Wrote File',
callingTitle: args.filePath ? `Writing ${args.filePath}` : 'Writing File',
errorTitle: args.filePath ? `Failed to write ${args.filePath}` : 'Failed to Write File',
title: path ? `Wrote ${path}` : 'Wrote File',
callingTitle: path ? `Writing ${path}` : 'Writing File',
errorTitle: path ? `Failed to write ${path}` : 'Failed to Write File',
};
}
case 'edit':
case 'edit': {
const rawPath = args.filePath ? String(args.filePath) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: args.filePath ? `Edited ${args.filePath}` : 'Edited File',
callingTitle: args.filePath ? `Editing ${args.filePath}` : 'Editing File',
errorTitle: args.filePath ? `Failed to edit ${args.filePath}` : 'Failed to Edit File',
title: path ? `Edited ${path}` : 'Edited File',
callingTitle: path ? `Editing ${path}` : 'Editing File',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to Edit File',
};
}
case 'glob':
return {
icon: Eye,
title: args.pattern ? `Glob: ${args.pattern}` : 'File Pattern Search',
callingTitle: args.pattern ? `Searching: ${args.pattern}` : 'Searching Files',
errorTitle: args.pattern ? `Failed to search: ${args.pattern}` : 'Search Failed',
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'File Pattern Search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching Files',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search Failed',
};
case 'grep':
return {
icon: Eye,
title: args.pattern ? `Grep: ${args.pattern}` : 'Content Search',
callingTitle: args.pattern ? `Searching: ${args.pattern}` : 'Searching Content',
errorTitle: args.pattern ? `Failed to search: ${args.pattern}` : 'Search Failed',
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'Content Search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching Content',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search Failed',
};
// Legacy tools (kept for old chat history)
case 'text_editor_view': {
const path = args.path ? String(args.path) : 'File';
const rawPath = args.path ? String(args.path) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const hasLineRange = args.start_line || args.end_line;
const lineInfo = hasLineRange
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
@@ -154,21 +179,27 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
};
}
case 'text_editor_write':
case 'text_editor_write': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: args.path ? `Wrote ${args.path}` : 'Wrote File',
callingTitle: args.path ? `Writing ${args.path}` : 'Writing File',
errorTitle: args.path ? `Failed to write ${args.path}` : 'Failed to Write File',
title: path ? `Wrote ${path}` : 'Wrote File',
callingTitle: path ? `Writing ${path}` : 'Writing File',
errorTitle: path ? `Failed to write ${path}` : 'Failed to Write File',
};
}
case 'text_editor_str_replace':
case 'text_editor_str_replace': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: args.path ? `Edited ${args.path}` : 'Edited File',
callingTitle: args.path ? `Editing ${args.path}` : 'Editing File',
errorTitle: args.path ? `Failed to edit ${args.path}` : 'Failed to Edit File',
title: path ? `Edited ${path}` : 'Edited File',
callingTitle: path ? `Editing ${path}` : 'Editing File',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to Edit File',
};
}
case 'npm_add_package': {
const name = args.name ? String(args.name) : 'Package';
@@ -349,12 +380,13 @@ function parseToolError(result: string | undefined, expectedToolName: string): s
/**
* Unified component for displaying tool calls in all states
*/
export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallDisplayProps) {
export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }: ToolCallDisplayProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const [imageLoadError, setImageLoadError] = useState(false);
const { projectsPath } = useFSPaths();
const toolInfo = getToolInfo(toolName, toolArgs);
const toolInfo = getToolInfo(toolName, toolArgs, projectId, projectsPath);
const IconComponent = toolInfo.icon;
// Check if this is an error result
@@ -444,6 +476,56 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
// Read tool expanded content - parse and display file content nicely
if (toolName === 'read' || toolName === 'text_editor_view') {
// Parse the result to extract file content from <file> tags
const fileMatch = result.match(/<file>\n([\s\S]*?)\n\n\((.*?)\)\n<\/file>/);
if (fileMatch) {
const fileContent = fileMatch[1];
const footerMessage = fileMatch[2];
// Split content into lines and parse line numbers
const lines = fileContent.split('\n');
return (
<div className="mt-1 rounded border bg-background text-xs font-mono overflow-hidden">
<div className="max-h-96 overflow-y-auto">
<div>
{lines.map((line, idx) => {
// Parse line number and content (format: " 1| content")
const match = line.match(/^(\s*\d+)\|(.*)$/);
if (match) {
return (
<div key={idx} className="flex hover:bg-muted/30 transition-colors">
<div className="text-muted-foreground/60 select-none px-3 py-0.5 text-right min-w-[3rem] bg-muted/20">
{match[1].trim()}
</div>
<div className="flex-1 px-3 py-0.5 whitespace-pre-wrap break-words">
{match[2]}
</div>
</div>
);
}
// Fallback for lines that don't match expected format
return (
<div key={idx} className="px-3 py-0.5 whitespace-pre-wrap break-words">
{line}
</div>
);
})}
</div>
</div>
{footerMessage && (
<div className="px-3 py-1.5 bg-muted/30 border-t text-muted-foreground text-[10px]">
{footerMessage}
</div>
)}
</div>
);
}
// Fallback to default rendering if no <file> tags found
}
if (toolName === 'generate_image') {
// For generate_image, when expanded show the full prompt
return (
+455 -450
View File
@@ -17,9 +17,13 @@ interface EditParams {
replaceAll?: boolean;
}
// Similarity thresholds for block anchor fallback matching
const SINGLE_CANDIDATE_SIMILARITY_THRESHOLD = 0.0;
const MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD = 0.3;
interface EditToolOptions {
projectsPath?: string;
tmpPath?: string;
onFileChanged?: (filePath: string) => void;
singleCandidateSimilarityThreshold?: number;
multipleCandidatesSimilarityThreshold?: number;
}
export class EditTool implements Tool<EditParams> {
private fs: JSRuntimeFS;
@@ -27,12 +31,14 @@ export class EditTool implements Tool<EditParams> {
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
private singleCandidateSimilarityThreshold: number;
private multipleCandidatesSimilarityThreshold: number;
readonly description = `Performs exact string replacements in files.
Usage:
- You must use your \`Read\` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.
- You must use your \`read\` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
- When editing text from read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- The edit will FAIL if \`oldString\` is not found in the file with an error "oldString not found in content".
@@ -46,12 +52,14 @@ Usage:
replaceAll: z.boolean().optional().describe("Replace all occurrences of oldString (default false)"),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) {
constructor(fs: JSRuntimeFS, cwd: string, options?: EditToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
this.onFileChanged = options?.onFileChanged;
this.singleCandidateSimilarityThreshold = options?.singleCandidateSimilarityThreshold ?? 0.0;
this.multipleCandidatesSimilarityThreshold = options?.multipleCandidatesSimilarityThreshold ?? 0.3;
}
async execute(args: EditParams): Promise<ToolResult> {
@@ -121,7 +129,7 @@ Usage:
const contentOld = await this.fs.readFile(filepath, "utf8");
// Perform replacement using fuzzy matching strategies
const contentNew = replace(contentOld, args.oldString, args.newString, args.replaceAll);
const contentNew = this.replace(contentOld, args.oldString, args.newString, args.replaceAll);
// Write updated content
await this.fs.writeFile(filepath, contentNew, "utf8");
@@ -137,10 +145,447 @@ Usage:
throw new Error(String(error));
}
}
}
// Type for replacer functions
type Replacer = (content: string, find: string) => Generator<string, void, unknown>;
/**
* Main replace function that tries multiple fuzzy matching strategies
*/
private replace(content: string, oldString: string, newString: string, replaceAll = false): string {
if (oldString === newString) {
throw new Error("oldString and newString must be different");
}
let notFound = true;
for (const replacer of [
this.SimpleReplacer,
this.LineTrimmedReplacer,
this.BlockAnchorReplacer,
this.WhitespaceNormalizedReplacer,
this.IndentationFlexibleReplacer,
this.EscapeNormalizedReplacer,
this.TrimmedBoundaryReplacer,
this.ContextAwareReplacer,
this.MultiOccurrenceReplacer,
]) {
for (const search of replacer.call(this, content, oldString)) {
const index = content.indexOf(search);
if (index === -1) continue;
notFound = false;
if (replaceAll) {
return content.replaceAll(search, newString);
}
const lastIndex = content.lastIndexOf(search);
if (index !== lastIndex) continue;
return content.substring(0, index) + newString + content.substring(index + search.length);
}
}
if (notFound) {
throw new Error("oldString not found in content");
}
throw new Error(
"oldString found multiple times and requires more code context to uniquely identify the intended match",
);
}
private *SimpleReplacer(_content: string, find: string): Generator<string, void, unknown> {
yield find;
}
private *LineTrimmedReplacer(content: string, find: string): Generator<string, void, unknown> {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
for (let i = 0; i <= originalLines.length - searchLines.length; i++) {
let matches = true;
for (let j = 0; j < searchLines.length; j++) {
const originalTrimmed = originalLines[i + j].trim();
const searchTrimmed = searchLines[j].trim();
if (originalTrimmed !== searchTrimmed) {
matches = false;
break;
}
}
if (matches) {
let matchStartIndex = 0;
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length;
if (k < searchLines.length - 1) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
}
private *BlockAnchorReplacer(content: string, find: string): Generator<string, void, unknown> {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines.length < 3) {
return;
}
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
const firstLineSearch = searchLines[0].trim();
const lastLineSearch = searchLines[searchLines.length - 1].trim();
const searchBlockSize = searchLines.length;
// Collect all candidate positions where both anchors match
const candidates: Array<{ startLine: number; endLine: number }> = [];
for (let i = 0; i < originalLines.length; i++) {
if (originalLines[i].trim() !== firstLineSearch) {
continue;
}
// Look for the matching last line after this first line
for (let j = i + 2; j < originalLines.length; j++) {
if (originalLines[j].trim() === lastLineSearch) {
candidates.push({ startLine: i, endLine: j });
break; // Only match the first occurrence of the last line
}
}
}
// Return immediately if no candidates
if (candidates.length === 0) {
return;
}
// Handle single candidate scenario (using relaxed threshold)
if (candidates.length === 1) {
const { startLine, endLine } = candidates[0];
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += (1 - distance / maxLen) / linesToCheck;
// Exit early when threshold is reached
if (similarity >= this.singleCandidateSimilarityThreshold) {
break;
}
}
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity >= this.singleCandidateSimilarityThreshold) {
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
return;
}
// Calculate similarity for multiple candidates
let bestMatch: { startLine: number; endLine: number } | null = null;
let maxSimilarity = -1;
for (const candidate of candidates) {
const { startLine, endLine } = candidate;
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += 1 - distance / maxLen;
}
similarity /= linesToCheck; // Average similarity
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestMatch = candidate;
}
}
// Threshold judgment
if (maxSimilarity >= this.multipleCandidatesSimilarityThreshold && bestMatch) {
const { startLine, endLine } = bestMatch;
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1;
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
private *WhitespaceNormalizedReplacer(content: string, find: string): Generator<string, void, unknown> {
const normalizeWhitespace = (text: string) => text.replace(/\s+/g, " ").trim();
const normalizedFind = normalizeWhitespace(find);
// Handle single line matches
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (normalizeWhitespace(line) === normalizedFind) {
yield line;
} else {
// Only check for substring matches if the full line doesn't match
const normalizedLine = normalizeWhitespace(line);
if (normalizedLine.includes(normalizedFind)) {
// Find the actual substring in the original line that matches
const words = find.trim().split(/\s+/);
if (words.length > 0) {
const pattern = words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+");
try {
const regex = new RegExp(pattern);
const match = line.match(regex);
if (match) {
yield match[0];
}
} catch {
// Invalid regex pattern, skip
}
}
}
}
}
// Handle multi-line matches
const findLines = find.split("\n");
if (findLines.length > 1) {
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length);
if (normalizeWhitespace(block.join("\n")) === normalizedFind) {
yield block.join("\n");
}
}
}
}
private *IndentationFlexibleReplacer(content: string, find: string): Generator<string, void, unknown> {
const removeIndentation = (text: string) => {
const lines = text.split("\n");
const nonEmptyLines = lines.filter((line) => line.trim().length > 0);
if (nonEmptyLines.length === 0) return text;
const minIndent = Math.min(
...nonEmptyLines.map((line) => {
const match = line.match(/^(\s*)/);
return match ? match[1].length : 0;
}),
);
return lines.map((line) => (line.trim().length === 0 ? line : line.slice(minIndent))).join("\n");
};
const normalizedFind = removeIndentation(find);
const contentLines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= contentLines.length - findLines.length; i++) {
const block = contentLines.slice(i, i + findLines.length).join("\n");
if (removeIndentation(block) === normalizedFind) {
yield block;
}
}
}
private *EscapeNormalizedReplacer(content: string, find: string): Generator<string, void, unknown> {
const unescapeString = (str: string): string => {
return str.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g, (match, capturedChar) => {
switch (capturedChar) {
case "n":
return "\n";
case "t":
return "\t";
case "r":
return "\r";
case "'":
return "'";
case '"':
return '"';
case "`":
return "`";
case "\\":
return "\\";
case "\n":
return "\n";
case "$":
return "$";
default:
return match;
}
});
};
const unescapedFind = unescapeString(find);
// Try direct match with unescaped find string
if (content.includes(unescapedFind)) {
yield unescapedFind;
}
// Also try finding escaped versions in content that match unescaped find
const lines = content.split("\n");
const findLines = unescapedFind.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
const unescapedBlock = unescapeString(block);
if (unescapedBlock === unescapedFind) {
yield block;
}
}
}
private *MultiOccurrenceReplacer(content: string, find: string): Generator<string, void, unknown> {
// This replacer yields all exact matches, allowing the replace function
// to handle multiple occurrences based on replaceAll parameter
let startIndex = 0;
while (true) {
const index = content.indexOf(find, startIndex);
if (index === -1) break;
yield find;
startIndex = index + find.length;
}
}
private *TrimmedBoundaryReplacer(content: string, find: string): Generator<string, void, unknown> {
const trimmedFind = find.trim();
if (trimmedFind === find) {
// Already trimmed, no point in trying
return;
}
// Try to find the trimmed version
if (content.includes(trimmedFind)) {
yield trimmedFind;
}
// Also try finding blocks where trimmed content matches
const lines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
if (block.trim() === trimmedFind) {
yield block;
}
}
}
private *ContextAwareReplacer(content: string, find: string): Generator<string, void, unknown> {
const findLines = find.split("\n");
if (findLines.length < 3) {
// Need at least 3 lines to have meaningful context
return;
}
// Remove trailing empty line if present
if (findLines[findLines.length - 1] === "") {
findLines.pop();
}
const contentLines = content.split("\n");
// Extract first and last lines as context anchors
const firstLine = findLines[0].trim();
const lastLine = findLines[findLines.length - 1].trim();
// Find blocks that start and end with the context anchors
for (let i = 0; i < contentLines.length; i++) {
if (contentLines[i].trim() !== firstLine) continue;
// Look for the matching last line
for (let j = i + 2; j < contentLines.length; j++) {
if (contentLines[j].trim() === lastLine) {
// Found a potential context block
const blockLines = contentLines.slice(i, j + 1);
const block = blockLines.join("\n");
// Check if the middle content has reasonable similarity
// (simple heuristic: at least 50% of non-empty lines should match when trimmed)
if (blockLines.length === findLines.length) {
let matchingLines = 0;
let totalNonEmptyLines = 0;
for (let k = 1; k < blockLines.length - 1; k++) {
const blockLine = blockLines[k].trim();
const findLine = findLines[k].trim();
if (blockLine.length > 0 || findLine.length > 0) {
totalNonEmptyLines++;
if (blockLine === findLine) {
matchingLines++;
}
}
}
if (totalNonEmptyLines === 0 || matchingLines / totalNonEmptyLines >= 0.5) {
yield block;
break; // Only match the first occurrence
}
}
break;
}
}
}
}
}
/**
* Levenshtein distance algorithm implementation
@@ -162,443 +607,3 @@ function levenshtein(a: string, b: string): number {
}
return matrix[a.length][b.length];
}
const SimpleReplacer: Replacer = function* (_content, find) {
yield find;
};
const LineTrimmedReplacer: Replacer = function* (content, find) {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
for (let i = 0; i <= originalLines.length - searchLines.length; i++) {
let matches = true;
for (let j = 0; j < searchLines.length; j++) {
const originalTrimmed = originalLines[i + j].trim();
const searchTrimmed = searchLines[j].trim();
if (originalTrimmed !== searchTrimmed) {
matches = false;
break;
}
}
if (matches) {
let matchStartIndex = 0;
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length;
if (k < searchLines.length - 1) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
};
const BlockAnchorReplacer: Replacer = function* (content, find) {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines.length < 3) {
return;
}
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
const firstLineSearch = searchLines[0].trim();
const lastLineSearch = searchLines[searchLines.length - 1].trim();
const searchBlockSize = searchLines.length;
// Collect all candidate positions where both anchors match
const candidates: Array<{ startLine: number; endLine: number }> = [];
for (let i = 0; i < originalLines.length; i++) {
if (originalLines[i].trim() !== firstLineSearch) {
continue;
}
// Look for the matching last line after this first line
for (let j = i + 2; j < originalLines.length; j++) {
if (originalLines[j].trim() === lastLineSearch) {
candidates.push({ startLine: i, endLine: j });
break; // Only match the first occurrence of the last line
}
}
}
// Return immediately if no candidates
if (candidates.length === 0) {
return;
}
// Handle single candidate scenario (using relaxed threshold)
if (candidates.length === 1) {
const { startLine, endLine } = candidates[0];
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += (1 - distance / maxLen) / linesToCheck;
// Exit early when threshold is reached
if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) {
break;
}
}
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) {
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
return;
}
// Calculate similarity for multiple candidates
let bestMatch: { startLine: number; endLine: number } | null = null;
let maxSimilarity = -1;
for (const candidate of candidates) {
const { startLine, endLine } = candidate;
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += 1 - distance / maxLen;
}
similarity /= linesToCheck; // Average similarity
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestMatch = candidate;
}
}
// Threshold judgment
if (maxSimilarity >= MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD && bestMatch) {
const { startLine, endLine } = bestMatch;
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1;
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
};
const WhitespaceNormalizedReplacer: Replacer = function* (content, find) {
const normalizeWhitespace = (text: string) => text.replace(/\s+/g, " ").trim();
const normalizedFind = normalizeWhitespace(find);
// Handle single line matches
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (normalizeWhitespace(line) === normalizedFind) {
yield line;
} else {
// Only check for substring matches if the full line doesn't match
const normalizedLine = normalizeWhitespace(line);
if (normalizedLine.includes(normalizedFind)) {
// Find the actual substring in the original line that matches
const words = find.trim().split(/\s+/);
if (words.length > 0) {
const pattern = words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+");
try {
const regex = new RegExp(pattern);
const match = line.match(regex);
if (match) {
yield match[0];
}
} catch {
// Invalid regex pattern, skip
}
}
}
}
}
// Handle multi-line matches
const findLines = find.split("\n");
if (findLines.length > 1) {
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length);
if (normalizeWhitespace(block.join("\n")) === normalizedFind) {
yield block.join("\n");
}
}
}
};
const IndentationFlexibleReplacer: Replacer = function* (content, find) {
const removeIndentation = (text: string) => {
const lines = text.split("\n");
const nonEmptyLines = lines.filter((line) => line.trim().length > 0);
if (nonEmptyLines.length === 0) return text;
const minIndent = Math.min(
...nonEmptyLines.map((line) => {
const match = line.match(/^(\s*)/);
return match ? match[1].length : 0;
}),
);
return lines.map((line) => (line.trim().length === 0 ? line : line.slice(minIndent))).join("\n");
};
const normalizedFind = removeIndentation(find);
const contentLines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= contentLines.length - findLines.length; i++) {
const block = contentLines.slice(i, i + findLines.length).join("\n");
if (removeIndentation(block) === normalizedFind) {
yield block;
}
}
};
const EscapeNormalizedReplacer: Replacer = function* (content, find) {
const unescapeString = (str: string): string => {
return str.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g, (match, capturedChar) => {
switch (capturedChar) {
case "n":
return "\n";
case "t":
return "\t";
case "r":
return "\r";
case "'":
return "'";
case '"':
return '"';
case "`":
return "`";
case "\\":
return "\\";
case "\n":
return "\n";
case "$":
return "$";
default:
return match;
}
});
};
const unescapedFind = unescapeString(find);
// Try direct match with unescaped find string
if (content.includes(unescapedFind)) {
yield unescapedFind;
}
// Also try finding escaped versions in content that match unescaped find
const lines = content.split("\n");
const findLines = unescapedFind.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
const unescapedBlock = unescapeString(block);
if (unescapedBlock === unescapedFind) {
yield block;
}
}
};
const MultiOccurrenceReplacer: Replacer = function* (content, find) {
// This replacer yields all exact matches, allowing the replace function
// to handle multiple occurrences based on replaceAll parameter
let startIndex = 0;
while (true) {
const index = content.indexOf(find, startIndex);
if (index === -1) break;
yield find;
startIndex = index + find.length;
}
};
const TrimmedBoundaryReplacer: Replacer = function* (content, find) {
const trimmedFind = find.trim();
if (trimmedFind === find) {
// Already trimmed, no point in trying
return;
}
// Try to find the trimmed version
if (content.includes(trimmedFind)) {
yield trimmedFind;
}
// Also try finding blocks where trimmed content matches
const lines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
if (block.trim() === trimmedFind) {
yield block;
}
}
};
const ContextAwareReplacer: Replacer = function* (content, find) {
const findLines = find.split("\n");
if (findLines.length < 3) {
// Need at least 3 lines to have meaningful context
return;
}
// Remove trailing empty line if present
if (findLines[findLines.length - 1] === "") {
findLines.pop();
}
const contentLines = content.split("\n");
// Extract first and last lines as context anchors
const firstLine = findLines[0].trim();
const lastLine = findLines[findLines.length - 1].trim();
// Find blocks that start and end with the context anchors
for (let i = 0; i < contentLines.length; i++) {
if (contentLines[i].trim() !== firstLine) continue;
// Look for the matching last line
for (let j = i + 2; j < contentLines.length; j++) {
if (contentLines[j].trim() === lastLine) {
// Found a potential context block
const blockLines = contentLines.slice(i, j + 1);
const block = blockLines.join("\n");
// Check if the middle content has reasonable similarity
// (simple heuristic: at least 50% of non-empty lines should match when trimmed)
if (blockLines.length === findLines.length) {
let matchingLines = 0;
let totalNonEmptyLines = 0;
for (let k = 1; k < blockLines.length - 1; k++) {
const blockLine = blockLines[k].trim();
const findLine = findLines[k].trim();
if (blockLine.length > 0 || findLine.length > 0) {
totalNonEmptyLines++;
if (blockLine === findLine) {
matchingLines++;
}
}
}
if (totalNonEmptyLines === 0 || matchingLines / totalNonEmptyLines >= 0.5) {
yield block;
break; // Only match the first occurrence
}
}
break;
}
}
}
};
/**
* Main replace function that tries multiple fuzzy matching strategies
*/
function replace(content: string, oldString: string, newString: string, replaceAll = false): string {
if (oldString === newString) {
throw new Error("oldString and newString must be different");
}
let notFound = true;
for (const replacer of [
SimpleReplacer,
LineTrimmedReplacer,
BlockAnchorReplacer,
WhitespaceNormalizedReplacer,
IndentationFlexibleReplacer,
EscapeNormalizedReplacer,
TrimmedBoundaryReplacer,
ContextAwareReplacer,
MultiOccurrenceReplacer,
]) {
for (const search of replacer(content, oldString)) {
const index = content.indexOf(search);
if (index === -1) continue;
notFound = false;
if (replaceAll) {
return content.replaceAll(search, newString);
}
const lastIndex = content.lastIndexOf(search);
if (index !== lastIndex) continue;
return content.substring(0, index) + newString + content.substring(index + search.length);
}
}
if (notFound) {
throw new Error("oldString not found in content");
}
throw new Error(
"oldString found multiple times and requires more code context to uniquely identify the intended match",
);
}
+1 -1
View File
@@ -22,7 +22,7 @@ export class GlobTool implements Tool<GlobParams> {
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
- Returns matching file paths sorted by modification time
- Use this tool when you need to find files by name patterns
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the task tool instead
- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.`;
readonly inputSchema = z.object({
+2 -2
View File
@@ -27,8 +27,8 @@ export class GrepTool implements Tool<GrepParams> {
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
- Returns file paths and line numbers with at least one match sorted by modification time
- Use this tool when you need to find files containing specific patterns
- If you need to identify/count the number of matches within files, use the Bash tool with \`rg\` (ripgrep) directly. Do NOT use \`grep\`.
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead`;
- If you need to identify/count the number of matches within files, use the shell tool with \`rg\` (ripgrep) directly. Do NOT use \`grep\`.
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the task tool instead`;
readonly inputSchema = z.object({
pattern: z.string().describe("The regex pattern to search for in file contents"),
+1 -1
View File
@@ -21,7 +21,7 @@ export class WriteTool implements Tool<WriteParams> {
Usage:
- This tool will overwrite the existing file if there is one at the provided path.
- If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.
- If this is an existing file, you MUST use the read tool first to read the file's contents. This tool will fail if you did not read the file first.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`;