Add text_editor tools

This commit is contained in:
Alex Gleason committed 2025-07-25 02:19:28 -05:00
1 parent 99723f1d43
commit 5a3f282817
11 files changed
+1090 -333

No files matched your search

+7 -5
View File
@@ -5,13 +5,15 @@ import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Send, Settings, Play, CloudUpload } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { FsToolSet } from '@/lib/FsToolSet';
import { useFS } from '@/hooks/useFS';
import { useJSRuntime } from '@/hooks/useJSRuntime';
import { copyDirectory } from '@/lib/copyFiles';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
import { bytesToHex } from 'nostr-tools/utils';
import { MessageItem } from '@/components/ai/MessageItem';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
interface ChatPaneProps {
projectId: string;
@@ -165,18 +167,19 @@ BASE_DOMAIN=nostrdeploy.com`);
});
const provider = openai(settings.model);
const toolSet = new FsToolSet(browserFS, `/projects/${projectId}`);
return generateText({
model: provider,
messages,
maxSteps: 100,
onStepFinish(stepResult) {
console.log(stepResult);
addMessages(stepResult.response.messages);
},
tools: {
readFile: toolSet.readFile,
writeFile: toolSet.writeFile,
text_editor_view: new TextEditorViewTool(browserFS, `/projects/${projectId}`),
text_editor_write: new TextEditorWriteTool(browserFS, `/projects/${projectId}`),
text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, `/projects/${projectId}`),
},
system: `You are an AI assistant helping users build custom Nostr websites. You have access to tools that allow you to read, write, and manage files in the project, as well as build the project.
@@ -332,7 +335,6 @@ When creating new components or pages, follow the existing patterns in the codeb
key={index}
message={message}
userDisplayName="You"
allMessages={messages}
/>
))}
+20 -104
View File
@@ -9,34 +9,13 @@ import { FileViewer } from '@/components/ai/FileViewer';
import { FileWriter } from '@/components/ai/FileWriter';
import { ShellCommand } from '@/components/ai/ShellCommand';
import { PackageManager } from '@/components/ai/PackageManager';
import type { CoreAssistantMessage, CoreToolMessage } from 'ai';
import type { CoreAssistantMessage } from 'ai';
interface AssistantContentProps {
content: CoreAssistantMessage['content'];
allMessages?: unknown[];
}
export const AssistantContent = memo(({ content, allMessages = [] }: AssistantContentProps) => {
// Helper function to find tool result for a given tool call
const findToolResult = (toolCallId: string) => {
// Look through all tool messages to find the one with our toolCallId
for (const msg of allMessages) {
if ((msg as { role: string }).role === 'tool') {
const toolMessage = msg as CoreToolMessage;
if (Array.isArray(toolMessage.content)) {
const toolResultPart = toolMessage.content.find(
part => part.type === 'tool-result' && part.toolCallId === toolCallId
);
if (toolResultPart) {
return toolResultPart;
}
}
}
}
return undefined;
};
export const AssistantContent = memo(({ content }: AssistantContentProps) => {
// Handle string content (simple text messages)
if (typeof content === 'string') {
return (
@@ -136,8 +115,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
</div>
);
} else if (item.type === 'tool-call') {
// Special rendering for js-dev__text_editor_str_replace tool
if (item.toolName === 'js-dev__text_editor_str_replace' && item.args) {
// Special rendering for text_editor_str_replace tool
if (item.toolName === 'text_editor_str_replace' && item.args) {
const { path, old_str, new_str } = item.args as { path: string; old_str: string; new_str: string };
return (
<DiffRenderer
@@ -149,8 +128,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
);
}
// Special rendering for js-dev__run_script tool
if (item.toolName === 'js-dev__run_script' && item.args) {
// Special rendering for run_script tool
if (item.toolName === 'run_script' && item.args) {
const { script } = item.args as { script: string };
return (
<ScriptRunner
@@ -160,71 +139,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
);
}
// Special rendering for readFile tool
if (item.toolName === 'readFile' && item.args) {
const { filePath } = item.args as { filePath: string };
const toolResultPart = findToolResult(item.toolCallId);
let result: string | undefined;
const isError = toolResultPart?.isError || false;
if (toolResultPart && toolResultPart.result) {
if (typeof toolResultPart.result === 'string') {
result = toolResultPart.result;
} else if (toolResultPart.result && typeof toolResultPart.result === 'object') {
// Handle FsToolSet readFile result format: { content, success }
const resultObj = toolResultPart.result as Record<string, unknown>;
if (resultObj.content && typeof resultObj.content === 'string') {
result = resultObj.content;
} else {
result = JSON.stringify(toolResultPart.result);
}
}
}
return (
<FileViewer
key={index}
path={filePath}
result={result}
isError={isError}
/>
);
}
// Special rendering for writeFile tool
if (item.toolName === 'writeFile' && item.args) {
const { filePath, content } = item.args as { filePath: string; content: string };
const toolResultPart = findToolResult(item.toolCallId);
let result: string | undefined;
const isError = toolResultPart?.isError || false;
if (toolResultPart && toolResultPart.result) {
if (typeof toolResultPart.result === 'string') {
result = toolResultPart.result;
} else if (toolResultPart.result && typeof toolResultPart.result === 'object') {
// Handle FsToolSet writeFile result format: { success, message }
const resultObj = toolResultPart.result as Record<string, unknown>;
if (resultObj.message && typeof resultObj.message === 'string') {
result = resultObj.message;
} else {
result = JSON.stringify(toolResultPart.result);
}
}
}
return (
<FileWriter
key={index}
path={filePath}
fileText={content}
result={result}
isError={isError}
/>
);
}
// Special rendering for js-dev__text_editor_view tool
if (item.toolName === 'js-dev__text_editor_view' && item.args) {
// Special rendering for text_editor_view tool
if (item.toolName === 'text_editor_view' && item.args) {
const { path } = item.args as { path: string };
return (
<FileViewer
@@ -234,8 +150,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
);
}
// Special rendering for js-dev__text_editor_write tool
if (item.toolName === 'js-dev__text_editor_write' && item.args) {
// Special rendering for text_editor_write tool
if (item.toolName === 'text_editor_write' && item.args) {
const { path, file_text } = item.args as { path: string; file_text: string };
return (
<FileWriter
@@ -246,8 +162,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
);
}
// Special rendering for js-dev__shell tool
if (item.toolName === 'js-dev__shell' && item.args) {
// Special rendering for shell tool
if (item.toolName === 'shell' && item.args) {
const { command } = item.args as { command: string };
return (
<ShellCommand
@@ -257,8 +173,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
);
}
// Special rendering for js-dev__npm_add_package tool
if (item.toolName === 'js-dev__npm_add_package' && item.args) {
// Special rendering for npm_add_package tool
if (item.toolName === 'npm_add_package' && item.args) {
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
return (
<PackageManager
@@ -272,8 +188,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
);
}
// Special rendering for js-dev__npm_remove_package tool
if (item.toolName === 'js-dev__npm_remove_package' && item.args) {
// Special rendering for npm_remove_package tool
if (item.toolName === 'npm_remove_package' && item.args) {
const { name } = item.args as { name: string };
return (
<PackageManager
@@ -285,8 +201,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
);
}
// Special rendering for js-dev__jsr_add_package tool
if (item.toolName === 'js-dev__jsr_add_package' && item.args) {
// Special rendering for jsr_add_package tool
if (item.toolName === 'jsr_add_package' && item.args) {
const { name, version, dev } = item.args as { name: string; version?: string; dev?: boolean };
return (
<PackageManager
@@ -300,8 +216,8 @@ export const AssistantContent = memo(({ content, allMessages = [] }: AssistantCo
);
}
// Special rendering for js-dev__jsr_remove_package tool
if (item.toolName === 'js-dev__jsr_remove_package' && item.args) {
// Special rendering for jsr_remove_package tool
if (item.toolName === 'jsr_remove_package' && item.args) {
const { name } = item.args as { name: string };
return (
<PackageManager
+1 -4
View File
@@ -8,14 +8,12 @@ interface MessageItemProps {
message: (CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string };
userDisplayName?: string;
userProfileImage?: string;
allMessages?: ((CoreUserMessage | CoreAssistantMessage | CoreToolMessage) & { id: string })[];
}
export const MessageItem = memo(({
message,
userDisplayName = 'You',
userProfileImage,
allMessages = []
userProfileImage
}: MessageItemProps) => {
// Don't render tool messages as separate items - they're integrated into assistant messages
if (message.role === 'tool') {
@@ -62,7 +60,6 @@ export const MessageItem = memo(({
) : message.role === 'assistant' ? (
<AssistantContent
content={(message as CoreAssistantMessage).content}
allMessages={allMessages}
/>
) : null}
</div>
-220
View File
@@ -1,220 +0,0 @@
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { join } from "@std/path/posix/join";
import { dirname } from "@std/path/posix/dirname";
import { relative } from "@std/path/posix/relative";
import { resolve } from "@std/path/posix/resolve";
import { tool } from "ai";
import z from 'zod';
export class FsToolSet {
constructor(readonly fs: JSRuntimeFS, private cwd?: string) {}
readonly readFile = tool({
description: 'Read the contents of a file in the project',
parameters: FsToolSet.readFileSchema,
execute: async (args) => {
const filepath = this.resolvePath(args.filePath);
try {
const content = await this.fs.readFile(filepath, 'utf8');
return { content, success: true };
} catch (error) {
throw new Error(`Failed to read file ${args.filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
},
});
readonly writeFile = tool({
description: 'Write content to a file in the project',
parameters: FsToolSet.writeFileSchema,
execute: async (args) => {
const filepath = this.resolvePath(args.filePath);
try {
// Ensure directory exists
const dir = dirname(filepath);
await this.ensureDirectory(dir);
await this.fs.writeFile(filepath, args.content, 'utf8');
return { success: true, message: `File ${args.filePath} written successfully` };
} catch (error) {
throw new Error(`Failed to write file ${args.filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
},
});
readonly listDirectory = tool({
description: 'List contents of a directory',
parameters: FsToolSet.listDirectorySchema,
execute: async (args) => {
const dirpath = this.resolvePath(args.directoryPath || '.');
try {
const items = await this.fs.readdir(dirpath);
const details = await Promise.all(
items.map(async (item) => {
const itemPath = join(dirpath, item);
const stat = await this.fs.stat(itemPath);
return {
name: item,
type: stat.isDirectory() ? 'directory' : 'file',
size: stat.size,
modified: stat.mtimeMs,
path: relative(this.cwd || '/', itemPath),
};
})
);
return { items: details, success: true };
} catch (error) {
throw new Error(`Failed to list directory ${args.directoryPath}: ${error instanceof Error ? error.message : String(error)}`);
}
},
});
readonly createDirectory = tool({
description: 'Create a directory (and any necessary parent directories)',
parameters: FsToolSet.createDirectorySchema,
execute: async (args) => {
const dirpath = this.resolvePath(args.directoryPath);
try {
await this.ensureDirectory(dirpath);
return { success: true, message: `Directory ${args.directoryPath} created successfully` };
} catch (error) {
throw new Error(`Failed to create directory ${args.directoryPath}: ${error instanceof Error ? error.message : String(error)}`);
}
},
});
readonly deleteFile = tool({
description: 'Delete a file',
parameters: FsToolSet.deleteFileSchema,
execute: async (args) => {
const filepath = this.resolvePath(args.filePath);
try {
await this.fs.unlink(filepath);
return { success: true, message: `File ${args.filePath} deleted successfully` };
} catch (error) {
throw new Error(`Failed to delete file ${args.filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
},
});
readonly deleteDirectory = tool({
description: 'Delete a directory and all its contents',
parameters: FsToolSet.deleteDirectorySchema,
execute: async (args) => {
const dirpath = this.resolvePath(args.directoryPath);
try {
await this.fs.rmdir(dirpath);
return { success: true, message: `Directory ${args.directoryPath} deleted successfully` };
} catch (error) {
throw new Error(`Failed to delete directory ${args.directoryPath}: ${error instanceof Error ? error.message : String(error)}`);
}
},
});
readonly moveFile = tool({
description: 'Move or rename a file or directory',
parameters: FsToolSet.moveFileSchema,
execute: async (args) => {
const sourcePath = this.resolvePath(args.sourcePath);
const destPath = this.resolvePath(args.destinationPath);
try {
// Ensure destination directory exists
const destDir = dirname(destPath);
await this.ensureDirectory(destDir);
await this.fs.rename(sourcePath, destPath);
return { success: true, message: `Moved ${args.sourcePath} to ${args.destinationPath}` };
} catch (error) {
throw new Error(`Failed to move ${args.sourcePath} to ${args.destinationPath}: ${error instanceof Error ? error.message : String(error)}`);
}
},
});
readonly copyFile = tool({
description: 'Copy a file from source to destination',
parameters: FsToolSet.copyFileSchema,
execute: async (args) => {
const sourcePath = this.resolvePath(args.sourcePath);
const destPath = this.resolvePath(args.destinationPath);
try {
// Ensure destination directory exists
const destDir = dirname(destPath);
await this.ensureDirectory(destDir);
const content = await this.fs.readFile(sourcePath);
await this.fs.writeFile(destPath, content);
return { success: true, message: `Copied ${args.sourcePath} to ${args.destinationPath}` };
} catch (error) {
throw new Error(`Failed to copy ${args.sourcePath} to ${args.destinationPath}: ${error instanceof Error ? error.message : String(error)}`);
}
},
});
// Helper methods
private resolvePath(path: string): string {
if (!this.cwd) return path;
return resolve(this.cwd, path);
}
private async ensureDirectory(dirpath: string): Promise<void> {
try {
await this.fs.mkdir(dirpath);
} catch {
// Directory might already exist, ignore
}
}
// Schema definitions
static readFileSchema = z.object({
filePath: z.string().describe('Path to the file to read'),
});
static writeFileSchema = z.object({
filePath: z.string().describe('Path to the file to write'),
content: z.string().describe('Content to write to the file'),
});
static listDirectorySchema = z.object({
directoryPath: z.string().optional().describe('Directory path to list (defaults to current directory)'),
});
static createDirectorySchema = z.object({
directoryPath: z.string().describe('Directory path to create'),
});
static deleteFileSchema = z.object({
filePath: z.string().describe('Path to the file to delete'),
});
static deleteDirectorySchema = z.object({
directoryPath: z.string().describe('Path to the directory to delete'),
});
static moveFileSchema = z.object({
sourcePath: z.string().describe('Current path of the file or directory'),
destinationPath: z.string().describe('New path for the file or directory'),
});
static copyFileSchema = z.object({
sourcePath: z.string().describe('Path to the source file'),
destinationPath: z.string().describe('Path to the destination file'),
});
static fileExistsSchema = z.object({
path: z.string().describe('Path to check for existence'),
});
static getFileInfoSchema = z.object({
path: z.string().describe('Path to get information about'),
});
static readDirectoryRecursiveSchema = z.object({
directoryPath: z.string().optional().describe('Directory path to start from (defaults to current directory)'),
maxDepth: z.number().optional().describe('Maximum depth to traverse (optional)'),
});
static searchFilesSchema = z.object({
pattern: z.string().describe('File name pattern to search for (supports * and ? wildcards)'),
directoryPath: z.string().optional().describe('Directory to search in (defaults to current directory)'),
maxDepth: z.number().optional().describe('Maximum depth to search (optional)'),
});
}
@@ -0,0 +1,159 @@
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<string, string> = new Map();
private dirs: Set<string> = 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<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
return encoding ? content : new TextEncoder().encode(content);
}
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
return [];
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
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<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
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.isError).toBe(false);
expect(result.content[0].text).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 () => {
const result = await tool.execute({
path: 'src/test.ts',
old_str: 'nonexistent string',
new_str: 'replacement'
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('The string to replace was not found in src/test.ts');
});
it('should reject absolute paths with helpful error message', async () => {
const result = await tool.execute({
path: '/absolute/path/test.ts',
old_str: 'old',
new_str: 'new'
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Absolute paths are not supported');
expect(result.content[0].text).toContain('Current working directory: /project');
});
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.isError).toBe(false);
expect(mockFS.getFileContent('/project/src/test.ts')).toContain('const greeting = "hello universe";');
});
});
+204
View File
@@ -0,0 +1,204 @@
import { join } from "@std/path";
import { z } from "zod";
import type { Tool, CallToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface TextEditorStrReplaceParams {
path: string;
old_str: string;
new_str: string;
normalize_whitespace?: boolean;
}
export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams> {
private fs: JSRuntimeFS;
private cwd: string;
readonly description = "Replace a string in a file with a new string";
readonly parameters = 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) {
this.fs = fs;
this.cwd = cwd;
}
async execute(args: TextEditorStrReplaceParams): Promise<CallToolResult> {
const { path, old_str, new_str, normalize_whitespace = true } = args;
// Check for absolute paths and provide helpful error
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
return {
content: [{
type: "text",
text: `❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`,
}],
isError: true,
};
}
// 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)
)
) {
return {
content: [{
type: "text",
text:
`🔒 Direct edits to dependencies in package.json are disallowed.\n👉 Please use npm_add_package or npm_remove_package tools for these changes.`,
}],
isError: true,
};
}
}
try {
const absolutePath = join(this.cwd, path);
const content = await this.fs.readFile(absolutePath, "utf-8");
// 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.`;
}
return {
content: [{
type: "text",
text: errorMessage,
}],
isError: true,
};
}
// 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, "utf-8");
let successMessage = `String successfully replaced in ${path}`;
if (occurrences > 1) {
successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`;
}
return {
content: [{
type: "text",
text: successMessage,
}],
isError: false,
};
} catch (error) {
return {
content: [{
type: "text",
text: String(error),
}],
isError: true,
};
}
}
}
+180
View File
@@ -0,0 +1,180 @@
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<string, string> = new Map();
private dirs: Set<string> = new Set();
constructor() {
// Set up a basic project structure
this.dirs.add('/project');
this.dirs.add('/project/.git');
this.dirs.add('/project/src');
this.dirs.add('/project/node_modules');
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');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
return encoding ? content : new TextEncoder().encode(content);
}
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
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(path + '/')) {
const relativePath = filePath.slice(path.length + 1);
const parts = relativePath.split('/');
if (parts.length === 1) {
entries.push(parts[0]);
}
}
}
for (const dirPath of this.dirs) {
if (dirPath.startsWith(path + '/')) {
const relativePath = dirPath.slice(path.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(`${path}/${name}`),
isFile: () => this.files.has(`${path}/${name}`)
}));
}
return entries;
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
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<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
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 without ignore library errors', async () => {
const result = await tool.execute({ path: '.' });
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('src/');
expect(result.content[0].text).toContain('package.json');
// .git should be filtered out by gitignore, but .gitignore should be present
expect(result.content[0].text).toContain('.gitignore');
expect(result.content[0].text).not.toContain('.git/'); // Check for .git directory specifically
});
it('should handle viewing subdirectory', async () => {
const result = await tool.execute({ path: 'src' });
expect(result.isError).toBe(false);
expect(result.content[0].text).toContain('index.ts');
});
it('should handle viewing a file', async () => {
const result = await tool.execute({ path: 'src/index.ts' });
expect(result.isError).toBe(false);
expect(result.content[0].text).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.isError).toBe(false);
expect(result.content[0].text).toBe('console.log("hello");');
});
});
+267
View File
@@ -0,0 +1,267 @@
import { join } from "@std/path";
import ignore from "ignore";
import { z } from "zod";
import type { Tool, CallToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface TextEditorViewParams {
path: string;
start_line?: number;
end_line?: number;
}
export class TextEditorViewTool implements Tool<TextEditorViewParams> {
private fs: JSRuntimeFS;
private cwd: string;
readonly description = "View the contents of a text file or directory";
readonly parameters = z.object({
path: z.string().describe(
'Path of the file or directory to view, eg "src/index.ts" or "src/"',
),
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) {
this.fs = fs;
this.cwd = cwd;
}
async execute(args: TextEditorViewParams): Promise<CallToolResult> {
const { path, start_line, end_line } = args;
try {
// Check for absolute paths and provide helpful error
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
return {
content: [{
type: "text",
text: `❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`,
}],
isError: true,
};
}
const absolutePath = join(this.cwd, path);
// Check if the path is a directory
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
// 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);
return {
content: [{
type: "text",
text: tree,
}],
isError: false,
};
}
// If it's a file, read and return its contents
let content = await this.fs.readFile(absolutePath, "utf-8");
// 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) {
return {
content: [{
type: "text",
text: "Error: start_line must be >= 1",
}],
isError: true,
};
}
if (end_line !== undefined && end_line < 1) {
return {
content: [{
type: "text",
text: "Error: end_line must be >= 1",
}],
isError: true,
};
}
if (start_line !== undefined && end_line !== undefined && start_line > end_line) {
return {
content: [{
type: "text",
text: "Error: start_line cannot be greater than end_line",
}],
isError: true,
};
}
if (start_line !== undefined && start_line > lines.length) {
return {
content: [{
type: "text",
text: `Error: start_line ${start_line} is beyond the end of the file (${lines.length} lines)`,
}],
isError: true,
};
}
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: [{
type: "text",
text: content,
}],
isError: false,
};
} catch (error) {
return {
content: [{
type: "text",
text: String(error),
}],
isError: true,
};
}
}
/**
* Generate a tree-like directory listing
*/
private async generateDirectoryTree(
dirPath: string,
prefix: string = "",
maxDepth: number = 3,
currentDepth: number = 0,
ignoreFilter?: (path: string) => boolean,
): Promise<string> {
if (currentDepth >= maxDepth) {
return prefix + "...\n";
}
// Create ignore filter on first call (root level)
if (!ignoreFilter) {
ignoreFilter = await this.createIgnoreFilter();
}
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
// Filter entries using gitignore patterns
const filteredEntries = entries.filter((entry) => {
// Calculate relative path from the project root (cwd)
const fullEntryPath = join(dirPath, entry.name);
const entryPath = this.makeRelativeToCwd(fullEntryPath);
return ignoreFilter!(entryPath);
});
// Sort entries: directories first, then files, both alphabetically
filteredEntries.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 < filteredEntries.length; i++) {
const entry = filteredEntries[i]!;
const isLastEntry = i === filteredEntries.length - 1;
const connector = isLastEntry ? "└── " : "├── ";
const nextPrefix = prefix + (isLastEntry ? " " : "│ ");
if (entry.isDirectory()) {
result += prefix + connector + entry.name + "/\n";
const subPath = join(dirPath, entry.name);
result += await this.generateDirectoryTree(
subPath,
nextPrefix,
maxDepth,
currentDepth + 1,
ignoreFilter,
);
} else {
result += prefix + connector + entry.name + "\n";
}
}
return result;
} catch (error) {
return prefix + `[Error reading directory: ${error}]\n`;
}
}
/**
* Create an ignore filter based on .gitignore files
*/
private async createIgnoreFilter(): Promise<(path: string) => boolean> {
const ig = ignore();
// Always ignore .git directory
ig.add(".git");
// Default ignore patterns if no .gitignore is found
const defaultIgnorePatterns = [
"node_modules",
"dist",
"build",
".next",
".tmp",
];
try {
// Try to read .gitignore file
const gitignoreContent = await this.fs.readFile(".gitignore", "utf-8");
ig.add(gitignoreContent);
} catch {
// If there's an error reading .gitignore, fall back to defaults
ig.add(defaultIgnorePatterns);
}
return (path: string) => !ig.ignores(path);
}
/**
* Convert an absolute path to a relative path from the current working directory
*/
private makeRelativeToCwd(absolutePath: string): string {
// Handle relative paths that start with "./"
if (absolutePath.startsWith('./')) {
return absolutePath.slice(2); // Remove "./" prefix
}
// Handle the current directory case
if (absolutePath === '.') {
return '.';
}
// If the path starts with the cwd, remove the cwd prefix
if (absolutePath.startsWith(this.cwd)) {
let relativePath = absolutePath.slice(this.cwd.length);
// Remove leading slash if present
if (relativePath.startsWith('/')) {
relativePath = relativePath.slice(1);
}
// Return '.' for empty path (current directory)
return relativePath || '.';
}
// If it doesn't start with cwd, just return the path as-is
// This handles cases where we might have relative paths already
return absolutePath;
}
};
+148
View File
@@ -0,0 +1,148 @@
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<string, string> = new Map();
private dirs: Set<string> = new Set();
constructor() {
this.dirs.add('/project');
this.dirs.add('/project/src');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, encoding: 'utf8'): Promise<string>;
async readFile(path: string, encoding: string): Promise<string>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
return encoding ? content : new TextEncoder().encode(content);
}
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
return [];
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
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<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
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.isError).toBe(false);
expect(result.content[0].text).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 with helpful error message', async () => {
const result = await tool.execute({
path: '/absolute/path/test.ts',
file_text: 'test content'
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('❌ Absolute paths are not supported');
expect(result.content[0].text).toContain('Current working directory: /project');
});
it('should reject package.json writes', async () => {
const result = await tool.execute({
path: 'package.json',
file_text: '{"name": "test"}'
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('🔒 Direct writes to package.json are disallowed');
});
});
+92
View File
@@ -0,0 +1,92 @@
import { join } from "@std/path";
import { z } from "zod";
import type { Tool, CallToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
// Simple dirname implementation that works in browser environments
function dirname(path: string): string {
if (path === '' || path === '.') return '.';
// Handle Windows and Unix paths
const lastSlash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
if (lastSlash === -1) return '.';
if (lastSlash === 0) return '/';
return path.slice(0, lastSlash);
}
interface TextEditorWriteParams {
path: string;
file_text: string;
}
export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
private fs: JSRuntimeFS;
private cwd: string;
readonly description = "Create or overwrite a file with new content";
readonly parameters = 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) {
this.fs = fs;
this.cwd = cwd;
}
async execute(args: TextEditorWriteParams): Promise<CallToolResult> {
const { path, file_text } = args;
// Check for absolute paths and provide helpful error
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
return {
content: [{
type: "text",
text: `❌ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\n💡 Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`,
}],
isError: true,
};
}
if (
path === "package.json" || path.endsWith("/package.json") ||
path.endsWith("\\package.json")
) {
return {
content: [{
type: "text",
text:
`🔒 Direct writes to package.json are disallowed.\n👉 Please use \`npm_add_package\` or \`npm_remove_package\` tools instead.`,
}],
isError: true,
};
}
try {
const absolutePath = join(this.cwd, path);
await this.fs.mkdir(dirname(absolutePath), { recursive: true });
await this.fs.writeFile(absolutePath, file_text, "utf-8");
return {
content: [{
type: "text",
text: `File successfully written to ${path}`,
}],
isError: false,
};
} catch (error) {
return {
content: [{
type: "text",
text: String(error),
}],
isError: true,
};
}
}
}
+12
View File
@@ -0,0 +1,12 @@
import type z from "zod";
export interface Tool<TParams> {
description: string;
parameters: z.ZodType<TParams>;
execute(args: TParams): Promise<CallToolResult>;
}
export interface CallToolResult {
content: { type: "text"; text: string; }[];
isError?: boolean;
}