file-tool-port.test.ts 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. import { join, resolve } from "node:path";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. READ_IMAGE_MAX_BASE64_BYTES,
  5. READ_IMAGE_MAX_DIMENSION,
  6. READ_IMAGE_MAX_INPUT_BYTES,
  7. READ_IMAGE_TARGET_BYTES,
  8. READ_MAX_OUTPUT_TOKENS,
  9. createImageProcessorError,
  10. createFileSystemError,
  11. type FileSystemLineEndings,
  12. type FileSystemPort,
  13. type FileSystemReadTextRangeResult,
  14. type FileSystemReadTextResult,
  15. type FileSystemRevision,
  16. type FileSystemSearchFilesResult,
  17. type FileSystemSearchTextResult,
  18. type FileSystemStatResult,
  19. type FileSystemTextEncoding,
  20. type FileSystemWriteTextRequest,
  21. type ImageProcessorPort,
  22. type ApplyPatchOutput,
  23. } from "@zcode/contracts";
  24. import { globHandler } from "../src/tool/handlers/glob.js";
  25. import { grepHandler } from "../src/tool/handlers/grep.js";
  26. import { readHandler, readToolEntry } from "../src/tool/handlers/read.js";
  27. import { readTextFileForModel } from "../src/tool/handlers/read-text.js";
  28. import { estimateTokens } from "../src/context/utils.js";
  29. import { writeHandler } from "../src/tool/handlers/write.js";
  30. import { editHandler } from "../src/tool/handlers/edit.js";
  31. import { applyPatchHandler } from "../src/tool/handlers/apply-patch.js";
  32. import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
  33. import type { ReadFileStateMap, ToolExecutionContext } from "../src/tool/types.js";
  34. // 只有个别用例替换 token 估算(模拟开头远比全文密的文件);其余用例用真实估算。
  35. const tokenEstimate = vi.hoisted(() => ({
  36. override: undefined as ((text: string) => number) | undefined,
  37. }));
  38. vi.mock("../src/context/utils.js", async (importOriginal) => {
  39. const actual = await importOriginal<typeof import("../src/context/utils.js")>();
  40. return {
  41. ...actual,
  42. estimateTokens: (text: string) => tokenEstimate.override?.(text) ?? actual.estimateTokens(text),
  43. };
  44. });
  45. const workspaceRoot = resolve("/work");
  46. const projectRoot = join(workspaceRoot, "project");
  47. const filePath = join(workspaceRoot, "file.txt");
  48. const projectFilePath = join(projectRoot, "src", "file.txt");
  49. const outsidePath = join(resolve("/tmp"), "outside.txt");
  50. describe("file tool handlers", () => {
  51. it("reads text through FileSystemPort and applies visible line ranges", async () => {
  52. const fs = createMemoryFileSystem({
  53. [filePath]: "one\ntwo\nthree\n",
  54. });
  55. const output = await readHandler(
  56. {
  57. file_path: filePath,
  58. offset: 1,
  59. limit: 2,
  60. },
  61. contextWith(fs),
  62. );
  63. expect(output).toMatchObject({
  64. type: "text",
  65. filePath,
  66. content: "one\ntwo",
  67. numLines: 2,
  68. startLine: 1,
  69. totalLines: 4,
  70. });
  71. expect(fs.readPaths).toEqual([filePath]);
  72. });
  73. it("rejects large full text reads with the 256KB guard", async () => {
  74. const fs = createMemoryFileSystem({
  75. [filePath]: `${"x".repeat(256 * 1024)}\n`,
  76. });
  77. await expect(
  78. readHandler(
  79. {
  80. file_path: filePath,
  81. },
  82. contextWith(fs),
  83. ),
  84. ).rejects.toMatchObject({
  85. type: "tool_execution_failed",
  86. message: expect.stringContaining("maximum allowed size (256KB)"),
  87. context: {
  88. code: "read_file_too_large",
  89. filePath,
  90. maxBytes: 256 * 1024,
  91. },
  92. });
  93. });
  94. it("returns an error instead of empty-file content when Read targets a missing file", async () => {
  95. const fs = createMemoryFileSystem({});
  96. await expect(
  97. readHandler(
  98. {
  99. file_path: filePath,
  100. },
  101. contextWith(fs),
  102. ),
  103. ).rejects.toMatchObject({
  104. type: "tool_execution_failed",
  105. message: expect.stringContaining("File does not exist. Note: your current working directory"),
  106. context: {
  107. code: "read_file_not_found",
  108. filePath,
  109. },
  110. });
  111. });
  112. it("reads a real later range from a large file when limit is explicit", async () => {
  113. const content = Array.from(
  114. { length: 3000 },
  115. (_, index) => `${index + 1}: ${"x".repeat(120)}`,
  116. ).join("\n");
  117. const fs = createMemoryFileSystem({
  118. [filePath]: content,
  119. });
  120. const output = await readHandler(
  121. {
  122. file_path: filePath,
  123. offset: 2500,
  124. limit: 2,
  125. },
  126. contextWith(fs),
  127. );
  128. expect(output).toMatchObject({
  129. type: "text",
  130. filePath,
  131. content: `2500: ${"x".repeat(120)}\n2501: ${"x".repeat(120)}`,
  132. numLines: 2,
  133. startLine: 2500,
  134. totalLines: 3000,
  135. });
  136. });
  137. it("rejects selected text ranges that exceed the Read token budget", async () => {
  138. const fs = createMemoryFileSystem({
  139. [filePath]: "x".repeat(80_000),
  140. });
  141. await expect(
  142. readHandler(
  143. {
  144. file_path: filePath,
  145. limit: 1,
  146. },
  147. contextWith(fs),
  148. ),
  149. ).rejects.toMatchObject({
  150. type: "tool_execution_failed",
  151. message: expect.stringContaining("maximum allowed tokens (25000)"),
  152. context: {
  153. code: "read_output_too_many_tokens",
  154. filePath,
  155. maxTokens: 25_000,
  156. },
  157. });
  158. });
  159. it("downgrades initial full text reads to a partial view when they exceed the token budget", async () => {
  160. const content = Array.from(
  161. { length: 1800 },
  162. (_, index) => `${index + 1}: ${"x".repeat(120)}`,
  163. ).join("\n");
  164. const fs = createMemoryFileSystem({
  165. [filePath]: content,
  166. });
  167. const output = await readHandler(
  168. {
  169. file_path: filePath,
  170. },
  171. contextWith(fs),
  172. );
  173. expect(output).toMatchObject({
  174. type: "text",
  175. filePath,
  176. startLine: 1,
  177. totalLines: 1800,
  178. truncated: true,
  179. truncatedByTokenCap: true,
  180. });
  181. const banner = new RegExp(
  182. `^\\[Truncated: PARTIAL view — ${filePath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}: showing lines 1-(\\d+) of 1800 total \\((\\d+) tokens, cap 25000\\)\\. Call Read with offset=(\\d+) limit=(\\d+) for the next page, or Grep to find a specific section\\. Do NOT answer from this page alone if the answer may be further in the file\\.\\]$`,
  183. ).exec(output.partialViewNotice ?? "");
  184. expect(banner).not.toBeNull();
  185. const [, shown, tokens, nextOffset, pageLimit] = banner!.map(Number);
  186. // 保留行数按 行数 × 上限 / 全文 token × 0.85 估算,下一页从其后一行开始,页长相同。
  187. expect(output.numLines).toBe(shown);
  188. expect(shown).toBe(Math.floor(((1800 * 25_000) / tokens!) * 0.85));
  189. expect(nextOffset).toBe(shown! + 1);
  190. expect(pageLimit).toBe(shown);
  191. // 提示不在 tool_result 内;由工具批次之后的附件单独发送。
  192. const modelContent = readToolEntry.formatModelContent?.(output);
  193. expect(modelContent).not.toContain("<system-reminder>");
  194. expect(modelContent).not.toContain("Truncated");
  195. expect(String(modelContent).startsWith("1\t1:")).toBe(true);
  196. });
  197. it("keeps a partial view within the token cap when the file starts denser than its average", async () => {
  198. // 前 400 行是中文、后 1000 行是 ASCII:全文平均字符密度低于前段。
  199. const content = [
  200. ...Array.from({ length: 400 }, () => "汉".repeat(100)),
  201. ...Array.from({ length: 1000 }, () => "x".repeat(120)),
  202. ].join("\n");
  203. expect(estimateTokens(content)).toBeGreaterThan(25_000);
  204. const fs = createMemoryFileSystem({ [filePath]: content });
  205. const output = await readHandler({ file_path: filePath }, contextWith(fs));
  206. // 前段比全文平均更密时,部分视图仍不能超过上限。
  207. expect(output).toMatchObject({ type: "text", truncatedByTokenCap: true });
  208. expect(output.partialViewNotice).toContain(`showing lines 1-${output.numLines} of 1400 total`);
  209. expect(estimateTokens(output.content)).toBeLessThanOrEqual(25_000);
  210. });
  211. it("numbers a partial view from the requested start line", async () => {
  212. const content = Array.from(
  213. { length: 1800 },
  214. (_, index) => `${index + 1}: ${"x".repeat(120)}`,
  215. ).join("\n");
  216. const fs = createMemoryFileSystem({ [filePath]: content });
  217. const output = await readTextFileForModel({
  218. allowPartialFallback: true,
  219. filePath,
  220. fileSystemPort: fs,
  221. offset: 101,
  222. });
  223. // 视图从第 101 行开始:提示里的行号与下一页 offset 都按真实行号写。
  224. expect(output).toMatchObject({ startLine: 101, truncatedByTokenCap: true });
  225. const shown = output.numLines!;
  226. expect(output.partialViewNotice).toContain(`showing lines 101-${100 + shown} of 1800 total`);
  227. expect(output.partialViewNotice).toContain(`offset=${101 + shown} limit=${shown}`);
  228. });
  229. it("fails instead of returning a partial view that still exceeds the token cap", async () => {
  230. // 开头 30 个 "#" 就超过上限:按字符缩小 6 次后仍放不下。
  231. tokenEstimate.override = (text) =>
  232. Math.ceil([...text].reduce((sum, char) => sum + (char === "#" ? 1000 : 0.25), 0));
  233. try {
  234. const fs = createMemoryFileSystem({ [filePath]: `${"#".repeat(30)}${"a".repeat(200_000)}` });
  235. await expect(readHandler({ file_path: filePath }, contextWith(fs))).rejects.toMatchObject({
  236. context: { code: "read_output_too_many_tokens", filePath },
  237. });
  238. } finally {
  239. tokenEstimate.override = undefined;
  240. }
  241. });
  242. it("returns Read model content that can be copied into Edit without escaped tab drift", async () => {
  243. const fs = createMemoryFileSystem({
  244. [filePath]: "工作任务\n- [ ] prd auto research 的\n\t- [ ] beta 部分继续",
  245. });
  246. const context = contextWith(fs);
  247. const readOutput = await readHandler(
  248. {
  249. file_path: filePath,
  250. },
  251. context,
  252. );
  253. const modelContent = readToolEntry.formatModelContent?.(readOutput);
  254. expect(modelContent).toContain("3\t\t- [ ] beta 部分继续");
  255. expect(modelContent).not.toContain("\\t- [ ] beta 部分继续");
  256. await expect(
  257. editHandler(
  258. {
  259. file_path: filePath,
  260. old_string: "- [ ] prd auto research 的\n\t- [ ] beta 部分继续",
  261. new_string: "- [x] prd auto research 的\n\t- [x] beta 部分继续",
  262. },
  263. context,
  264. ),
  265. ).resolves.toMatchObject({
  266. oldString: "- [ ] prd auto research 的\n\t- [ ] beta 部分继续",
  267. newString: "- [x] prd auto research 的\n\t- [x] beta 部分继续",
  268. });
  269. await expect(
  270. editHandler(
  271. {
  272. file_path: filePath,
  273. old_string: "\\t- [x] beta 部分继续",
  274. new_string: "\\t- [ ] beta 部分继续",
  275. },
  276. context,
  277. ),
  278. ).resolves.toMatchObject({
  279. matchStrategy: "escape_normalized",
  280. oldString: "\t- [x] beta 部分继续",
  281. newString: "\t- [ ] beta 部分继续",
  282. });
  283. expect(fs.files.get(filePath)).toContain("\t- [ ] beta 部分继续");
  284. });
  285. it("reads images through ImageProcessorPort with model image budgets", async () => {
  286. const imagePath = join(workspaceRoot, "screen.png");
  287. const fs = createMemoryFileSystem({
  288. [imagePath]: "image",
  289. });
  290. const prepareRequests: Parameters<ImageProcessorPort["prepareForModel"]>[0][] = [];
  291. const imageProcessorPort: ImageProcessorPort = {
  292. async resizeToFit() {
  293. throw new Error("unexpected resizeToFit");
  294. },
  295. async prepareForModel(request) {
  296. prepareRequests.push(request);
  297. return {
  298. data: Buffer.from("resized-image"),
  299. height: 667,
  300. mediaType: "image/jpeg",
  301. originalHeight: 1000,
  302. originalSizeBytes: Buffer.from(request.data).byteLength,
  303. originalWidth: 3000,
  304. resized: true,
  305. compressed: true,
  306. strategy: "jpeg-quality",
  307. transformedSizeBytes: 13,
  308. width: 2000,
  309. };
  310. },
  311. };
  312. const output = await readHandler(
  313. {
  314. file_path: imagePath,
  315. },
  316. contextWith(fs, { imageProcessorPort }),
  317. );
  318. expect(fs.readPaths).toEqual([imagePath]);
  319. expect(prepareRequests).toHaveLength(1);
  320. expect(prepareRequests[0]).toMatchObject({
  321. maxBase64Bytes: READ_IMAGE_MAX_BASE64_BYTES,
  322. maxDimension: READ_IMAGE_MAX_DIMENSION,
  323. maxRawBytes: READ_IMAGE_TARGET_BYTES,
  324. maxTokens: READ_MAX_OUTPUT_TOKENS,
  325. mediaType: "image/png",
  326. });
  327. expect(Buffer.from(prepareRequests[0]!.data).toString("utf8")).toBe("image");
  328. expect(output).toEqual({
  329. type: "image",
  330. base64: "cmVzaXplZC1pbWFnZQ==",
  331. mimeType: "image/jpeg",
  332. originalSize: 5,
  333. transformedSize: 13,
  334. resized: true,
  335. compressed: true,
  336. compressionStrategy: "jpeg-quality",
  337. dimensions: {
  338. originalWidth: 3000,
  339. originalHeight: 1000,
  340. displayWidth: 2000,
  341. displayHeight: 667,
  342. },
  343. });
  344. expect(readToolEntry.formatModelContent?.(output)).toEqual([
  345. {
  346. type: "image",
  347. mediaType: "image/jpeg",
  348. dataUrl: "data:image/jpeg;base64,cmVzaXplZC1pbWFnZQ==",
  349. source: {
  350. id: "read-image",
  351. kind: "inline",
  352. mimeType: "image/jpeg",
  353. placeholder: "Read image",
  354. sizeBytes: 5,
  355. },
  356. },
  357. ]);
  358. });
  359. it("maps empty image processor failures to a stable Read error code", async () => {
  360. const imagePath = join(workspaceRoot, "empty.png");
  361. const fs = createMemoryFileSystem({
  362. [imagePath]: "",
  363. });
  364. const imageProcessorPort: ImageProcessorPort = {
  365. async resizeToFit(request) {
  366. throw new Error(`unexpected resizeToFit: ${request.mediaType}`);
  367. },
  368. async prepareForModel() {
  369. throw createImageProcessorError({
  370. code: "empty",
  371. message: "Image file is empty (0 bytes)",
  372. });
  373. },
  374. };
  375. await expect(
  376. readHandler(
  377. {
  378. file_path: imagePath,
  379. },
  380. contextWith(fs, { imageProcessorPort }),
  381. ),
  382. ).rejects.toMatchObject({
  383. context: {
  384. code: "read_image_empty",
  385. maxInputBytes: READ_IMAGE_MAX_INPUT_BYTES,
  386. },
  387. type: "tool_execution_failed",
  388. });
  389. });
  390. it("rejects image inputs before decoding when the raw file exceeds the Read cap", async () => {
  391. const imagePath = join(workspaceRoot, "huge.png");
  392. const fs = createMemoryFileSystem({
  393. [imagePath]: "x".repeat(READ_IMAGE_MAX_INPUT_BYTES + 1),
  394. });
  395. const imageProcessorPort: ImageProcessorPort = {
  396. async resizeToFit(request) {
  397. throw new Error(`unexpected resizeToFit: ${request.mediaType}`);
  398. },
  399. async prepareForModel(request) {
  400. throw new Error(`unexpected prepareForModel: ${request.mediaType}`);
  401. },
  402. };
  403. await expect(
  404. readHandler(
  405. {
  406. file_path: imagePath,
  407. },
  408. contextWith(fs, { imageProcessorPort }),
  409. ),
  410. ).rejects.toMatchObject({
  411. context: {
  412. code: "read_image_input_too_large",
  413. },
  414. type: "tool_execution_failed",
  415. });
  416. });
  417. it("resolves relative file tool paths from the session cwd", async () => {
  418. const fs = createMemoryFileSystem({
  419. [projectFilePath]: "old value",
  420. });
  421. const readFileState: ReadFileStateMap = new Map();
  422. const context = contextWith(fs, {
  423. readFileState,
  424. workingDirectory: projectRoot,
  425. workspaceRoot: projectRoot,
  426. });
  427. const readOutput = await readHandler(
  428. {
  429. file_path: "src/file.txt",
  430. },
  431. context,
  432. );
  433. const writeOutput = await writeHandler(
  434. {
  435. file_path: "src/file.txt",
  436. content: "new value",
  437. },
  438. context,
  439. );
  440. expect(readOutput).toMatchObject({
  441. filePath: projectFilePath,
  442. content: "old value",
  443. });
  444. expect(writeOutput).toMatchObject({
  445. filePath: "src/file.txt",
  446. originalFile: "old value",
  447. type: "update",
  448. });
  449. expect(fs.readPaths).toEqual([projectFilePath, projectFilePath]);
  450. expect(fs.files.get(projectFilePath)).toBe("new value");
  451. });
  452. it("allows file tool paths outside the workspace root in the current release", async () => {
  453. const siblingPath = join(workspaceRoot, "outside.txt");
  454. const fs = createMemoryFileSystem({
  455. [outsidePath]: "external value",
  456. });
  457. const context = contextWith(fs, {
  458. workingDirectory: projectRoot,
  459. workspaceRoot: projectRoot,
  460. });
  461. const writeOutput = await writeHandler(
  462. {
  463. file_path: "../outside.txt",
  464. content: "allowed",
  465. },
  466. context,
  467. );
  468. const readOutput = await readHandler(
  469. {
  470. file_path: outsidePath,
  471. },
  472. context,
  473. );
  474. expect(writeOutput).toMatchObject({
  475. filePath: "../outside.txt",
  476. type: "create",
  477. });
  478. expect(fs.files.get(siblingPath)).toBe("allowed");
  479. expect(readOutput).toMatchObject({
  480. filePath: outsidePath,
  481. content: "external value",
  482. });
  483. });
  484. it("allows search tool paths outside the workspace root in the current release", async () => {
  485. const externalRoot = join(resolve("/tmp"), "external-project");
  486. const externalFile = join(externalRoot, "src", "index.ts");
  487. const fs = createMemoryFileSystem({
  488. [externalFile]: "export const answer = 42;",
  489. });
  490. const context = contextWith(fs, {
  491. workingDirectory: projectRoot,
  492. workspaceRoot: projectRoot,
  493. });
  494. const globOutput = await globHandler(
  495. {
  496. pattern: "**/*.ts",
  497. path: externalRoot,
  498. },
  499. context,
  500. );
  501. const grepOutput = await grepHandler(
  502. {
  503. pattern: "answer",
  504. path: externalRoot,
  505. },
  506. context,
  507. );
  508. expect(globOutput).toMatchObject({
  509. filenames: [externalFile],
  510. numFiles: 1,
  511. });
  512. expect(grepOutput).toMatchObject({
  513. filenames: [externalFile],
  514. numFiles: 1,
  515. numMatches: 1,
  516. });
  517. expect(fs.lastSearchFiles?.path).toBe(externalRoot);
  518. expect(fs.lastSearchText?.path).toBe(externalRoot);
  519. });
  520. it("finds files through FileSystemPort searchFiles", async () => {
  521. const fs = createMemoryFileSystem({
  522. [join(projectRoot, "src", "index.ts")]: "export const answer = 42;",
  523. [join(projectRoot, "src", "index.test.ts")]: "expect(answer).toBe(42);",
  524. [join(projectRoot, "README.md")]: "# Project",
  525. });
  526. const context = contextWith(fs, {
  527. workingDirectory: projectRoot,
  528. workspaceRoot: projectRoot,
  529. });
  530. const output = await globHandler(
  531. {
  532. pattern: "**/*.ts",
  533. },
  534. context,
  535. );
  536. expect(output).toMatchObject({
  537. numFiles: 2,
  538. filenames: ["src/index.test.ts", "src/index.ts"],
  539. truncated: false,
  540. });
  541. expect(fs.lastSearchFiles?.path).toBe(projectRoot);
  542. expect(fs.lastSearchFiles?.pattern).toBe("**/*.ts");
  543. });
  544. it("searches file contents through FileSystemPort searchText", async () => {
  545. const fs = createMemoryFileSystem({
  546. [join(projectRoot, "src", "index.ts")]: "export const answer = 42;\nconsole.log(answer);",
  547. [join(projectRoot, "src", "other.ts")]: "export const other = true;",
  548. });
  549. const context = contextWith(fs, {
  550. workingDirectory: projectRoot,
  551. workspaceRoot: projectRoot,
  552. });
  553. const filesOutput = await grepHandler(
  554. {
  555. pattern: "answer",
  556. glob: "**/*.ts",
  557. },
  558. context,
  559. );
  560. const contentOutput = await grepHandler(
  561. {
  562. pattern: "answer",
  563. output_mode: "content",
  564. "-n": true,
  565. },
  566. context,
  567. );
  568. expect(filesOutput).toMatchObject({
  569. mode: "files_with_matches",
  570. filenames: ["src/index.ts"],
  571. numFiles: 1,
  572. numMatches: 2,
  573. truncated: false,
  574. });
  575. expect(contentOutput).toMatchObject({
  576. mode: "content",
  577. content: "src/index.ts:1:export const answer = 42;\nsrc/index.ts:2:console.log(answer);",
  578. numLines: 2,
  579. numMatches: 2,
  580. });
  581. expect(fs.lastSearchText?.pattern).toBe("answer");
  582. expect(fs.lastSearchText?.glob).toBeUndefined();
  583. });
  584. it("maps cancelled Grep searches to tool cancellation", async () => {
  585. const fs = createMemoryFileSystem({});
  586. const context = contextWith(fs, {
  587. workingDirectory: projectRoot,
  588. workspaceRoot: projectRoot,
  589. });
  590. const controller = new AbortController();
  591. controller.abort();
  592. const cancelledContext = {
  593. ...context,
  594. abortSignal: controller.signal,
  595. };
  596. await expect(
  597. grepHandler(
  598. {
  599. pattern: "answer",
  600. },
  601. cancelledContext,
  602. ),
  603. ).rejects.toMatchObject({
  604. type: "tool_cancelled",
  605. message: "Grep was cancelled",
  606. });
  607. });
  608. it("writes text through FileSystemPort and returns the previous contents", async () => {
  609. const fs = createMemoryFileSystem({
  610. [filePath]: "old",
  611. });
  612. const output = await writeHandler(
  613. {
  614. file_path: filePath,
  615. content: "new",
  616. },
  617. contextWith(fs, { readFileState: createReadFileState(filePath, "old") }),
  618. );
  619. expect(output).toMatchObject({
  620. type: "update",
  621. filePath,
  622. content: "new",
  623. originalFile: "old",
  624. });
  625. expect(output.structuredPatch).toEqual([
  626. {
  627. oldStart: 1,
  628. oldLines: 1,
  629. newStart: 1,
  630. newLines: 1,
  631. lines: ["-old", "\\ No newline at end of file", "+new", "\\ No newline at end of file"],
  632. },
  633. ]);
  634. expect(fs.files.get(filePath)).toBe("new");
  635. });
  636. it("passes legacy text encoding metadata through Write updates", async () => {
  637. const fs = createMemoryFileSystem(
  638. {
  639. [filePath]: "// 你好\nconst answer = 1;\n",
  640. },
  641. { encoding: "gb2312" },
  642. );
  643. await writeHandler(
  644. {
  645. file_path: filePath,
  646. content: "// 你好\nconst answer = 2;\n",
  647. },
  648. contextWith(fs, {
  649. readFileState: createReadFileState(filePath, "// 你好\nconst answer = 1;\n"),
  650. }),
  651. );
  652. expect(fs.lastWrite?.encoding).toBe("gb2312");
  653. expect(fs.files.get(filePath)).toBe("// 你好\nconst answer = 2;\n");
  654. });
  655. it("edits text through FileSystemPort with a stale-write revision guard", async () => {
  656. const fs = createMemoryFileSystem({
  657. [filePath]: "alpha beta beta",
  658. });
  659. const output = await editHandler(
  660. {
  661. file_path: filePath,
  662. old_string: "beta",
  663. new_string: "gamma",
  664. replace_all: true,
  665. },
  666. contextWith(fs),
  667. );
  668. expect(output).toMatchObject({
  669. filePath,
  670. oldString: "beta",
  671. newString: "gamma",
  672. originalFile: "alpha beta beta",
  673. replaceAll: true,
  674. userModified: false,
  675. });
  676. expect(output.structuredPatch).toEqual([
  677. {
  678. oldStart: 1,
  679. oldLines: 1,
  680. newStart: 1,
  681. newLines: 1,
  682. lines: [
  683. "-alpha beta beta",
  684. "\\ No newline at end of file",
  685. "+alpha gamma gamma",
  686. "\\ No newline at end of file",
  687. ],
  688. },
  689. ]);
  690. expect(fs.lastWrite?.expectedRevision?.id).toBe(`rev:${filePath}:15`);
  691. expect(fs.files.get(filePath)).toBe("alpha gamma gamma");
  692. });
  693. it("edits CRLF files with LF strings from Read and preserves CRLF on disk", async () => {
  694. const fs = createMemoryFileSystem({
  695. [filePath]: "first\r\n\tsecond\r\nthird\r\n",
  696. });
  697. const context = contextWith(fs);
  698. const readOutput = await readHandler(
  699. {
  700. file_path: filePath,
  701. },
  702. context,
  703. );
  704. const modelContent = readToolEntry.formatModelContent?.(readOutput);
  705. expect(modelContent).toContain("2\t\tsecond");
  706. expect(modelContent).not.toContain("\r");
  707. const output = await editHandler(
  708. {
  709. file_path: filePath,
  710. old_string: "first\n\tsecond",
  711. new_string: "first\n\tchanged",
  712. },
  713. context,
  714. );
  715. expect(output).toMatchObject({
  716. oldString: "first\n\tsecond",
  717. newString: "first\n\tchanged",
  718. originalFile: "first\n\tsecond\nthird\n",
  719. });
  720. expect(fs.lastWrite?.lineEndings).toBe("CRLF");
  721. expect(fs.lastWrite?.content).toBe("first\n\tchanged\nthird\n");
  722. expect(fs.files.get(filePath)).toBe("first\r\n\tchanged\r\nthird\r\n");
  723. });
  724. it("edits LF files when old_string accidentally contains CRLF after Read", async () => {
  725. const jsxPath = join(projectRoot, "src", "Component.jsx");
  726. const fs = createMemoryFileSystem({
  727. [jsxPath]: "export function Component() {\n return <div>old</div>;\n}\n",
  728. });
  729. const readFileState: ReadFileStateMap = new Map();
  730. const context = contextWith(fs, { readFileState });
  731. await readHandler({ file_path: jsxPath }, context);
  732. const output = await editHandler(
  733. {
  734. file_path: jsxPath,
  735. old_string: "export function Component() {\r\n return <div>old</div>;\r\n}",
  736. new_string: "export function Component() {\n return <div>new</div>;\n}",
  737. },
  738. context,
  739. );
  740. expect(output).toMatchObject({
  741. oldString: "export function Component() {\n return <div>old</div>;\n}",
  742. newString: "export function Component() {\n return <div>new</div>;\n}",
  743. originalFile: "export function Component() {\n return <div>old</div>;\n}\n",
  744. });
  745. expect(fs.files.get(jsxPath)).toBe(
  746. "export function Component() {\n return <div>new</div>;\n}\n",
  747. );
  748. });
  749. it("does not double carriage returns when new_string already contains CRLF", async () => {
  750. const fs = createMemoryFileSystem({
  751. [filePath]: "one\r\ntwo\r\nthree\r\n",
  752. });
  753. await editHandler(
  754. {
  755. file_path: filePath,
  756. old_string: "two",
  757. new_string: "two\r\ninserted",
  758. },
  759. contextWith(fs),
  760. );
  761. expect(fs.files.get(filePath)).toBe("one\r\ntwo\r\ninserted\r\nthree\r\n");
  762. });
  763. it("passes legacy text encoding metadata through Edit writes", async () => {
  764. const fs = createMemoryFileSystem(
  765. {
  766. [filePath]: "// 你好\nconst answer = 1;\n",
  767. },
  768. { encoding: "gb2312" },
  769. );
  770. await editHandler(
  771. {
  772. file_path: filePath,
  773. old_string: "const answer = 1;",
  774. new_string: "const answer = 2;",
  775. },
  776. contextWith(fs),
  777. );
  778. expect(fs.lastWrite?.encoding).toBe("gb2312");
  779. expect(fs.files.get(filePath)).toBe("// 你好\nconst answer = 2;\n");
  780. });
  781. it("preserves curly quote style when matching normalized quotes", async () => {
  782. const fs = createMemoryFileSystem({
  783. [filePath]: "const label = “Old value”;\n",
  784. });
  785. const output = await editHandler(
  786. {
  787. file_path: filePath,
  788. old_string: '"Old value"',
  789. new_string: '"New value"',
  790. },
  791. contextWith(fs),
  792. );
  793. expect(output.oldString).toBe("“Old value”");
  794. expect(output.newString).toBe("“New value”");
  795. expect(fs.files.get(filePath)).toBe("const label = “New value”;\n");
  796. });
  797. it("edits text when old_string accidentally includes Read line prefixes", async () => {
  798. const fs = createMemoryFileSystem({
  799. [filePath]: "\tfirst\n\tsecond\n",
  800. });
  801. const output = await editHandler(
  802. {
  803. file_path: filePath,
  804. old_string: "1: \tfirst\n2: \tsecond",
  805. new_string: "\tchanged\n\tsecond",
  806. },
  807. contextWith(fs),
  808. );
  809. expect(output).toMatchObject({
  810. oldString: "\tfirst\n\tsecond",
  811. matchStrategy: "line_number_prefix_stripped",
  812. });
  813. expect(fs.files.get(filePath)).toBe("\tchanged\n\tsecond\n");
  814. });
  815. it("edits text when indentation copied from Read has extra tabs", async () => {
  816. const fs = createMemoryFileSystem({
  817. [filePath]: "\tif (ready) {\n\t\tawait Load();\n\t}\n",
  818. });
  819. const output = await editHandler(
  820. {
  821. file_path: filePath,
  822. old_string: "\t\tif (ready) {\n\t\t\tawait Load();\n\t\t}",
  823. new_string: "\tif (ready) {\n\t\tawait Save();\n\t}",
  824. },
  825. contextWith(fs),
  826. );
  827. expect(output).toMatchObject({
  828. oldString: "\tif (ready) {\n\t\tawait Load();\n\t}",
  829. matchStrategy: "line_trimmed",
  830. });
  831. expect(fs.files.get(filePath)).toBe("\tif (ready) {\n\t\tawait Save();\n\t}\n");
  832. });
  833. it("rejects fuzzy edit matches when multiple candidates are possible", async () => {
  834. const fs = createMemoryFileSystem({
  835. [filePath]: "\tawait Load();\n await Load();\n",
  836. });
  837. await expect(
  838. editHandler(
  839. {
  840. file_path: filePath,
  841. old_string: "\t\tawait Load();",
  842. new_string: "await Save();",
  843. },
  844. contextWith(fs),
  845. ),
  846. ).resolves.toMatchObject({
  847. result: false,
  848. errorCode: 9,
  849. });
  850. expect(fs.files.get(filePath)).toBe("\tawait Load();\n await Load();\n");
  851. });
  852. it("applies structured patches after verifying all hunks", async () => {
  853. const fs = createMemoryFileSystem({
  854. [filePath]: "one\n two\nthree\n",
  855. });
  856. const output = (await applyPatchHandler(
  857. {
  858. patch_text: [
  859. "*** Begin Patch",
  860. `*** Update File: ${filePath}`,
  861. "@@",
  862. "-two",
  863. "+changed",
  864. "*** End Patch",
  865. ].join("\n"),
  866. },
  867. contextWith(fs),
  868. )) as ApplyPatchOutput;
  869. expect(output.summary).toContain(`M ${filePath}`);
  870. expect(output.files[0]).toMatchObject({
  871. filePath,
  872. type: "update",
  873. additions: 1,
  874. deletions: 1,
  875. });
  876. expect(fs.files.get(filePath)).toBe("one\nchanged\nthree\n");
  877. });
  878. it("passes legacy text encoding metadata through ApplyPatch updates", async () => {
  879. const fs = createMemoryFileSystem(
  880. {
  881. [filePath]: "// 你好\nconst answer = 1;\n",
  882. },
  883. { encoding: "gb2312" },
  884. );
  885. await applyPatchHandler(
  886. {
  887. patch_text: [
  888. "*** Begin Patch",
  889. `*** Update File: ${filePath}`,
  890. "@@",
  891. "-const answer = 1;",
  892. "+const answer = 2;",
  893. "*** End Patch",
  894. ].join("\n"),
  895. },
  896. contextWith(fs),
  897. );
  898. expect(fs.lastWrite?.encoding).toBe("gb2312");
  899. expect(fs.files.get(filePath)).toBe("// 你好\nconst answer = 2;\n");
  900. });
  901. it("does not write any patch files when verification fails", async () => {
  902. const createdPath = join(workspaceRoot, "created.txt");
  903. const fs = createMemoryFileSystem({
  904. [filePath]: "one\ntwo\n",
  905. });
  906. await expect(
  907. applyPatchHandler(
  908. {
  909. patch_text: [
  910. "*** Begin Patch",
  911. `*** Add File: ${createdPath}`,
  912. "+created",
  913. `*** Update File: ${filePath}`,
  914. "@@",
  915. "-missing",
  916. "+changed",
  917. "*** End Patch",
  918. ].join("\n"),
  919. },
  920. contextWith(fs),
  921. ),
  922. ).rejects.toMatchObject({
  923. type: "tool_execution_failed",
  924. context: {
  925. code: "apply_patch_hunk_not_found",
  926. },
  927. });
  928. expect(fs.files.has(createdPath)).toBe(false);
  929. expect(fs.files.get(filePath)).toBe("one\ntwo\n");
  930. });
  931. it("rejects ambiguous single replacements unless replace_all is explicit", async () => {
  932. const fs = createMemoryFileSystem({
  933. [filePath]: "alpha beta beta",
  934. });
  935. await expect(
  936. editHandler(
  937. {
  938. file_path: filePath,
  939. old_string: "beta",
  940. new_string: "gamma",
  941. },
  942. contextWith(fs),
  943. ),
  944. ).resolves.toMatchObject({
  945. result: false,
  946. errorCode: 9,
  947. });
  948. expect(fs.files.get(filePath)).toBe("alpha beta beta");
  949. });
  950. it("rejects empty old_string instead of inserting text implicitly", async () => {
  951. const fs = createMemoryFileSystem({
  952. [filePath]: "alpha",
  953. });
  954. await expect(
  955. editHandler(
  956. {
  957. file_path: filePath,
  958. old_string: "",
  959. new_string: "prefix ",
  960. },
  961. contextWith(fs),
  962. ),
  963. ).resolves.toMatchObject({
  964. result: false,
  965. errorCode: 3,
  966. });
  967. expect(fs.files.get(filePath)).toBe("alpha");
  968. });
  969. });
  970. interface MemoryFileSystem extends FileSystemPort {
  971. files: Map<string, string>;
  972. readPaths: string[];
  973. lastWrite?: FileSystemWriteTextRequest;
  974. lastSearchFiles?: { path: string; pattern: string };
  975. lastSearchText?: { path: string; pattern: string; glob?: string };
  976. }
  977. function createMemoryFileSystem(
  978. initial: Record<string, string>,
  979. options: { encoding?: FileSystemTextEncoding } = {},
  980. ): MemoryFileSystem {
  981. const files = new Map(Object.entries(initial));
  982. const fs: MemoryFileSystem = {
  983. files,
  984. readPaths: [],
  985. async stat(request): Promise<FileSystemStatResult> {
  986. const content = files.get(request.path);
  987. if (content === undefined) {
  988. throw createFileSystemError({
  989. code: "not_found",
  990. path: request.path,
  991. message: `missing: ${request.path}`,
  992. });
  993. }
  994. return {
  995. path: request.path,
  996. kind: "file",
  997. sizeBytes: Buffer.byteLength(content, "utf8"),
  998. revision: revisionFor(request.path, content),
  999. };
  1000. },
  1001. async readBinaryFile(request) {
  1002. fs.readPaths.push(request.path);
  1003. const content = files.get(request.path);
  1004. if (content === undefined) {
  1005. throw createFileSystemError({
  1006. code: "not_found",
  1007. path: request.path,
  1008. message: `missing: ${request.path}`,
  1009. });
  1010. }
  1011. const buffer = Buffer.from(content, "utf8");
  1012. if (request.maxBytes !== undefined && buffer.byteLength > request.maxBytes) {
  1013. throw createFileSystemError({
  1014. code: "too_large",
  1015. path: request.path,
  1016. message: `File content (${formatTestFileSize(buffer.byteLength)}) exceeds maximum allowed size (${formatTestFileSize(request.maxBytes)}).`,
  1017. });
  1018. }
  1019. return {
  1020. path: request.path,
  1021. content: buffer,
  1022. bytesRead: buffer.byteLength,
  1023. sizeBytes: buffer.byteLength,
  1024. revision: revisionFor(request.path, content),
  1025. };
  1026. },
  1027. async readTextFile(request): Promise<FileSystemReadTextResult> {
  1028. fs.readPaths.push(request.path);
  1029. const content = files.get(request.path);
  1030. if (content === undefined) {
  1031. throw createFileSystemError({
  1032. code: "not_found",
  1033. path: request.path,
  1034. message: `missing: ${request.path}`,
  1035. });
  1036. }
  1037. const lineEndings = detectTestLineEndings(content);
  1038. const normalizedContent = normalizeTestLineEndings(content);
  1039. return {
  1040. path: request.path,
  1041. content: normalizedContent,
  1042. encoding: request.encoding ?? options.encoding ?? "utf8",
  1043. lineEndings,
  1044. bytesRead: content.length,
  1045. sizeBytes: content.length,
  1046. truncated: false,
  1047. revision: revisionFor(request.path, content),
  1048. };
  1049. },
  1050. async readTextFileRange(request): Promise<FileSystemReadTextRangeResult> {
  1051. fs.readPaths.push(request.path);
  1052. const content = files.get(request.path);
  1053. if (content === undefined) {
  1054. throw createFileSystemError({
  1055. code: "not_found",
  1056. path: request.path,
  1057. message: `missing: ${request.path}`,
  1058. });
  1059. }
  1060. const sizeBytes = Buffer.byteLength(content, "utf8");
  1061. if (request.maxBytes !== undefined && sizeBytes > request.maxBytes) {
  1062. throw createFileSystemError({
  1063. code: "too_large",
  1064. path: request.path,
  1065. message: `File content (${formatTestFileSize(sizeBytes)}) exceeds maximum allowed size (${formatTestFileSize(request.maxBytes)}). Use offset and limit parameters to read specific portions of the file, or search for specific content instead of reading the whole file.`,
  1066. });
  1067. }
  1068. const lineEndings = detectTestLineEndings(content);
  1069. const normalizedContent = normalizeTestLineEndings(content);
  1070. const lines = normalizedContent.length === 0 ? [] : normalizedContent.split("\n");
  1071. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  1072. const limitLines =
  1073. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  1074. const selected =
  1075. limitLines === undefined
  1076. ? lines.slice(offsetLine)
  1077. : lines.slice(offsetLine, offsetLine + limitLines);
  1078. return {
  1079. path: request.path,
  1080. content: selected.join("\n"),
  1081. encoding: request.encoding ?? options.encoding ?? "utf8",
  1082. lineEndings,
  1083. bytesRead: sizeBytes,
  1084. sizeBytes,
  1085. truncated: false,
  1086. startLine: offsetLine + 1,
  1087. lineCount: selected.length,
  1088. totalLines: lines.length,
  1089. revision: revisionFor(request.path, content),
  1090. };
  1091. },
  1092. async writeTextFile(request) {
  1093. if (request.expectedRevision) {
  1094. const current = files.get(request.path);
  1095. if (!current || revisionFor(request.path, current).id !== request.expectedRevision.id) {
  1096. throw createFileSystemError({
  1097. code: "stale_write",
  1098. path: request.path,
  1099. message: `stale: ${request.path}`,
  1100. });
  1101. }
  1102. }
  1103. fs.lastWrite = request;
  1104. const content = applyTestLineEndings(request.content, request.lineEndings);
  1105. files.set(request.path, content);
  1106. return {
  1107. path: request.path,
  1108. bytesWritten: content.length,
  1109. revision: revisionFor(request.path, content),
  1110. };
  1111. },
  1112. async removeFile(request) {
  1113. const existed = files.delete(request.path);
  1114. if (!existed && request.missingOk !== true) {
  1115. throw createFileSystemError({
  1116. code: "not_found",
  1117. path: request.path,
  1118. message: `missing: ${request.path}`,
  1119. });
  1120. }
  1121. return {
  1122. path: request.path,
  1123. removed: existed,
  1124. };
  1125. },
  1126. async listDirectory(request) {
  1127. const prefix = `${request.path.replace(/\/+$/, "")}/`;
  1128. const seen = new Set<string>();
  1129. const entries = Array.from(files.keys())
  1130. .filter((path) => path.startsWith(prefix))
  1131. .flatMap((path) => {
  1132. const rest = path.slice(prefix.length);
  1133. const [name] = rest.split("/");
  1134. if (!name || seen.has(name)) return [];
  1135. seen.add(name);
  1136. return [
  1137. {
  1138. kind: rest.includes("/") ? ("directory" as const) : ("file" as const),
  1139. name,
  1140. path: `${prefix}${name}`,
  1141. },
  1142. ];
  1143. });
  1144. return {
  1145. path: request.path,
  1146. durationMs: 0,
  1147. entries,
  1148. numEntries: entries.length,
  1149. };
  1150. },
  1151. async searchFiles(request): Promise<FileSystemSearchFilesResult> {
  1152. fs.lastSearchFiles = { path: request.path, pattern: request.pattern };
  1153. const matcher = createTestGlobMatcher(request.pattern);
  1154. const filesMatched = Array.from(files.keys())
  1155. .filter((path) => path.startsWith(request.path))
  1156. .filter((path) => matcher(toRelativeTestPath(request.path, path)))
  1157. .sort();
  1158. const offset = request.offset ?? 0;
  1159. const limit = request.maxResults ?? 100;
  1160. const selected = filesMatched.slice(offset, offset + limit);
  1161. return {
  1162. path: request.path,
  1163. pattern: request.pattern,
  1164. durationMs: 0,
  1165. files: selected,
  1166. numFiles: selected.length,
  1167. truncated: filesMatched.length > offset + limit,
  1168. };
  1169. },
  1170. async searchText(request, options): Promise<FileSystemSearchTextResult> {
  1171. fs.lastSearchText = { path: request.path, pattern: request.pattern, glob: request.glob };
  1172. if (options?.signal?.aborted) {
  1173. throw createFileSystemError({
  1174. code: "cancelled",
  1175. path: request.path,
  1176. message: `cancelled: ${request.path}`,
  1177. });
  1178. }
  1179. const regex = new RegExp(request.pattern, request.ignoreCase ? "i" : "");
  1180. const globMatcher = request.glob ? createTestGlobMatcher(request.glob) : undefined;
  1181. const entries = [];
  1182. const countEntries = [];
  1183. const matchedFiles: string[] = [];
  1184. let numMatches = 0;
  1185. for (const [path, content] of Array.from(files.entries()).sort()) {
  1186. if (!path.startsWith(request.path)) continue;
  1187. const relativePath = toRelativeTestPath(request.path, path);
  1188. if (globMatcher && !globMatcher(relativePath)) continue;
  1189. const lines = content.split("\n");
  1190. let fileMatches = 0;
  1191. for (let index = 0; index < lines.length; index += 1) {
  1192. if (regex.test(lines[index] ?? "")) {
  1193. fileMatches += 1;
  1194. entries.push({
  1195. path,
  1196. lineNumber: index + 1,
  1197. text: lines[index] ?? "",
  1198. matched: true,
  1199. });
  1200. }
  1201. }
  1202. if (fileMatches > 0) {
  1203. matchedFiles.push(path);
  1204. countEntries.push({ path, count: fileMatches });
  1205. numMatches += fileMatches;
  1206. }
  1207. }
  1208. const mode = request.outputMode ?? "files_with_matches";
  1209. return {
  1210. path: request.path,
  1211. pattern: request.pattern,
  1212. mode,
  1213. durationMs: 0,
  1214. files: matchedFiles,
  1215. entries: mode === "count" ? countEntries : mode === "content" ? entries : [],
  1216. numMatches,
  1217. truncated: false,
  1218. };
  1219. },
  1220. };
  1221. return fs;
  1222. }
  1223. function detectTestLineEndings(content: string): FileSystemLineEndings {
  1224. let crlfCount = 0;
  1225. let lfCount = 0;
  1226. for (let index = 0; index < content.length; index += 1) {
  1227. if (content[index] !== "\n") continue;
  1228. if (index > 0 && content[index - 1] === "\r") {
  1229. crlfCount += 1;
  1230. } else {
  1231. lfCount += 1;
  1232. }
  1233. }
  1234. return crlfCount > lfCount ? "CRLF" : "LF";
  1235. }
  1236. function normalizeTestLineEndings(content: string): string {
  1237. return content.replaceAll("\r\n", "\n");
  1238. }
  1239. function applyTestLineEndings(
  1240. content: string,
  1241. lineEndings: FileSystemLineEndings | undefined,
  1242. ): string {
  1243. if (lineEndings === undefined) {
  1244. return content;
  1245. }
  1246. const normalized = normalizeTestLineEndings(content);
  1247. return lineEndings === "CRLF" ? normalized.split("\n").join("\r\n") : normalized;
  1248. }
  1249. function revisionFor(path: string, content: string): FileSystemRevision {
  1250. return {
  1251. id: `rev:${path}:${content.length}`,
  1252. sizeBytes: content.length,
  1253. };
  1254. }
  1255. function createReadFileState(filePath: string, content: string): ReadFileStateMap {
  1256. const revision = revisionFor(filePath, content);
  1257. return new Map([
  1258. [
  1259. createReadFileStatePathKey(filePath),
  1260. {
  1261. path: filePath,
  1262. content: normalizeTestLineEndings(content),
  1263. offset: 1,
  1264. limit: undefined,
  1265. isPartialView: false,
  1266. readAt: new Date(),
  1267. revisionId: revision.id,
  1268. sizeBytes: revision.sizeBytes,
  1269. },
  1270. ],
  1271. ]);
  1272. }
  1273. function formatTestFileSize(bytes: number): string {
  1274. if (bytes < 1024) return `${bytes}B`;
  1275. if (bytes < 1024 * 1024) {
  1276. const kb = bytes / 1024;
  1277. return `${Number.isInteger(kb) ? kb : kb.toFixed(1)}KB`;
  1278. }
  1279. const mb = bytes / (1024 * 1024);
  1280. return `${Number.isInteger(mb) ? mb : mb.toFixed(1)}MB`;
  1281. }
  1282. function createTestGlobMatcher(pattern: string): (path: string) => boolean {
  1283. const normalized = pattern.replaceAll("\\", "/");
  1284. let regex = "^";
  1285. for (let index = 0; index < normalized.length; index += 1) {
  1286. const char = normalized[index];
  1287. const next = normalized[index + 1];
  1288. if (char === "*" && next === "*") {
  1289. if (normalized[index + 2] === "/") {
  1290. regex += "(?:.*/)?";
  1291. index += 2;
  1292. } else {
  1293. regex += ".*";
  1294. index += 1;
  1295. }
  1296. continue;
  1297. }
  1298. if (char === "*") {
  1299. regex += "[^/]*";
  1300. continue;
  1301. }
  1302. regex += char?.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&") ?? "";
  1303. }
  1304. return (path: string) => new RegExp(`${regex}$`).test(path.replaceAll("\\", "/"));
  1305. }
  1306. function toRelativeTestPath(root: string, path: string): string {
  1307. return path
  1308. .slice(root.length)
  1309. .replace(/^[/\\]/, "")
  1310. .replaceAll("\\", "/");
  1311. }
  1312. function contextWith(
  1313. fileSystemPort: FileSystemPort,
  1314. options: {
  1315. imageProcessorPort?: ImageProcessorPort;
  1316. readFileState?: ReadFileStateMap;
  1317. workingDirectory?: string;
  1318. workspaceRoot?: string;
  1319. } = {},
  1320. ): ToolExecutionContext {
  1321. return {
  1322. toolCallId: "tool_test",
  1323. traceId: "trace_test",
  1324. spanId: "span_test",
  1325. abortSignal: new AbortController().signal,
  1326. fileSystemPort,
  1327. imageProcessorPort: options.imageProcessorPort,
  1328. readFileState: options.readFileState,
  1329. workingDirectory: options.workingDirectory ?? workspaceRoot,
  1330. workspaceRoot: options.workspaceRoot ?? workspaceRoot,
  1331. sessionId: "sess_test",
  1332. turnId: "turn_test",
  1333. };
  1334. }