read-tool-contract.test.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import {
  6. CoreErrorType,
  7. READ_MAX_FILE_SIZE_BYTES,
  8. READ_VIDEO_MAX_INPUT_BYTES,
  9. createFileSystemError,
  10. createRootTraceContext,
  11. createSessionId,
  12. createToolCallId,
  13. createTurnId,
  14. modelMessageContentToText,
  15. type FileSystemPort,
  16. type FileSystemReadTextRangeResult,
  17. type FileSystemReadTextResult,
  18. type FileSystemRevision,
  19. type FileSystemSearchFilesResult,
  20. type FileSystemSearchTextResult,
  21. type FileSystemStatResult,
  22. type ImageProcessorPort,
  23. type ModelMessageContent,
  24. } from "@zcode/contracts";
  25. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  26. import { createToolExecutor } from "../src/tool/executor.js";
  27. import { readHandler, readToolEntry } from "../src/tool/handlers/read.js";
  28. import { createReadFileStateKey } from "../src/tool/read-file-state.js";
  29. import { createToolRegistry } from "../src/tool/registry.js";
  30. import type { ReadFileStateMap, ToolExecutionContext } from "../src/tool/types.js";
  31. const RUN_READ_STRICT_CONTRACT = process.env.ZCODE_RUN_READ_STRICT_CONTRACT === "1";
  32. const describeReadStrictContract = RUN_READ_STRICT_CONTRACT ? describe : describe.skip;
  33. const FILE_UNCHANGED_STUB =
  34. "Wasted call — file unchanged since your last Read. Refer to that earlier tool_result instead.";
  35. let tmpDir: string;
  36. beforeEach(async () => {
  37. tmpDir = await mkdtemp(join(tmpdir(), "zcode-read-contract-"));
  38. });
  39. afterEach(async () => {
  40. await rm(tmpDir, { recursive: true, force: true });
  41. });
  42. describe("Read model-result harness", () => {
  43. it("returns video bytes as one provider-visible video block", async () => {
  44. const file = join(tmpDir, "demo.mp4");
  45. const fs = createMemoryFileSystem({
  46. [file]: "video",
  47. });
  48. const result = await readForModel({ file_path: file }, contextWith(fs));
  49. expect(result.output).toEqual({
  50. type: "video",
  51. base64: "dmlkZW8=",
  52. mimeType: "video/mp4",
  53. originalSize: 5,
  54. });
  55. expect(result.modelContent).toEqual([
  56. {
  57. type: "video",
  58. mediaType: "video/mp4",
  59. dataUrl: "data:video/mp4;base64,dmlkZW8=",
  60. source: {
  61. id: "read-video",
  62. kind: "inline",
  63. mimeType: "video/mp4",
  64. placeholder: "Read video",
  65. sizeBytes: 5,
  66. },
  67. },
  68. ]);
  69. });
  70. it("rejects an empty video before creating provider-visible media", async () => {
  71. const file = join(tmpDir, "empty.mp4");
  72. const fs = createMemoryFileSystem({
  73. [file]: "",
  74. });
  75. await expect(readForModel({ file_path: file }, contextWith(fs))).rejects.toMatchObject({
  76. type: CoreErrorType.ToolExecutionFailed,
  77. context: expect.objectContaining({ code: "read_video_input_empty" }),
  78. });
  79. });
  80. it("maps bounded binary-read overflow to the video-specific tool error", async () => {
  81. const file = join(tmpDir, "large.mp4");
  82. const fs = createMemoryFileSystem({ [file]: "video" });
  83. fs.readBinaryFile = async (request) => {
  84. throw createFileSystemError({
  85. code: "too_large",
  86. path: request.path,
  87. message: "video exceeds read limit",
  88. });
  89. };
  90. await expect(readForModel({ file_path: file }, contextWith(fs))).rejects.toMatchObject({
  91. type: CoreErrorType.ToolExecutionFailed,
  92. context: expect.objectContaining({
  93. code: "read_video_input_too_large",
  94. maxBytes: READ_VIDEO_MAX_INPUT_BYTES,
  95. }),
  96. });
  97. });
  98. it("returns the executor modelContent as cat-n text for normal text reads", async () => {
  99. const file = join(tmpDir, "notes.txt");
  100. const fs = createMemoryFileSystem({
  101. [file]: "alpha\nbeta",
  102. });
  103. const result = await executeRead({ file_path: file }, fs);
  104. expect(result.success).toBe(true);
  105. expect(result.output).toMatchObject({
  106. type: "text",
  107. filePath: file,
  108. content: "alpha\nbeta",
  109. numLines: 2,
  110. startLine: 1,
  111. totalLines: 2,
  112. });
  113. expect(result.modelContent).toBe("1\talpha\n2\tbeta");
  114. expect(result.serialization?.content).toBe("1\talpha\n2\tbeta");
  115. });
  116. it("numbers offset zero from line zero while reading the first physical line", async () => {
  117. const file = join(tmpDir, "zero-offset.txt");
  118. const fs = createMemoryFileSystem({
  119. [file]: "first\nsecond",
  120. });
  121. const result = await readForModel(
  122. {
  123. file_path: file,
  124. offset: 0,
  125. limit: 1,
  126. },
  127. contextWith(fs),
  128. );
  129. expect(result.output).toMatchObject({
  130. type: "text",
  131. content: "first",
  132. numLines: 1,
  133. startLine: 0,
  134. totalLines: 2,
  135. });
  136. expect(asModelText(result.modelContent)).toBe("0\tfirst");
  137. });
  138. it("records explicit ranges as range views instead of partial views", async () => {
  139. const file = join(tmpDir, "range-state.txt");
  140. const fs = createMemoryFileSystem({
  141. [file]: "first\nsecond\nthird",
  142. });
  143. const readFileState: ReadFileStateMap = new Map();
  144. const context = contextWith(fs, { readFileState });
  145. await readForModel(
  146. {
  147. file_path: file,
  148. offset: 2,
  149. limit: 1,
  150. },
  151. context,
  152. );
  153. expect(readFileState.get(createReadFileStateKey(file, 2, 1))).toMatchObject({
  154. isPartialView: false,
  155. limit: 1,
  156. offset: 2,
  157. });
  158. });
  159. it("keeps empty-file output metadata on the fast path", async () => {
  160. const file = join(tmpDir, "empty.txt");
  161. const fs = createMemoryFileSystem({
  162. [file]: "",
  163. });
  164. const result = await readForModel({ file_path: file }, contextWith(fs));
  165. expect(result.output).toMatchObject({
  166. type: "text",
  167. content: "",
  168. numLines: 1,
  169. startLine: 1,
  170. totalLines: 1,
  171. });
  172. });
  173. it("reads past 2000 lines by default when byte and token budgets allow", async () => {
  174. const file = join(tmpDir, "many-lines.txt");
  175. const lines = Array.from({ length: 2005 }, (_, index) => `line-${index + 1}`);
  176. const fs = createMemoryFileSystem({
  177. [file]: lines.join("\n"),
  178. });
  179. const result = await readForModel({ file_path: file }, contextWith(fs));
  180. expect(result.output).toMatchObject({
  181. type: "text",
  182. numLines: 2005,
  183. totalLines: 2005,
  184. });
  185. expect(result.output).toHaveProperty("content", expect.stringContaining("line-2005"));
  186. });
  187. it("deduplicates repeated unchanged reads in the handler path", async () => {
  188. const file = join(tmpDir, "dedup.txt");
  189. const fs = createMemoryFileSystem({
  190. [file]: "same\ncontent",
  191. });
  192. const context = contextWith(fs);
  193. const first = await readForModel({ file_path: file }, context);
  194. const second = await readForModel({ file_path: file }, context);
  195. expect(first.output).toMatchObject({ type: "text", content: "same\ncontent" });
  196. expect(second.output).toEqual({ type: "file_unchanged", filePath: file });
  197. expect(asModelText(second.modelContent)).toBe(FILE_UNCHANGED_STUB);
  198. });
  199. it("deduplicates repeated reads when mtime only drifts inside the same millisecond", async () => {
  200. const file = join(tmpDir, "dedup-sub-ms.txt");
  201. const fs = createMemoryFileSystem({
  202. [file]: "same\ncontent",
  203. });
  204. fs.setMtime(file, 1000.2);
  205. const context = contextWith(fs);
  206. await readForModel({ file_path: file }, context);
  207. fs.setMtime(file, 1000.8);
  208. const second = await readForModel({ file_path: file }, context);
  209. expect(second.output).toEqual({ type: "file_unchanged", filePath: file });
  210. });
  211. it("re-reads when mtime advances to the next millisecond bucket", async () => {
  212. const file = join(tmpDir, "dedup-next-ms.txt");
  213. const fs = createMemoryFileSystem({
  214. [file]: "same\ncontent",
  215. });
  216. fs.setMtime(file, 1000.9);
  217. const context = contextWith(fs);
  218. await readForModel({ file_path: file }, context);
  219. fs.setMtime(file, 1001);
  220. const second = await readForModel({ file_path: file }, context);
  221. expect(second.output).toMatchObject({
  222. type: "text",
  223. content: "same\ncontent",
  224. });
  225. });
  226. it("re-reads after the file revision changes", async () => {
  227. const file = join(tmpDir, "changed.txt");
  228. const fs = createMemoryFileSystem({
  229. [file]: "before",
  230. });
  231. const context = contextWith(fs);
  232. await readForModel({ file_path: file }, context);
  233. fs.files.set(file, "after");
  234. const second = await readForModel({ file_path: file }, context);
  235. expect(second.output).toMatchObject({
  236. type: "text",
  237. content: "after",
  238. });
  239. });
  240. it("returns a missing-file message with cwd and a suggestion", async () => {
  241. const existing = join(tmpDir, "target.ts");
  242. const missing = join(tmpDir, "target.js");
  243. const fs = createMemoryFileSystem({
  244. [existing]: "export const ok = true",
  245. });
  246. await expect(
  247. readForModel(
  248. { file_path: missing },
  249. contextWith(fs, {
  250. workingDirectory: tmpDir,
  251. workspaceRoot: tmpDir,
  252. }),
  253. ),
  254. ).rejects.toMatchObject({
  255. message: `File does not exist. Note: your current working directory is ${tmpDir}. Did you mean target.ts?`,
  256. });
  257. });
  258. it("rejects unsupported binary extensions and blocking device paths before I/O", () => {
  259. expect(readInputSafeParse({ file_path: "/tmp/archive.zip" }).success).toBe(false);
  260. expect(readInputSafeParse({ file_path: "/dev/zero" }).success).toBe(false);
  261. expect(readInputSafeParse({ file_path: "/tmp/image.png" }).success).toBe(true);
  262. expect(readInputSafeParse({ file_path: "/tmp/doc.pdf" }).success).toBe(true);
  263. });
  264. it("returns tool_use_error text for Read preflight failures", async () => {
  265. const fs = createMemoryFileSystem({});
  266. const binary = await executeRead({ file_path: "/tmp/archive.zip" }, fs);
  267. const device = await executeRead({ file_path: "/dev/zero" }, fs);
  268. expect(binary.success).toBe(false);
  269. expect(binary.error?.message).toBe(
  270. "<tool_use_error>This tool cannot read binary files. The file appears to be a binary .zip file. Please use appropriate tools for binary file analysis.</tool_use_error>",
  271. );
  272. expect(device.success).toBe(false);
  273. expect(device.error?.message).toBe(
  274. "<tool_use_error>Cannot read '/dev/zero': this device file would block or produce infinite output.</tool_use_error>",
  275. );
  276. });
  277. it("documents current non-text model-content formatting", () => {
  278. const pdf = {
  279. type: "pdf" as const,
  280. filePath: "/work/report.pdf",
  281. base64: "pdf-data",
  282. originalSize: 4,
  283. };
  284. expect(formatReadModelContent(pdf)).toEqual([
  285. { type: "text", text: "PDF file read: /work/report.pdf (4 bytes)" },
  286. {
  287. type: "file",
  288. mediaType: "application/pdf",
  289. name: "report.pdf",
  290. dataUrl: "data:application/pdf;base64,pdf-data",
  291. source: {
  292. id: "read-pdf",
  293. kind: "inline",
  294. mimeType: "application/pdf",
  295. placeholder: "report.pdf",
  296. sizeBytes: 4,
  297. },
  298. },
  299. ]);
  300. expect(
  301. formatReadModelContent({
  302. type: "image",
  303. base64: "abc123",
  304. mimeType: "image/png",
  305. originalSize: 3,
  306. dimensions: {
  307. originalWidth: 3000,
  308. originalHeight: 1000,
  309. displayWidth: 2000,
  310. displayHeight: 667,
  311. },
  312. }),
  313. ).toEqual([
  314. {
  315. type: "image",
  316. mediaType: "image/png",
  317. dataUrl: "data:image/png;base64,abc123",
  318. source: {
  319. id: "read-image",
  320. kind: "inline",
  321. mimeType: "image/png",
  322. placeholder: "Read image",
  323. sizeBytes: 3,
  324. },
  325. },
  326. ]);
  327. });
  328. });
  329. describeReadStrictContract("Read strict model-result contract", () => {
  330. it("normalizes UTF-8 BOM and CRLF while preserving requested offset and limit", async () => {
  331. const file = join(tmpDir, "windows.txt");
  332. const fs = createMemoryFileSystem({
  333. [file]: "\uFEFFfirst\r\nsecond\r\nthird",
  334. });
  335. const result = await readForModel(
  336. {
  337. file_path: file,
  338. offset: 2,
  339. limit: 1,
  340. },
  341. contextWith(fs),
  342. );
  343. expect(result.output).toMatchObject({
  344. type: "text",
  345. filePath: file,
  346. content: "second",
  347. numLines: 1,
  348. startLine: 2,
  349. totalLines: 3,
  350. });
  351. expect(asModelText(result.modelContent)).toBe("2\tsecond");
  352. });
  353. it("reads relative paths against cwd while preserving the original input path in output data", async () => {
  354. const file = join(tmpDir, "relative.txt");
  355. const fs = createMemoryFileSystem({
  356. [file]: "relative content",
  357. });
  358. const result = await readForModel(
  359. { file_path: "relative.txt" },
  360. contextWith(fs, {
  361. workingDirectory: tmpDir,
  362. workspaceRoot: tmpDir,
  363. }),
  364. );
  365. expect(result.output).toMatchObject({
  366. type: "text",
  367. filePath: "relative.txt",
  368. content: "relative content",
  369. startLine: 1,
  370. totalLines: 1,
  371. });
  372. expect(asModelText(result.modelContent)).toBe("1\trelative content");
  373. });
  374. it("maps an offset beyond EOF to the shorter-than-offset system reminder", async () => {
  375. const file = join(tmpDir, "short.txt");
  376. const fs = createMemoryFileSystem({
  377. [file]: "one\ntwo",
  378. });
  379. const result = await readForModel({ file_path: file, offset: 10 }, contextWith(fs));
  380. expect(result.output).toMatchObject({
  381. type: "text",
  382. content: "",
  383. numLines: 0,
  384. startLine: 10,
  385. totalLines: 2,
  386. });
  387. expect(asModelText(result.modelContent)).toBe(
  388. "<system-reminder>Warning: the file exists but is shorter than the provided offset (10). The file has 2 lines.</system-reminder>",
  389. );
  390. });
  391. it("matches the empty-file fast-path result", async () => {
  392. const file = join(tmpDir, "empty.txt");
  393. const fs = createMemoryFileSystem({
  394. [file]: "",
  395. });
  396. const result = await readForModel({ file_path: file }, contextWith(fs));
  397. expect(result.output).toMatchObject({
  398. type: "text",
  399. content: "",
  400. numLines: 1,
  401. startLine: 1,
  402. totalLines: 1,
  403. });
  404. expect(asModelText(result.modelContent)).toBe(
  405. "<system-reminder>Warning: the file exists but is shorter than the provided offset (1). The file has 1 lines.</system-reminder>",
  406. );
  407. });
  408. it("maps a zero-total-lines text output to the empty-file system reminder", () => {
  409. const modelContent = formatReadModelContent({
  410. type: "text",
  411. filePath: "/tmp/empty.txt",
  412. content: "",
  413. numLines: 0,
  414. startLine: 1,
  415. totalLines: 0,
  416. });
  417. expect(asModelText(modelContent)).toBe(
  418. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  419. );
  420. });
  421. it("throws a file-size error for whole-file reads above the Read byte guard", async () => {
  422. const file = join(tmpDir, "too-large.txt");
  423. const fs = createMemoryFileSystem({
  424. [file]: "x".repeat(READ_MAX_FILE_SIZE_BYTES + 1),
  425. });
  426. await expect(readForModel({ file_path: file }, contextWith(fs))).rejects.toMatchObject({
  427. type: "tool_execution_failed",
  428. message: `File content (${READ_MAX_FILE_SIZE_BYTES + 1} bytes) exceeds maximum allowed size (${READ_MAX_FILE_SIZE_BYTES} bytes). Use offset and limit parameters to read specific portions of the file, or search for specific content instead of reading the whole file.`,
  429. });
  430. });
  431. it("does not apply the byte guard when an explicit line limit is provided", async () => {
  432. const file = join(tmpDir, "large-but-limited.txt");
  433. const fs = createMemoryFileSystem({
  434. [file]: `0123456789\n${"x".repeat(READ_MAX_FILE_SIZE_BYTES + 1)}`,
  435. });
  436. const result = await readForModel(
  437. {
  438. file_path: file,
  439. limit: 1,
  440. },
  441. contextWith(fs),
  442. );
  443. expect(result.output).toMatchObject({
  444. type: "text",
  445. content: "0123456789",
  446. numLines: 1,
  447. startLine: 1,
  448. totalLines: 2,
  449. });
  450. });
  451. it("returns file_unchanged for repeated reads of the same unchanged range", async () => {
  452. const file = join(tmpDir, "dedup.txt");
  453. const fs = createMemoryFileSystem({
  454. [file]: "same\ncontent",
  455. });
  456. const readFileState: ReadFileStateMap = new Map();
  457. const context = contextWith(fs, { readFileState });
  458. const first = await readForModel({ file_path: file }, context);
  459. const second = await readForModel({ file_path: file }, context);
  460. const differentRange = await readForModel(
  461. {
  462. file_path: file,
  463. offset: 2,
  464. limit: 1,
  465. },
  466. context,
  467. );
  468. expect(first.output).toMatchObject({ type: "text" });
  469. expect(second.output).toEqual({
  470. type: "file_unchanged",
  471. filePath: file,
  472. });
  473. expect(asModelText(second.modelContent)).toBe(FILE_UNCHANGED_STUB);
  474. expect(differentRange.output).toMatchObject({
  475. type: "text",
  476. content: "content",
  477. startLine: 2,
  478. });
  479. expect(readFileState.get(createReadFileStateKey(file, 2, 1))).toMatchObject({
  480. isPartialView: false,
  481. limit: 1,
  482. offset: 2,
  483. });
  484. });
  485. it("throws the directory read error returned by the line reader", async () => {
  486. const dir = join(tmpDir, "folder");
  487. const fs = createMemoryFileSystem({}, [dir]);
  488. await expect(readForModel({ file_path: dir }, contextWith(fs))).rejects.toMatchObject({
  489. message: `EISDIR: illegal operation on a directory, read '${dir}'`,
  490. });
  491. });
  492. it("reads notebooks and maps cells to model-facing text blocks", async () => {
  493. const file = join(tmpDir, "demo.ipynb");
  494. const fs = createMemoryFileSystem({
  495. [file]: JSON.stringify({
  496. metadata: { language_info: { name: "python" } },
  497. cells: [
  498. {
  499. id: "markdown-1",
  500. cell_type: "markdown",
  501. source: ["# Title\n", "body"],
  502. },
  503. {
  504. id: "code-1",
  505. cell_type: "code",
  506. execution_count: 3,
  507. source: "print('hi')",
  508. outputs: [
  509. {
  510. output_type: "stream",
  511. text: "hi\n",
  512. },
  513. ],
  514. },
  515. ],
  516. }),
  517. });
  518. const result = await readForModel({ file_path: file }, contextWith(fs));
  519. expect(result.output).toMatchObject({
  520. type: "notebook",
  521. notebookPath: file,
  522. });
  523. expect(asModelText(result.modelContent)).toContain(
  524. '<cell id="markdown-1"><cell_type>markdown</cell_type># Title\nbody</cell id="markdown-1">',
  525. );
  526. expect(asModelText(result.modelContent)).toContain(
  527. '<cell id="code-1">print(\'hi\')</cell id="code-1">',
  528. );
  529. });
  530. it("serializes PDF parts Read output for the model", () => {
  531. const content = formatReadModelContent({
  532. type: "parts",
  533. filePath: "/tmp/report.pdf",
  534. numParts: 3,
  535. originalSize: 2048,
  536. pages: [1, 2, 3].map((pageNumber) => ({
  537. type: "image" as const,
  538. pageNumber,
  539. base64: `page-${pageNumber}`,
  540. mimeType: "image/jpeg" as const,
  541. originalSize: 6,
  542. })),
  543. });
  544. expect(content[0]).toEqual({
  545. type: "text",
  546. text: "PDF pages extracted: 3 page(s) from /tmp/report.pdf (2KB)",
  547. });
  548. expect(content.slice(1).map((block) => block.source?.id)).toEqual([
  549. "read-pdf-page-1",
  550. "read-pdf-page-2",
  551. "read-pdf-page-3",
  552. ]);
  553. });
  554. it("rejects malformed PDF page ranges before I/O", () => {
  555. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "abc" }).success).toBe(false);
  556. });
  557. it("rejects oversized PDF page ranges before I/O", () => {
  558. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "1-21" }).success).toBe(false);
  559. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "20-" }).success).toBe(false);
  560. });
  561. });
  562. async function readForModel(input: unknown, context: ToolExecutionContext) {
  563. const output = await readHandler(input, context);
  564. return {
  565. output,
  566. modelContent: formatReadModelContent(output),
  567. };
  568. }
  569. function formatReadModelContent(output: unknown): ModelMessageContent {
  570. const modelContent = readToolEntry.formatModelContent?.(output);
  571. if (modelContent === undefined) {
  572. throw new Error("Read tool is missing formatModelContent");
  573. }
  574. return modelContent;
  575. }
  576. function asModelText(content: ModelMessageContent | undefined): string {
  577. if (content === undefined) {
  578. throw new Error("Missing model content");
  579. }
  580. return modelMessageContentToText(content);
  581. }
  582. async function executeRead(
  583. input: unknown,
  584. fileSystemPort: FileSystemPort,
  585. options: {
  586. imageProcessorPort?: ImageProcessorPort;
  587. workingDirectory?: string;
  588. workspaceRoot?: string;
  589. } = {},
  590. ) {
  591. const sessionId = createSessionId("read-contract");
  592. const turnId = createTurnId("read-contract");
  593. const traceContext = createRootTraceContext({ sessionId, turnId });
  594. const registry = createToolRegistry();
  595. registry.register(readToolEntry);
  596. return createToolExecutor({
  597. emitEvent: async () => {},
  598. fileSystemPort,
  599. imageProcessorPort: options.imageProcessorPort,
  600. permissionService: new PermissionService(defaultPermissionConfig),
  601. registry,
  602. sessionId,
  603. traceContext,
  604. turnId,
  605. workingDirectory: options.workingDirectory ?? tmpDir,
  606. workspaceRoot: options.workspaceRoot ?? tmpDir,
  607. }).execute(
  608. {
  609. id: createToolCallId("read-contract"),
  610. input,
  611. name: "Read",
  612. },
  613. { traceContext },
  614. );
  615. }
  616. function contextWith(
  617. fileSystemPort: FileSystemPort,
  618. options: {
  619. imageProcessorPort?: ImageProcessorPort;
  620. readFileState?: ReadFileStateMap;
  621. workingDirectory?: string;
  622. workspaceRoot?: string;
  623. } = {},
  624. ): ToolExecutionContext {
  625. return {
  626. toolCallId: "tool_test",
  627. traceId: "trace_test",
  628. spanId: "span_test",
  629. abortSignal: new AbortController().signal,
  630. fileSystemPort,
  631. imageProcessorPort: options.imageProcessorPort,
  632. readFileState: options.readFileState,
  633. workingDirectory: options.workingDirectory ?? tmpDir,
  634. workspaceRoot: options.workspaceRoot ?? tmpDir,
  635. sessionId: "sess_test",
  636. turnId: "turn_test",
  637. };
  638. }
  639. interface MemoryFileSystem extends FileSystemPort {
  640. files: Map<string, string>;
  641. directories: Set<string>;
  642. mtimes: Map<string, number>;
  643. readRangeRequests: Array<Parameters<FileSystemPort["readTextFileRange"]>[0]>;
  644. setMtime(path: string, mtimeMs: number): void;
  645. }
  646. function createMemoryFileSystem(
  647. initial: Record<string, string>,
  648. directories: string[] = [],
  649. ): MemoryFileSystem {
  650. const files = new Map(Object.entries(initial));
  651. const directorySet = new Set(directories);
  652. const mtimes = new Map<string, number>();
  653. const fs: MemoryFileSystem = {
  654. files,
  655. directories: directorySet,
  656. mtimes,
  657. readRangeRequests: [],
  658. setMtime(path, mtimeMs) {
  659. mtimes.set(path, mtimeMs);
  660. },
  661. async stat(request): Promise<FileSystemStatResult> {
  662. if (directorySet.has(request.path)) {
  663. return {
  664. path: request.path,
  665. kind: "directory",
  666. sizeBytes: 0,
  667. };
  668. }
  669. const content = files.get(request.path);
  670. if (content === undefined) throw missingFile(request.path);
  671. const mtimeMs = mtimes.get(request.path) ?? 1;
  672. return {
  673. path: request.path,
  674. kind: "file",
  675. mtimeMs,
  676. sizeBytes: Buffer.byteLength(content, "utf8"),
  677. revision: revisionFor(request.path, content, mtimeMs),
  678. };
  679. },
  680. async readTextFile(request): Promise<FileSystemReadTextResult> {
  681. const content = readTextOrThrow(request.path, files, directorySet);
  682. const normalized = normalizeLineEndings(content);
  683. const mtimeMs = mtimes.get(request.path) ?? 1;
  684. return {
  685. path: request.path,
  686. content: normalized,
  687. encoding: request.encoding ?? "utf8",
  688. lineEndings: detectLineEndings(content),
  689. bytesRead: Buffer.byteLength(content, "utf8"),
  690. sizeBytes: Buffer.byteLength(content, "utf8"),
  691. truncated: false,
  692. revision: revisionFor(request.path, content, mtimeMs),
  693. };
  694. },
  695. async readBinaryFile(request) {
  696. const content = readTextOrThrow(request.path, files, directorySet);
  697. const buffer = Buffer.from(content, "utf8");
  698. const mtimeMs = mtimes.get(request.path) ?? 1;
  699. if (request.maxBytes !== undefined && buffer.byteLength > request.maxBytes) {
  700. throw createFileSystemError({
  701. code: "too_large",
  702. path: request.path,
  703. message: `File content (${buffer.byteLength} bytes) exceeds maximum allowed size (${request.maxBytes} bytes).`,
  704. });
  705. }
  706. return {
  707. path: request.path,
  708. content: buffer,
  709. bytesRead: buffer.byteLength,
  710. sizeBytes: buffer.byteLength,
  711. revision: revisionFor(request.path, content, mtimeMs),
  712. };
  713. },
  714. async readTextFileRange(request): Promise<FileSystemReadTextRangeResult> {
  715. fs.readRangeRequests.push(request);
  716. const content = readTextOrThrow(request.path, files, directorySet);
  717. const mtimeMs = mtimes.get(request.path) ?? 1;
  718. const sizeBytes = Buffer.byteLength(content, "utf8");
  719. if (request.maxBytes !== undefined && sizeBytes > request.maxBytes) {
  720. throw createFileSystemError({
  721. code: "too_large",
  722. path: request.path,
  723. message: `File content (${sizeBytes} bytes) exceeds maximum allowed size (${request.maxBytes} bytes). Use offset and limit parameters to read specific portions of the file, or search for specific content instead of reading the whole file.`,
  724. });
  725. }
  726. const normalized = normalizeLineEndings(content);
  727. const lines = normalized.length === 0 ? [] : normalized.split("\n");
  728. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  729. const limitLines =
  730. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  731. const selected =
  732. limitLines === undefined
  733. ? lines.slice(offsetLine)
  734. : lines.slice(offsetLine, offsetLine + limitLines);
  735. return {
  736. path: request.path,
  737. content: selected.join("\n"),
  738. encoding: request.encoding ?? "utf8",
  739. lineEndings: detectLineEndings(content),
  740. bytesRead: sizeBytes,
  741. sizeBytes,
  742. truncated: false,
  743. startLine: offsetLine + 1,
  744. lineCount: selected.length,
  745. totalLines: lines.length,
  746. revision: revisionFor(request.path, content, mtimeMs),
  747. };
  748. },
  749. async writeTextFile(request) {
  750. files.set(request.path, request.content);
  751. mtimes.set(request.path, (mtimes.get(request.path) ?? 1) + 1);
  752. return {
  753. path: request.path,
  754. bytesWritten: Buffer.byteLength(request.content, "utf8"),
  755. revision: revisionFor(request.path, request.content, mtimes.get(request.path) ?? 1),
  756. };
  757. },
  758. async removeFile(request) {
  759. const removed = files.delete(request.path);
  760. if (!removed && request.missingOk !== true) throw missingFile(request.path);
  761. return {
  762. path: request.path,
  763. removed,
  764. };
  765. },
  766. async listDirectory(request) {
  767. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  768. const entries = Array.from(files.keys())
  769. .filter((path) => path.startsWith(prefix))
  770. .map((path) => ({
  771. kind: "file" as const,
  772. name: path.slice(prefix.length),
  773. path,
  774. }));
  775. return {
  776. path: request.path,
  777. durationMs: 0,
  778. entries,
  779. numEntries: entries.length,
  780. };
  781. },
  782. async searchFiles(request): Promise<FileSystemSearchFilesResult> {
  783. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  784. const filesMatched = Array.from(files.keys()).filter((path) => path.startsWith(prefix));
  785. return {
  786. path: request.path,
  787. pattern: request.pattern,
  788. durationMs: 0,
  789. files: filesMatched,
  790. numFiles: filesMatched.length,
  791. truncated: false,
  792. };
  793. },
  794. async searchText(request): Promise<FileSystemSearchTextResult> {
  795. return {
  796. path: request.path,
  797. pattern: request.pattern,
  798. mode: request.outputMode ?? "files_with_matches",
  799. durationMs: 0,
  800. files: [],
  801. entries: [],
  802. numMatches: 0,
  803. truncated: false,
  804. };
  805. },
  806. };
  807. return fs;
  808. }
  809. function readTextOrThrow(
  810. path: string,
  811. files: Map<string, string>,
  812. directories: Set<string>,
  813. ): string {
  814. if (directories.has(path)) {
  815. throw createFileSystemError({
  816. code: "is_directory",
  817. path,
  818. message: `EISDIR: illegal operation on a directory, read '${path}'`,
  819. });
  820. }
  821. const content = files.get(path);
  822. if (content === undefined) throw missingFile(path);
  823. return content;
  824. }
  825. function missingFile(path: string): Error {
  826. return createFileSystemError({
  827. code: "not_found",
  828. path,
  829. message: `missing: ${path}`,
  830. });
  831. }
  832. function normalizeLineEndings(content: string): string {
  833. return content.replaceAll("\r\n", "\n");
  834. }
  835. function detectLineEndings(content: string): "LF" | "CRLF" {
  836. let crlfCount = 0;
  837. let lfCount = 0;
  838. for (let index = 0; index < content.length; index += 1) {
  839. if (content[index] !== "\n") continue;
  840. if (index > 0 && content[index - 1] === "\r") crlfCount += 1;
  841. else lfCount += 1;
  842. }
  843. return crlfCount > lfCount ? "CRLF" : "LF";
  844. }
  845. function revisionFor(path: string, content: string, mtimeMs = 1): FileSystemRevision {
  846. return {
  847. id: `rev:${path}:${content.length}:${mtimeMs}`,
  848. mtimeMs,
  849. sizeBytes: Buffer.byteLength(content, "utf8"),
  850. };
  851. }
  852. function readInputSafeParse(input: unknown): { success: boolean } {
  853. const schema = readToolEntry.runtimeInputSchema as
  854. | { safeParse: (input: unknown) => { success: boolean } }
  855. | undefined;
  856. if (!schema) {
  857. throw new Error("Read tool is missing runtimeInputSchema");
  858. }
  859. return schema.safeParse(input);
  860. }