commit
1630ead25c
18 changed files with 1184 additions and 118 deletions
43
src/permissions/defaultPolicies.test.ts
Normal file
43
src/permissions/defaultPolicies.test.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
||||
|
||||
describe("defaultPolicies", () => {
|
||||
it("should have correct permissions for read-only tools", () => {
|
||||
const readOnlyTools = ["Read", "List", "Search", "Fetch", "Exit", "Diff", "Checklist"];
|
||||
|
||||
for (const tool of readOnlyTools) {
|
||||
const policy = DEFAULT_TOOL_POLICIES.find(p => p.tool === tool);
|
||||
expect(policy, `Policy should exist for ${tool}`).toBeDefined();
|
||||
expect(policy?.permission, `${tool} should be allowed`).toBe("allow");
|
||||
}
|
||||
});
|
||||
|
||||
it("should have correct permissions for write tools", () => {
|
||||
const writeTools = ["Write", "Edit", "MultiEdit", "Bash"];
|
||||
|
||||
for (const tool of writeTools) {
|
||||
const policy = DEFAULT_TOOL_POLICIES.find(p => p.tool === tool);
|
||||
expect(policy, `Policy should exist for ${tool}`).toBeDefined();
|
||||
expect(policy?.permission, `${tool} should require confirmation`).toBe("ask");
|
||||
}
|
||||
});
|
||||
|
||||
it("should have a catch-all policy", () => {
|
||||
const catchAllPolicy = DEFAULT_TOOL_POLICIES.find(p => p.tool === "*");
|
||||
expect(catchAllPolicy).toBeDefined();
|
||||
expect(catchAllPolicy?.permission).toBe("ask");
|
||||
});
|
||||
|
||||
it("should include MultiEdit policy", () => {
|
||||
const multiEditPolicy = DEFAULT_TOOL_POLICIES.find(p => p.tool === "MultiEdit");
|
||||
expect(multiEditPolicy).toBeDefined();
|
||||
expect(multiEditPolicy?.permission).toBe("ask");
|
||||
});
|
||||
|
||||
it("should have policies in correct order", () => {
|
||||
// The catch-all policy should be last
|
||||
const catchAllIndex = DEFAULT_TOOL_POLICIES.findIndex(p => p.tool === "*");
|
||||
expect(catchAllIndex).toBe(DEFAULT_TOOL_POLICIES.length - 1);
|
||||
});
|
||||
});
|
||||
|
|
@ -14,6 +14,7 @@ export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [
|
|||
// Write operations should require confirmation
|
||||
{ tool: "Write", permission: "ask" },
|
||||
{ tool: "Edit", permission: "ask" },
|
||||
{ tool: "MultiEdit", permission: "ask" },
|
||||
|
||||
// Write to a checklist
|
||||
{ tool: "Checklist", permission: "allow" },
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ describe("permissionsYamlLoader", () => {
|
|||
]);
|
||||
});
|
||||
|
||||
it("should normalize tool names", () => {
|
||||
it("should use exact tool names without normalization", () => {
|
||||
const config = {
|
||||
allow: ["read", "READ", "Read"],
|
||||
};
|
||||
|
|
@ -27,8 +27,8 @@ describe("permissionsYamlLoader", () => {
|
|||
const policies = yamlConfigToPolicies(config);
|
||||
|
||||
expect(policies).toEqual([
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "read", permission: "allow" },
|
||||
{ tool: "READ", permission: "allow" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
|
|
@ -79,7 +79,7 @@ describe("permissionsYamlLoader", () => {
|
|||
{ tool: "Fetch", permission: "exclude" },
|
||||
{ tool: "Exit", permission: "exclude" },
|
||||
{ tool: "Write", permission: "ask" },
|
||||
{ tool: "Bash", permission: "ask" },
|
||||
{ tool: "Terminal", permission: "ask" },
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "List", permission: "allow" },
|
||||
]);
|
||||
|
|
@ -183,14 +183,14 @@ describe("permissionsYamlLoader", () => {
|
|||
expect(() => parseToolPattern("Write(unclosed", "allow")).toThrow("Invalid tool pattern: Write(unclosed");
|
||||
});
|
||||
|
||||
it("should normalize tool names in patterns", () => {
|
||||
it("should use exact tool names in patterns", () => {
|
||||
const policy = parseToolPattern("write(**/*.ts)", "allow");
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "Write",
|
||||
tool: "write",
|
||||
permission: "allow",
|
||||
argumentMatches: {
|
||||
file_path: "**/*.ts"
|
||||
pattern: "**/*.ts"
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,12 +1,11 @@
|
|||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import * as yaml from "yaml";
|
||||
import YAML from "yaml";
|
||||
|
||||
import { env } from "../env.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { normalizeToolName } from "./toolNameMapping.js";
|
||||
import { PermissionPolicy, ToolPermissionPolicy } from "./types.js";
|
||||
|
||||
export const PERMISSIONS_YAML_PATH = path.resolve(
|
||||
|
|
@ -33,7 +32,7 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null {
|
|||
}
|
||||
|
||||
const content = fs.readFileSync(PERMISSIONS_YAML_PATH, "utf-8");
|
||||
const parsed = yaml.parse(content) as PermissionsYamlConfig;
|
||||
const parsed = YAML.parse(content) as PermissionsYamlConfig;
|
||||
|
||||
// Validate the structure
|
||||
if (parsed && typeof parsed === "object") {
|
||||
|
|
@ -85,7 +84,7 @@ export function parseToolPattern(
|
|||
}
|
||||
|
||||
const [, toolName, args] = match;
|
||||
const normalizedName = normalizeToolName(toolName.trim());
|
||||
const normalizedName = toolName.trim();
|
||||
|
||||
const policy: ToolPermissionPolicy = {
|
||||
tool: normalizedName,
|
||||
|
|
|
|||
|
|
@ -28,11 +28,11 @@ describe("policyWriter", () => {
|
|||
expect(generatePolicyRule("Bash", { command: " " })).toBe("Bash");
|
||||
});
|
||||
|
||||
it("should handle tool name normalization", () => {
|
||||
expect(generatePolicyRule("bash", { command: "ls" })).toBe("Bash(ls*)");
|
||||
expect(generatePolicyRule("BASH", { command: "pwd" })).toBe("Bash(pwd*)");
|
||||
expect(generatePolicyRule("read", { file_path: "/test" })).toBe("Read");
|
||||
expect(generatePolicyRule("write", { file_path: "/test", content: "test" })).toBe("Write");
|
||||
it("should use exact tool names without normalization", () => {
|
||||
expect(generatePolicyRule("bash", { command: "ls" })).toBe("bash");
|
||||
expect(generatePolicyRule("BASH", { command: "pwd" })).toBe("BASH");
|
||||
expect(generatePolicyRule("read", { file_path: "/test" })).toBe("read");
|
||||
expect(generatePolicyRule("write", { file_path: "/test", content: "test" })).toBe("write");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import * as fs from "fs";
|
||||
import fs from "fs";
|
||||
|
||||
import * as yaml from "yaml";
|
||||
import YAML from "yaml";
|
||||
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
|
|
@ -9,7 +9,6 @@ import {
|
|||
PermissionsYamlConfig,
|
||||
loadPermissionsYaml,
|
||||
} from "./permissionsYamlLoader.js";
|
||||
import { normalizeToolName, getDisplayName } from "./toolNameMapping.js";
|
||||
|
||||
/**
|
||||
* Generates a policy rule for a given tool call
|
||||
|
|
@ -17,7 +16,7 @@ import { normalizeToolName, getDisplayName } from "./toolNameMapping.js";
|
|||
* For Bash tool, generates command-specific patterns like "Bash(ls*)"
|
||||
*/
|
||||
export function generatePolicyRule(toolName: string, toolArgs: any): string {
|
||||
const normalizedName = normalizeToolName(toolName);
|
||||
const normalizedName = toolName;
|
||||
|
||||
// For Bash tool, create command-specific policies
|
||||
if (normalizedName === "Bash" && toolArgs?.command) {
|
||||
|
|
@ -32,7 +31,7 @@ export function generatePolicyRule(toolName: string, toolArgs: any): string {
|
|||
}
|
||||
|
||||
// For all other tools, return the display name
|
||||
return getDisplayName(normalizedName);
|
||||
return normalizedName;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -53,7 +52,7 @@ export async function addPolicyToYaml(policyRule: string): Promise<void> {
|
|||
config.allow.push(policyRule);
|
||||
|
||||
// Write the updated config back to the file
|
||||
const yamlContent = yaml.stringify(config);
|
||||
const yamlContent = YAML.stringify(config);
|
||||
|
||||
// Add header comment
|
||||
const finalContent = `# Continue CLI Permissions Configuration
|
||||
|
|
|
|||
|
|
@ -15,9 +15,9 @@ describe("policyWriter verification", () => {
|
|||
expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe("Bash(ls*)");
|
||||
});
|
||||
|
||||
it("should handle mixed case tool names", () => {
|
||||
expect(generatePolicyRule("edit", { filepath: "test.txt" })).toBe("Edit");
|
||||
expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("Edit");
|
||||
it("should use exact tool names without case normalization", () => {
|
||||
expect(generatePolicyRule("edit", { filepath: "test.txt" })).toBe("edit");
|
||||
expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("EDIT");
|
||||
expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit");
|
||||
});
|
||||
});
|
||||
|
|
@ -44,7 +44,7 @@ describe("precedenceResolver", () => {
|
|||
]);
|
||||
});
|
||||
|
||||
it("should normalize tool names in command line flags", () => {
|
||||
it("should use exact tool names from command line flags", () => {
|
||||
const policies = resolvePermissionPrecedence({
|
||||
commandLineFlags: {
|
||||
allow: ["Read", "write", "BASH"],
|
||||
|
|
@ -55,8 +55,8 @@ describe("precedenceResolver", () => {
|
|||
|
||||
expect(policies).toEqual([
|
||||
{ tool: "Read", permission: "allow" },
|
||||
{ tool: "Write", permission: "allow" },
|
||||
{ tool: "Bash", permission: "allow" },
|
||||
{ tool: "write", permission: "allow" },
|
||||
{ tool: "BASH", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -5,8 +5,7 @@ import {
|
|||
loadPermissionsYaml,
|
||||
yamlConfigToPolicies,
|
||||
} from "./permissionsYamlLoader.js";
|
||||
import { normalizeToolName } from "./toolNameMapping.js";
|
||||
import { ToolPermissionPolicy } from "./types.js";
|
||||
import { type ToolPermissionPolicy } from "./types.js";
|
||||
|
||||
export interface PermissionSources {
|
||||
/** Command line flags - highest precedence */
|
||||
|
|
@ -107,21 +106,21 @@ function commandLineFlagsToPolicies(flags: {
|
|||
// Order matters for CLI flags too
|
||||
if (flags.exclude) {
|
||||
for (const tool of flags.exclude) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
const normalizedName = tool;
|
||||
policies.push({ tool: normalizedName, permission: "exclude" });
|
||||
}
|
||||
}
|
||||
|
||||
if (flags.ask) {
|
||||
for (const tool of flags.ask) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
const normalizedName = tool;
|
||||
policies.push({ tool: normalizedName, permission: "ask" });
|
||||
}
|
||||
}
|
||||
|
||||
if (flags.allow) {
|
||||
for (const tool of flags.allow) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
const normalizedName = tool;
|
||||
policies.push({ tool: normalizedName, permission: "allow" });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@
|
|||
* This ensures they're available immediately, before services are initialized
|
||||
*/
|
||||
|
||||
import { normalizeToolName } from "./toolNameMapping.js";
|
||||
import { ToolPermissionPolicy } from "./types.js";
|
||||
|
||||
let runtimeOverrides: ToolPermissionPolicy[] | null = null;
|
||||
|
|
@ -23,21 +22,21 @@ export function setRuntimePermissionOverrides(overrides: {
|
|||
// Convert runtime overrides to policies
|
||||
if (overrides.exclude) {
|
||||
for (const tool of overrides.exclude) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
const normalizedName = tool;
|
||||
policies.push({ tool: normalizedName, permission: "exclude" });
|
||||
}
|
||||
}
|
||||
|
||||
if (overrides.ask) {
|
||||
for (const tool of overrides.ask) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
const normalizedName = tool;
|
||||
policies.push({ tool: normalizedName, permission: "ask" });
|
||||
}
|
||||
}
|
||||
|
||||
if (overrides.allow) {
|
||||
for (const tool of overrides.allow) {
|
||||
const normalizedName = normalizeToolName(tool);
|
||||
const normalizedName = tool;
|
||||
policies.push({ tool: normalizedName, permission: "allow" });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,63 +0,0 @@
|
|||
/**
|
||||
* Maps common variations to standardized tool names
|
||||
*/
|
||||
const TOOL_NAME_MAPPINGS: Record<string, string> = {
|
||||
// Standard tool names (passthrough)
|
||||
Read: "Read",
|
||||
Write: "Write",
|
||||
List: "List",
|
||||
Search: "Search",
|
||||
Bash: "Bash",
|
||||
Fetch: "Fetch",
|
||||
Exit: "Exit",
|
||||
Diff: "Diff",
|
||||
Edit: "Edit",
|
||||
Checklist: "Checklist",
|
||||
|
||||
// Common variations (case insensitive)
|
||||
read: "Read",
|
||||
write: "Write",
|
||||
list: "List",
|
||||
search: "Search",
|
||||
bash: "Bash",
|
||||
terminal: "Bash",
|
||||
Terminal: "Bash",
|
||||
cmd: "Bash",
|
||||
command: "Bash",
|
||||
fetch: "Fetch",
|
||||
exit: "Exit",
|
||||
diff: "Diff",
|
||||
edit: "Edit",
|
||||
checklist: "Checklist",
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes a tool name from various formats (variations, legacy names) to the standardized tool name
|
||||
*/
|
||||
export function normalizeToolName(input: string): string {
|
||||
// First try exact match (case sensitive)
|
||||
if (TOOL_NAME_MAPPINGS[input]) {
|
||||
return TOOL_NAME_MAPPINGS[input];
|
||||
}
|
||||
|
||||
// Try case insensitive match
|
||||
const lowerInput = input.toLowerCase();
|
||||
for (const [key, value] of Object.entries(TOOL_NAME_MAPPINGS)) {
|
||||
if (key.toLowerCase() === lowerInput) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// If no mapping found, return as-is (might be an MCP tool or future tool)
|
||||
return input;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the display name for a tool name
|
||||
* Since we now use display names as the primary names, this mostly returns the input
|
||||
* but handles any remaining edge cases
|
||||
*/
|
||||
export function getDisplayName(toolName: string): string {
|
||||
// Simply normalize and return - the tool name is already the display name
|
||||
return normalizeToolName(toolName);
|
||||
}
|
||||
|
|
@ -62,20 +62,12 @@ exclude: []`;
|
|||
expect(result3.permission).toBe('ask'); // Should not match, falls back to ask
|
||||
});
|
||||
|
||||
it('should check what normalizeToolName returns for Edit variations', async () => {
|
||||
const { normalizeToolName } = await import('./toolNameMapping.js');
|
||||
it('should use exact tool names without normalization', () => {
|
||||
// Tools are now used exactly as they are named, no normalization
|
||||
const editName = "Edit";
|
||||
const multiEditName = "MultiEdit";
|
||||
|
||||
console.log('normalizeToolName("Edit"):', normalizeToolName("Edit"));
|
||||
console.log('normalizeToolName("edit"):', normalizeToolName("edit"));
|
||||
console.log('normalizeToolName("edit_file"):', normalizeToolName("edit_file"));
|
||||
console.log('normalizeToolName("search_and_replace_in_file"):', normalizeToolName("search_and_replace_in_file"));
|
||||
|
||||
// Only proper names and case variations should normalize
|
||||
expect(normalizeToolName("Edit")).toBe("Edit");
|
||||
expect(normalizeToolName("edit")).toBe("Edit");
|
||||
|
||||
// Legacy snake_case names should not normalize anymore
|
||||
expect(normalizeToolName("edit_file")).toBe("edit_file");
|
||||
expect(normalizeToolName("search_and_replace_in_file")).toBe("search_and_replace_in_file");
|
||||
expect(editName).toBe("Edit");
|
||||
expect(multiEditName).toBe("MultiEdit");
|
||||
});
|
||||
});
|
||||
208
src/tools/edit.test.ts
Normal file
208
src/tools/edit.test.ts
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
|
||||
import { editTool, markFileAsRead, readFilesSet } from "./edit.js";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("../telemetry/telemetryService.js");
|
||||
vi.mock("../telemetry/utils.js", () => ({
|
||||
calculateLinesOfCodeDiff: vi.fn().mockReturnValue({ added: 1, removed: 0 }),
|
||||
getLanguageFromFilePath: vi.fn().mockReturnValue("javascript"),
|
||||
}));
|
||||
vi.mock("./writeFile.js", () => ({
|
||||
generateDiff: vi.fn().mockReturnValue("mocked diff"),
|
||||
}));
|
||||
vi.mock("fs", async () => {
|
||||
const actual = await vi.importActual("fs");
|
||||
return {
|
||||
...actual,
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
unlinkSync: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("editTool", () => {
|
||||
const testFilePath = "/tmp/test-edit-file.txt";
|
||||
const originalContent = "Hello world\nThis is a test file\nGoodbye world";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Mock fs functions to simulate file operations
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
|
||||
vi.mocked(fs.writeFileSync).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
readFilesSet.clear();
|
||||
});
|
||||
|
||||
describe("preprocess", () => {
|
||||
it("should throw error if file has not been read", async () => {
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi there",
|
||||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
`You must use the Read tool to read ${testFilePath} before editing it.`
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if file does not exist", async () => {
|
||||
const nonExistentFile = "/tmp/non-existent-file.txt";
|
||||
markFileAsRead(nonExistentFile);
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
|
||||
const args = {
|
||||
file_path: nonExistentFile,
|
||||
old_string: "Hello",
|
||||
new_string: "Hi",
|
||||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
`File ${nonExistentFile} does not exist`
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if old_string is not found", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
vi.mocked(fs.readFileSync).mockReturnValue("Different content");
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
old_string: "Not found",
|
||||
new_string: "Hi there",
|
||||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
"String not found in file: Not found"
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if old_string appears multiple times and replace_all is false", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
old_string: "world",
|
||||
new_string: "universe",
|
||||
replace_all: false,
|
||||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.'
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if old_string and new_string are the same", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
old_string: "Hello world",
|
||||
new_string: "Hello world",
|
||||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
"old_string and new_string must be different"
|
||||
);
|
||||
});
|
||||
|
||||
it("should successfully preprocess valid single replacement", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi there",
|
||||
};
|
||||
|
||||
const result = await editTool.preprocess!(args);
|
||||
|
||||
expect(result.args).toEqual({
|
||||
file_path: testFilePath,
|
||||
newContent: "Hi there\nThis is a test file\nGoodbye world",
|
||||
oldContent: originalContent,
|
||||
});
|
||||
expect(result.preview).toHaveLength(2);
|
||||
expect(result.preview?.[0]).toEqual({
|
||||
type: "text",
|
||||
content: "Will make the following changes:",
|
||||
});
|
||||
expect(result.preview?.[1]).toEqual({
|
||||
type: "diff",
|
||||
content: "mocked diff",
|
||||
});
|
||||
});
|
||||
|
||||
it("should successfully preprocess replace_all", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
old_string: "world",
|
||||
new_string: "universe",
|
||||
replace_all: true,
|
||||
};
|
||||
|
||||
const result = await editTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"Hello universe\nThis is a test file\nGoodbye universe"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("run", () => {
|
||||
it("should successfully write file and return success message", async () => {
|
||||
const newContent = "Hi there\nThis is a test file\nGoodbye world";
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
newContent,
|
||||
oldContent: originalContent,
|
||||
};
|
||||
|
||||
const result = await editTool.run(args);
|
||||
|
||||
expect(result).toBe(`Successfully edited ${testFilePath}`);
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8");
|
||||
});
|
||||
|
||||
it("should throw error if file write fails", async () => {
|
||||
vi.mocked(fs.writeFileSync).mockImplementation(() => {
|
||||
throw new Error("Write failed");
|
||||
});
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
newContent: "new content",
|
||||
oldContent: originalContent,
|
||||
};
|
||||
|
||||
await expect(editTool.run(args)).rejects.toThrow(
|
||||
`Error: failed to edit ${testFilePath}: Write failed`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("markFileAsRead", () => {
|
||||
it("should allow editing after marking file as read", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi there",
|
||||
};
|
||||
|
||||
const result = await editTool.preprocess!(args);
|
||||
expect(result.args.newContent).toContain("Hi there");
|
||||
});
|
||||
});
|
||||
});
|
||||
195
src/tools/edit.ts
Normal file
195
src/tools/edit.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import {
|
||||
calculateLinesOfCodeDiff,
|
||||
getLanguageFromFilePath,
|
||||
} from "../telemetry/utils.js";
|
||||
|
||||
import { Tool } from "./types.js";
|
||||
import { generateDiff } from "./writeFile.js";
|
||||
|
||||
export interface EditArgs {
|
||||
file_path: string;
|
||||
old_string: string;
|
||||
new_string: string;
|
||||
replace_all?: boolean;
|
||||
}
|
||||
|
||||
// Track files that have been read in the current session
|
||||
export const readFilesSet = new Set<string>();
|
||||
|
||||
export const editTool: Tool = {
|
||||
name: "Edit",
|
||||
displayName: "Edit",
|
||||
readonly: false,
|
||||
isBuiltIn: true,
|
||||
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 old_string or new_string.
|
||||
|
||||
- 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 \`old_string\` is not unique in the file. Either provide
|
||||
a larger string with more surrounding context to make it unique or use
|
||||
\`replace_all\` to change every instance of \`old_string\`.
|
||||
|
||||
- Use \`replace_all\` for replacing and renaming strings across the file. This
|
||||
parameter is useful if you want to rename a variable for instance.`,
|
||||
parameters: {
|
||||
file_path: {
|
||||
type: "string",
|
||||
description: "The absolute path to the file to modify",
|
||||
required: true,
|
||||
},
|
||||
old_string: {
|
||||
type: "string",
|
||||
description: "The text to replace",
|
||||
required: true,
|
||||
},
|
||||
new_string: {
|
||||
type: "string",
|
||||
description:
|
||||
"The text to replace it with (must be different from old_string)",
|
||||
required: true,
|
||||
},
|
||||
replace_all: {
|
||||
type: "boolean",
|
||||
description: "Replace all occurences of old_string (default false)",
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
preprocess: async (args) => {
|
||||
const {
|
||||
file_path,
|
||||
old_string,
|
||||
new_string,
|
||||
replace_all = false,
|
||||
} = args as EditArgs;
|
||||
|
||||
// Check if file has been read
|
||||
if (!readFilesSet.has(file_path)) {
|
||||
throw new Error(
|
||||
`You must use the Read tool to read ${file_path} before editing it.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Validate arguments
|
||||
if (!file_path) {
|
||||
throw new Error("file_path is required");
|
||||
}
|
||||
if (!old_string) {
|
||||
throw new Error("old_string is required");
|
||||
}
|
||||
if (new_string === undefined) {
|
||||
throw new Error("new_string is required");
|
||||
}
|
||||
if (old_string === new_string) {
|
||||
throw new Error("old_string and new_string must be different");
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if (!fs.existsSync(file_path)) {
|
||||
throw new Error(`File ${file_path} does not exist`);
|
||||
}
|
||||
|
||||
// Read current file content
|
||||
const oldContent = fs.readFileSync(file_path, "utf-8");
|
||||
|
||||
// Check if old_string exists in the file
|
||||
if (!oldContent.includes(old_string)) {
|
||||
throw new Error(`String not found in file: ${old_string}`);
|
||||
}
|
||||
|
||||
let newContent: string;
|
||||
|
||||
if (replace_all) {
|
||||
// Replace all occurrences
|
||||
newContent = oldContent.split(old_string).join(new_string);
|
||||
} else {
|
||||
// Replace only the first occurrence
|
||||
const occurrences = oldContent.split(old_string).length - 1;
|
||||
if (occurrences > 1) {
|
||||
throw new Error(
|
||||
`String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
|
||||
);
|
||||
}
|
||||
newContent = oldContent.replace(old_string, new_string);
|
||||
}
|
||||
|
||||
// Generate diff for preview
|
||||
const diff = generateDiff(oldContent, newContent, file_path);
|
||||
|
||||
return {
|
||||
args: {
|
||||
file_path,
|
||||
newContent,
|
||||
oldContent,
|
||||
},
|
||||
preview: [
|
||||
{
|
||||
type: "text",
|
||||
content: "Will make the following changes:",
|
||||
},
|
||||
{
|
||||
type: "diff",
|
||||
content: diff,
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
run: async (args: {
|
||||
file_path: string;
|
||||
newContent: string;
|
||||
oldContent: string;
|
||||
}) => {
|
||||
try {
|
||||
fs.writeFileSync(args.file_path, args.newContent, "utf-8");
|
||||
|
||||
// Get lines for telemetry
|
||||
const { added, removed } = calculateLinesOfCodeDiff(
|
||||
args.oldContent,
|
||||
args.newContent,
|
||||
);
|
||||
const language = getLanguageFromFilePath(args.file_path);
|
||||
|
||||
if (added > 0) {
|
||||
telemetryService.recordLinesOfCodeModified("added", added, language);
|
||||
}
|
||||
if (removed > 0) {
|
||||
telemetryService.recordLinesOfCodeModified(
|
||||
"removed",
|
||||
removed,
|
||||
language,
|
||||
);
|
||||
}
|
||||
|
||||
return `Successfully edited ${args.file_path}`;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Error: failed to edit ${args.file_path}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Function to mark a file as read (to be called from the read tool)
|
||||
export function markFileAsRead(filePath: string) {
|
||||
readFilesSet.add(filePath);
|
||||
}
|
||||
|
|
@ -4,13 +4,14 @@ import type { ToolPermissionServiceState } from "../services/ToolPermissionServi
|
|||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { editTool } from "./edit.js";
|
||||
import { exitTool } from "./exit.js";
|
||||
import { fetchTool } from "./fetch.js";
|
||||
import { formatToolArgument } from "./formatters.js";
|
||||
import { listFilesTool } from "./listFiles.js";
|
||||
import { multiEditTool } from "./multiEdit.js";
|
||||
import { readFileTool } from "./readFile.js";
|
||||
import { runTerminalCommandTool } from "./runTerminalCommand.js";
|
||||
import { searchAndReplaceInFileTool } from "./searchAndReplace/index.js";
|
||||
import { searchCodeTool } from "./searchCode.js";
|
||||
import {
|
||||
type Tool,
|
||||
|
|
@ -26,8 +27,10 @@ export type { Tool, ToolCall, ToolParameters };
|
|||
// Base tools that are always available
|
||||
const BASE_BUILTIN_TOOLS: Tool[] = [
|
||||
readFileTool,
|
||||
editTool,
|
||||
multiEditTool,
|
||||
writeFileTool,
|
||||
searchAndReplaceInFileTool,
|
||||
// searchAndReplaceInFileTool,
|
||||
listFilesTool,
|
||||
searchCodeTool,
|
||||
runTerminalCommandTool,
|
||||
|
|
|
|||
398
src/tools/multiEdit.test.ts
Normal file
398
src/tools/multiEdit.test.ts
Normal file
|
|
@ -0,0 +1,398 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
|
||||
import { multiEditTool, markFileAsRead } from "./multiEdit.js";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("../telemetry/telemetryService.js");
|
||||
vi.mock("../telemetry/utils.js", () => ({
|
||||
calculateLinesOfCodeDiff: vi.fn().mockReturnValue({ added: 1, removed: 0 }),
|
||||
getLanguageFromFilePath: vi.fn().mockReturnValue("javascript"),
|
||||
}));
|
||||
vi.mock("./writeFile.js", () => ({
|
||||
generateDiff: vi.fn().mockReturnValue("mocked diff"),
|
||||
}));
|
||||
vi.mock("fs", async () => {
|
||||
const actual = await vi.importActual("fs");
|
||||
return {
|
||||
...actual,
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
unlinkSync: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("multiEditTool", () => {
|
||||
const testFilePath = "/tmp/test-multi-edit-file.txt";
|
||||
const originalContent = "Hello world\nThis is a test file\nGoodbye world";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Mock fs functions to simulate file operations
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
|
||||
vi.mocked(fs.writeFileSync).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("preprocess", () => {
|
||||
it("should throw error if file has not been read", async () => {
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi there",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
`You must use the Read tool to read ${testFilePath} before editing it.`
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if file does not exist", async () => {
|
||||
const nonExistentFile = "/tmp/non-existent-file.txt";
|
||||
markFileAsRead(nonExistentFile);
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
|
||||
const args = {
|
||||
file_path: nonExistentFile,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Hello",
|
||||
new_string: "Hi",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
`File ${nonExistentFile} does not exist`
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if edits array is empty", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [],
|
||||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
"edits array is required and must contain at least one edit"
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if edit has missing old_string", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: undefined as any,
|
||||
new_string: "Hi there",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
"Edit 1: old_string is required"
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if edit has missing new_string", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Hello world",
|
||||
new_string: undefined as any,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
"Edit 1: new_string is required"
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if old_string and new_string are the same", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Hello world",
|
||||
new_string: "Hello world",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
"Edit 1: old_string and new_string must be different"
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if old_string is not found", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
vi.mocked(fs.readFileSync).mockReturnValue("Different content");
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Not found",
|
||||
new_string: "Hi there",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
'Edit 1: String not found in file: "Not found"'
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if old_string appears multiple times and replace_all is false", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "world",
|
||||
new_string: "universe",
|
||||
replace_all: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
'Edit 1: String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.'
|
||||
);
|
||||
});
|
||||
|
||||
it("should successfully preprocess single edit", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi there",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args).toEqual({
|
||||
file_path: testFilePath,
|
||||
newContent: "Hi there\nThis is a test file\nGoodbye world",
|
||||
originalContent: originalContent,
|
||||
isCreatingNewFile: false,
|
||||
editCount: 1,
|
||||
});
|
||||
expect(result.preview).toHaveLength(2);
|
||||
expect(result.preview?.[0]).toEqual({
|
||||
type: "text",
|
||||
content: "Will apply 1 edit to modify /tmp/test-multi-edit-file.txt:",
|
||||
});
|
||||
expect(result.preview?.[1]).toEqual({
|
||||
type: "diff",
|
||||
content: "mocked diff",
|
||||
});
|
||||
});
|
||||
|
||||
it("should successfully preprocess multiple edits", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi there",
|
||||
},
|
||||
{
|
||||
old_string: "Goodbye world",
|
||||
new_string: "See you later",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"Hi there\nThis is a test file\nSee you later"
|
||||
);
|
||||
expect(result.args.editCount).toBe(2);
|
||||
expect(result.preview?.[0]?.content).toContain("Will apply 2 edits");
|
||||
});
|
||||
|
||||
it("should successfully preprocess replace_all edit", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "world",
|
||||
new_string: "universe",
|
||||
replace_all: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"Hello universe\nThis is a test file\nGoodbye universe"
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle new file creation with empty old_string", async () => {
|
||||
const newFilePath = "/tmp/new-file.txt";
|
||||
vi.mocked(fs.existsSync).mockImplementation((path) => {
|
||||
// Parent directory exists, but file doesn't
|
||||
if (path === "/tmp") return true;
|
||||
if (path === newFilePath) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const args = {
|
||||
file_path: newFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "",
|
||||
new_string: "New file content\nSecond line",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe("New file content\nSecond line");
|
||||
expect(result.args.isCreatingNewFile).toBe(true);
|
||||
expect(result.preview?.[0]?.content).toContain("create");
|
||||
});
|
||||
|
||||
it("should apply edits sequentially", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi universe",
|
||||
},
|
||||
{
|
||||
old_string: "Hi universe",
|
||||
new_string: "Greetings cosmos",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"Greetings cosmos\nThis is a test file\nGoodbye world"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("run", () => {
|
||||
it("should successfully write file and return success message", async () => {
|
||||
const newContent = "Hi there\nThis is a test file\nGoodbye world";
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
newContent,
|
||||
originalContent: originalContent,
|
||||
isCreatingNewFile: false,
|
||||
editCount: 1,
|
||||
};
|
||||
|
||||
const result = await multiEditTool.run(args);
|
||||
|
||||
expect(result).toBe(`Successfully edited ${testFilePath} with 1 edit`);
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8");
|
||||
});
|
||||
|
||||
it("should return correct message for multiple edits", async () => {
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
newContent: "New content",
|
||||
originalContent: originalContent,
|
||||
isCreatingNewFile: false,
|
||||
editCount: 3,
|
||||
};
|
||||
|
||||
const result = await multiEditTool.run(args);
|
||||
|
||||
expect(result).toBe(`Successfully edited ${testFilePath} with 3 edits`);
|
||||
});
|
||||
|
||||
it("should return correct message for new file creation", async () => {
|
||||
const args = {
|
||||
file_path: "/tmp/new-file.txt",
|
||||
newContent: "New file content",
|
||||
originalContent: "",
|
||||
isCreatingNewFile: true,
|
||||
editCount: 1,
|
||||
};
|
||||
|
||||
const result = await multiEditTool.run(args);
|
||||
|
||||
expect(result).toBe(`Successfully created /tmp/new-file.txt with 1 edit`);
|
||||
});
|
||||
|
||||
it("should throw error if file write fails", async () => {
|
||||
vi.mocked(fs.writeFileSync).mockImplementation(() => {
|
||||
throw new Error("Write failed");
|
||||
});
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
newContent: "new content",
|
||||
originalContent: originalContent,
|
||||
isCreatingNewFile: false,
|
||||
editCount: 1,
|
||||
};
|
||||
|
||||
await expect(multiEditTool.run(args)).rejects.toThrow(
|
||||
`Error: failed to edit ${testFilePath}: Write failed`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("markFileAsRead", () => {
|
||||
it("should allow editing after marking file as read", async () => {
|
||||
markFileAsRead(testFilePath);
|
||||
|
||||
const args = {
|
||||
file_path: testFilePath,
|
||||
edits: [
|
||||
{
|
||||
old_string: "Hello world",
|
||||
new_string: "Hi there",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = await multiEditTool.preprocess!(args);
|
||||
expect(result.args.newContent).toContain("Hi there");
|
||||
});
|
||||
});
|
||||
});
|
||||
290
src/tools/multiEdit.ts
Normal file
290
src/tools/multiEdit.ts
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import { telemetryService } from "../telemetry/telemetryService.js";
|
||||
import {
|
||||
calculateLinesOfCodeDiff,
|
||||
getLanguageFromFilePath,
|
||||
} from "../telemetry/utils.js";
|
||||
|
||||
import { readFilesSet, markFileAsRead } from "./edit.js";
|
||||
import { Tool } from "./types.js";
|
||||
import { generateDiff } from "./writeFile.js";
|
||||
|
||||
export { markFileAsRead };
|
||||
|
||||
export interface EditOperation {
|
||||
old_string: string;
|
||||
new_string: string;
|
||||
replace_all?: boolean;
|
||||
}
|
||||
|
||||
export interface MultiEditArgs {
|
||||
file_path: string;
|
||||
edits: EditOperation[];
|
||||
}
|
||||
|
||||
// Function to check if file has been read (shared with edit tool)
|
||||
function hasFileBeenRead(filePath: string): boolean {
|
||||
return readFilesSet.has(filePath);
|
||||
}
|
||||
|
||||
export const multiEditTool: Tool = {
|
||||
name: "MultiEdit",
|
||||
displayName: "MultiEdit",
|
||||
readonly: false,
|
||||
isBuiltIn: true,
|
||||
description: `This is a tool for making multiple edits to a single file in one operation. It
|
||||
is built on top of the Edit tool and allows you to perform multiple
|
||||
find-and-replace operations efficiently. Prefer this tool over the Edit tool
|
||||
when you need to make multiple edits to the same file.
|
||||
|
||||
|
||||
Before using this tool:
|
||||
|
||||
|
||||
1. Use the Read tool to understand the file's contents and context
|
||||
|
||||
2. Verify the directory path is correct
|
||||
|
||||
|
||||
To make multiple file edits, provide the following:
|
||||
|
||||
1. file_path: The absolute path to the file to modify (must be absolute, not
|
||||
relative)
|
||||
|
||||
2. edits: An array of edit operations to perform, where each edit contains:
|
||||
- old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
|
||||
- new_string: The edited text to replace the old_string
|
||||
- replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false.
|
||||
|
||||
IMPORTANT:
|
||||
|
||||
- All edits are applied in sequence, in the order they are provided
|
||||
|
||||
- Each edit operates on the result of the previous edit
|
||||
|
||||
- All edits must be valid for the operation to succeed - if any edit fails,
|
||||
none will be applied
|
||||
|
||||
- This tool is ideal when you need to make several changes to different parts
|
||||
of the same file
|
||||
|
||||
- For Jupyter notebooks (.ipynb files), use the NotebookEdit instead
|
||||
|
||||
|
||||
CRITICAL REQUIREMENTS:
|
||||
|
||||
1. All edits follow the same requirements as the single Edit tool
|
||||
|
||||
2. The edits are atomic - either all succeed or none are applied
|
||||
|
||||
3. Plan your edits carefully to avoid conflicts between sequential operations
|
||||
|
||||
|
||||
WARNING:
|
||||
|
||||
- The tool will fail if edits.old_string doesn't match the file contents
|
||||
exactly (including whitespace)
|
||||
|
||||
- The tool will fail if edits.old_string and edits.new_string are the same
|
||||
|
||||
- Since edits are applied in sequence, ensure that earlier edits don't affect
|
||||
the text that later edits are trying to find
|
||||
|
||||
|
||||
When making edits:
|
||||
|
||||
- Ensure all edits result in idiomatic, correct code
|
||||
|
||||
- Do not leave the code in a broken state
|
||||
|
||||
- Always use absolute file paths (starting with /)
|
||||
|
||||
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
|
||||
files unless asked.
|
||||
|
||||
- Use replace_all for replacing and renaming strings across the file. This
|
||||
parameter is useful if you want to rename a variable for instance.
|
||||
|
||||
|
||||
If you want to create a new file, use:
|
||||
|
||||
- A new file path, including dir name if needed
|
||||
|
||||
- First edit: empty old_string and the new file's contents as new_string
|
||||
|
||||
- Subsequent edits: normal edit operations on the created content`,
|
||||
parameters: {
|
||||
file_path: {
|
||||
type: "string",
|
||||
description: "The absolute path to the file to modify",
|
||||
required: true,
|
||||
},
|
||||
edits: {
|
||||
type: "array",
|
||||
description:
|
||||
"Array of edit operations to perform sequentially on the file",
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
preprocess: async (args) => {
|
||||
const { file_path, edits } = args as MultiEditArgs;
|
||||
|
||||
// Validate arguments
|
||||
if (!file_path) {
|
||||
throw new Error("file_path is required");
|
||||
}
|
||||
if (!path.isAbsolute(file_path)) {
|
||||
throw new Error("file_path must be an absolute path");
|
||||
}
|
||||
if (!edits || !Array.isArray(edits) || edits.length === 0) {
|
||||
throw new Error(
|
||||
"edits array is required and must contain at least one edit",
|
||||
);
|
||||
}
|
||||
|
||||
// Validate each edit operation
|
||||
for (let i = 0; i < edits.length; i++) {
|
||||
const edit = edits[i];
|
||||
if (!edit.old_string && edit.old_string !== "") {
|
||||
throw new Error(`Edit ${i + 1}: old_string is required`);
|
||||
}
|
||||
if (edit.new_string === undefined) {
|
||||
throw new Error(`Edit ${i + 1}: new_string is required`);
|
||||
}
|
||||
if (edit.old_string === edit.new_string) {
|
||||
throw new Error(
|
||||
`Edit ${i + 1}: old_string and new_string must be different`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if this is creating a new file (first edit has empty old_string)
|
||||
const isCreatingNewFile = edits[0].old_string === "";
|
||||
|
||||
if (isCreatingNewFile) {
|
||||
// For new file creation, check if parent directory exists
|
||||
const parentDir = path.dirname(file_path);
|
||||
if (parentDir && !fs.existsSync(parentDir)) {
|
||||
throw new Error(`Parent directory does not exist: ${parentDir}`);
|
||||
}
|
||||
// Don't check if file has been read for new file creation
|
||||
} else {
|
||||
// For existing files, check if file has been read
|
||||
if (!hasFileBeenRead(file_path)) {
|
||||
throw new Error(
|
||||
`You must use the Read tool to read ${file_path} before editing it.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if (!fs.existsSync(file_path)) {
|
||||
throw new Error(`File ${file_path} does not exist`);
|
||||
}
|
||||
}
|
||||
|
||||
// Read current file content (or start with empty for new files)
|
||||
let currentContent = "";
|
||||
if (!isCreatingNewFile) {
|
||||
currentContent = fs.readFileSync(file_path, "utf-8");
|
||||
}
|
||||
|
||||
const originalContent = currentContent;
|
||||
let newContent = currentContent;
|
||||
|
||||
// Apply all edits sequentially
|
||||
for (let i = 0; i < edits.length; i++) {
|
||||
const edit = edits[i];
|
||||
const { old_string, new_string, replace_all = false } = edit;
|
||||
|
||||
// For new file creation, the first edit can have empty old_string
|
||||
if (i === 0 && isCreatingNewFile && old_string === "") {
|
||||
newContent = new_string;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if old_string exists in current content
|
||||
if (!newContent.includes(old_string)) {
|
||||
throw new Error(
|
||||
`Edit ${i + 1}: String not found in file: "${old_string}"`,
|
||||
);
|
||||
}
|
||||
|
||||
if (replace_all) {
|
||||
// Replace all occurrences
|
||||
newContent = newContent.split(old_string).join(new_string);
|
||||
} else {
|
||||
// Replace only the first occurrence, but check for uniqueness
|
||||
const occurrences = newContent.split(old_string).length - 1;
|
||||
if (occurrences > 1) {
|
||||
throw new Error(
|
||||
`Edit ${i + 1}: String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
|
||||
);
|
||||
}
|
||||
newContent = newContent.replace(old_string, new_string);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate diff for preview
|
||||
const diff = generateDiff(originalContent, newContent, file_path);
|
||||
|
||||
return {
|
||||
args: {
|
||||
file_path,
|
||||
newContent,
|
||||
originalContent,
|
||||
isCreatingNewFile,
|
||||
editCount: edits.length,
|
||||
},
|
||||
preview: [
|
||||
{
|
||||
type: "text",
|
||||
content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${file_path}:`,
|
||||
},
|
||||
{
|
||||
type: "diff",
|
||||
content: diff,
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
run: async (args: {
|
||||
file_path: string;
|
||||
newContent: string;
|
||||
originalContent: string;
|
||||
isCreatingNewFile: boolean;
|
||||
editCount: number;
|
||||
}) => {
|
||||
try {
|
||||
fs.writeFileSync(args.file_path, args.newContent, "utf-8");
|
||||
|
||||
// Get lines for telemetry
|
||||
const { added, removed } = calculateLinesOfCodeDiff(
|
||||
args.originalContent,
|
||||
args.newContent,
|
||||
);
|
||||
const language = getLanguageFromFilePath(args.file_path);
|
||||
|
||||
if (added > 0) {
|
||||
telemetryService.recordLinesOfCodeModified("added", added, language);
|
||||
}
|
||||
if (removed > 0) {
|
||||
telemetryService.recordLinesOfCodeModified(
|
||||
"removed",
|
||||
removed,
|
||||
language,
|
||||
);
|
||||
}
|
||||
|
||||
const action = args.isCreatingNewFile ? "created" : "edited";
|
||||
return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}`;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Error: failed to edit ${args.file_path}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import { markFileAsRead } from "./edit.js";
|
||||
import { formatToolArgument } from "./formatters.js";
|
||||
import { Tool } from "./types.js";
|
||||
|
||||
|
|
@ -33,6 +34,8 @@ export const readFileTool: Tool = {
|
|||
return `Error: File does not exist: ${args.filepath}`;
|
||||
}
|
||||
const content = fs.readFileSync(args.filepath, "utf-8");
|
||||
// Mark this file as read for the edit tool
|
||||
markFileAsRead(args.filepath);
|
||||
return `Content of ${args.filepath}:\n${content}`;
|
||||
} catch (error) {
|
||||
return `Error reading file: ${
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue