mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Add text_editor tools
This commit is contained in:
11 files changed
+1090
-333
No files matched your search
@@ -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";');
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user