@@ -4,48 +4,44 @@ import { z } from "zod";
44 import type { ToolDef } from "../llm-api/types.ts";
55 import { generateDiff } from "./diff.ts";
66
7-const WriteInput = z.object({
8- path: z.string().describe("File path to write (absolute or relative to cwd)"),
9- content: z.string().describe("Full content to write to the file"),
10- cwd: z
11- .string()
12- .optional()
13- .describe("Working directory for resolving relative paths"),
7+const WriteSchema = z.object({
8+ path: z.string().describe("File path to write (absolute or relative to cwd)"),
9+ content: z.string().describe("Full content to write to the file"),
1410 });
1511
16-type WriteInput = z.infer<typeof WriteInput>;
12+type WriteInput = z.infer<typeof WriteSchema> & { cwd?: string };
1713
1814 export interface WriteOutput {
19- path: string;
20- diff: string;
21- created: boolean;
15+ path: string;
16+ diff: string;
17+ created: boolean;
2218 }
2319
2420 export const writeTool: ToolDef<WriteInput, WriteOutput> = {
25- name: "write",
26- description:
27- "Create a new file or fully overwrite an existing file with the given content. " +
28- "Use this for new files or when replacing an entire file. " +
29- "For targeted line edits on existing files, use `edit` or `insert` instead.",
30- schema: WriteInput,
31- execute: async (input) => {
32- const cwd = input.cwd ?? process.cwd();
33- const filePath = input.path.startsWith("/")
34- ? input.path
35- : join(cwd, input.path);
36-
37- const relPath = relative(cwd, filePath);
38-
39- const dir = dirname(filePath);
40- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
41-
42- const file = Bun.file(filePath);
43- const created = !(await file.exists());
44- const before = created ? "" : await file.text();
45-
46- await Bun.write(filePath, input.content);
47-
48- const diff = generateDiff(relPath, before, input.content);
49- return { path: relPath, diff, created };
50- },
21+ name: "write",
22+ description:
23+ "Create a new file or fully overwrite an existing file with the given content. " +
24+ "Use this only for new files. " +
25+ "For targeted line edits on existing files, **use `edit` or `insert` instead**.",
26+ schema: WriteSchema,
27+ execute: async (input) => {
28+ const cwd = input.cwd ?? process.cwd();
29+ const filePath = input.path.startsWith("/")
30+ ? input.path
31+ : join(cwd, input.path);
32+
33+ const relPath = relative(cwd, filePath);
34+
35+ const dir = dirname(filePath);
36+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
37+
38+ const file = Bun.file(filePath);
39+ const created = !(await file.exists());
40+ const before = created ? "" : await file.text();
41+
42+ await Bun.write(filePath, input.content);
43+
44+ const diff = generateDiff(relPath, before, input.content);
45+ return { path: relPath, diff, created };
46+ },
5147 };