read-tool-contract.test.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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. expect(
  279. formatReadModelContent({
  280. type: "file_unchanged",
  281. filePath: "/work/same.txt",
  282. }),
  283. ).toBe(FILE_UNCHANGED_STUB);
  284. const pdf = {
  285. type: "pdf" as const,
  286. filePath: "/work/report.pdf",
  287. base64: "pdf-data",
  288. originalSize: 4,
  289. };
  290. expect(formatReadModelContent(pdf)).toEqual([
  291. { type: "text", text: "PDF file read: /work/report.pdf (4 bytes)" },
  292. {
  293. type: "file",
  294. mediaType: "application/pdf",
  295. name: "report.pdf",
  296. dataUrl: "data:application/pdf;base64,pdf-data",
  297. source: {
  298. id: "read-pdf",
  299. kind: "inline",
  300. mimeType: "application/pdf",
  301. placeholder: "report.pdf",
  302. sizeBytes: 4,
  303. },
  304. },
  305. ]);
  306. expect(
  307. formatReadModelContent({
  308. type: "image",
  309. base64: "abc123",
  310. mimeType: "image/png",
  311. originalSize: 3,
  312. dimensions: {
  313. originalWidth: 3000,
  314. originalHeight: 1000,
  315. displayWidth: 2000,
  316. displayHeight: 667,
  317. },
  318. }),
  319. ).toEqual([
  320. {
  321. type: "image",
  322. mediaType: "image/png",
  323. dataUrl: "data:image/png;base64,abc123",
  324. source: {
  325. id: "read-image",
  326. kind: "inline",
  327. mimeType: "image/png",
  328. placeholder: "Read image",
  329. sizeBytes: 3,
  330. },
  331. },
  332. ]);
  333. });
  334. });
  335. describeReadStrictContract("Read strict model-result contract", () => {
  336. it("returns numbered text content without the legacy file-read mitigation reminder", async () => {
  337. const file = join(tmpDir, "notes.txt");
  338. const fs = createMemoryFileSystem({
  339. [file]: "alpha\nbeta",
  340. });
  341. const result = await readForModel({ file_path: file }, contextWith(fs));
  342. expect(result.output).toMatchObject({
  343. type: "text",
  344. filePath: file,
  345. content: "alpha\nbeta",
  346. numLines: 2,
  347. startLine: 1,
  348. totalLines: 2,
  349. });
  350. expect(asModelText(result.modelContent)).toBe("1\talpha\n2\tbeta");
  351. });
  352. it("normalizes UTF-8 BOM and CRLF while preserving requested offset and limit", async () => {
  353. const file = join(tmpDir, "windows.txt");
  354. const fs = createMemoryFileSystem({
  355. [file]: "\uFEFFfirst\r\nsecond\r\nthird",
  356. });
  357. const result = await readForModel(
  358. {
  359. file_path: file,
  360. offset: 2,
  361. limit: 1,
  362. },
  363. contextWith(fs),
  364. );
  365. expect(result.output).toMatchObject({
  366. type: "text",
  367. filePath: file,
  368. content: "second",
  369. numLines: 1,
  370. startLine: 2,
  371. totalLines: 3,
  372. });
  373. expect(asModelText(result.modelContent)).toBe("2\tsecond");
  374. });
  375. it("allows offset zero and numbers model-facing content from line zero", async () => {
  376. const file = join(tmpDir, "zero-offset.txt");
  377. const fs = createMemoryFileSystem({
  378. [file]: "first\nsecond",
  379. });
  380. const result = await readForModel(
  381. {
  382. file_path: file,
  383. offset: 0,
  384. limit: 1,
  385. },
  386. contextWith(fs),
  387. );
  388. expect(result.output).toMatchObject({
  389. type: "text",
  390. content: "first",
  391. numLines: 1,
  392. startLine: 0,
  393. totalLines: 2,
  394. });
  395. expect(asModelText(result.modelContent)).toBe("0\tfirst");
  396. });
  397. it("reads relative paths against cwd while preserving the original input path in output data", async () => {
  398. const file = join(tmpDir, "relative.txt");
  399. const fs = createMemoryFileSystem({
  400. [file]: "relative content",
  401. });
  402. const result = await readForModel(
  403. { file_path: "relative.txt" },
  404. contextWith(fs, {
  405. workingDirectory: tmpDir,
  406. workspaceRoot: tmpDir,
  407. }),
  408. );
  409. expect(result.output).toMatchObject({
  410. type: "text",
  411. filePath: "relative.txt",
  412. content: "relative content",
  413. startLine: 1,
  414. totalLines: 1,
  415. });
  416. expect(asModelText(result.modelContent)).toBe("1\trelative content");
  417. });
  418. it("maps an offset beyond EOF to the shorter-than-offset system reminder", async () => {
  419. const file = join(tmpDir, "short.txt");
  420. const fs = createMemoryFileSystem({
  421. [file]: "one\ntwo",
  422. });
  423. const result = await readForModel({ file_path: file, offset: 10 }, contextWith(fs));
  424. expect(result.output).toMatchObject({
  425. type: "text",
  426. content: "",
  427. numLines: 0,
  428. startLine: 10,
  429. totalLines: 2,
  430. });
  431. expect(asModelText(result.modelContent)).toBe(
  432. "<system-reminder>Warning: the file exists but is shorter than the provided offset (10). The file has 2 lines.</system-reminder>",
  433. );
  434. });
  435. it("matches the empty-file fast-path result", async () => {
  436. const file = join(tmpDir, "empty.txt");
  437. const fs = createMemoryFileSystem({
  438. [file]: "",
  439. });
  440. const result = await readForModel({ file_path: file }, contextWith(fs));
  441. expect(result.output).toMatchObject({
  442. type: "text",
  443. content: "",
  444. numLines: 1,
  445. startLine: 1,
  446. totalLines: 1,
  447. });
  448. expect(asModelText(result.modelContent)).toBe(
  449. "<system-reminder>Warning: the file exists but is shorter than the provided offset (1). The file has 1 lines.</system-reminder>",
  450. );
  451. });
  452. it("maps a zero-total-lines text output to the empty-file system reminder", () => {
  453. const modelContent = formatReadModelContent({
  454. type: "text",
  455. filePath: "/tmp/empty.txt",
  456. content: "",
  457. numLines: 0,
  458. startLine: 1,
  459. totalLines: 0,
  460. });
  461. expect(asModelText(modelContent)).toBe(
  462. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  463. );
  464. });
  465. it("reads more than 2000 lines when byte and token limits allow", async () => {
  466. const file = join(tmpDir, "many-lines.txt");
  467. const lines = Array.from({ length: 2005 }, (_, index) => `line-${index + 1}`);
  468. const fs = createMemoryFileSystem({
  469. [file]: lines.join("\n"),
  470. });
  471. const result = await readForModel({ file_path: file }, contextWith(fs));
  472. expect(result.output).toMatchObject({
  473. type: "text",
  474. numLines: 2005,
  475. totalLines: 2005,
  476. });
  477. expect(result.output).toHaveProperty("content", expect.stringContaining("line-2005"));
  478. });
  479. it("throws a file-size error for whole-file reads above the Read byte guard", async () => {
  480. const file = join(tmpDir, "too-large.txt");
  481. const fs = createMemoryFileSystem({
  482. [file]: "x".repeat(READ_MAX_FILE_SIZE_BYTES + 1),
  483. });
  484. await expect(readForModel({ file_path: file }, contextWith(fs))).rejects.toMatchObject({
  485. type: "tool_execution_failed",
  486. 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.`,
  487. });
  488. });
  489. it("does not apply the byte guard when an explicit line limit is provided", async () => {
  490. const file = join(tmpDir, "large-but-limited.txt");
  491. const fs = createMemoryFileSystem({
  492. [file]: `0123456789\n${"x".repeat(READ_MAX_FILE_SIZE_BYTES + 1)}`,
  493. });
  494. const result = await readForModel(
  495. {
  496. file_path: file,
  497. limit: 1,
  498. },
  499. contextWith(fs),
  500. );
  501. expect(result.output).toMatchObject({
  502. type: "text",
  503. content: "0123456789",
  504. numLines: 1,
  505. startLine: 1,
  506. totalLines: 2,
  507. });
  508. });
  509. it("returns file_unchanged for repeated reads of the same unchanged range", async () => {
  510. const file = join(tmpDir, "dedup.txt");
  511. const fs = createMemoryFileSystem({
  512. [file]: "same\ncontent",
  513. });
  514. const readFileState: ReadFileStateMap = new Map();
  515. const context = contextWith(fs, { readFileState });
  516. const first = await readForModel({ file_path: file }, context);
  517. const second = await readForModel({ file_path: file }, context);
  518. const differentRange = await readForModel(
  519. {
  520. file_path: file,
  521. offset: 2,
  522. limit: 1,
  523. },
  524. context,
  525. );
  526. expect(first.output).toMatchObject({ type: "text" });
  527. expect(second.output).toEqual({
  528. type: "file_unchanged",
  529. filePath: file,
  530. });
  531. expect(asModelText(second.modelContent)).toBe(FILE_UNCHANGED_STUB);
  532. expect(differentRange.output).toMatchObject({
  533. type: "text",
  534. content: "content",
  535. startLine: 2,
  536. });
  537. expect(readFileState.get(createReadFileStateKey(file, 2, 1))).toMatchObject({
  538. isPartialView: false,
  539. limit: 1,
  540. offset: 2,
  541. });
  542. });
  543. it("re-reads full content when the file changes after a cached read", async () => {
  544. const file = join(tmpDir, "changed.txt");
  545. const fs = createMemoryFileSystem({
  546. [file]: "before",
  547. });
  548. const context = contextWith(fs);
  549. await readForModel({ file_path: file }, context);
  550. fs.files.set(file, "after");
  551. const second = await readForModel({ file_path: file }, context);
  552. expect(second.output).toMatchObject({
  553. type: "text",
  554. content: "after",
  555. });
  556. });
  557. it.todo("does not dedup partial-view or edit/write-seeded cache entries");
  558. it.todo("notifies file-read listeners with the selected text slice only");
  559. it("throws a friendly ENOENT message with cwd note and a similar filename suggestion", async () => {
  560. const existing = join(tmpDir, "target.ts");
  561. const missing = join(tmpDir, "target.js");
  562. const fs = createMemoryFileSystem({
  563. [existing]: "export const ok = true",
  564. });
  565. await expect(
  566. readForModel(
  567. { file_path: missing },
  568. contextWith(fs, {
  569. workingDirectory: tmpDir,
  570. workspaceRoot: tmpDir,
  571. }),
  572. ),
  573. ).rejects.toMatchObject({
  574. message: `File does not exist. Note: your current working directory is ${tmpDir}. Did you mean target.ts?`,
  575. });
  576. });
  577. it("throws the directory read error returned by the line reader", async () => {
  578. const dir = join(tmpDir, "folder");
  579. const fs = createMemoryFileSystem({}, [dir]);
  580. await expect(readForModel({ file_path: dir }, contextWith(fs))).rejects.toMatchObject({
  581. message: `EISDIR: illegal operation on a directory, read '${dir}'`,
  582. });
  583. });
  584. it("reads notebooks and maps cells to model-facing text blocks", async () => {
  585. const file = join(tmpDir, "demo.ipynb");
  586. const fs = createMemoryFileSystem({
  587. [file]: JSON.stringify({
  588. metadata: { language_info: { name: "python" } },
  589. cells: [
  590. {
  591. id: "markdown-1",
  592. cell_type: "markdown",
  593. source: ["# Title\n", "body"],
  594. },
  595. {
  596. id: "code-1",
  597. cell_type: "code",
  598. execution_count: 3,
  599. source: "print('hi')",
  600. outputs: [
  601. {
  602. output_type: "stream",
  603. text: "hi\n",
  604. },
  605. ],
  606. },
  607. ],
  608. }),
  609. });
  610. const result = await readForModel({ file_path: file }, contextWith(fs));
  611. expect(result.output).toMatchObject({
  612. type: "notebook",
  613. notebookPath: file,
  614. });
  615. expect(asModelText(result.modelContent)).toContain(
  616. '<cell id="markdown-1"><cell_type>markdown</cell_type># Title\nbody</cell id="markdown-1">',
  617. );
  618. expect(asModelText(result.modelContent)).toContain(
  619. '<cell id="code-1">print(\'hi\')</cell id="code-1">',
  620. );
  621. });
  622. it("keeps resized image Read output media-only before provider projection", () => {
  623. expect(
  624. formatReadModelContent({
  625. type: "image",
  626. base64: "abc123",
  627. mimeType: "image/png",
  628. originalSize: 3,
  629. dimensions: {
  630. originalWidth: 3000,
  631. originalHeight: 1000,
  632. displayWidth: 2000,
  633. displayHeight: 667,
  634. },
  635. }),
  636. ).toEqual([
  637. {
  638. type: "image",
  639. mediaType: "image/png",
  640. dataUrl: "data:image/png;base64,abc123",
  641. source: {
  642. id: "read-image",
  643. kind: "inline",
  644. mimeType: "image/png",
  645. placeholder: "Read image",
  646. sizeBytes: 3,
  647. },
  648. },
  649. ]);
  650. });
  651. it("serializes PDF Read output for the model", () => {
  652. expect(
  653. asModelText(
  654. formatReadModelContent({
  655. type: "pdf",
  656. filePath: "/tmp/report.pdf",
  657. base64: "pdf-data",
  658. originalSize: 4,
  659. }),
  660. ),
  661. ).toBe("PDF file read: /tmp/report.pdf (4 bytes)");
  662. });
  663. it("serializes PDF parts Read output for the model", () => {
  664. const content = formatReadModelContent({
  665. type: "parts",
  666. filePath: "/tmp/report.pdf",
  667. numParts: 3,
  668. originalSize: 2048,
  669. pages: [1, 2, 3].map((pageNumber) => ({
  670. type: "image" as const,
  671. pageNumber,
  672. base64: `page-${pageNumber}`,
  673. mimeType: "image/jpeg" as const,
  674. originalSize: 6,
  675. })),
  676. });
  677. expect(content[0]).toEqual({
  678. type: "text",
  679. text: "PDF pages extracted: 3 page(s) from /tmp/report.pdf (2KB)",
  680. });
  681. expect(content.slice(1).map((block) => block.source?.id)).toEqual([
  682. "read-pdf-page-1",
  683. "read-pdf-page-2",
  684. "read-pdf-page-3",
  685. ]);
  686. });
  687. it("serializes file_unchanged Read output for the model", () => {
  688. expect(
  689. asModelText(
  690. formatReadModelContent({
  691. type: "file_unchanged",
  692. filePath: "/tmp/same.txt",
  693. }),
  694. ),
  695. ).toBe(FILE_UNCHANGED_STUB);
  696. });
  697. it("rejects malformed PDF page ranges before I/O", () => {
  698. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "abc" }).success).toBe(false);
  699. });
  700. it("rejects oversized PDF page ranges before I/O", () => {
  701. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "1-21" }).success).toBe(false);
  702. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "20-" }).success).toBe(false);
  703. });
  704. it("rejects non-renderable binary extensions", () => {
  705. expect(readInputSafeParse({ file_path: "/tmp/archive.zip" }).success).toBe(false);
  706. });
  707. it("allows PDFs and images through Read input validation", () => {
  708. expect(readInputSafeParse({ file_path: "/tmp/image.png" }).success).toBe(true);
  709. expect(readInputSafeParse({ file_path: "/tmp/doc.pdf" }).success).toBe(true);
  710. });
  711. it("rejects device paths that would block or stream indefinitely", () => {
  712. expect(readInputSafeParse({ file_path: "/dev/zero" }).success).toBe(false);
  713. });
  714. });
  715. async function readForModel(input: unknown, context: ToolExecutionContext) {
  716. const output = await readHandler(input, context);
  717. return {
  718. output,
  719. modelContent: formatReadModelContent(output),
  720. };
  721. }
  722. function formatReadModelContent(output: unknown): ModelMessageContent {
  723. const modelContent = readToolEntry.formatModelContent?.(output);
  724. if (modelContent === undefined) {
  725. throw new Error("Read tool is missing formatModelContent");
  726. }
  727. return modelContent;
  728. }
  729. function asModelText(content: ModelMessageContent | undefined): string {
  730. if (content === undefined) {
  731. throw new Error("Missing model content");
  732. }
  733. return modelMessageContentToText(content);
  734. }
  735. async function executeRead(
  736. input: unknown,
  737. fileSystemPort: FileSystemPort,
  738. options: {
  739. imageProcessorPort?: ImageProcessorPort;
  740. workingDirectory?: string;
  741. workspaceRoot?: string;
  742. } = {},
  743. ) {
  744. const sessionId = createSessionId("read-contract");
  745. const turnId = createTurnId("read-contract");
  746. const traceContext = createRootTraceContext({ sessionId, turnId });
  747. const registry = createToolRegistry();
  748. registry.register(readToolEntry);
  749. return createToolExecutor({
  750. emitEvent: async () => {},
  751. fileSystemPort,
  752. imageProcessorPort: options.imageProcessorPort,
  753. permissionService: new PermissionService(defaultPermissionConfig),
  754. registry,
  755. sessionId,
  756. traceContext,
  757. turnId,
  758. workingDirectory: options.workingDirectory ?? tmpDir,
  759. workspaceRoot: options.workspaceRoot ?? tmpDir,
  760. }).execute(
  761. {
  762. id: createToolCallId("read-contract"),
  763. input,
  764. name: "Read",
  765. },
  766. { traceContext },
  767. );
  768. }
  769. function contextWith(
  770. fileSystemPort: FileSystemPort,
  771. options: {
  772. imageProcessorPort?: ImageProcessorPort;
  773. readFileState?: ReadFileStateMap;
  774. workingDirectory?: string;
  775. workspaceRoot?: string;
  776. } = {},
  777. ): ToolExecutionContext {
  778. return {
  779. toolCallId: "tool_test",
  780. traceId: "trace_test",
  781. spanId: "span_test",
  782. abortSignal: new AbortController().signal,
  783. fileSystemPort,
  784. imageProcessorPort: options.imageProcessorPort,
  785. readFileState: options.readFileState,
  786. workingDirectory: options.workingDirectory ?? tmpDir,
  787. workspaceRoot: options.workspaceRoot ?? tmpDir,
  788. sessionId: "sess_test",
  789. turnId: "turn_test",
  790. };
  791. }
  792. interface MemoryFileSystem extends FileSystemPort {
  793. files: Map<string, string>;
  794. directories: Set<string>;
  795. mtimes: Map<string, number>;
  796. readRangeRequests: Array<Parameters<FileSystemPort["readTextFileRange"]>[0]>;
  797. setMtime(path: string, mtimeMs: number): void;
  798. }
  799. function createMemoryFileSystem(
  800. initial: Record<string, string>,
  801. directories: string[] = [],
  802. ): MemoryFileSystem {
  803. const files = new Map(Object.entries(initial));
  804. const directorySet = new Set(directories);
  805. const mtimes = new Map<string, number>();
  806. const fs: MemoryFileSystem = {
  807. files,
  808. directories: directorySet,
  809. mtimes,
  810. readRangeRequests: [],
  811. setMtime(path, mtimeMs) {
  812. mtimes.set(path, mtimeMs);
  813. },
  814. async stat(request): Promise<FileSystemStatResult> {
  815. if (directorySet.has(request.path)) {
  816. return {
  817. path: request.path,
  818. kind: "directory",
  819. sizeBytes: 0,
  820. };
  821. }
  822. const content = files.get(request.path);
  823. if (content === undefined) throw missingFile(request.path);
  824. const mtimeMs = mtimes.get(request.path) ?? 1;
  825. return {
  826. path: request.path,
  827. kind: "file",
  828. mtimeMs,
  829. sizeBytes: Buffer.byteLength(content, "utf8"),
  830. revision: revisionFor(request.path, content, mtimeMs),
  831. };
  832. },
  833. async readTextFile(request): Promise<FileSystemReadTextResult> {
  834. const content = readTextOrThrow(request.path, files, directorySet);
  835. const normalized = normalizeLineEndings(content);
  836. const mtimeMs = mtimes.get(request.path) ?? 1;
  837. return {
  838. path: request.path,
  839. content: normalized,
  840. encoding: request.encoding ?? "utf8",
  841. lineEndings: detectLineEndings(content),
  842. bytesRead: Buffer.byteLength(content, "utf8"),
  843. sizeBytes: Buffer.byteLength(content, "utf8"),
  844. truncated: false,
  845. revision: revisionFor(request.path, content, mtimeMs),
  846. };
  847. },
  848. async readBinaryFile(request) {
  849. const content = readTextOrThrow(request.path, files, directorySet);
  850. const buffer = Buffer.from(content, "utf8");
  851. const mtimeMs = mtimes.get(request.path) ?? 1;
  852. if (request.maxBytes !== undefined && buffer.byteLength > request.maxBytes) {
  853. throw createFileSystemError({
  854. code: "too_large",
  855. path: request.path,
  856. message: `File content (${buffer.byteLength} bytes) exceeds maximum allowed size (${request.maxBytes} bytes).`,
  857. });
  858. }
  859. return {
  860. path: request.path,
  861. content: buffer,
  862. bytesRead: buffer.byteLength,
  863. sizeBytes: buffer.byteLength,
  864. revision: revisionFor(request.path, content, mtimeMs),
  865. };
  866. },
  867. async readTextFileRange(request): Promise<FileSystemReadTextRangeResult> {
  868. fs.readRangeRequests.push(request);
  869. const content = readTextOrThrow(request.path, files, directorySet);
  870. const mtimeMs = mtimes.get(request.path) ?? 1;
  871. const sizeBytes = Buffer.byteLength(content, "utf8");
  872. if (request.maxBytes !== undefined && sizeBytes > request.maxBytes) {
  873. throw createFileSystemError({
  874. code: "too_large",
  875. path: request.path,
  876. 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.`,
  877. });
  878. }
  879. const normalized = normalizeLineEndings(content);
  880. const lines = normalized.length === 0 ? [] : normalized.split("\n");
  881. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  882. const limitLines =
  883. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  884. const selected =
  885. limitLines === undefined
  886. ? lines.slice(offsetLine)
  887. : lines.slice(offsetLine, offsetLine + limitLines);
  888. return {
  889. path: request.path,
  890. content: selected.join("\n"),
  891. encoding: request.encoding ?? "utf8",
  892. lineEndings: detectLineEndings(content),
  893. bytesRead: sizeBytes,
  894. sizeBytes,
  895. truncated: false,
  896. startLine: offsetLine + 1,
  897. lineCount: selected.length,
  898. totalLines: lines.length,
  899. revision: revisionFor(request.path, content, mtimeMs),
  900. };
  901. },
  902. async writeTextFile(request) {
  903. files.set(request.path, request.content);
  904. mtimes.set(request.path, (mtimes.get(request.path) ?? 1) + 1);
  905. return {
  906. path: request.path,
  907. bytesWritten: Buffer.byteLength(request.content, "utf8"),
  908. revision: revisionFor(request.path, request.content, mtimes.get(request.path) ?? 1),
  909. };
  910. },
  911. async removeFile(request) {
  912. const removed = files.delete(request.path);
  913. if (!removed && request.missingOk !== true) throw missingFile(request.path);
  914. return {
  915. path: request.path,
  916. removed,
  917. };
  918. },
  919. async listDirectory(request) {
  920. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  921. const entries = Array.from(files.keys())
  922. .filter((path) => path.startsWith(prefix))
  923. .map((path) => ({
  924. kind: "file" as const,
  925. name: path.slice(prefix.length),
  926. path,
  927. }));
  928. return {
  929. path: request.path,
  930. durationMs: 0,
  931. entries,
  932. numEntries: entries.length,
  933. };
  934. },
  935. async searchFiles(request): Promise<FileSystemSearchFilesResult> {
  936. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  937. const filesMatched = Array.from(files.keys()).filter((path) => path.startsWith(prefix));
  938. return {
  939. path: request.path,
  940. pattern: request.pattern,
  941. durationMs: 0,
  942. files: filesMatched,
  943. numFiles: filesMatched.length,
  944. truncated: false,
  945. };
  946. },
  947. async searchText(request): Promise<FileSystemSearchTextResult> {
  948. return {
  949. path: request.path,
  950. pattern: request.pattern,
  951. mode: request.outputMode ?? "files_with_matches",
  952. durationMs: 0,
  953. files: [],
  954. entries: [],
  955. numMatches: 0,
  956. truncated: false,
  957. };
  958. },
  959. };
  960. return fs;
  961. }
  962. function readTextOrThrow(
  963. path: string,
  964. files: Map<string, string>,
  965. directories: Set<string>,
  966. ): string {
  967. if (directories.has(path)) {
  968. throw createFileSystemError({
  969. code: "is_directory",
  970. path,
  971. message: `EISDIR: illegal operation on a directory, read '${path}'`,
  972. });
  973. }
  974. const content = files.get(path);
  975. if (content === undefined) throw missingFile(path);
  976. return content;
  977. }
  978. function missingFile(path: string): Error {
  979. return createFileSystemError({
  980. code: "not_found",
  981. path,
  982. message: `missing: ${path}`,
  983. });
  984. }
  985. function normalizeLineEndings(content: string): string {
  986. return content.replaceAll("\r\n", "\n");
  987. }
  988. function detectLineEndings(content: string): "LF" | "CRLF" {
  989. let crlfCount = 0;
  990. let lfCount = 0;
  991. for (let index = 0; index < content.length; index += 1) {
  992. if (content[index] !== "\n") continue;
  993. if (index > 0 && content[index - 1] === "\r") crlfCount += 1;
  994. else lfCount += 1;
  995. }
  996. return crlfCount > lfCount ? "CRLF" : "LF";
  997. }
  998. function revisionFor(path: string, content: string, mtimeMs = 1): FileSystemRevision {
  999. return {
  1000. id: `rev:${path}:${content.length}:${mtimeMs}`,
  1001. mtimeMs,
  1002. sizeBytes: Buffer.byteLength(content, "utf8"),
  1003. };
  1004. }
  1005. function readInputSafeParse(input: unknown): { success: boolean } {
  1006. const schema = readToolEntry.runtimeInputSchema as
  1007. | { safeParse: (input: unknown) => { success: boolean } }
  1008. | undefined;
  1009. if (!schema) {
  1010. throw new Error("Read tool is missing runtimeInputSchema");
  1011. }
  1012. return schema.safeParse(input);
  1013. }