tools.test.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. import { applyPatch } from "diff";
  2. import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
  3. import { tmpdir } from "os";
  4. import { join } from "path";
  5. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. import { executeBashWithOperations } from "../src/core/bash-executor.ts";
  7. import { type BashOperations, createBashTool, createBashToolDefinition, createLocalBashOperations } from "../src/core/tools/bash.ts";
  8. import { computeEditsDiff } from "../src/core/tools/edit-diff.ts";
  9. import { OutputAccumulator } from "../src/core/tools/output-accumulator.ts";
  10. import {
  11. createEditTool,
  12. createFindTool,
  13. createGrepTool,
  14. createLsTool,
  15. createReadTool,
  16. createWriteTool,
  17. } from "../src/index.ts";
  18. import * as shellModule from "../src/utils/shell.ts";
  19. const readTool = createReadTool(process.cwd());
  20. const writeTool = createWriteTool(process.cwd());
  21. const editTool = createEditTool(process.cwd());
  22. const bashTool = createBashTool(process.cwd());
  23. const grepTool = createGrepTool(process.cwd());
  24. const findTool = createFindTool(process.cwd());
  25. const lsTool = createLsTool(process.cwd());
  26. // Helper to extract text from content blocks
  27. function getTextOutput(result: any): string {
  28. return (
  29. result.content
  30. ?.filter((c: any) => c.type === "text")
  31. .map((c: any) => c.text)
  32. .join("\n") || ""
  33. );
  34. }
  35. describe("Coding Agent Tools", () => {
  36. let testDir: string;
  37. beforeEach(() => {
  38. // Create a unique temporary directory for each test
  39. testDir = join(tmpdir(), `coding-agent-test-${Date.now()}`);
  40. mkdirSync(testDir, { recursive: true });
  41. });
  42. afterEach(() => {
  43. // Clean up test directory
  44. rmSync(testDir, { recursive: true, force: true });
  45. });
  46. describe("read tool", () => {
  47. it("should read file contents that fit within limits", async () => {
  48. const testFile = join(testDir, "test.txt");
  49. const content = "Hello, world!\nLine 2\nLine 3";
  50. writeFileSync(testFile, content);
  51. const result = await readTool.execute("test-call-1", { path: testFile });
  52. expect(getTextOutput(result)).toBe(content);
  53. // No truncation message since file fits within limits
  54. expect(getTextOutput(result)).not.toContain("Use offset=");
  55. expect(result.details?.textFile).toEqual({
  56. path: testFile,
  57. content,
  58. numLines: 3,
  59. startLine: 1,
  60. totalLines: 3,
  61. truncatedByOutputLimit: false,
  62. wholeFileAutoTruncated: false,
  63. });
  64. });
  65. it("should handle non-existent files", async () => {
  66. const testFile = join(testDir, "nonexistent.txt");
  67. await expect(readTool.execute("test-call-2", { path: testFile })).rejects.toThrow(/ENOENT|not found/i);
  68. });
  69. it("should truncate files exceeding line limit", async () => {
  70. const testFile = join(testDir, "large.txt");
  71. const lines = Array.from({ length: 2500 }, (_, i) => `Line ${i + 1}`);
  72. writeFileSync(testFile, lines.join("\n"));
  73. const result = await readTool.execute("test-call-3", { path: testFile });
  74. const output = getTextOutput(result);
  75. expect(output).toContain("Line 1");
  76. expect(output).toContain("Line 2000");
  77. expect(output).not.toContain("Line 2001");
  78. expect(output).toContain("[Showing lines 1-2000 of 2500. Use offset=2001 to continue.]");
  79. });
  80. it("should truncate when byte limit exceeded", async () => {
  81. const testFile = join(testDir, "large-bytes.txt");
  82. // Create file that exceeds 50KB byte limit but has fewer than 2000 lines
  83. const lines = Array.from({ length: 500 }, (_, i) => `Line ${i + 1}: ${"x".repeat(200)}`);
  84. writeFileSync(testFile, lines.join("\n"));
  85. const result = await readTool.execute("test-call-4", { path: testFile });
  86. const output = getTextOutput(result);
  87. expect(output).toContain("Line 1:");
  88. // Should show byte limit message
  89. expect(output).toMatch(/\[Showing lines 1-\d+ of 500 \(.* limit\)\. Use offset=\d+ to continue\.\]/);
  90. });
  91. it("should handle offset parameter", async () => {
  92. const testFile = join(testDir, "offset-test.txt");
  93. const lines = Array.from({ length: 100 }, (_, i) => `Line ${i + 1}`);
  94. writeFileSync(testFile, lines.join("\n"));
  95. const result = await readTool.execute("test-call-5", { path: testFile, offset: 51 });
  96. const output = getTextOutput(result);
  97. expect(output).not.toContain("Line 50");
  98. expect(output).toContain("Line 51");
  99. expect(output).toContain("Line 100");
  100. // No truncation message since file fits within limits
  101. expect(output).not.toContain("Use offset=");
  102. });
  103. it("should handle limit parameter", async () => {
  104. const testFile = join(testDir, "limit-test.txt");
  105. const lines = Array.from({ length: 100 }, (_, i) => `Line ${i + 1}`);
  106. writeFileSync(testFile, lines.join("\n"));
  107. const result = await readTool.execute("test-call-6", { path: testFile, limit: 10 });
  108. const output = getTextOutput(result);
  109. expect(output).toContain("Line 1");
  110. expect(output).toContain("Line 10");
  111. expect(output).not.toContain("Line 11");
  112. expect(output).toContain("[90 more lines in file. Use offset=11 to continue.]");
  113. expect(result.details?.textFile).toEqual({
  114. path: testFile,
  115. content: lines.slice(0, 10).join("\n"),
  116. numLines: 10,
  117. startLine: 1,
  118. totalLines: 100,
  119. truncatedByOutputLimit: false,
  120. wholeFileAutoTruncated: false,
  121. });
  122. });
  123. it("should handle offset + limit together", async () => {
  124. const testFile = join(testDir, "offset-limit-test.txt");
  125. const lines = Array.from({ length: 100 }, (_, i) => `Line ${i + 1}`);
  126. writeFileSync(testFile, lines.join("\n"));
  127. const result = await readTool.execute("test-call-7", {
  128. path: testFile,
  129. offset: 41,
  130. limit: 20,
  131. });
  132. const output = getTextOutput(result);
  133. expect(output).not.toContain("Line 40");
  134. expect(output).toContain("Line 41");
  135. expect(output).toContain("Line 60");
  136. expect(output).not.toContain("Line 61");
  137. expect(output).toContain("[40 more lines in file. Use offset=61 to continue.]");
  138. });
  139. it("should show error when offset is beyond file length", async () => {
  140. const testFile = join(testDir, "short.txt");
  141. writeFileSync(testFile, "Line 1\nLine 2\nLine 3");
  142. await expect(readTool.execute("test-call-8", { path: testFile, offset: 100 })).rejects.toThrow(
  143. /Offset 100 is beyond end of file \(3 lines total\)/,
  144. );
  145. });
  146. it("should include truncation details when truncated", async () => {
  147. const testFile = join(testDir, "large-file.txt");
  148. const lines = Array.from({ length: 2500 }, (_, i) => `Line ${i + 1}`);
  149. writeFileSync(testFile, lines.join("\n"));
  150. const result = await readTool.execute("test-call-9", { path: testFile });
  151. expect(result.details).toBeDefined();
  152. expect(result.details?.truncation).toBeDefined();
  153. expect(result.details?.truncation?.truncated).toBe(true);
  154. expect(result.details?.truncation?.truncatedBy).toBe("lines");
  155. expect(result.details?.truncation?.totalLines).toBe(2500);
  156. expect(result.details?.truncation?.outputLines).toBe(2000);
  157. });
  158. it("should detect image MIME type from file magic (not extension)", async () => {
  159. const png1x1Base64 =
  160. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAX+XDSwAAAABJRU5ErkJggg==";
  161. const pngBuffer = Buffer.from(png1x1Base64, "base64");
  162. const testFile = join(testDir, "image.txt");
  163. writeFileSync(testFile, pngBuffer);
  164. const result = await readTool.execute("test-call-img-1", { path: testFile });
  165. expect(result.content[0]?.type).toBe("text");
  166. expect(getTextOutput(result)).toContain("Read image file [image/png]");
  167. const imageBlock = result.content.find(
  168. (c): c is { type: "image"; mimeType: string; data: string } => c.type === "image",
  169. );
  170. expect(imageBlock).toBeDefined();
  171. expect(imageBlock?.mimeType).toBe("image/png");
  172. expect(typeof imageBlock?.data).toBe("string");
  173. expect((imageBlock?.data ?? "").length).toBeGreaterThan(0);
  174. });
  175. it("should treat files with image extension but non-image content as text", async () => {
  176. const testFile = join(testDir, "not-an-image.png");
  177. writeFileSync(testFile, "definitely not a png");
  178. const result = await readTool.execute("test-call-img-2", { path: testFile });
  179. const output = getTextOutput(result);
  180. expect(output).toContain("definitely not a png");
  181. expect(result.content.some((c: any) => c.type === "image")).toBe(false);
  182. });
  183. });
  184. describe("write tool", () => {
  185. it("should write file contents", async () => {
  186. const testFile = join(testDir, "write-test.txt");
  187. const content = "Test content";
  188. const result = await writeTool.execute("test-call-3", { path: testFile, content });
  189. expect(getTextOutput(result)).toContain("Successfully wrote");
  190. expect(getTextOutput(result)).toContain(testFile);
  191. expect(result.details).toBeUndefined();
  192. });
  193. it("should create parent directories", async () => {
  194. const testFile = join(testDir, "nested", "dir", "test.txt");
  195. const content = "Nested content";
  196. const result = await writeTool.execute("test-call-4", { path: testFile, content });
  197. expect(getTextOutput(result)).toContain("Successfully wrote");
  198. });
  199. });
  200. describe("edit tool", () => {
  201. it("should replace text in file", async () => {
  202. const testFile = join(testDir, "edit-test.txt");
  203. const originalContent = "Hello, world!";
  204. writeFileSync(testFile, originalContent);
  205. const result = await editTool.execute("test-call-5", {
  206. path: testFile,
  207. edits: [{ oldText: "world", newText: "testing" }],
  208. });
  209. expect(getTextOutput(result)).toContain("Successfully replaced");
  210. expect(result.details).toBeDefined();
  211. expect(result.details.diff).toBeDefined();
  212. expect(typeof result.details.diff).toBe("string");
  213. expect(result.details.diff).toContain("testing");
  214. expect(result.details.patch).toContain("--- ");
  215. expect(result.details.patch).toContain("+++ ");
  216. expect(result.details.patch).toContain("@@");
  217. expect(result.details.patch).toContain("-Hello, world!");
  218. expect(result.details.patch).toContain("+Hello, testing!");
  219. expect(applyPatch(originalContent, result.details.patch)).toBe("Hello, testing!");
  220. });
  221. it("should fail if text not found", async () => {
  222. const testFile = join(testDir, "edit-test.txt");
  223. const originalContent = "Hello, world!";
  224. writeFileSync(testFile, originalContent);
  225. await expect(
  226. editTool.execute("test-call-6", {
  227. path: testFile,
  228. edits: [{ oldText: "nonexistent", newText: "testing" }],
  229. }),
  230. ).rejects.toThrow(/Could not find the exact text/);
  231. });
  232. it("should include ENOENT when the edit target does not exist", async () => {
  233. const missingFile = join(testDir, "missing.txt");
  234. await expect(
  235. editTool.execute("test-call-6b", {
  236. path: missingFile,
  237. edits: [{ oldText: "hello", newText: "world" }],
  238. }),
  239. ).rejects.toThrow(`Could not edit file: ${missingFile}. Error code: ENOENT.`);
  240. });
  241. it("should fail if text appears multiple times", async () => {
  242. const testFile = join(testDir, "edit-test.txt");
  243. const originalContent = "foo foo foo";
  244. writeFileSync(testFile, originalContent);
  245. await expect(
  246. editTool.execute("test-call-7", {
  247. path: testFile,
  248. edits: [{ oldText: "foo", newText: "bar" }],
  249. }),
  250. ).rejects.toThrow(/Found 3 occurrences/);
  251. });
  252. it("should replace multiple disjoint regions in one call", async () => {
  253. const testFile = join(testDir, "edit-multi.txt");
  254. writeFileSync(testFile, "alpha\nbeta\ngamma\ndelta\n");
  255. const result = await editTool.execute("test-call-8", {
  256. path: testFile,
  257. edits: [
  258. { oldText: "alpha\n", newText: "ALPHA\n" },
  259. { oldText: "gamma\n", newText: "GAMMA\n" },
  260. ],
  261. });
  262. expect(getTextOutput(result)).toContain("Successfully replaced 2 block(s)");
  263. expect(readFileSync(testFile, "utf-8")).toBe("ALPHA\nbeta\nGAMMA\ndelta\n");
  264. expect(result.details?.diff).toContain("ALPHA");
  265. expect(result.details?.diff).toContain("GAMMA");
  266. });
  267. it("should collapse large unchanged gaps in multi-edit diffs", async () => {
  268. const testFile = join(testDir, "edit-multi-large-gap.txt");
  269. const lines = Array.from({ length: 600 }, (_, i) => `line ${String(i + 1).padStart(3, "0")}`);
  270. writeFileSync(testFile, `${lines.join("\n")}\n`);
  271. const result = await editTool.execute("test-call-8b", {
  272. path: testFile,
  273. edits: [
  274. { oldText: "line 100\n", newText: "LINE 100\n" },
  275. { oldText: "line 300\n", newText: "LINE 300\n" },
  276. { oldText: "line 500\n", newText: "LINE 500\n" },
  277. ],
  278. });
  279. const diff = result.details?.diff ?? "";
  280. expect(diff).toContain("LINE 100");
  281. expect(diff).toContain("LINE 300");
  282. expect(diff).toContain("LINE 500");
  283. expect(diff).toContain("...");
  284. expect(diff).not.toContain("line 250");
  285. expect(diff.split("\n").length).toBeLessThan(50);
  286. });
  287. it("should match edits against the original file, not incrementally", async () => {
  288. const testFile = join(testDir, "edit-multi-original.txt");
  289. writeFileSync(testFile, "foo\nbar\nbaz\n");
  290. await editTool.execute("test-call-9", {
  291. path: testFile,
  292. edits: [
  293. { oldText: "foo\n", newText: "foo bar\n" },
  294. { oldText: "bar\n", newText: "BAR\n" },
  295. ],
  296. });
  297. expect(readFileSync(testFile, "utf-8")).toBe("foo bar\nBAR\nbaz\n");
  298. });
  299. it("should fail when edits is empty", async () => {
  300. const testFile = join(testDir, "edit-empty-edits.txt");
  301. writeFileSync(testFile, "hello\nworld\n");
  302. await expect(
  303. editTool.execute("test-call-11", {
  304. path: testFile,
  305. edits: [],
  306. }),
  307. ).rejects.toThrow(/edits must contain at least one replacement/);
  308. });
  309. it("should fail when multi-edit regions overlap", async () => {
  310. const testFile = join(testDir, "edit-overlap.txt");
  311. writeFileSync(testFile, "one\ntwo\nthree\n");
  312. await expect(
  313. editTool.execute("test-call-12", {
  314. path: testFile,
  315. edits: [
  316. { oldText: "one\ntwo\n", newText: "ONE\nTWO\n" },
  317. { oldText: "two\nthree\n", newText: "TWO\nTHREE\n" },
  318. ],
  319. }),
  320. ).rejects.toThrow(/overlap/);
  321. });
  322. it("should not partially apply edits when one edit fails", async () => {
  323. const testFile = join(testDir, "edit-no-partial.txt");
  324. const originalContent = "alpha\nbeta\ngamma\n";
  325. writeFileSync(testFile, originalContent);
  326. await expect(
  327. editTool.execute("test-call-13", {
  328. path: testFile,
  329. edits: [
  330. { oldText: "alpha\n", newText: "ALPHA\n" },
  331. { oldText: "missing\n", newText: "MISSING\n" },
  332. ],
  333. }),
  334. ).rejects.toThrow(/Could not find/);
  335. expect(readFileSync(testFile, "utf-8")).toBe(originalContent);
  336. });
  337. it("should include EACCES for read-only files", async () => {
  338. const testFile = join(testDir, "edit-readonly.txt");
  339. writeFileSync(testFile, "hello\n");
  340. chmodSync(testFile, 0o444);
  341. await expect(
  342. editTool.execute("test-call-14", {
  343. path: testFile,
  344. edits: [{ oldText: "hello", newText: "world" }],
  345. }),
  346. ).rejects.toThrow(`Could not edit file: ${testFile}. Error code: EACCES.`);
  347. });
  348. it("should include the original error message for unknown edit access errors", async () => {
  349. const genericFailureTool = createEditTool(testDir, {
  350. operations: {
  351. access: async () => {
  352. throw new Error("disk offline");
  353. },
  354. readFile: async () => Buffer.from("hello\n", "utf-8"),
  355. writeFile: async () => {},
  356. },
  357. });
  358. await expect(
  359. genericFailureTool.execute("test-call-16", {
  360. path: "broken.txt",
  361. edits: [{ oldText: "hello", newText: "world" }],
  362. }),
  363. ).rejects.toThrow("Could not edit file: broken.txt. Error: disk offline.");
  364. });
  365. it("should include ENOENT in diff preview for missing files", async () => {
  366. const missingFile = join(testDir, "missing-preview.txt");
  367. const result = await computeEditsDiff(missingFile, [{ oldText: "hello", newText: "world" }], testDir);
  368. expect(result).toEqual({ error: `Could not edit file: ${missingFile}. Error code: ENOENT.` });
  369. });
  370. it("should include EACCES in diff preview for unreadable files", async () => {
  371. const unreadableFile = join(testDir, "unreadable-preview.txt");
  372. writeFileSync(unreadableFile, "hello\n");
  373. chmodSync(unreadableFile, 0o222);
  374. const result = await computeEditsDiff(unreadableFile, [{ oldText: "hello", newText: "world" }], testDir);
  375. expect(result).toEqual({ error: `Could not edit file: ${unreadableFile}. Error code: EACCES.` });
  376. });
  377. });
  378. describe("bash tool", () => {
  379. it("persists valid UTF-8 when stdout and stderr chunks interleave", async () => {
  380. const accumulator = new OutputAccumulator({ maxBytes: 3, maxLines: 100 });
  381. accumulator.append(Buffer.from([0xe6]), "stdout");
  382. accumulator.append(Buffer.from("X"), "stderr");
  383. accumulator.append(Buffer.from([0xb1, 0x89]), "stdout");
  384. accumulator.finish();
  385. const snapshot = accumulator.snapshot({ persistIfTruncated: true });
  386. await accumulator.closeTempFile();
  387. expect(snapshot.content).toBe("汉");
  388. expect(snapshot.fullOutputPath).toBeDefined();
  389. expect(readFileSync(snapshot.fullOutputPath!, "utf8")).toBe("X汉");
  390. rmSync(snapshot.fullOutputPath!, { force: true });
  391. });
  392. it("describes the command as the current shell rather than always calling it Bash", () => {
  393. const definition = createBashToolDefinition(testDir, { operations: { exec: async () => ({ exitCode: 0 }) } });
  394. const commandDescription = (definition.parameters as { properties?: { command?: { description?: string } } }).properties
  395. ?.command?.description;
  396. expect(commandDescription).toContain("current shell");
  397. expect(commandDescription).toContain("default shell is PowerShell");
  398. });
  399. it("should execute simple commands", async () => {
  400. const result = await bashTool.execute("test-call-8", { command: "echo 'test output'" });
  401. expect(getTextOutput(result)).toContain("test output");
  402. expect(result.details?.processOutput).toEqual({
  403. stdout: "test output\n",
  404. stderr: "",
  405. exitCode: 0,
  406. interrupted: false,
  407. stdoutTruncated: false,
  408. stderrTruncated: false,
  409. });
  410. });
  411. it("preserves stdout and stderr as separate source-owned process facts", async () => {
  412. const result = await bashTool.execute("test-call-split-streams", {
  413. command: "printf 'from-stdout'; printf 'from-stderr' >&2",
  414. });
  415. expect(result.details?.processOutput).toMatchObject({
  416. stdout: "from-stdout",
  417. stderr: "from-stderr",
  418. exitCode: 0,
  419. interrupted: false,
  420. stdoutTruncated: false,
  421. stderrTruncated: false,
  422. });
  423. });
  424. it("should handle command errors", async () => {
  425. await expect(bashTool.execute("test-call-9", { command: "exit 1" })).rejects.toThrow(
  426. /(Command failed|code 1)/,
  427. );
  428. });
  429. it("should respect timeout", async () => {
  430. await expect(bashTool.execute("test-call-10", { command: "sleep 5", timeout: 1 })).rejects.toThrow(
  431. /timed out/i,
  432. );
  433. });
  434. it("should include full output path for truncated timeout and abort errors", async () => {
  435. for (const testCase of [
  436. { error: "timeout:5", expected: "Command timed out after 5 seconds" },
  437. { error: "aborted", expected: "Command aborted" },
  438. ]) {
  439. const operations: BashOperations = {
  440. exec: async (_command, _cwd, { onData }) => {
  441. for (let i = 1; i <= 3000; i++) {
  442. onData(Buffer.from(`${i}\n`, "utf-8"));
  443. }
  444. throw new Error(testCase.error);
  445. },
  446. };
  447. const bash = createBashTool(testDir, { operations });
  448. let error: unknown;
  449. try {
  450. await bash.execute(`test-call-${testCase.error}`, { command: "chatty-fail" });
  451. } catch (err) {
  452. error = err;
  453. }
  454. expect(error).toBeInstanceOf(Error);
  455. const message = (error as Error).message;
  456. expect(message).toContain(testCase.expected);
  457. expect(message).toMatch(/\[Showing lines \d+-\d+ of \d+\. Full output: /);
  458. expect(message).not.toContain("Full output: undefined");
  459. const fullOutputPath = message.match(/Full output: ([^\]\n]+)/)?.[1];
  460. expect(fullOutputPath).toBeDefined();
  461. expect(existsSync(fullOutputPath!)).toBe(true);
  462. const fullOutput = readFileSync(fullOutputPath!, "utf-8");
  463. expect(fullOutput).toContain("1\n2\n3");
  464. expect(fullOutput).toContain("2998\n2999\n3000");
  465. }
  466. });
  467. it("should throw error when cwd does not exist", async () => {
  468. const nonexistentCwd = "/this/directory/definitely/does/not/exist/12345";
  469. const bashToolWithBadCwd = createBashTool(nonexistentCwd);
  470. await expect(bashToolWithBadCwd.execute("test-call-11", { command: "echo test" })).rejects.toThrow(
  471. /Working directory does not exist/,
  472. );
  473. });
  474. it("should handle process spawn errors", async () => {
  475. const invalidShell = {
  476. shell: "/nonexistent-shell-path-xyz123",
  477. args: ["-c"],
  478. type: "bash" as const,
  479. };
  480. vi.spyOn(shellModule, "getShellConfig").mockReturnValueOnce(invalidShell).mockReturnValueOnce(invalidShell);
  481. const bashWithBadShell = createBashTool(testDir);
  482. await expect(bashWithBadShell.execute("test-call-12", { command: "echo test" })).rejects.toThrow(/ENOENT/);
  483. });
  484. it("should pass shellPath through to shell resolution", async () => {
  485. const getShellConfigSpy = vi.spyOn(shellModule, "getShellConfig");
  486. const bashWithCustomShell = createBashTool(testDir, {
  487. shellPath: "/custom/bash",
  488. operations: {
  489. exec: async () => ({ exitCode: 0 }),
  490. },
  491. });
  492. await bashWithCustomShell.execute("test-call-12b", { command: "echo test" });
  493. expect(getShellConfigSpy).not.toHaveBeenCalled();
  494. const ops = createLocalBashOperations({ shellPath: "/custom/bash" });
  495. await expect(
  496. ops.exec("echo test", testDir, {
  497. onData: () => {},
  498. }),
  499. ).rejects.toThrow("Custom shell path not found: /custom/bash");
  500. expect(getShellConfigSpy).toHaveBeenCalledWith("/custom/bash");
  501. });
  502. it("should prepend command prefix when configured", async () => {
  503. const bashWithPrefix = createBashTool(testDir, {
  504. commandPrefix: "export TEST_VAR=hello",
  505. });
  506. const result = await bashWithPrefix.execute("test-prefix-1", { command: "echo $TEST_VAR" });
  507. expect(getTextOutput(result).trim()).toBe("hello");
  508. });
  509. it("should include output from both prefix and command", async () => {
  510. const bashWithPrefix = createBashTool(testDir, {
  511. commandPrefix: "echo prefix-output",
  512. });
  513. const result = await bashWithPrefix.execute("test-prefix-2", { command: "echo command-output" });
  514. expect(getTextOutput(result).trim()).toBe("prefix-output\ncommand-output");
  515. });
  516. it("should work without command prefix", async () => {
  517. const bashWithoutPrefix = createBashTool(testDir, {});
  518. const result = await bashWithoutPrefix.execute("test-prefix-3", { command: "echo no-prefix" });
  519. expect(getTextOutput(result).trim()).toBe("no-prefix");
  520. });
  521. it("should coalesce streaming updates for chatty output", async () => {
  522. const operations: BashOperations = {
  523. exec: async (_command, _cwd, { onData }) => {
  524. for (let i = 0; i < 5000; i++) {
  525. onData(Buffer.from(`line ${i}\n`, "utf-8"));
  526. }
  527. return { exitCode: 0 };
  528. },
  529. };
  530. const updates: Array<{ content: Array<{ type: string; text?: string }>; details?: unknown }> = [];
  531. const bash = createBashTool(testDir, { operations });
  532. const result = await bash.execute("test-call-chatty-updates", { command: "chatty" }, undefined, (update) =>
  533. updates.push(update),
  534. );
  535. expect(updates.length).toBeLessThan(25);
  536. expect(getTextOutput(result)).toContain("line 4999");
  537. });
  538. it("should not count a trailing newline as an extra truncated bash output line", async () => {
  539. const operations: BashOperations = {
  540. exec: async (_command, _cwd, { onData }) => {
  541. for (let i = 1; i <= 4000; i++) {
  542. onData(Buffer.from(`line-${String(i).padStart(4, "0")}\n`, "utf-8"));
  543. }
  544. return { exitCode: 0 };
  545. },
  546. };
  547. const bash = createBashTool(testDir, { operations });
  548. const result = await bash.execute("test-call-trailing-newline-line-count", { command: "many-lines" });
  549. const output = getTextOutput(result);
  550. expect(result.details?.truncation?.totalLines).toBe(4000);
  551. expect(result.details?.truncation?.outputLines).toBe(2000);
  552. expect(output).toContain("line-2001");
  553. expect(output).toContain("line-4000");
  554. expect(output).toMatch(/\[Showing lines 2001-4000 of 4000\. Full output: /);
  555. expect(output).not.toContain("4001");
  556. });
  557. it("should decode UTF-8 characters split across output chunks", async () => {
  558. const euro = Buffer.from("€\n", "utf-8");
  559. const operations: BashOperations = {
  560. exec: async (_command, _cwd, { onData }) => {
  561. onData(euro.subarray(0, 1));
  562. onData(euro.subarray(1));
  563. return { exitCode: 0 };
  564. },
  565. };
  566. const bash = createBashTool(testDir, { operations });
  567. const result = await bash.execute("test-call-split-utf8", { command: "split-utf8" });
  568. expect(getTextOutput(result).trim()).toBe("€");
  569. });
  570. it("should expose local bash operations for extension reuse", async () => {
  571. const ops = createLocalBashOperations();
  572. const chunks: Buffer[] = [];
  573. const result = await ops.exec("echo $TEST_LOCAL_BASH_OPS", testDir, {
  574. onData: (data) => chunks.push(data),
  575. env: { ...process.env, TEST_LOCAL_BASH_OPS: "from-local-ops" },
  576. });
  577. expect(result.exitCode).toBe(0);
  578. expect(Buffer.concat(chunks).toString("utf-8").trim()).toBe("from-local-ops");
  579. });
  580. it("should preserve executeBash sanitization when using local bash operations", async () => {
  581. const result = await executeBashWithOperations(
  582. "printf '\\033[31mred\\033[0m\\r\\n'",
  583. process.cwd(),
  584. createLocalBashOperations(),
  585. );
  586. expect(result.exitCode).toBe(0);
  587. expect(result.output).toBe("red\n");
  588. });
  589. it("should persist full output when truncation happens by line count only", async () => {
  590. const bash = createBashTool(testDir);
  591. const result = await bash.execute("test-call-line-truncation", { command: "seq 3000" });
  592. const output = getTextOutput(result);
  593. const fullOutputPath = result.details?.fullOutputPath;
  594. expect(result.details?.truncation?.truncated).toBe(true);
  595. expect(result.details?.truncation?.truncatedBy).toBe("lines");
  596. expect(fullOutputPath).toBeDefined();
  597. expect(output).toMatch(/\[Showing lines \d+-\d+ of \d+\. Full output: /);
  598. expect(output).not.toContain("Full output: undefined");
  599. for (let i = 0; i < 20 && (!fullOutputPath || !existsSync(fullOutputPath)); i++) {
  600. await new Promise((resolve) => setTimeout(resolve, 10));
  601. }
  602. expect(fullOutputPath).toBeDefined();
  603. expect(existsSync(fullOutputPath!)).toBe(true);
  604. const fullOutput = readFileSync(fullOutputPath!, "utf-8");
  605. expect(fullOutput).toContain("1\n2\n3");
  606. expect(fullOutput).toContain("2998\n2999\n3000");
  607. });
  608. it("executeBash should persist full output when truncation happens by line count only", async () => {
  609. const result = await executeBashWithOperations("seq 3000", process.cwd(), createLocalBashOperations());
  610. const fullOutputPath = result.fullOutputPath;
  611. expect(result.truncated).toBe(true);
  612. expect(fullOutputPath).toBeDefined();
  613. for (let i = 0; i < 20 && (!fullOutputPath || !existsSync(fullOutputPath)); i++) {
  614. await new Promise((resolve) => setTimeout(resolve, 10));
  615. }
  616. expect(existsSync(fullOutputPath!)).toBe(true);
  617. const fullOutput = readFileSync(fullOutputPath!, "utf-8");
  618. expect(fullOutput).toContain("1\n2\n3");
  619. expect(fullOutput).toContain("2998\n2999\n3000");
  620. });
  621. });
  622. describe("grep tool", () => {
  623. it("should include filename when searching a single file", async () => {
  624. const testFile = join(testDir, "example.txt");
  625. writeFileSync(testFile, "first line\nmatch line\nlast line");
  626. const result = await grepTool.execute("test-call-11", {
  627. pattern: "match",
  628. path: testFile,
  629. });
  630. const output = getTextOutput(result);
  631. expect(output).toContain("example.txt:2: match line");
  632. });
  633. it("should respect global limit and include context lines", async () => {
  634. const testFile = join(testDir, "context.txt");
  635. const content = ["before", "match one", "after", "middle", "match two", "after two"].join("\n");
  636. writeFileSync(testFile, content);
  637. const result = await grepTool.execute("test-call-12", {
  638. pattern: "match",
  639. path: testFile,
  640. limit: 1,
  641. context: 1,
  642. });
  643. const output = getTextOutput(result);
  644. expect(output).toContain("context.txt-1- before");
  645. expect(output).toContain("context.txt:2: match one");
  646. expect(output).toContain("context.txt-3- after");
  647. expect(output).toContain("[1 matches limit reached. Use limit=2 for more, or refine pattern]");
  648. // Ensure second match is not present
  649. expect(output).not.toContain("match two");
  650. });
  651. it("should treat flag-like patterns as search text", async () => {
  652. const marker = join(testDir, "grep-injection-marker");
  653. const payload = join(testDir, "payload.sh");
  654. const testFile = join(testDir, "target.txt");
  655. writeFileSync(payload, `#!/bin/sh\necho executed > ${marker}\ncat "$1"\n`);
  656. chmodSync(payload, 0o755);
  657. writeFileSync(testFile, "target\n");
  658. const result = await grepTool.execute("test-call-grep-injection", {
  659. pattern: `--pre=${payload}`,
  660. path: testDir,
  661. });
  662. expect(getTextOutput(result)).toContain("No matches found");
  663. expect(existsSync(marker)).toBe(false);
  664. });
  665. });
  666. describe("find tool", () => {
  667. it("should include hidden files that are not gitignored", async () => {
  668. const hiddenDir = join(testDir, ".secret");
  669. mkdirSync(hiddenDir);
  670. writeFileSync(join(hiddenDir, "hidden.txt"), "hidden");
  671. writeFileSync(join(testDir, "visible.txt"), "visible");
  672. const result = await findTool.execute("test-call-13", {
  673. pattern: "**/*.txt",
  674. path: testDir,
  675. });
  676. const outputLines = getTextOutput(result)
  677. .split("\n")
  678. .map((line) => line.trim())
  679. .filter(Boolean);
  680. expect(outputLines).toContain("visible.txt");
  681. expect(outputLines).toContain(".secret/hidden.txt");
  682. });
  683. it("should respect .gitignore", async () => {
  684. writeFileSync(join(testDir, ".gitignore"), "ignored.txt\n");
  685. writeFileSync(join(testDir, "ignored.txt"), "ignored");
  686. writeFileSync(join(testDir, "kept.txt"), "kept");
  687. const result = await findTool.execute("test-call-14", {
  688. pattern: "**/*.txt",
  689. path: testDir,
  690. });
  691. const output = getTextOutput(result);
  692. expect(output).toContain("kept.txt");
  693. expect(output).not.toContain("ignored.txt");
  694. });
  695. it("should surface fd glob parse errors", async () => {
  696. await expect(
  697. findTool.execute("test-call-15", {
  698. pattern: "[",
  699. path: testDir,
  700. }),
  701. ).rejects.toThrow(/error parsing glob|fd exited with code 1|fd error/i);
  702. });
  703. it("should treat flag-like patterns as search text", async () => {
  704. const result = await findTool.execute("test-call-find-flag-pattern", {
  705. pattern: "--help",
  706. path: testDir,
  707. });
  708. expect(getTextOutput(result)).toContain("No files found matching pattern");
  709. });
  710. });
  711. describe("ls tool", () => {
  712. it("should list dotfiles and directories", async () => {
  713. writeFileSync(join(testDir, ".hidden-file"), "secret");
  714. mkdirSync(join(testDir, ".hidden-dir"));
  715. const result = await lsTool.execute("test-call-15", { path: testDir });
  716. const output = getTextOutput(result);
  717. expect(output).toContain(".hidden-file");
  718. expect(output).toContain(".hidden-dir/");
  719. });
  720. });
  721. });
  722. describe("edit tool fuzzy matching", () => {
  723. let testDir: string;
  724. beforeEach(() => {
  725. testDir = join(tmpdir(), `coding-agent-fuzzy-test-${Date.now()}`);
  726. mkdirSync(testDir, { recursive: true });
  727. });
  728. afterEach(() => {
  729. rmSync(testDir, { recursive: true, force: true });
  730. });
  731. it("should match text with trailing whitespace stripped", async () => {
  732. const testFile = join(testDir, "trailing-ws.txt");
  733. // File has trailing spaces on lines
  734. writeFileSync(testFile, "line one \nline two \nline three\n");
  735. // oldText without trailing whitespace should still match
  736. const result = await editTool.execute("test-fuzzy-1", {
  737. path: testFile,
  738. edits: [{ oldText: "line one\nline two\n", newText: "replaced\n" }],
  739. });
  740. expect(getTextOutput(result)).toContain("Successfully replaced");
  741. const content = readFileSync(testFile, "utf-8");
  742. expect(content).toBe("replaced\nline three\n");
  743. });
  744. it("should match fullwidth punctuation in Chinese text", async () => {
  745. const testFile = join(testDir, "chinese-punctuation.txt");
  746. writeFileSync(testFile, "你好,世界\n你好(世界)\n");
  747. const result = await editTool.execute("test-fuzzy-chinese", {
  748. path: testFile,
  749. edits: [{ oldText: "你好,世界\n你好(世界)\n", newText: "你好,pi\n你好(pi)\n" }],
  750. });
  751. expect(getTextOutput(result)).toContain("Successfully replaced");
  752. const content = readFileSync(testFile, "utf-8");
  753. expect(content).toBe("你好,pi\n你好(pi)\n");
  754. });
  755. it("should match compatibility-equivalent Unicode forms", async () => {
  756. const testFile = join(testDir, "unicode-compatibility.txt");
  757. writeFileSync(testFile, "ABC123\ncafe\u0301\n");
  758. const result = await editTool.execute("test-fuzzy-unicode", {
  759. path: testFile,
  760. edits: [{ oldText: "ABC123\ncafé\n", newText: "XYZ789\ncoffee\n" }],
  761. });
  762. expect(getTextOutput(result)).toContain("Successfully replaced");
  763. const content = readFileSync(testFile, "utf-8");
  764. expect(content).toBe("XYZ789\ncoffee\n");
  765. });
  766. it("should match smart single quotes to ASCII quotes", async () => {
  767. const testFile = join(testDir, "smart-quotes.txt");
  768. // File has smart/curly single quotes (U+2018, U+2019)
  769. writeFileSync(testFile, "console.log(\u2018hello\u2019);\n");
  770. // oldText with ASCII quotes should match
  771. const result = await editTool.execute("test-fuzzy-2", {
  772. path: testFile,
  773. edits: [{ oldText: "console.log('hello');", newText: "console.log('world');" }],
  774. });
  775. expect(getTextOutput(result)).toContain("Successfully replaced");
  776. const content = readFileSync(testFile, "utf-8");
  777. expect(content).toContain("world");
  778. });
  779. it("should match smart double quotes to ASCII quotes", async () => {
  780. const testFile = join(testDir, "smart-double-quotes.txt");
  781. // File has smart/curly double quotes (U+201C, U+201D)
  782. writeFileSync(testFile, "const msg = \u201CHello World\u201D;\n");
  783. // oldText with ASCII quotes should match
  784. const result = await editTool.execute("test-fuzzy-3", {
  785. path: testFile,
  786. edits: [{ oldText: 'const msg = "Hello World";', newText: 'const msg = "Goodbye";' }],
  787. });
  788. expect(getTextOutput(result)).toContain("Successfully replaced");
  789. const content = readFileSync(testFile, "utf-8");
  790. expect(content).toContain("Goodbye");
  791. });
  792. it("should match Unicode dashes to ASCII hyphen", async () => {
  793. const testFile = join(testDir, "unicode-dashes.txt");
  794. // File has en-dash (U+2013) and em-dash (U+2014)
  795. writeFileSync(testFile, "range: 1\u20135\nbreak\u2014here\n");
  796. // oldText with ASCII hyphens should match
  797. const result = await editTool.execute("test-fuzzy-4", {
  798. path: testFile,
  799. edits: [{ oldText: "range: 1-5\nbreak-here", newText: "range: 10-50\nbreak--here" }],
  800. });
  801. expect(getTextOutput(result)).toContain("Successfully replaced");
  802. const content = readFileSync(testFile, "utf-8");
  803. expect(content).toContain("10-50");
  804. });
  805. it("should match non-breaking space to regular space", async () => {
  806. const testFile = join(testDir, "nbsp.txt");
  807. // File has non-breaking space (U+00A0)
  808. writeFileSync(testFile, "hello\u00A0world\n");
  809. // oldText with regular space should match
  810. const result = await editTool.execute("test-fuzzy-5", {
  811. path: testFile,
  812. edits: [{ oldText: "hello world", newText: "hello universe" }],
  813. });
  814. expect(getTextOutput(result)).toContain("Successfully replaced");
  815. const content = readFileSync(testFile, "utf-8");
  816. expect(content).toContain("universe");
  817. });
  818. it("should prefer exact match over fuzzy match", async () => {
  819. const testFile = join(testDir, "exact-preferred.txt");
  820. // File has both exact and fuzzy-matchable content
  821. writeFileSync(testFile, "const x = 'exact';\nconst y = 'other';\n");
  822. const result = await editTool.execute("test-fuzzy-6", {
  823. path: testFile,
  824. edits: [{ oldText: "const x = 'exact';", newText: "const x = 'changed';" }],
  825. });
  826. expect(getTextOutput(result)).toContain("Successfully replaced");
  827. const content = readFileSync(testFile, "utf-8");
  828. expect(content).toBe("const x = 'changed';\nconst y = 'other';\n");
  829. });
  830. it("should still fail when text is not found even with fuzzy matching", async () => {
  831. const testFile = join(testDir, "no-match.txt");
  832. writeFileSync(testFile, "completely different content\n");
  833. await expect(
  834. editTool.execute("test-fuzzy-7", {
  835. path: testFile,
  836. edits: [{ oldText: "this does not exist", newText: "replacement" }],
  837. }),
  838. ).rejects.toThrow(/Could not find the exact text/);
  839. });
  840. it("should detect duplicates after fuzzy normalization", async () => {
  841. const testFile = join(testDir, "fuzzy-dups.txt");
  842. // Two lines that are identical after trailing whitespace is stripped
  843. writeFileSync(testFile, "hello world \nhello world\n");
  844. await expect(
  845. editTool.execute("test-fuzzy-8", {
  846. path: testFile,
  847. edits: [{ oldText: "hello world", newText: "replaced" }],
  848. }),
  849. ).rejects.toThrow(/Found 2 occurrences/);
  850. });
  851. it("should support fuzzy matching in multi-edit mode", async () => {
  852. const testFile = join(testDir, "fuzzy-multi.txt");
  853. writeFileSync(testFile, "console.log(\u2018hello\u2019);\nhello\u00A0world\n");
  854. await editTool.execute("test-fuzzy-9", {
  855. path: testFile,
  856. edits: [
  857. { oldText: "console.log('hello');\n", newText: "console.log('world');\n" },
  858. { oldText: "hello world\n", newText: "hello universe\n" },
  859. ],
  860. });
  861. expect(readFileSync(testFile, "utf-8")).toBe("console.log('world');\nhello universe\n");
  862. });
  863. });
  864. describe("edit tool CRLF handling", () => {
  865. let testDir: string;
  866. beforeEach(() => {
  867. testDir = join(tmpdir(), `coding-agent-crlf-test-${Date.now()}`);
  868. mkdirSync(testDir, { recursive: true });
  869. });
  870. afterEach(() => {
  871. rmSync(testDir, { recursive: true, force: true });
  872. });
  873. it("should match LF oldText against CRLF file content", async () => {
  874. const testFile = join(testDir, "crlf-test.txt");
  875. writeFileSync(testFile, "line one\r\nline two\r\nline three\r\n");
  876. const result = await editTool.execute("test-crlf-1", {
  877. path: testFile,
  878. edits: [{ oldText: "line two\n", newText: "replaced line\n" }],
  879. });
  880. expect(getTextOutput(result)).toContain("Successfully replaced");
  881. });
  882. it("should preserve CRLF line endings after edit", async () => {
  883. const testFile = join(testDir, "crlf-preserve.txt");
  884. writeFileSync(testFile, "first\r\nsecond\r\nthird\r\n");
  885. await editTool.execute("test-crlf-2", {
  886. path: testFile,
  887. edits: [{ oldText: "second\n", newText: "REPLACED\n" }],
  888. });
  889. const content = readFileSync(testFile, "utf-8");
  890. expect(content).toBe("first\r\nREPLACED\r\nthird\r\n");
  891. });
  892. it("should preserve LF line endings for LF files", async () => {
  893. const testFile = join(testDir, "lf-preserve.txt");
  894. writeFileSync(testFile, "first\nsecond\nthird\n");
  895. await editTool.execute("test-lf-1", {
  896. path: testFile,
  897. edits: [{ oldText: "second\n", newText: "REPLACED\n" }],
  898. });
  899. const content = readFileSync(testFile, "utf-8");
  900. expect(content).toBe("first\nREPLACED\nthird\n");
  901. });
  902. it("should detect duplicates across CRLF/LF variants", async () => {
  903. const testFile = join(testDir, "mixed-endings.txt");
  904. writeFileSync(testFile, "hello\r\nworld\r\n---\r\nhello\nworld\n");
  905. await expect(
  906. editTool.execute("test-crlf-dup", {
  907. path: testFile,
  908. edits: [{ oldText: "hello\nworld\n", newText: "replaced\n" }],
  909. }),
  910. ).rejects.toThrow(/Found 2 occurrences/);
  911. });
  912. it("should preserve UTF-8 BOM after edit", async () => {
  913. const testFile = join(testDir, "bom-test.txt");
  914. writeFileSync(testFile, "\uFEFFfirst\r\nsecond\r\nthird\r\n");
  915. await editTool.execute("test-bom", {
  916. path: testFile,
  917. edits: [{ oldText: "second\n", newText: "REPLACED\n" }],
  918. });
  919. const content = readFileSync(testFile, "utf-8");
  920. expect(content).toBe("\uFEFFfirst\r\nREPLACED\r\nthird\r\n");
  921. });
  922. it("should preserve CRLF line endings and BOM in multi-edit mode", async () => {
  923. const testFile = join(testDir, "bom-crlf-multi.txt");
  924. writeFileSync(testFile, "\uFEFFfirst\r\nsecond\r\nthird\r\nfourth\r\n");
  925. await editTool.execute("test-crlf-multi", {
  926. path: testFile,
  927. edits: [
  928. { oldText: "second\n", newText: "SECOND\n" },
  929. { oldText: "fourth\n", newText: "FOURTH\n" },
  930. ],
  931. });
  932. const content = readFileSync(testFile, "utf-8");
  933. expect(content).toBe("\uFEFFfirst\r\nSECOND\r\nthird\r\nFOURTH\r\n");
  934. });
  935. });