diff --git a/package-lock.json b/package-lock.json index 035fc334..b548c126 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10685,9 +10685,9 @@ } }, "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", "license": "MIT" }, "node_modules/lodash.castarray": { diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index a6754705..4d2fd0c1 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -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(null); @@ -71,6 +73,7 @@ export const AIMessageItem = memo(({ toolArgs={toolArgs} state="completed" result={content} + projectId={projectId} /> ); } diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 4c31689b..e3ecfff3 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -18,9 +18,11 @@ import { useMCPTools } from '@/hooks/useMCPTools'; import { useQueryClient } from '@tanstack/react-query'; import { AIMessageItem } from '@/components/AIMessageItem'; import { ToolCallDisplay } from '@/components/ToolCallDisplay'; -import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool'; -import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool'; -import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool'; +import { ReadTool } from '@/lib/tools/ReadTool'; +import { WriteTool } from '@/lib/tools/WriteTool'; +import { EditTool } from '@/lib/tools/EditTool'; +import { GlobTool } from '@/lib/tools/GlobTool'; +import { GrepTool } from '@/lib/tools/GrepTool'; import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool'; import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool'; import { GitCommitTool } from '@/lib/tools/GitCommitTool'; @@ -174,10 +176,15 @@ export const ChatPane = forwardRef(({ // Separate built-in tools from MCP tools for clarity const builtInTools = useMemo(() => { const tools: Record> = { + // File operation tools (OpenCode-compatible API) + read: new ReadTool(fs, cwd, { projectsPath }), + write: new WriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), + edit: new EditTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), + glob: new GlobTool(fs, cwd), + grep: new GrepTool(fs, cwd), + + // Other tools git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }), - text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }), - text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), - text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), npm_add_package: new NpmAddPackageTool(fs, cwd), npm_remove_package: new NpmRemovePackageTool(fs, cwd), build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current), @@ -638,6 +645,7 @@ export const ChatPane = forwardRef(({ key="streaming-message" message={streamingMessage} isCurrentlyLoading={isLoading} + projectId={projectId} /> )} {/* Show tool call in "calling" state if streaming tool call is in progress */} @@ -653,6 +661,7 @@ export const ChatPane = forwardRef(({ } })()} state="calling" + projectId={projectId} /> ) : ( <> @@ -689,6 +698,7 @@ export const ChatPane = forwardRef(({ } })()} state="waiting" + projectId={projectId} /> ); } @@ -820,6 +830,7 @@ export const ChatPane = forwardRef(({ key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`} message={message} toolCall={toolCall} + projectId={projectId} /> ); })} diff --git a/src/components/ToolCallDisplay.test.tsx b/src/components/ToolCallDisplay.test.tsx new file mode 100644 index 00000000..0d142b2e --- /dev/null +++ b/src/components/ToolCallDisplay.test.tsx @@ -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( + + + + ); + + expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument(); + }); + + it('should strip project prefix from absolute paths for write tool', () => { + render( + + + + ); + + expect(screen.getByText('Wrote src/App.tsx')).toBeInTheDocument(); + }); + + it('should strip project prefix from absolute paths for edit tool', () => { + render( + + + + ); + + expect(screen.getByText('Edited src/components/Header.tsx')).toBeInTheDocument(); + }); + + it('should handle paths without project prefix', () => { + render( + + + + ); + + expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument(); + }); + + it('should handle legacy text_editor_view tool', () => { + render( + + + + ); + + expect(screen.getByText('Viewed README.md')).toBeInTheDocument(); + }); + + it('should handle legacy text_editor_write tool', () => { + render( + + + + ); + + expect(screen.getByText('Wrote package.json')).toBeInTheDocument(); + }); + + it('should handle legacy text_editor_str_replace tool', () => { + render( + + + + ); + + expect(screen.getByText('Edited src/utils.ts')).toBeInTheDocument(); + }); + + it('should handle different projects with same relative path', () => { + render( + + + + ); + + expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument(); + }); + }); +}); diff --git a/src/components/ToolCallDisplay.tsx b/src/components/ToolCallDisplay.tsx index 95a39c76..7bfa8e72 100644 --- a/src/components/ToolCallDisplay.tsx +++ b/src/components/ToolCallDisplay.tsx @@ -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; 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): ToolInfo { +function getToolInfo(toolName: string, args: Record, projectId?: string, projectsPath?: string): ToolInfo { switch (toolName) { case 'shell': return { @@ -90,8 +108,65 @@ function getToolInfo(toolName: string, args: Record): ToolInfo errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell Command Failed', }; + // New tools (OpenCode-compatible names) + case 'read': { + 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 : undefined; + const lineInfo = (typeof offset === 'number' && typeof limit === 'number') + ? ` (lines ${(offset || 0) + 1}-${limit ? offset + limit : ''})` + : ''; + return { + icon: Eye, + title: `Viewed ${path}${lineInfo}`, + callingTitle: `Viewing ${path}${lineInfo}`, + errorTitle: `Failed to view ${path}${lineInfo}`, + }; + } + + case 'write': { + const rawPath = args.filePath ? String(args.filePath) : ''; + const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : ''; + return { + icon: FileText, + title: path ? `Wrote ${path}` : 'Wrote File', + callingTitle: path ? `Writing ${path}` : 'Writing File', + errorTitle: path ? `Failed to write ${path}` : 'Failed to Write File', + }; + } + + case 'edit': { + const rawPath = args.filePath ? String(args.filePath) : ''; + const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : ''; + return { + icon: Edit, + 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: 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: 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'})` @@ -104,21 +179,27 @@ function getToolInfo(toolName: string, args: Record): 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'; @@ -299,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(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 @@ -342,19 +424,26 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD ); } - if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') { + // Write tool expanded content (new and legacy) + if ((toolName === 'write' && typeof toolArgs.content === 'string') || + (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string')) { + const content = toolName === 'write' ? String(toolArgs.content) : String(toolArgs.file_text); return (
- {toolArgs.file_text} + {content}
); } - if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') { - const oldLines = String(toolArgs.old_str).split('\n'); - const newLines = String(toolArgs.new_str).split('\n'); + // Edit tool expanded content (new and legacy) + if ((toolName === 'edit' && typeof toolArgs.oldString === 'string' && typeof toolArgs.newString === 'string') || + (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string')) { + const oldStr = toolName === 'edit' ? String(toolArgs.oldString) : String(toolArgs.old_str); + const newStr = toolName === 'edit' ? String(toolArgs.newString) : String(toolArgs.new_str); + const oldLines = oldStr.split('\n'); + const newLines = newStr.split('\n'); return (
@@ -387,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 tags + const fileMatch = result.match(/\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 ( +
+
+
+ {lines.map((line, idx) => { + // Parse line number and content (format: " 1| content") + const match = line.match(/^(\s*\d+)\|(.*)$/); + if (match) { + return ( +
+
+ {match[1].trim()} +
+
+ {match[2]} +
+
+ ); + } + // Fallback for lines that don't match expected format + return ( +
+ {line} +
+ ); + })} +
+
+ {footerMessage && ( +
+ {footerMessage} +
+ )} +
+ ); + } + // Fallback to default rendering if no tags found + } + if (toolName === 'generate_image') { // For generate_image, when expanded show the full prompt return ( diff --git a/src/lib/git.ts b/src/lib/git.ts index 36de93a7..f3cedc2c 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -1107,7 +1107,7 @@ class GitHttp implements HttpClient { constructor(proxy?: string, fetch?: typeof globalThis.fetch) { this.proxy = proxy; - this.fetch = fetch ?? globalThis.fetch; + this.fetch = fetch ?? globalThis.fetch.bind(globalThis); } async request(request: GitHttpRequest): Promise { diff --git a/src/lib/tools/EditTool.ts b/src/lib/tools/EditTool.ts new file mode 100644 index 00000000..38c4a711 --- /dev/null +++ b/src/lib/tools/EditTool.ts @@ -0,0 +1,609 @@ +// The approaches in this edit tool are sourced from OpenCode which credits: +// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/diff-06-23-25.ts +// https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/utils/editCorrector.ts +// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/diff-06-26-25.ts + +import { join } from "path-browserify"; +import { z } from "zod"; + +import type { Tool, ToolResult } from "./Tool"; +import type { JSRuntimeFS } from "../JSRuntime"; +import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security"; + +interface EditParams { + filePath: string; + oldString: string; + newString: string; + replaceAll?: boolean; +} + +interface EditToolOptions { + projectsPath?: string; + tmpPath?: string; + onFileChanged?: (filePath: string) => void; + singleCandidateSimilarityThreshold?: number; + multipleCandidatesSimilarityThreshold?: number; +} + +export class EditTool implements Tool { + private fs: JSRuntimeFS; + private cwd: string; + 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. +- 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". +- The edit will FAIL if \`oldString\` is found multiple times in the file with an error "oldString found multiple times and requires more code context to uniquely identify the intended match". Either provide a larger string with more surrounding context to make it unique or use \`replaceAll\` to change every instance of \`oldString\`. +- Use \`replaceAll\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`; + + readonly inputSchema = z.object({ + filePath: z.string().describe("The absolute path to the file to modify"), + oldString: z.string().describe("The text to replace"), + newString: z.string().describe("The text to replace it with (must be different from oldString)"), + replaceAll: z.boolean().optional().describe("Replace all occurrences of oldString (default false)"), + }); + + 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 { + if (!args.filePath) { + throw new Error("filePath is required"); + } + + if (args.oldString === args.newString) { + throw new Error("oldString and newString must be different"); + } + + let filepath = args.filePath; + + // Convert to absolute path if needed + if (!isAbsolutePath(filepath)) { + filepath = join(this.cwd, filepath); + } + + // Check write permissions + if (!isWriteAllowed(filepath, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) { + throw new Error(createWriteAccessDeniedError(filepath, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })); + } + + // Ban editing dependencies in package.json + if ( + filepath === "package.json" || + filepath.endsWith("/package.json") || + filepath.endsWith("\\package.json") + ) { + const depKeys = [ + '"dependencies"', + '"devDependencies"', + '"peerDependencies"', + '"optionalDependencies"', + ]; + if ( + depKeys.some((key) => + args.oldString.includes(key) || args.newString.includes(key) + ) + ) { + throw new Error(`šŸ”’ Direct edits to dependencies in package.json are disallowed.\nšŸ‘‰ Please use npm_add_package or npm_remove_package tools for these changes.`); + } + } + + try { + // Handle empty oldString as a special case (write new file) + if (args.oldString === "") { + await this.fs.writeFile(filepath, args.newString, "utf8"); + + if (this.onFileChanged) { + this.onFileChanged(filepath); + } + + return { content: `File successfully created at ${filepath}` }; + } + + // Check if file exists + const stats = await this.fs.stat(filepath).catch(() => null); + if (!stats) { + throw new Error(`File ${filepath} not found`); + } + if (stats.isDirectory()) { + throw new Error(`Path is a directory, not a file: ${filepath}`); + } + + // Read file content + const contentOld = await this.fs.readFile(filepath, "utf8"); + + // Perform replacement using fuzzy matching strategies + const contentNew = this.replace(contentOld, args.oldString, args.newString, args.replaceAll); + + // Write updated content + await this.fs.writeFile(filepath, contentNew, "utf8"); + + // Notify about file change (for auto-build) + if (this.onFileChanged) { + this.onFileChanged(filepath); + } + + return { content: `Edit applied successfully.` }; + + } catch (error) { + throw new Error(String(error)); + } + } + + /** + * 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 { + yield find; + } + + private *LineTrimmedReplacer(content: string, find: string): Generator { + 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 { + 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 { + 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 { + 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 { + 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 { + // 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 { + 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 { + 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 + */ +function levenshtein(a: string, b: string): number { + // Handle empty strings + if (a === "" || b === "") { + return Math.max(a.length, b.length); + } + const matrix = Array.from({ length: a.length + 1 }, (_, i) => + Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)), + ); + + for (let i = 1; i <= a.length; i++) { + for (let j = 1; j <= b.length; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost); + } + } + return matrix[a.length][b.length]; +} diff --git a/src/lib/tools/GlobTool.ts b/src/lib/tools/GlobTool.ts new file mode 100644 index 00000000..667b47f8 --- /dev/null +++ b/src/lib/tools/GlobTool.ts @@ -0,0 +1,218 @@ +import { join } from "path-browserify"; +import { z } from "zod"; + +import type { Tool, ToolResult } from "./Tool"; +import type { JSRuntimeFS } from "../JSRuntime"; + +interface GlobParams { + pattern: string; + path?: string; +} + +interface GlobToolOptions { + resultLimit?: number; +} + +export class GlobTool implements Tool { + private fs: JSRuntimeFS; + private cwd: string; + private resultLimit: number; + + readonly description = `- Fast file pattern matching tool that works with any codebase size +- 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 +- 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({ + pattern: z.string().describe("The glob pattern to match files against"), + path: z + .string() + .optional() + .describe( + `The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.`, + ), + }); + + constructor(fs: JSRuntimeFS, cwd: string, options?: GlobToolOptions) { + this.fs = fs; + this.cwd = cwd; + this.resultLimit = options?.resultLimit || 100; + } + + async execute(args: GlobParams): Promise { + try { + // Determine the search path and pattern + // If args.path is provided, use it as the base directory + // Otherwise, extract any leading directory path from the pattern itself + let searchPath: string; + let pattern: string; + + if (args.path) { + // User explicitly specified a path parameter + searchPath = join(this.cwd, args.path); + pattern = args.pattern; + } else { + // Parse the pattern to extract base directory + const parsed = this.parsePatternPath(args.pattern); + searchPath = parsed.basePath ? join(this.cwd, parsed.basePath) : this.cwd; + pattern = parsed.globPattern; + } + + // Check if search path exists + const stats = await this.fs.stat(searchPath); + if (!stats.isDirectory()) { + throw new Error(`Not a directory: ${searchPath}`); + } + + // Perform the search + const files = await this.searchFiles(searchPath, pattern); + + // Sort by modification time (most recent first) + files.sort((a, b) => b.mtime - a.mtime); + + // Truncate results if needed + const truncated = files.length > this.resultLimit; + const finalFiles = truncated ? files.slice(0, this.resultLimit) : files; + + // Format output + const output: string[] = []; + if (finalFiles.length === 0) { + output.push("No files found"); + } else { + output.push(...finalFiles.map((f) => f.path)); + if (truncated) { + output.push(""); + output.push("(Results are truncated. Consider using a more specific path or pattern.)"); + } + } + + return { content: output.join("\n") }; + + } catch (error) { + throw new Error(String(error)); + } + } + + private parsePatternPath(pattern: string): { basePath: string; globPattern: string } { + const segments = pattern.split('/'); + + // Find the first segment that contains glob characters + const firstGlobIndex = segments.findIndex(seg => + seg.includes('*') || seg.includes('?') || seg.includes('[') + ); + + if (firstGlobIndex === -1) { + // No glob characters found - treat entire pattern as base path + return { basePath: pattern, globPattern: '**/*' }; + } + + if (firstGlobIndex === 0) { + // Pattern starts with glob - no base path + return { basePath: '', globPattern: pattern }; + } + + // Split into base path and glob pattern + const basePath = segments.slice(0, firstGlobIndex).join('/'); + const globPattern = segments.slice(firstGlobIndex).join('/'); + + return { basePath, globPattern }; + } + + private async searchFiles( + dirPath: string, + pattern: string + ): Promise> { + const results: Array<{ path: string; mtime: number }> = []; + + // Parse the glob pattern into segments + const segments = pattern.split('/'); + + await this.searchRecursive(dirPath, dirPath, segments, 0, results); + + return results; + } + + private async searchRecursive( + basePath: string, + currentPath: string, + segments: string[], + segmentIndex: number, + results: Array<{ path: string; mtime: number }> + ): Promise { + // If we've matched all segments, we're done + if (segmentIndex >= segments.length) { + return; + } + + const segment = segments[segmentIndex]; + + try { + const entries = await this.fs.readdir(currentPath, { withFileTypes: true }); + + for (const entry of entries) { + const entryPath = join(currentPath, entry.name); + + // Handle ** (recursive wildcard) + if (segment === '**') { + // ** can match zero or more directories + if (entry.isDirectory()) { + // Continue matching with ** at current level + await this.searchRecursive(basePath, entryPath, segments, segmentIndex, results); + } + + // Try matching the next segment + if (segmentIndex + 1 < segments.length) { + if (this.matchesPattern(entry.name, segments[segmentIndex + 1])) { + if (segmentIndex + 2 === segments.length) { + // This is the final match + if (entry.isFile()) { + const stats = await this.fs.stat(entryPath); + const mtime = stats.mtimeMs || 0; + results.push({ path: entryPath, mtime }); + } + } else { + // Continue matching subsequent segments + if (entry.isDirectory()) { + await this.searchRecursive(basePath, entryPath, segments, segmentIndex + 2, results); + } + } + } + } + } else if (this.matchesPattern(entry.name, segment)) { + // Regular segment match + if (segmentIndex === segments.length - 1) { + // This is the final segment - add matching files + if (entry.isFile()) { + const stats = await this.fs.stat(entryPath); + const mtime = stats.mtimeMs || 0; + results.push({ path: entryPath, mtime }); + } + } else { + // More segments to match - continue into directories + if (entry.isDirectory()) { + await this.searchRecursive(basePath, entryPath, segments, segmentIndex + 1, results); + } + } + } + } + } catch { + // Skip directories we can't read + return; + } + } + + private matchesPattern(filename: string, pattern: string): boolean { + // Convert glob pattern to regex + const regexPattern = pattern + .replace(/\./g, '\\.') + .replace(/\*\*/g, '\u00A7\u00A7\u00A7') + .replace(/\*/g, '[^/]*') + .replace(/\u00A7\u00A7\u00A7/g, '.*') + .replace(/\?/g, '[^/]'); + + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(filename); + } +} diff --git a/src/lib/tools/GrepTool.ts b/src/lib/tools/GrepTool.ts new file mode 100644 index 00000000..40472df8 --- /dev/null +++ b/src/lib/tools/GrepTool.ts @@ -0,0 +1,241 @@ +import { join } from "path-browserify"; +import { z } from "zod"; + +import type { Tool, ToolResult } from "./Tool"; +import type { JSRuntimeFS } from "../JSRuntime"; + +interface GrepParams { + pattern: string; + path?: string; + include?: string; +} + +interface GrepToolOptions { + maxLineLength?: number; + resultLimit?: number; +} + +export class GrepTool implements Tool { + private fs: JSRuntimeFS; + private cwd: string; + private maxLineLength: number; + private resultLimit: number; + + readonly description = `- Fast content search tool that works with any codebase size +- Searches file contents using regular expressions +- Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.) +- 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 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"), + path: z.string().optional().describe("The directory to search in. Defaults to the current working directory."), + include: z.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'), + }); + + constructor(fs: JSRuntimeFS, cwd: string, options?: GrepToolOptions) { + this.fs = fs; + this.cwd = cwd; + this.maxLineLength = options?.maxLineLength || 2000; + this.resultLimit = options?.resultLimit || 100; + } + + async execute(args: GrepParams): Promise { + if (!args.pattern) { + throw new Error("pattern is required"); + } + + const searchPath = args.path ? join(this.cwd, args.path) : this.cwd; + + try { + // Check if search path exists + const stats = await this.fs.stat(searchPath); + if (!stats.isDirectory()) { + throw new Error(`Not a directory: ${searchPath}`); + } + + // Create regex from pattern + let regex: RegExp; + try { + regex = new RegExp(args.pattern, 'g'); + } catch { + throw new Error(`Invalid regex pattern: ${args.pattern}`); + } + + // Perform the search + const matches = await this.searchFiles(searchPath, regex, args.include); + + // Sort by modification time (most recent first) + matches.sort((a, b) => b.modTime - a.modTime); + + // Truncate results if needed + const truncated = matches.length > this.resultLimit; + const finalMatches = truncated ? matches.slice(0, this.resultLimit) : matches; + + if (finalMatches.length === 0) { + return { content: "No files found" }; + } + + // Format output + const outputLines = [`Found ${finalMatches.length} matches`]; + + let currentFile = ""; + for (const match of finalMatches) { + if (currentFile !== match.path) { + if (currentFile !== "") { + outputLines.push(""); + } + currentFile = match.path; + outputLines.push(`${match.path}:`); + } + const truncatedLineText = + match.lineText.length > this.maxLineLength + ? match.lineText.substring(0, this.maxLineLength) + "..." + : match.lineText; + outputLines.push(` Line ${match.lineNum}: ${truncatedLineText}`); + } + + if (truncated) { + outputLines.push(""); + outputLines.push("(Results are truncated. Consider using a more specific path or pattern.)"); + } + + return { content: outputLines.join("\n") }; + + } catch (error) { + throw new Error(String(error)); + } + } + + /** + * Search for files containing the pattern + */ + private async searchFiles( + dirPath: string, + regex: RegExp, + includePattern?: string + ): Promise> { + const results: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> = []; + + await this.searchRecursive(dirPath, regex, includePattern, results); + + return results; + } + + /** + * Recursively search directories for pattern matches + */ + private async searchRecursive( + dirPath: string, + regex: RegExp, + includePattern: string | undefined, + results: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> + ): Promise { + try { + const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const entryPath = join(dirPath, entry.name); + + if (entry.isDirectory()) { + // Skip common directories that should be ignored + if (entry.name === 'node_modules' || entry.name === '.git') { + continue; + } + // Recursively search subdirectory + await this.searchRecursive(entryPath, regex, includePattern, results); + } else if (entry.isFile()) { + // Check if file matches include pattern + if (includePattern && !this.matchesIncludePattern(entry.name, includePattern)) { + continue; + } + + // Search file content + const fileMatches = await this.searchFileContent(entryPath, regex); + results.push(...fileMatches); + } + } + } catch { + // Skip directories we can't read + return; + } + } + + /** + * Search a single file for pattern matches + */ + private async searchFileContent( + filePath: string, + regex: RegExp + ): Promise> { + try { + // Get file modification time + const stats = await this.fs.stat(filePath); + const modTime = stats.mtimeMs || 0; + + // Read file content + const content = await this.fs.readFile(filePath, 'utf8'); + const lines = content.split('\n'); + const matches: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> = []; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Reset regex lastIndex for global regex + regex.lastIndex = 0; + + if (regex.test(line)) { + matches.push({ + path: filePath, + lineNum: i + 1, + lineText: line, + modTime, + }); + } + } + + return matches; + } catch { + // Skip files we can't read (likely binary) + return []; + } + } + + /** + * Check if a filename matches the include pattern + */ + private matchesIncludePattern(filename: string, includePattern: string): boolean { + // Handle brace expansion like "*.{ts,tsx}" + if (includePattern.includes('{') && includePattern.includes('}')) { + const braceStart = includePattern.indexOf('{'); + const braceEnd = includePattern.indexOf('}'); + const prefix = includePattern.substring(0, braceStart); + const suffix = includePattern.substring(braceEnd + 1); + const options = includePattern.substring(braceStart + 1, braceEnd).split(','); + + return options.some(option => { + const fullPattern = prefix + option + suffix; + return this.matchesSimplePattern(filename, fullPattern); + }); + } + + return this.matchesSimplePattern(filename, includePattern); + } + + /** + * Check if a filename matches a simple glob pattern + */ + private matchesSimplePattern(filename: string, pattern: string): boolean { + // Convert glob pattern to regex + const regexPattern = pattern + .replace(/\./g, '\\.') // Escape dots + .replace(/\*/g, '.*') // * matches anything + .replace(/\?/g, '.'); // ? matches single character + + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(filename); + } +} diff --git a/src/lib/tools/ReadTool.ts b/src/lib/tools/ReadTool.ts new file mode 100644 index 00000000..009189bc --- /dev/null +++ b/src/lib/tools/ReadTool.ts @@ -0,0 +1,359 @@ +import { join } from "path-browserify"; +import { z } from "zod"; + +import type { Tool, ToolResult } from "./Tool"; +import type { JSRuntimeFS } from "../JSRuntime"; + +interface ReadParams { + filePath: string; + offset?: number; + limit?: number; +} + +interface ReadToolOptions { + projectsPath?: string; + defaultReadLimit?: number; + maxLineLength?: number; +} + +export class ReadTool implements Tool { + private fs: JSRuntimeFS; + private cwd: string; + private projectsPath: string; + private defaultReadLimit: number; + private maxLineLength: number; + + readonly description = `Reads a file from the local filesystem. You can access any file directly by using this tool. +Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned. + +Usage: +- The filePath parameter must be an absolute path, not a relative path +- By default, it reads up to 2000 lines starting from the beginning of the file +- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters +- Any lines longer than 2000 characters will be truncated +- Results are returned using cat -n format, with line numbers starting at 1 +- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful. +- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents. +- You can read image files using this tool.`; + + readonly inputSchema = z.object({ + filePath: z.string().describe("The path to the file to read"), + offset: z.coerce.number().describe("The line number to start reading from (0-based)").optional(), + limit: z.coerce.number().describe("The number of lines to read (defaults to 2000)").optional(), + }); + + constructor(fs: JSRuntimeFS, cwd: string, options?: ReadToolOptions) { + this.fs = fs; + this.cwd = cwd; + this.projectsPath = options?.projectsPath || '/projects'; + this.defaultReadLimit = options?.defaultReadLimit || 2000; + this.maxLineLength = options?.maxLineLength || 2000; + } + + async execute(args: ReadParams): Promise { + let filepath = args.filePath; + + // Handle both absolute and relative paths + if (!filepath.startsWith('/') && !filepath.startsWith('\\') && !/^[A-Za-z]:[\\/]/.test(filepath)) { + filepath = join(this.cwd, filepath); + } + + try { + const file = await this.fs.stat(filepath); + + // Handle directory viewing + if (file.isDirectory()) { + // Special handling for projects directory - only show project directories, not their contents + const normalizedPath = filepath.replace(/\/$/, ''); // Remove trailing slash + if (normalizedPath === this.projectsPath) { + const tree = await this.generateDirectoryTree(filepath, "", 1); // Only show immediate children + return { content: tree }; + } + + // Check if we're starting from a .git directory + const isGitRoot = filepath.endsWith('/.git') || filepath === '.git'; + + // If it's a directory, generate a tree-like listing + const tree = await this.generateDirectoryTree(filepath, "", 3, 0, isGitRoot); + return { content: tree }; + } + + // Check if it's an image file + const isImage = this.isImageFile(filepath); + if (isImage) { + // Read image as base64 + const bytes = await this.fs.readFile(filepath); + const base64 = this.arrayBufferToBase64(bytes); + const ext = this.getFileExtension(filepath).toLowerCase(); + const mimeType = this.getMimeType(ext); + + // Return base64 data URL in the content + return { + content: `[Image file: ${ext.toUpperCase()} file]\n\nImage read successfully.\n\nData URL: data:${mimeType};base64,${base64}`, + }; + } + + // Check if it's binary + if (await this.isBinaryFile(filepath)) { + const stats = await this.fs.stat(filepath); + const fileSize = this.formatFileSize(stats.size || 0); + const fileExtension = this.getFileExtension(filepath); + return { + content: `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.` + }; + } + + // Read text file + const content = await this.fs.readFile(filepath, "utf8"); + const limit = args.limit ?? this.defaultReadLimit; + const offset = args.offset || 0; + const lines = content.split("\n"); + + // Apply line filtering + const raw: string[] = []; + for (let i = offset; i < Math.min(lines.length, offset + limit); i++) { + const line = lines[i].length > this.maxLineLength + ? lines[i].substring(0, this.maxLineLength) + "..." + : lines[i]; + raw.push(line); + } + + // Format with line numbers (cat -n format, 1-indexed) + const formatted = raw.map((line, index) => { + return `${(index + offset + 1).toString().padStart(5, " ")}| ${line}`; + }); + + let output = "\n"; + output += formatted.join("\n"); + + const totalLines = lines.length; + const lastReadLine = offset + raw.length; + const hasMoreLines = totalLines > lastReadLine; + + if (hasMoreLines) { + output += `\n\n(File has more lines. Use 'offset' parameter to read beyond line ${lastReadLine})`; + } else { + output += `\n\n(End of file - total ${totalLines} lines)`; + } + output += "\n"; + + return { content: output }; + + } catch { + // File not found - try to suggest similar files + try { + const dir = filepath.split('/').slice(0, -1).join('/') || '/'; + const base = filepath.split('/').pop() || ''; + const dirEntries = await this.fs.readdir(dir); + + const suggestions = dirEntries + .filter(entry => + entry.toLowerCase().includes(base.toLowerCase()) || + base.toLowerCase().includes(entry.toLowerCase()) + ) + .map(entry => join(dir, entry)) + .slice(0, 3); + + if (suggestions.length > 0) { + throw new Error(`File not found: ${filepath}\n\nDid you mean one of these?\n${suggestions.join("\n")}`); + } + } catch { + // Ignore suggestion errors + } + + throw new Error(`File not found: ${filepath}`); + } + } + + /** + * Generate a tree-like directory listing + */ + private async generateDirectoryTree( + dirPath: string, + prefix: string = "", + maxDepth: number = 3, + currentDepth: number = 0, + isGitRoot: boolean = false, + ): Promise { + if (currentDepth >= maxDepth) { + return prefix + "...\n"; + } + + try { + const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); + + // Sort entries: directories first, then files, both alphabetically + entries.sort((a, b) => { + if (a.isDirectory() && !b.isDirectory()) return -1; + if (!a.isDirectory() && b.isDirectory()) return 1; + return a.name.localeCompare(b.name); + }); + + let result = ""; + + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]! + const isLastEntry = i === entries.length - 1; + const connector = isLastEntry ? "└── " : "ā”œā”€ā”€ "; + const nextPrefix = prefix + (isLastEntry ? " " : "│ "); + + if (entry.isDirectory()) { + result += prefix + connector + entry.name + "/\n"; + + // Special handling for .git directories - don't traverse unless we started from .git + if (entry.name === '.git' && !isGitRoot) { + result += nextPrefix + "...\n"; + } else { + const subPath = join(dirPath, entry.name); + result += await this.generateDirectoryTree( + subPath, + nextPrefix, + maxDepth, + currentDepth + 1, + isGitRoot, + ); + } + } else { + result += prefix + connector + entry.name + "\n"; + } + } + + return result; + } catch (error) { + return prefix + `[Error reading directory: ${error}]\n`; + } + } + + /** + * Check if a file is an image based on extension + */ + private isImageFile(filePath: string): boolean { + const extension = this.getFileExtension(filePath).toLowerCase(); + const imageExtensions = new Set(['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg', 'ico', 'avif']); + return imageExtensions.has(extension); + } + + /** + * Get MIME type for image extensions + */ + private getMimeType(extension: string): string { + const mimeTypes: Record = { + 'png': 'image/png', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'gif': 'image/gif', + 'bmp': 'image/bmp', + 'webp': 'image/webp', + 'svg': 'image/svg+xml', + 'ico': 'image/x-icon', + 'avif': 'image/avif', + }; + return mimeTypes[extension] || 'application/octet-stream'; + } + + /** + * Convert ArrayBuffer to base64 + */ + private arrayBufferToBase64(buffer: ArrayBuffer | Uint8Array): string { + const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer); + let binary = ''; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); + } + + /** + * Check if a file is likely to be binary based on file extension and content sampling + */ + private async isBinaryFile(filePath: string): Promise { + // Check file extension first for known binary types + const extension = this.getFileExtension(filePath).toLowerCase(); + const binaryExtensions = new Set([ + // Images (already handled separately) + 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tif', 'webp', 'ico', 'avif', + // Videos + 'mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', '3gp', 'm4v', + // Audio + 'mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a', 'opus', + // Archives + 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'lz4', 'zst', + // Executables + 'exe', 'dll', 'so', 'dylib', 'bin', 'app', 'deb', 'rpm', 'msi', + // Documents (binary formats) + 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp', + // Fonts + 'ttf', 'otf', 'woff', 'woff2', 'eot', + // Other binary formats + 'sqlite', 'db', 'sqlite3', 'pyc', 'class', 'jar', 'war', 'ear', 'wasm', + ]); + + if (binaryExtensions.has(extension)) { + return true; + } + + try { + // For files without clear binary extensions, sample the first chunk of content + const bytes = await this.fs.readFile(filePath); + + // Check first 1024 bytes (or entire file if smaller) + const sampleSize = Math.min(1024, bytes.length); + + // Count null bytes and non-printable characters + let nullBytes = 0; + let nonPrintableBytes = 0; + + for (let i = 0; i < sampleSize; i++) { + const byte = bytes[i]; + + if (byte === 0) { + nullBytes++; + } + + // Consider bytes outside printable ASCII range (except common whitespace) + // Printable ASCII: 32-126, plus tab (9), newline (10), carriage return (13) + if (byte !== 9 && byte !== 10 && byte !== 13 && (byte < 32 || byte > 126)) { + nonPrintableBytes++; + } + } + + // If more than 1% null bytes or more than 30% non-printable, consider it binary + const nullRatio = nullBytes / sampleSize; + const nonPrintableRatio = nonPrintableBytes / sampleSize; + + return nullRatio > 0.01 || nonPrintableRatio > 0.3; + + } catch { + // If we can't read the file, assume it might be binary + return true; + } + } + + /** + * Get file extension from path + */ + private getFileExtension(filePath: string): string { + const lastDotIndex = filePath.lastIndexOf('.'); + const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\')); + + // If there's no dot, or the dot is before the last slash (hidden file), return empty string + if (lastDotIndex === -1 || lastDotIndex < lastSlashIndex) { + return ''; + } + + return filePath.slice(lastDotIndex + 1); + } + + /** + * Format file size in human-readable format + */ + private formatFileSize(bytes: number): string { + if (bytes === 0) return '0 B'; + + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + const k = 1024; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + + return `${(bytes / Math.pow(k, i)).toFixed(1)} ${units[i]}`; + } +} diff --git a/src/lib/tools/TextEditorStrReplaceTool.test.ts b/src/lib/tools/TextEditorStrReplaceTool.test.ts deleted file mode 100644 index f4f869ce..00000000 --- a/src/lib/tools/TextEditorStrReplaceTool.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { describe, it, expect, beforeEach } from 'vitest'; -import { TextEditorStrReplaceTool } from './TextEditorStrReplaceTool'; -import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime'; - -// Simple mock filesystem for testing -class MockFS implements JSRuntimeFS { - private files: Map = new Map(); - private dirs: Set = new Set(); - - constructor() { - this.dirs.add('/project'); - this.dirs.add('/project/src'); - this.files.set('/project/src/test.ts', 'const message = "hello world";\nconsole.log(message);'); - } - - async readFile(path: string): Promise; - async readFile(path: string, options: 'utf8'): Promise; - async readFile(path: string, options: string): Promise; - async readFile(path: string, options: { encoding: 'utf8' }): Promise; - async readFile(path: string, options: { encoding: string }): Promise; - async readFile(path: string, options?: string | { encoding?: string }): Promise; - async readFile(path: string, options?: string | { encoding?: string }): Promise { - const content = this.files.get(path); - if (content === undefined) { - throw new Error(`File not found: ${path}`); - } - const encoding = typeof options === 'string' ? options : options?.encoding; - return encoding ? content : new TextEncoder().encode(content); - } - - async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise { - const content = typeof data === 'string' ? data : new TextDecoder().decode(data); - this.files.set(path, content); - } - - async readdir(path: string): Promise; - async readdir(path: string, options: { withFileTypes: true }): Promise; - async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise { - return []; - } - - async mkdir(path: string, _options?: { recursive?: boolean }): Promise { - this.dirs.add(path); - } - - async stat(path: string): Promise<{ - isDirectory(): boolean; - isFile(): boolean; - size?: number; - mtimeMs?: number; - }> { - if (this.dirs.has(path)) { - return { - isDirectory: () => true, - isFile: () => false, - size: 0, - mtimeMs: Date.now() - }; - } - - if (this.files.has(path)) { - return { - isDirectory: () => false, - isFile: () => true, - size: this.files.get(path)!.length, - mtimeMs: Date.now() - }; - } - - throw new Error(`Path not found: ${path}`); - } - - async lstat(path: string) { - return this.stat(path); - } - - async unlink(path: string): Promise { - this.files.delete(path); - } - - async rmdir(path: string): Promise { - this.dirs.delete(path); - } - - async rename(oldPath: string, newPath: string): Promise { - if (this.files.has(oldPath)) { - this.files.set(newPath, this.files.get(oldPath)!); - this.files.delete(oldPath); - } - } - - async readlink(_path: string): Promise { - throw new Error('Symlinks not supported in mock'); - } - - async symlink(_target: string, _path: string): Promise { - throw new Error('Symlinks not supported in mock'); - } - - // Helper method to get file content - getFileContent(path: string): string | undefined { - return this.files.get(path); - } -} - -describe('TextEditorStrReplaceTool', () => { - let mockFS: MockFS; - let tool: TextEditorStrReplaceTool; - - beforeEach(() => { - mockFS = new MockFS(); - tool = new TextEditorStrReplaceTool(mockFS, '/project'); - }); - - it('should replace string in file successfully', async () => { - const result = await tool.execute({ - path: 'src/test.ts', - old_str: 'hello world', - new_str: 'hello universe' - }); - - expect(result.content).toContain('String successfully replaced in src/test.ts'); - expect(mockFS.getFileContent('/project/src/test.ts')).toContain('hello universe'); - expect(mockFS.getFileContent('/project/src/test.ts')).not.toContain('hello world'); - }); - - it('should handle string not found', async () => { - await expect(tool.execute({ - path: 'src/test.ts', - old_str: 'nonexistent string', - new_str: 'replacement' - })).rejects.toThrow('The string to replace was not found in src/test.ts'); - }); - - it('should reject absolute paths with helpful error message', async () => { - await expect(tool.execute({ - path: '/absolute/path/test.ts', - old_str: 'old', - new_str: 'new' - })).rejects.toThrow('Write access denied'); - }); - - it('should allow writes to /tmp/ directory', async () => { - // First create the file in /tmp/ - await mockFS.writeFile('/tmp/temp-file.txt', 'original content'); - - const result = await tool.execute({ - path: '/tmp/temp-file.txt', - old_str: 'original', - new_str: 'modified' - }); - - expect(result.content).toContain('String successfully replaced'); - expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('modified content'); - }); - - it('should handle whitespace normalization', async () => { - const result = await tool.execute({ - path: 'src/test.ts', - old_str: 'const message = "hello world";', - new_str: 'const greeting = "hello universe";', - normalize_whitespace: true - }); - - expect(result.content).toContain('String successfully replaced'); - expect(mockFS.getFileContent('/project/src/test.ts')).toContain('const greeting = "hello universe";'); - }); -}); \ No newline at end of file diff --git a/src/lib/tools/TextEditorStrReplaceTool.ts b/src/lib/tools/TextEditorStrReplaceTool.ts deleted file mode 100644 index 1622ebeb..00000000 --- a/src/lib/tools/TextEditorStrReplaceTool.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { join } from "path-browserify"; -import { z } from "zod"; - -import type { Tool, ToolResult } from "./Tool"; -import type { JSRuntimeFS } from "../JSRuntime"; -import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security"; - -interface TextEditorStrReplaceParams { - path: string; - old_str: string; - new_str: string; - normalize_whitespace?: boolean; -} - -export class TextEditorStrReplaceTool implements Tool { - private fs: JSRuntimeFS; - private cwd: string; - private projectsPath: string; - private tmpPath: string; - private onFileChanged?: (filePath: string) => void; - - readonly description = "Replace a string in a file with a new string"; - - readonly inputSchema = z.object({ - path: z.string().describe('Path to the file, eg "src/index.ts"'), - old_str: z.string().describe("The string to replace"), - new_str: z.string().describe("The new string to insert"), - normalize_whitespace: z.boolean().optional().describe( - "If true, normalize whitespace and line endings for more flexible matching (default: true)" - ), - }); - - constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) { - this.fs = fs; - this.cwd = cwd; - this.projectsPath = options?.projectsPath || '/projects'; - this.tmpPath = options?.tmpPath || '/tmp'; - this.onFileChanged = options?.onFileChanged; - } - - async execute(args: TextEditorStrReplaceParams): Promise { - const { path, old_str, new_str, normalize_whitespace = true } = args; - - // Check write permissions - if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) { - throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })); - } - - // Ban editing dependencies in package.json - if ( - path === "package.json" || path.endsWith("/package.json") || - path.endsWith("\\package.json") - ) { - const depKeys = [ - '"dependencies"', - '"devDependencies"', - '"peerDependencies"', - '"optionalDependencies"', - ]; - if ( - depKeys.some((key) => - old_str.includes(key) || new_str.includes(key) - ) - ) { - throw new Error(`šŸ”’ Direct edits to dependencies in package.json are disallowed.\nšŸ‘‰ Please use npm_add_package or npm_remove_package tools for these changes.`); - } - } - - try { - // Handle both absolute and relative paths - let absolutePath: string; - if (isAbsolutePath(path)) { - absolutePath = path; - } else { - absolutePath = join(this.cwd, path); - } - - const content = await this.fs.readFile(absolutePath, "utf8"); - - // Helper function to normalize whitespace - const normalizeWhitespace = (str: string): string => { - return str - .replace(/\r\n/g, '\n') // Convert CRLF to LF - .replace(/\r/g, '\n') // Convert CR to LF - .split('\n') - .map(line => line.trimEnd()) // Remove trailing whitespace from each line - .join('\n'); - }; - - let searchContent = content; - let searchOldStr = old_str; - let searchNewStr = new_str; - - if (normalize_whitespace) { - searchContent = normalizeWhitespace(content); - searchOldStr = normalizeWhitespace(old_str); - searchNewStr = normalizeWhitespace(new_str); - } - - if (!searchContent.includes(searchOldStr)) { - // Try to provide helpful debugging information - const lines = searchContent.split('\n'); - const oldLines = searchOldStr.split('\n'); - - // Find potential matches by looking for the first line of old_str - const firstLine = oldLines[0]; - const matchingLineNumbers: number[] = []; - - if (firstLine) { - lines.forEach((line, index) => { - if (line.includes(firstLine)) { - matchingLineNumbers.push(index + 1); - } - }); - } - - let errorMessage = `Error: The string to replace was not found in ${path}`; - - if (matchingLineNumbers.length > 0) { - errorMessage += `\n\nPossible matches found at lines: ${matchingLineNumbers.join(', ')}`; - - // Show context around the first potential match - const firstMatch = matchingLineNumbers[0]! - 1; - const contextStart = Math.max(0, firstMatch - 2); - const contextEnd = Math.min(lines.length, firstMatch + oldLines.length + 2); - const contextLines = lines.slice(contextStart, contextEnd); - - errorMessage += `\n\nContext around line ${matchingLineNumbers[0]}:`; - contextLines.forEach((line, index) => { - const lineNum = contextStart + index + 1; - const marker = lineNum === matchingLineNumbers[0] ? '→ ' : ' '; - errorMessage += `\n${marker}${lineNum}: ${line}`; - }); - } - - if (normalize_whitespace) { - errorMessage += `\n\nNote: Whitespace normalization was applied. Try setting normalize_whitespace to false if the replacement still fails.`; - } - - throw new Error(errorMessage); - } - - // Count occurrences (simple string counting) - let occurrences = 0; - let pos = 0; - while ((pos = searchContent.indexOf(searchOldStr, pos)) !== -1) { - occurrences++; - pos += searchOldStr.length; - } - - // Perform the replacement - let newContent: string; - if (normalize_whitespace) { - // Apply the replacement to the normalized content, then restore original line endings - const normalizedResult = searchContent.replace(searchOldStr, searchNewStr); - - // Try to preserve the original line ending style - const hasCarriageReturn = content.includes('\r'); - if (hasCarriageReturn) { - if (content.includes('\r\n')) { - // Original had CRLF - newContent = normalizedResult.replace(/\n/g, '\r\n'); - } else { - // Original had CR only - newContent = normalizedResult.replace(/\n/g, '\r'); - } - } else { - // Original had LF only - newContent = normalizedResult; - } - } else { - newContent = content.replace(old_str, new_str); - } - - await this.fs.writeFile(absolutePath, newContent, "utf8"); - - // Notify about file change (for auto-build) - if (this.onFileChanged) { - this.onFileChanged(path); - } - - let successMessage = `String successfully replaced in ${path}`; - if (occurrences > 1) { - successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`; - } - - return { content: successMessage }; - } catch (error) { - throw new Error(String(error)); - } - } -} \ No newline at end of file diff --git a/src/lib/tools/TextEditorViewTool.test.ts b/src/lib/tools/TextEditorViewTool.test.ts deleted file mode 100644 index 17c57d53..00000000 --- a/src/lib/tools/TextEditorViewTool.test.ts +++ /dev/null @@ -1,335 +0,0 @@ -import { describe, it, expect, beforeEach } from 'vitest'; -import { TextEditorViewTool } from './TextEditorViewTool'; -import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime'; - -// Mock filesystem for testing -class MockFS implements JSRuntimeFS { - private files: Map = new Map(); - private dirs: Set = new Set(); - - constructor() { - // Set up a basic project structure - this.dirs.add('/projects'); - this.dirs.add('/projects/project1'); - this.dirs.add('/projects/project1/src'); - this.dirs.add('/projects/project1/.git'); - this.dirs.add('/projects/project2'); - this.dirs.add('/projects/project2/src'); - this.dirs.add('/project'); - this.dirs.add('/project/.git'); - this.dirs.add('/project/src'); - this.dirs.add('/project/node_modules'); - this.dirs.add('/tmp'); - - this.files.set('/projects/project1/package.json', '{"name": "project1"}'); - this.files.set('/projects/project1/src/index.ts', 'console.log("project1");'); - this.files.set('/projects/project1/.git/config', '[core]\nrepositoryformatversion = 0'); - this.files.set('/projects/project1/.git/HEAD', 'ref: refs/heads/main'); - this.files.set('/projects/project2/package.json', '{"name": "project2"}'); - this.files.set('/projects/project2/src/main.ts', 'console.log("project2");'); - this.files.set('/project/package.json', '{"name": "test"}'); - this.files.set('/project/src/index.ts', 'console.log("hello");'); - this.files.set('/project/.gitignore', 'node_modules\n.git\n'); - this.files.set('/project/.git/config', '[core]\nrepositoryformatversion = 0'); - this.files.set('/project/.git/HEAD', 'ref: refs/heads/main'); - this.files.set('/tmp/uploaded-file.txt', 'This is an uploaded file'); - - // Add binary files for testing - this.files.set('/project/logo.png', 'BINARY_CONTENT_PNG'); - this.files.set('/project/document.pdf', 'BINARY_CONTENT_PDF'); - this.files.set('/tmp/image.jpg', 'BINARY_CONTENT_JPG'); - } - - async readFile(path: string): Promise; - async readFile(path: string, options: 'utf8'): Promise; - async readFile(path: string, options: string): Promise; - async readFile(path: string, options: { encoding: 'utf8' }): Promise; - async readFile(path: string, options: { encoding: string }): Promise; - async readFile(path: string, options?: string | { encoding?: string }): Promise; - async readFile(path: string, options?: string | { encoding?: string }): Promise { - const content = this.files.get(path); - if (content === undefined) { - throw new Error(`File not found: ${path}`); - } - - const encoding = typeof options === 'string' ? options : options?.encoding; - // If no encoding specified, return Uint8Array - if (!encoding) { - // For binary files, return mock binary data with null bytes - if (content.startsWith('BINARY_CONTENT')) { - const binaryData = new Uint8Array(100); - binaryData[0] = 0; // Add null byte to make it appear binary - binaryData[1] = 255; // Add some non-printable bytes - binaryData[2] = 0; - // Fill rest with some pattern - for (let i = 3; i < 100; i++) { - binaryData[i] = i % 256; - } - return binaryData; - } - return new TextEncoder().encode(content); - } - - return content; - } - - async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise { - const content = typeof data === 'string' ? data : new TextDecoder().decode(data); - this.files.set(path, content); - } - - async readdir(path: string): Promise; - async readdir(path: string, options: { withFileTypes: true }): Promise; - async readdir(path: string, options?: { withFileTypes?: boolean }): Promise; - async readdir(path: string, options?: { withFileTypes?: boolean }): Promise { - // Normalize path by removing trailing slash - const normalizedPath = path.replace(/\/$/, '') || '/'; - const entries: string[] = []; - - // Find all files and directories that are direct children of this path - for (const filePath of this.files.keys()) { - if (filePath.startsWith(normalizedPath + '/')) { - const relativePath = filePath.slice(normalizedPath.length + 1); - const parts = relativePath.split('/'); - if (parts.length === 1) { - entries.push(parts[0]); - } - } - } - - for (const dirPath of this.dirs) { - if (dirPath.startsWith(normalizedPath + '/')) { - const relativePath = dirPath.slice(normalizedPath.length + 1); - const parts = relativePath.split('/'); - if (parts.length === 1) { - entries.push(parts[0]); - } - } - } - - if (options?.withFileTypes) { - return entries.map(name => ({ - name, - isDirectory: () => this.dirs.has(`${normalizedPath}/${name}`), - isFile: () => this.files.has(`${normalizedPath}/${name}`) - })); - } - - return entries; - } - - async mkdir(path: string, _options?: { recursive?: boolean }): Promise { - this.dirs.add(path); - } - - async stat(path: string): Promise<{ - isDirectory(): boolean; - isFile(): boolean; - size?: number; - mtimeMs?: number; - }> { - // Normalize path by removing trailing slash for directories - const normalizedPath = path.replace(/\/$/, '') || '/'; - - if (this.dirs.has(normalizedPath)) { - return { - isDirectory: () => true, - isFile: () => false, - size: 0, - mtimeMs: Date.now() - }; - } - - if (this.files.has(normalizedPath)) { - return { - isDirectory: () => false, - isFile: () => true, - size: this.files.get(normalizedPath)!.length, - mtimeMs: Date.now() - }; - } - - throw new Error(`Path not found: ${path}`); - } - - async lstat(path: string) { - return this.stat(path); - } - - async unlink(path: string): Promise { - this.files.delete(path); - } - - async rmdir(path: string): Promise { - this.dirs.delete(path); - } - - async rename(oldPath: string, newPath: string): Promise { - if (this.files.has(oldPath)) { - this.files.set(newPath, this.files.get(oldPath)!); - this.files.delete(oldPath); - } - } - - async readlink(_path: string): Promise { - throw new Error('Symlinks not supported in mock'); - } - - async symlink(_target: string, _path: string): Promise { - throw new Error('Symlinks not supported in mock'); - } -} - -describe('TextEditorViewTool', () => { - let mockFS: MockFS; - let tool: TextEditorViewTool; - - beforeEach(() => { - mockFS = new MockFS(); - tool = new TextEditorViewTool(mockFS, '/project'); - }); - - it('should handle viewing current directory', async () => { - const result = await tool.execute({ path: '.' }); - - expect(result.content).toContain('src/'); - expect(result.content).toContain('package.json'); - expect(result.content).toContain('.gitignore'); - expect(result.content).toContain('.git/'); // .git directory should now be visible - }); - - it('should handle viewing subdirectory', async () => { - const result = await tool.execute({ path: 'src' }); - - expect(result.content).toContain('index.ts'); - }); - - it('should handle viewing a file', async () => { - const result = await tool.execute({ path: 'src/index.ts' }); - - expect(result.content).toBe('console.log("hello");'); - }); - - it('should handle line filtering', async () => { - const result = await tool.execute({ - path: 'src/index.ts', - start_line: 1, - end_line: 1 - }); - - expect(result.content).toBe('console.log("hello");'); - }); - - it('should handle absolute paths', async () => { - const result = await tool.execute({ path: '/tmp/uploaded-file.txt' }); - - expect(result.content).toBe('This is an uploaded file'); - }); - - it('should handle absolute directory paths', async () => { - const result = await tool.execute({ path: '/tmp' }); - - expect(result.content).toContain('uploaded-file.txt'); - }); - - it('should handle absolute paths with line filtering', async () => { - const result = await tool.execute({ - path: '/tmp/uploaded-file.txt', - start_line: 1, - end_line: 1 - }); - - expect(result.content).toBe('This is an uploaded file'); - }); - - it('should detect binary files by extension and show placeholder', async () => { - const result = await tool.execute({ path: 'logo.png' }); - - expect(result.content).toContain('[Binary file: PNG file'); - expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.'); - expect(result.content).not.toContain('BINARY_CONTENT_PNG'); - }); - - it('should detect PDF files as binary', async () => { - const result = await tool.execute({ path: 'document.pdf' }); - - expect(result.content).toContain('[Binary file: PDF file'); - expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.'); - }); - - it('should detect binary files with absolute paths', async () => { - const result = await tool.execute({ path: '/tmp/image.jpg' }); - - expect(result.content).toContain('[Binary file: JPG file'); - expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.'); - }); - - it('should show only project directories when viewing /projects', async () => { - const result = await tool.execute({ path: '/projects' }); - - // Should show the project directories - expect(result.content).toContain('project1/'); - expect(result.content).toContain('project2/'); - - // Should NOT show the contents of the project directories (depth 1 only) - expect(result.content).not.toContain('package.json'); - expect(result.content).not.toContain('src/'); - expect(result.content).not.toContain('index.ts'); - expect(result.content).not.toContain('main.ts'); - }); - - it('should show only project directories when viewing /projects/', async () => { - const result = await tool.execute({ path: '/projects/' }); - - // Should show the project directories - expect(result.content).toContain('project1/'); - expect(result.content).toContain('project2/'); - - // Should NOT show the contents of the project directories (depth 1 only) - expect(result.content).not.toContain('package.json'); - expect(result.content).not.toContain('src/'); - expect(result.content).not.toContain('index.ts'); - expect(result.content).not.toContain('main.ts'); - }); - - it('should show .git directory but not traverse its contents when viewing project root', async () => { - const result = await tool.execute({ path: '/project' }); - - // Should show the .git directory - expect(result.content).toContain('.git/'); - - // Should show "..." under .git instead of its contents - expect(result.content).toContain('...'); - - // Should NOT show .git file contents - expect(result.content).not.toContain('config'); - expect(result.content).not.toContain('HEAD'); - expect(result.content).not.toContain('repositoryformatversion'); - - // Should still show other directory contents normally - expect(result.content).toContain('src/'); - expect(result.content).toContain('package.json'); - }); - - it('should show .git contents when explicitly viewing .git directory', async () => { - const result = await tool.execute({ path: '/project/.git' }); - - // Should show the .git file contents when explicitly requested - expect(result.content).toContain('config'); - expect(result.content).toContain('HEAD'); - - // Should NOT show "..." when explicitly viewing .git - expect(result.content).not.toContain('...'); - }); - - it('should show .git contents when explicitly viewing .git with relative path', async () => { - const result = await tool.execute({ path: '.git' }); - - // Should show the .git file contents when explicitly requested - expect(result.content).toContain('config'); - expect(result.content).toContain('HEAD'); - - // Should NOT show "..." when explicitly viewing .git - expect(result.content).not.toContain('...'); - }); -}); \ No newline at end of file diff --git a/src/lib/tools/TextEditorViewTool.ts b/src/lib/tools/TextEditorViewTool.ts deleted file mode 100644 index 4f55c36f..00000000 --- a/src/lib/tools/TextEditorViewTool.ts +++ /dev/null @@ -1,276 +0,0 @@ -import { join } from "path-browserify"; -import { z } from "zod"; - -import type { Tool, ToolResult } from "./Tool"; -import type { JSRuntimeFS } from "../JSRuntime"; - -interface TextEditorViewParams { - path: string; - start_line?: number; - end_line?: number; -} - -export class TextEditorViewTool implements Tool { - private fs: JSRuntimeFS; - private cwd: string; - private projectsPath: string; - - readonly description = "View the contents of a text file or directory"; - - readonly inputSchema = z.object({ - path: z.string().describe( - 'Path of the file or directory to view, eg "src/index.ts" or "src/" for relative paths, or "/tmp/file.txt" for absolute paths', - ), - start_line: z.number().min(1).optional().describe( - "Starting line number (1-indexed, inclusive). If provided, only show lines from this line onwards.", - ), - end_line: z.number().min(1).optional().describe( - "Ending line number (1-indexed, inclusive). If provided, only show lines up to this line.", - ), - }); - - constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string }) { - this.fs = fs; - this.cwd = cwd; - this.projectsPath = options?.projectsPath || '/projects'; - } - - async execute(args: TextEditorViewParams): Promise { - const { path, start_line, end_line } = args; - - try { - // Handle both absolute and relative paths - let absolutePath: string; - - if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) { - // It's an absolute path - use it directly - absolutePath = path; - } else { - // It's a relative path - resolve it relative to the current working directory - absolutePath = join(this.cwd, path); - } - - // Check if the path is a directory - const stats = await this.fs.stat(absolutePath); - - if (stats.isDirectory()) { - // Special handling for projects directory - only show project directories, not their contents - const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash - if (normalizedPath === this.projectsPath) { - const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children - return { content: tree }; - } - - // Check if we're starting from a .git directory - const isGitRoot = absolutePath.endsWith('/.git') || absolutePath === '.git'; - - // If it's a directory, generate a tree-like listing - // Note: start_line and end_line are ignored for directories - const tree = await this.generateDirectoryTree(absolutePath, "", 3, 0, isGitRoot); - return { content: tree }; - } - - // If it's a file, check if it's binary first - if (await this.isBinaryFile(absolutePath)) { - const stats = await this.fs.stat(absolutePath); - const fileSize = this.formatFileSize(stats.size || 0); - const fileExtension = this.getFileExtension(absolutePath); - return { - content: `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.` - }; - } - - // If it's a text file, read and return its contents - let content = await this.fs.readFile(absolutePath, "utf8"); - - // Apply line filtering if start_line or end_line are provided - if (start_line !== undefined || end_line !== undefined) { - const lines = content.split('\n'); - - // Validate line numbers first - if (start_line !== undefined && start_line < 1) { - throw new Error("Error: start_line must be >= 1"); - } - - if (end_line !== undefined && end_line < 1) { - throw new Error("Error: end_line must be >= 1"); - } - - if (start_line !== undefined && end_line !== undefined && start_line > end_line) { - throw new Error("Error: start_line cannot be greater than end_line"); - } - - if (start_line !== undefined && start_line > lines.length) { - throw new Error(`Error: start_line ${start_line} is beyond the end of the file (${lines.length} lines)`); - } - - const startIdx = start_line !== undefined ? start_line - 1 : 0; - const endIdx = end_line !== undefined ? Math.min(lines.length, end_line) : lines.length; - - content = lines.slice(startIdx, endIdx).join('\n'); - } - - return { content }; - } catch (error) { - throw new Error(String(error)); - } - } - - /** - * Generate a tree-like directory listing - */ - private async generateDirectoryTree( - dirPath: string, - prefix: string = "", - maxDepth: number = 3, - currentDepth: number = 0, - isGitRoot: boolean = false, - ): Promise { - if (currentDepth >= maxDepth) { - return prefix + "...\n"; - } - - try { - const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); - - // Sort entries: directories first, then files, both alphabetically - entries.sort((a, b) => { - if (a.isDirectory() && !b.isDirectory()) return -1; - if (!a.isDirectory() && b.isDirectory()) return 1; - return a.name.localeCompare(b.name); - }); - - let result = ""; - - for (let i = 0; i < entries.length; i++) { - const entry = entries[i]! - const isLastEntry = i === entries.length - 1; - const connector = isLastEntry ? "└── " : "ā”œā”€ā”€ "; - const nextPrefix = prefix + (isLastEntry ? " " : "│ "); - - if (entry.isDirectory()) { - result += prefix + connector + entry.name + "/\n"; - - // Special handling for .git directories - don't traverse unless we started from .git - if (entry.name === '.git' && !isGitRoot) { - result += nextPrefix + "...\n"; - } else { - const subPath = join(dirPath, entry.name); - result += await this.generateDirectoryTree( - subPath, - nextPrefix, - maxDepth, - currentDepth + 1, - isGitRoot, - ); - } - } else { - result += prefix + connector + entry.name + "\n"; - } - } - - return result; - } catch (error) { - return prefix + `[Error reading directory: ${error}]\n`; - } - } - - - - /** - * Check if a file is likely to be binary based on file extension and content sampling - */ - private async isBinaryFile(filePath: string): Promise { - // Check file extension first for known binary types - const extension = this.getFileExtension(filePath).toLowerCase(); - const binaryExtensions = new Set([ - // Images - 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tif', 'webp', 'svg', 'ico', 'avif', - // Videos - 'mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', '3gp', 'm4v', - // Audio - 'mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a', 'opus', - // Archives - 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'lz4', 'zst', - // Executables - 'exe', 'dll', 'so', 'dylib', 'bin', 'app', 'deb', 'rpm', 'msi', - // Documents (binary formats) - 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp', - // Fonts - 'ttf', 'otf', 'woff', 'woff2', 'eot', - // Other binary formats - 'sqlite', 'db', 'sqlite3', 'pyc', 'class', 'jar', 'war', 'ear', - // Development - 'node_modules', 'git', 'gitignore', 'lock' - ]); - - if (binaryExtensions.has(extension)) { - return true; - } - - try { - // For files without clear binary extensions, sample the first chunk of content - // Read as Uint8Array to check for null bytes and non-printable characters - const bytes = await this.fs.readFile(filePath); - - // Check first 1024 bytes (or entire file if smaller) - const sampleSize = Math.min(1024, bytes.length); - - // Count null bytes and non-printable characters - let nullBytes = 0; - let nonPrintableBytes = 0; - - for (let i = 0; i < sampleSize; i++) { - const byte = bytes[i]; - - if (byte === 0) { - nullBytes++; - } - - // Consider bytes outside printable ASCII range (except common whitespace) - // Printable ASCII: 32-126, plus tab (9), newline (10), carriage return (13) - if (byte !== 9 && byte !== 10 && byte !== 13 && (byte < 32 || byte > 126)) { - nonPrintableBytes++; - } - } - - // If more than 1% null bytes or more than 30% non-printable, consider it binary - const nullRatio = nullBytes / sampleSize; - const nonPrintableRatio = nonPrintableBytes / sampleSize; - - return nullRatio > 0.01 || nonPrintableRatio > 0.3; - - } catch { - // If we can't read the file, assume it might be binary - return true; - } - } - - /** - * Get file extension from path - */ - private getFileExtension(filePath: string): string { - const lastDotIndex = filePath.lastIndexOf('.'); - const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\')); - - // If there's no dot, or the dot is before the last slash (hidden file), return empty string - if (lastDotIndex === -1 || lastDotIndex < lastSlashIndex) { - return ''; - } - - return filePath.slice(lastDotIndex + 1); - } - - /** - * Format file size in human-readable format - */ - private formatFileSize(bytes: number): string { - if (bytes === 0) return '0 B'; - - const units = ['B', 'KB', 'MB', 'GB', 'TB']; - const k = 1024; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - - return `${(bytes / Math.pow(k, i)).toFixed(1)} ${units[i]}`; - } -}; \ No newline at end of file diff --git a/src/lib/tools/TextEditorWriteTool.test.ts b/src/lib/tools/TextEditorWriteTool.test.ts deleted file mode 100644 index a4b7c198..00000000 --- a/src/lib/tools/TextEditorWriteTool.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { describe, it, expect, beforeEach } from 'vitest'; -import { TextEditorWriteTool } from './TextEditorWriteTool'; -import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime'; - -// Simple mock filesystem for testing -class MockFS implements JSRuntimeFS { - private files: Map = new Map(); - private dirs: Set = new Set(); - - constructor() { - this.dirs.add('/project'); - this.dirs.add('/project/src'); - } - - async readFile(path: string): Promise; - async readFile(path: string, options: 'utf8'): Promise; - async readFile(path: string, options: string): Promise; - async readFile(path: string, options: { encoding: 'utf8' }): Promise; - async readFile(path: string, options: { encoding: string }): Promise; - async readFile(path: string, options?: string | { encoding?: string }): Promise; - async readFile(path: string, options?: string | { encoding?: string }): Promise { - const content = this.files.get(path); - if (content === undefined) { - throw new Error(`File not found: ${path}`); - } - const encoding = typeof options === 'string' ? options : options?.encoding; - return encoding ? content : new TextEncoder().encode(content); - } - - async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise { - const content = typeof data === 'string' ? data : new TextDecoder().decode(data); - this.files.set(path, content); - } - - async readdir(path: string): Promise; - async readdir(path: string, options: { withFileTypes: true }): Promise; - async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise { - return []; - } - - async mkdir(path: string, _options?: { recursive?: boolean }): Promise { - this.dirs.add(path); - } - - async stat(path: string): Promise<{ - isDirectory(): boolean; - isFile(): boolean; - size?: number; - mtimeMs?: number; - }> { - if (this.dirs.has(path)) { - return { - isDirectory: () => true, - isFile: () => false, - size: 0, - mtimeMs: Date.now() - }; - } - - if (this.files.has(path)) { - return { - isDirectory: () => false, - isFile: () => true, - size: this.files.get(path)!.length, - mtimeMs: Date.now() - }; - } - - throw new Error(`Path not found: ${path}`); - } - - async lstat(path: string) { - return this.stat(path); - } - - async unlink(path: string): Promise { - this.files.delete(path); - } - - async rmdir(path: string): Promise { - this.dirs.delete(path); - } - - async rename(oldPath: string, newPath: string): Promise { - if (this.files.has(oldPath)) { - this.files.set(newPath, this.files.get(oldPath)!); - this.files.delete(oldPath); - } - } - - async readlink(_path: string): Promise { - throw new Error('Symlinks not supported in mock'); - } - - async symlink(_target: string, _path: string): Promise { - throw new Error('Symlinks not supported in mock'); - } - - // Helper method to check if file exists - hasFile(path: string): boolean { - return this.files.has(path); - } - - // Helper method to get file content - getFileContent(path: string): string | undefined { - return this.files.get(path); - } -} - -describe('TextEditorWriteTool', () => { - let mockFS: MockFS; - let tool: TextEditorWriteTool; - - beforeEach(() => { - mockFS = new MockFS(); - tool = new TextEditorWriteTool(mockFS, '/project'); - }); - - it('should write a file successfully', async () => { - const result = await tool.execute({ - path: 'src/test.ts', - file_text: 'console.log("test");' - }); - - expect(result.content).toContain('File successfully written to src/test.ts'); - expect(mockFS.hasFile('/project/src/test.ts')).toBe(true); - expect(mockFS.getFileContent('/project/src/test.ts')).toBe('console.log("test");'); - }); - - it('should reject absolute paths outside allowed directories', async () => { - await expect(tool.execute({ - path: '/absolute/path/test.ts', - file_text: 'test content' - })).rejects.toThrow('Write access denied'); - }); - - it('should allow writes to /tmp/ directory', async () => { - const result = await tool.execute({ - path: '/tmp/temp-file.txt', - file_text: 'temporary content' - }); - - expect(result.content).toContain('File successfully written to /tmp/temp-file.txt'); - expect(mockFS.hasFile('/tmp/temp-file.txt')).toBe(true); - expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('temporary content'); - }); - - it('should reject package.json writes', async () => { - await expect(tool.execute({ - path: 'package.json', - file_text: '{"name": "test"}' - })).rejects.toThrow('šŸ”’ Direct writes to package.json are disallowed'); - }); -}); \ No newline at end of file diff --git a/src/lib/tools/TextEditorWriteTool.ts b/src/lib/tools/TextEditorWriteTool.ts deleted file mode 100644 index 48e2e8d3..00000000 --- a/src/lib/tools/TextEditorWriteTool.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { join, dirname } from "path-browserify"; -import { z } from "zod"; - -import type { Tool, ToolResult } from "./Tool"; -import type { JSRuntimeFS } from "../JSRuntime"; -import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security"; - -interface TextEditorWriteParams { - path: string; - file_text: string; -} - -export class TextEditorWriteTool implements Tool { - private fs: JSRuntimeFS; - private cwd: string; - private projectsPath: string; - private tmpPath: string; - private onFileChanged?: (filePath: string) => void; - - readonly description = "Create or overwrite a file with new content"; - - readonly inputSchema = z.object({ - path: z.string().describe( - 'Path of the file to write, eg "src/index.ts"', - ), - file_text: z.string().describe("Content to write to the file"), - }); - - constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) { - this.fs = fs; - this.cwd = cwd; - this.projectsPath = options?.projectsPath || '/projects'; - this.tmpPath = options?.tmpPath || '/tmp'; - this.onFileChanged = options?.onFileChanged; - } - - async execute(args: TextEditorWriteParams): Promise { - const { path, file_text } = args; - - // Check write permissions - if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) { - throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })); - } - - if ( - path === "package.json" || path.endsWith("/package.json") || - path.endsWith("\\package.json") - ) { - throw new Error(`šŸ”’ Direct writes to package.json are disallowed.\nšŸ‘‰ Please use \`npm_add_package\` or \`npm_remove_package\` tools instead.`); - } - - try { - // Handle both absolute and relative paths - let absolutePath: string; - if (isAbsolutePath(path)) { - absolutePath = path; - } else { - absolutePath = join(this.cwd, path); - } - - await this.fs.mkdir(dirname(absolutePath), { recursive: true }); - await this.fs.writeFile(absolutePath, file_text, "utf8"); - - // Notify about file change (for auto-build) - if (this.onFileChanged) { - this.onFileChanged(path); - } - - return { content: `File successfully written to ${path}` }; - } catch (error) { - throw new Error(String(error)); - } - } -} \ No newline at end of file diff --git a/src/lib/tools/WriteTool.ts b/src/lib/tools/WriteTool.ts new file mode 100644 index 00000000..c203a4f1 --- /dev/null +++ b/src/lib/tools/WriteTool.ts @@ -0,0 +1,88 @@ +import { join, dirname } from "path-browserify"; +import { z } from "zod"; + +import type { Tool, ToolResult } from "./Tool"; +import type { JSRuntimeFS } from "../JSRuntime"; +import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security"; + +interface WriteParams { + content: string; + filePath: string; +} + +export class WriteTool implements Tool { + private fs: JSRuntimeFS; + private cwd: string; + private projectsPath: string; + private tmpPath: string; + private onFileChanged?: (filePath: string) => void; + + readonly description = `Writes a file to the local filesystem. + +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. +- 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.`; + + readonly inputSchema = z.object({ + content: z.string().describe("The content to write to the file"), + filePath: z.string().describe("The absolute path to the file to write (must be absolute, not relative)"), + }); + + constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) { + this.fs = fs; + this.cwd = cwd; + this.projectsPath = options?.projectsPath || '/projects'; + this.tmpPath = options?.tmpPath || '/tmp'; + this.onFileChanged = options?.onFileChanged; + } + + async execute(args: WriteParams): Promise { + let filepath = args.filePath; + + // Convert to absolute path if needed + if (!isAbsolutePath(filepath)) { + filepath = join(this.cwd, filepath); + } + + // Check write permissions + if (!isWriteAllowed(filepath, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) { + throw new Error(createWriteAccessDeniedError(filepath, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })); + } + + // Ban direct writes to package.json + if ( + filepath === "package.json" || + filepath.endsWith("/package.json") || + filepath.endsWith("\\package.json") + ) { + throw new Error(`šŸ”’ Direct writes to package.json are disallowed.\nšŸ‘‰ Please use \`npm_add_package\` or \`npm_remove_package\` tools instead.`); + } + + try { + // Check if file exists + const exists = await this.fs.stat(filepath).then(() => true).catch(() => false); + + // Create directory structure if needed + await this.fs.mkdir(dirname(filepath), { recursive: true }); + + // Write the file + await this.fs.writeFile(filepath, args.content, "utf8"); + + // Notify about file change (for auto-build) + if (this.onFileChanged) { + this.onFileChanged(filepath); + } + + return { + content: exists + ? `File successfully written to ${filepath}` + : `File successfully created at ${filepath}` + }; + } catch (error) { + throw new Error(String(error)); + } + } +}