xonecas.io
64875
Mc

mini-coder / commit 418acab

feat: add edit and shell tool implementations with tests

xonecas2026-04-04 418acab2ff5fe8f0bd35e0ca462b23c76b4773cd parent 4f87ab8

2 files changed

src/tools.test.ts+290−0
@@ -0,0 +1,290 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import {
3+ mkdirSync,
4+ mkdtempSync,
5+ readFileSync,
6+ rmSync,
7+ writeFileSync,
8+} from "node:fs";
9+import { tmpdir } from "node:os";
10+import { join } from "node:path";
11+import { executeEdit, executeShell, truncateOutput } from "./tools.ts";
12+
13+// ---------------------------------------------------------------------------
14+// Helpers
15+// ---------------------------------------------------------------------------
16+
17+let tmp: string;
18+
19+beforeEach(() => {
20+ tmp = mkdtempSync(join(tmpdir(), "mc-tools-"));
21+});
22+
23+afterEach(() => {
24+ rmSync(tmp, { recursive: true, force: true });
25+});
26+
27+function writeFile(name: string, content: string): string {
28+ const p = join(tmp, name);
29+ writeFileSync(p, content);
30+ return p;
31+}
32+
33+function readFile(name: string): string {
34+ return readFileSync(join(tmp, name), "utf-8");
35+}
36+
37+// ---------------------------------------------------------------------------
38+// edit
39+// ---------------------------------------------------------------------------
40+
41+describe("edit", () => {
42+ test("replaces exact text match", () => {
43+ writeFile("a.txt", "hello world");
44+ const result = executeEdit(
45+ { path: "a.txt", oldText: "hello", newText: "goodbye" },
46+ tmp,
47+ );
48+ expect(result.isError).toBe(false);
49+ expect(readFile("a.txt")).toBe("goodbye world");
50+ });
51+
52+ test("fails when old text is not found", () => {
53+ writeFile("a.txt", "hello world");
54+ const result = executeEdit(
55+ { path: "a.txt", oldText: "missing", newText: "x" },
56+ tmp,
57+ );
58+ expect(result.isError).toBe(true);
59+ expect(result.text).toContain("not found");
60+ // File unchanged
61+ expect(readFile("a.txt")).toBe("hello world");
62+ });
63+
64+ test("fails when old text matches multiple locations", () => {
65+ writeFile("a.txt", "aaa bbb aaa");
66+ const result = executeEdit(
67+ { path: "a.txt", oldText: "aaa", newText: "ccc" },
68+ tmp,
69+ );
70+ expect(result.isError).toBe(true);
71+ expect(result.text).toContain("multiple");
72+ // File unchanged
73+ expect(readFile("a.txt")).toBe("aaa bbb aaa");
74+ });
75+
76+ test("creates new file when oldText is empty", () => {
77+ const result = executeEdit(
78+ { path: "new.txt", oldText: "", newText: "brand new content" },
79+ tmp,
80+ );
81+ expect(result.isError).toBe(false);
82+ expect(readFile("new.txt")).toBe("brand new content");
83+ });
84+
85+ test("creates parent directories for new files", () => {
86+ const result = executeEdit(
87+ { path: "deep/nested/dir/file.txt", oldText: "", newText: "nested" },
88+ tmp,
89+ );
90+ expect(result.isError).toBe(false);
91+ expect(readFile("deep/nested/dir/file.txt")).toBe("nested");
92+ });
93+
94+ test("fails to create file when it already exists and oldText is empty", () => {
95+ writeFile("existing.txt", "already here");
96+ const result = executeEdit(
97+ { path: "existing.txt", oldText: "", newText: "overwrite" },
98+ tmp,
99+ );
100+ expect(result.isError).toBe(true);
101+ expect(result.text).toContain("already exists");
102+ // File unchanged
103+ expect(readFile("existing.txt")).toBe("already here");
104+ });
105+
106+ test("preserves LF line endings", () => {
107+ writeFile("lf.txt", "line1\nline2\nline3\n");
108+ executeEdit({ path: "lf.txt", oldText: "line2", newText: "replaced" }, tmp);
109+ expect(readFile("lf.txt")).toBe("line1\nreplaced\nline3\n");
110+ });
111+
112+ test("preserves CRLF line endings", () => {
113+ writeFile("crlf.txt", "line1\r\nline2\r\nline3\r\n");
114+ executeEdit(
115+ { path: "crlf.txt", oldText: "line2", newText: "replaced" },
116+ tmp,
117+ );
118+ expect(readFile("crlf.txt")).toBe("line1\r\nreplaced\r\nline3\r\n");
119+ });
120+
121+ test("handles UTF-8 content", () => {
122+ writeFile("utf8.txt", "こんにちは世界");
123+ const result = executeEdit(
124+ { path: "utf8.txt", oldText: "世界", newText: "🌍" },
125+ tmp,
126+ );
127+ expect(result.isError).toBe(false);
128+ expect(readFile("utf8.txt")).toBe("こんにちは🌍");
129+ });
130+
131+ test("handles multi-line old text", () => {
132+ writeFile("multi.txt", "function foo() {\n return 1;\n}\n");
133+ const result = executeEdit(
134+ {
135+ path: "multi.txt",
136+ oldText: "function foo() {\n return 1;\n}",
137+ newText: "function foo() {\n return 2;\n}",
138+ },
139+ tmp,
140+ );
141+ expect(result.isError).toBe(false);
142+ expect(readFile("multi.txt")).toBe("function foo() {\n return 2;\n}\n");
143+ });
144+
145+ test("resolves relative paths against cwd", () => {
146+ mkdirSync(join(tmp, "sub"), { recursive: true });
147+ writeFileSync(join(tmp, "sub", "rel.txt"), "original");
148+ const result = executeEdit(
149+ { path: "sub/rel.txt", oldText: "original", newText: "modified" },
150+ tmp,
151+ );
152+ expect(result.isError).toBe(false);
153+ expect(readFileSync(join(tmp, "sub", "rel.txt"), "utf-8")).toBe("modified");
154+ });
155+
156+ test("handles absolute paths directly", () => {
157+ const absPath = writeFile("abs.txt", "content");
158+ const result = executeEdit(
159+ { path: absPath, oldText: "content", newText: "new content" },
160+ tmp,
161+ );
162+ expect(result.isError).toBe(false);
163+ expect(readFile("abs.txt")).toBe("new content");
164+ });
165+
166+ test("fails when file does not exist for non-empty oldText", () => {
167+ const result = executeEdit(
168+ { path: "nonexistent.txt", oldText: "something", newText: "else" },
169+ tmp,
170+ );
171+ expect(result.isError).toBe(true);
172+ expect(result.text).toContain("not found");
173+ });
174+});
175+
176+// ---------------------------------------------------------------------------
177+// shell
178+// ---------------------------------------------------------------------------
179+
180+describe("shell", () => {
181+ test("returns stdout from a command", async () => {
182+ const result = await executeShell({ command: "echo hello" }, tmp);
183+ expect(result.isError).toBe(false);
184+ expect(result.text).toContain("hello");
185+ });
186+
187+ test("returns stderr from a command", async () => {
188+ const result = await executeShell({ command: "echo err >&2" }, tmp);
189+ expect(result.isError).toBe(false);
190+ expect(result.text).toContain("err");
191+ });
192+
193+ test("passes through exit code", async () => {
194+ const result = await executeShell({ command: "exit 42" }, tmp);
195+ expect(result.isError).toBe(true);
196+ expect(result.text).toContain("exit code 42");
197+ });
198+
199+ test("runs in the specified cwd", async () => {
200+ const result = await executeShell({ command: "pwd" }, tmp);
201+ expect(result.isError).toBe(false);
202+ expect(result.text).toContain(tmp);
203+ });
204+
205+ test("truncates large output", async () => {
206+ // Generate 2000 lines, which should exceed the default truncation limit
207+ const result = await executeShell({ command: "seq 1 2000" }, tmp, {
208+ maxLines: 100,
209+ });
210+ expect(result.isError).toBe(false);
211+ expect(result.text).toContain("… truncated");
212+ // Should contain head lines (near the start)
213+ expect(result.text).toContain("1\n");
214+ // Should contain tail lines (near the end)
215+ expect(result.text).toContain("2000");
216+ });
217+
218+ test("does not truncate output within the limit", async () => {
219+ const result = await executeShell({ command: "seq 1 10" }, tmp, {
220+ maxLines: 100,
221+ });
222+ expect(result.isError).toBe(false);
223+ expect(result.text).not.toContain("truncated");
224+ });
225+
226+ test("supports abort signal", async () => {
227+ const controller = new AbortController();
228+ // Abort immediately
229+ controller.abort();
230+ const result = await executeShell({ command: "sleep 10" }, tmp, {
231+ signal: controller.signal,
232+ });
233+ expect(result.isError).toBe(true);
234+ });
235+
236+ test("combines stdout and stderr in output", async () => {
237+ const result = await executeShell(
238+ { command: "echo out && echo err >&2" },
239+ tmp,
240+ );
241+ expect(result.text).toContain("out");
242+ expect(result.text).toContain("err");
243+ });
244+});
245+
246+// ---------------------------------------------------------------------------
247+// truncateOutput (pure function)
248+// ---------------------------------------------------------------------------
249+
250+describe("truncateOutput", () => {
251+ test("returns input unchanged when within limit", () => {
252+ const input = "line1\nline2\nline3";
253+ expect(truncateOutput(input, 10)).toBe(input);
254+ });
255+
256+ test("truncates keeping head and tail with marker", () => {
257+ const lines = Array.from({ length: 100 }, (_, i) => `line${i + 1}`);
258+ const input = lines.join("\n");
259+ const result = truncateOutput(input, 20);
260+
261+ expect(result).toContain("line1");
262+ expect(result).toContain("line100");
263+ expect(result).toContain("… truncated");
264+ });
265+
266+ test("head and tail do not overlap", () => {
267+ const lines = Array.from({ length: 50 }, (_, i) => `L${i + 1}`);
268+ const input = lines.join("\n");
269+ const result = truncateOutput(input, 20);
270+
271+ // Count total lines (head + marker + tail)
272+ const resultLines = result.split("\n");
273+ // Should be ≤ maxLines + 1 (for the marker line)
274+ expect(resultLines.length).toBeLessThanOrEqual(21);
275+ });
276+
277+ test("handles empty input", () => {
278+ expect(truncateOutput("", 10)).toBe("");
279+ });
280+
281+ test("handles single-line input", () => {
282+ expect(truncateOutput("hello", 10)).toBe("hello");
283+ });
284+
285+ test("handles input at exactly the limit", () => {
286+ const lines = Array.from({ length: 10 }, (_, i) => `line${i + 1}`);
287+ const input = lines.join("\n");
288+ expect(truncateOutput(input, 10)).toBe(input);
289+ });
290+});
src/tools.ts+248−0
@@ -0,0 +1,248 @@
1+/**
2+ * Built-in tool implementations: `edit` and `shell`.
3+ *
4+ * Each tool is exposed as a pure-ish execute function that takes typed
5+ * arguments and a working directory, returning a result object with `text`
6+ * and `isError`. The pi-ai {@link Tool} definitions (TypeBox schemas) are
7+ * exported separately for registration with the agent context.
8+ *
9+ * @module
10+ */
11+
12+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
13+import { dirname, isAbsolute, join } from "node:path";
14+import type { Tool } from "@mariozechner/pi-ai";
15+import { Type } from "@mariozechner/pi-ai";
16+
17+// ---------------------------------------------------------------------------
18+// Result type
19+// ---------------------------------------------------------------------------
20+
21+/** Result returned by a tool execution. */
22+export interface ToolResult {
23+ /** Human-readable result text. */
24+ text: string;
25+ /** Whether the execution encountered an error. */
26+ isError: boolean;
27+}
28+
29+// ---------------------------------------------------------------------------
30+// edit
31+// ---------------------------------------------------------------------------
32+
33+/** Arguments for the `edit` tool. */
34+export interface EditArgs {
35+ /** File path (absolute or relative to cwd). */
36+ path: string;
37+ /** Exact text to find. Empty string means "create new file". */
38+ oldText: string;
39+ /** Replacement text (or full content for new files). */
40+ newText: string;
41+}
42+
43+/**
44+ * Execute an exact-text replacement in a single file.
45+ *
46+ * - If `oldText` is empty, creates a new file (with parent directories).
47+ * Fails if the file already exists.
48+ * - Otherwise, reads the file, finds exactly one occurrence of `oldText`,
49+ * and replaces it with `newText`. Fails if the text is not found or
50+ * matches multiple locations.
51+ *
52+ * @param args - Edit arguments (path, oldText, newText).
53+ * @param cwd - Working directory for resolving relative paths.
54+ * @returns A {@link ToolResult} with confirmation or error message.
55+ */
56+export function executeEdit(args: EditArgs, cwd: string): ToolResult {
57+ const filePath = isAbsolute(args.path) ? args.path : join(cwd, args.path);
58+
59+ // Create new file
60+ if (args.oldText === "") {
61+ if (existsSync(filePath)) {
62+ return { text: `File already exists: ${args.path}`, isError: true };
63+ }
64+ mkdirSync(dirname(filePath), { recursive: true });
65+ writeFileSync(filePath, args.newText, "utf-8");
66+ return { text: `Created ${args.path}`, isError: false };
67+ }
68+
69+ // Replace in existing file
70+ if (!existsSync(filePath)) {
71+ return { text: `File not found: ${args.path}`, isError: true };
72+ }
73+
74+ const content = readFileSync(filePath, "utf-8");
75+
76+ // Count occurrences
77+ let count = 0;
78+ let idx = 0;
79+ while (true) {
80+ idx = content.indexOf(args.oldText, idx);
81+ if (idx === -1) break;
82+ count++;
83+ idx += args.oldText.length;
84+ }
85+
86+ if (count === 0) {
87+ return { text: `Old text not found in ${args.path}`, isError: true };
88+ }
89+ if (count > 1) {
90+ return {
91+ text: `Old text matches multiple locations (${count}) in ${args.path}`,
92+ isError: true,
93+ };
94+ }
95+
96+ // Exactly one match — replace
97+ const updated = content.replace(args.oldText, args.newText);
98+ writeFileSync(filePath, updated, "utf-8");
99+ return { text: `Edited ${args.path}`, isError: false };
100+}
101+
102+// ---------------------------------------------------------------------------
103+// shell
104+// ---------------------------------------------------------------------------
105+
106+/** Arguments for the `shell` tool. */
107+export interface ShellArgs {
108+ /** The command to run. */
109+ command: string;
110+}
111+
112+/** Options for shell execution. */
113+export interface ShellOpts {
114+ /** Maximum output lines before truncation. Default: 500. */
115+ maxLines?: number;
116+ /** Abort signal to cancel the command. */
117+ signal?: AbortSignal;
118+}
119+
120+const DEFAULT_MAX_LINES = 500;
121+
122+/**
123+ * Run a command in the user's shell.
124+ *
125+ * Executes via `$SHELL -c` (falling back to `/bin/sh`). Returns combined
126+ * stdout/stderr and the exit code. Large output is truncated to keep
127+ * head + tail lines with a middle marker.
128+ *
129+ * @param args - Shell arguments (command).
130+ * @param cwd - Working directory to run the command in.
131+ * @param opts - Optional execution options (maxLines, signal).
132+ * @returns A {@link ToolResult} with the command output.
133+ */
134+export async function executeShell(
135+ args: ShellArgs,
136+ cwd: string,
137+ opts?: ShellOpts,
138+): Promise<ToolResult> {
139+ const shell = process.env.SHELL || "/bin/sh";
140+ const maxLines = opts?.maxLines ?? DEFAULT_MAX_LINES;
141+
142+ try {
143+ const spawnOpts: Parameters<typeof Bun.spawn>[1] = {
144+ cwd,
145+ stdout: "pipe",
146+ stderr: "pipe",
147+ };
148+ if (opts?.signal) spawnOpts.signal = opts.signal;
149+ const proc = Bun.spawn([shell, "-c", args.command], spawnOpts);
150+
151+ const [stdoutBuf, stderrBuf] = await Promise.all([
152+ new Response(proc.stdout as ReadableStream).text(),
153+ new Response(proc.stderr as ReadableStream).text(),
154+ ]);
155+ const exitCode = await proc.exited;
156+
157+ const stdout = stdoutBuf.trimEnd();
158+ const stderr = stderrBuf.trimEnd();
159+
160+ let output = "";
161+ if (stdout && stderr) {
162+ output = `${stdout}\n\n[stderr]\n${stderr}`;
163+ } else if (stdout) {
164+ output = stdout;
165+ } else if (stderr) {
166+ output = `[stderr]\n${stderr}`;
167+ }
168+
169+ output = truncateOutput(output, maxLines);
170+
171+ const isError = exitCode !== 0;
172+ const prefix = isError ? `Command failed with exit code ${exitCode}\n` : "";
173+ const text = prefix + output;
174+
175+ return { text: text || "(no output)", isError };
176+ } catch (err) {
177+ const message = err instanceof Error ? err.message : String(err);
178+ return { text: `Shell error: ${message}`, isError: true };
179+ }
180+}
181+
182+// ---------------------------------------------------------------------------
183+// Output truncation
184+// ---------------------------------------------------------------------------
185+
186+/**
187+ * Truncate output to keep head and tail lines with a marker in between.
188+ *
189+ * If the output has fewer lines than `maxLines`, it is returned unchanged.
190+ * Otherwise, keeps roughly half the budget for head lines and half for tail
191+ * lines, joined by a truncation marker showing how many lines were omitted.
192+ *
193+ * @param output - The full output string.
194+ * @param maxLines - Maximum number of content lines to keep.
195+ * @returns The (possibly truncated) output string.
196+ */
197+export function truncateOutput(output: string, maxLines: number): string {
198+ if (!output) return output;
199+
200+ const lines = output.split("\n");
201+ if (lines.length <= maxLines) return output;
202+
203+ const headCount = Math.ceil(maxLines / 2);
204+ const tailCount = Math.floor(maxLines / 2);
205+ const omitted = lines.length - headCount - tailCount;
206+
207+ const head = lines.slice(0, headCount);
208+ const tail = lines.slice(lines.length - tailCount);
209+
210+ return [...head, `… truncated ${omitted} lines …`, ...tail].join("\n");
211+}
212+
213+// ---------------------------------------------------------------------------
214+// Tool definitions (pi-ai Tool schemas)
215+// ---------------------------------------------------------------------------
216+
217+/** pi-ai tool definition for `edit`. */
218+export const editTool: Tool = {
219+ name: "edit",
220+ description:
221+ "Make an exact-text replacement in a single file. " +
222+ "Provide the file path, the exact text to find, and the replacement text. " +
223+ "The old text must match exactly one location in the file. " +
224+ "To create a new file, use an empty old text and the full file content as new text.",
225+ parameters: Type.Object({
226+ path: Type.String({
227+ description: "File path (absolute or relative to cwd)",
228+ }),
229+ oldText: Type.String({
230+ description:
231+ 'Exact text to find and replace. Empty string means "create new file".',
232+ }),
233+ newText: Type.String({
234+ description: "Replacement text (or full content for new files)",
235+ }),
236+ }),
237+};
238+
239+/** pi-ai tool definition for `shell`. */
240+export const shellTool: Tool = {
241+ name: "shell",
242+ description:
243+ "Run a command in the user's shell. Returns stdout, stderr, and exit code. " +
244+ "Use for exploring the codebase (rg, find, ls, cat), running tests, builds, git, etc.",
245+ parameters: Type.Object({
246+ command: Type.String({ description: "The shell command to execute" }),
247+ }),
248+};