read-tool-contract.test.ts 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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 {
  28. readFileForCompactRestore,
  29. readHandler,
  30. readToolEntry,
  31. } from "../src/tool/handlers/read.js";
  32. import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
  33. import { createToolRegistry } from "../src/tool/registry.js";
  34. import type { ReadFileStateMap, ToolExecutionContext } from "../src/tool/types.js";
  35. const RUN_READ_STRICT_CONTRACT = process.env.ZCODE_RUN_READ_STRICT_CONTRACT === "1";
  36. const describeReadStrictContract = RUN_READ_STRICT_CONTRACT ? describe : describe.skip;
  37. const FILE_UNCHANGED_STUB =
  38. "Wasted call — file unchanged since your last Read. Refer to that earlier tool_result instead.";
  39. let tmpDir: string;
  40. beforeEach(async () => {
  41. tmpDir = await mkdtemp(join(tmpdir(), "zcode-read-contract-"));
  42. });
  43. afterEach(async () => {
  44. await rm(tmpDir, { recursive: true, force: true });
  45. });
  46. describe("Read model-result harness", () => {
  47. it("returns video bytes as one provider-visible video block", async () => {
  48. const file = join(tmpDir, "demo.mp4");
  49. const fs = createMemoryFileSystem({
  50. [file]: "video",
  51. });
  52. const result = await readForModel({ file_path: file }, contextWith(fs));
  53. expect(result.output).toEqual({
  54. type: "video",
  55. base64: "dmlkZW8=",
  56. mimeType: "video/mp4",
  57. originalSize: 5,
  58. });
  59. expect(result.modelContent).toEqual([
  60. {
  61. type: "video",
  62. mediaType: "video/mp4",
  63. dataUrl: "data:video/mp4;base64,dmlkZW8=",
  64. source: {
  65. id: "read-video",
  66. kind: "inline",
  67. mimeType: "video/mp4",
  68. placeholder: "Read video",
  69. sizeBytes: 5,
  70. },
  71. },
  72. ]);
  73. });
  74. it("rejects an empty video before creating provider-visible media", async () => {
  75. const file = join(tmpDir, "empty.mp4");
  76. const fs = createMemoryFileSystem({
  77. [file]: "",
  78. });
  79. await expect(readForModel({ file_path: file }, contextWith(fs))).rejects.toMatchObject({
  80. type: CoreErrorType.ToolExecutionFailed,
  81. context: expect.objectContaining({ code: "read_video_input_empty" }),
  82. });
  83. });
  84. it("maps bounded binary-read overflow to the video-specific tool error", async () => {
  85. const file = join(tmpDir, "large.mp4");
  86. const fs = createMemoryFileSystem({ [file]: "video" });
  87. fs.readBinaryFile = async (request) => {
  88. throw createFileSystemError({
  89. code: "too_large",
  90. path: request.path,
  91. message: "video exceeds read limit",
  92. });
  93. };
  94. await expect(readForModel({ file_path: file }, contextWith(fs))).rejects.toMatchObject({
  95. type: CoreErrorType.ToolExecutionFailed,
  96. context: expect.objectContaining({
  97. code: "read_video_input_too_large",
  98. maxBytes: READ_VIDEO_MAX_INPUT_BYTES,
  99. }),
  100. });
  101. });
  102. it("returns the executor modelContent as cat-n text for normal text reads", async () => {
  103. const file = join(tmpDir, "notes.txt");
  104. const fs = createMemoryFileSystem({
  105. [file]: "alpha\nbeta",
  106. });
  107. const result = await executeRead({ file_path: file }, fs);
  108. expect(result.success).toBe(true);
  109. expect(result.output).toMatchObject({
  110. type: "text",
  111. filePath: file,
  112. content: "alpha\nbeta",
  113. numLines: 2,
  114. startLine: 1,
  115. totalLines: 2,
  116. });
  117. expect(result.modelContent).toBe("1\talpha\n2\tbeta");
  118. expect(result.serialization?.content).toBe("1\talpha\n2\tbeta");
  119. });
  120. it("numbers offset zero from line zero while reading the first physical line", async () => {
  121. const file = join(tmpDir, "zero-offset.txt");
  122. const fs = createMemoryFileSystem({
  123. [file]: "first\nsecond",
  124. });
  125. const result = await readForModel(
  126. {
  127. file_path: file,
  128. offset: 0,
  129. limit: 1,
  130. },
  131. contextWith(fs),
  132. );
  133. expect(result.output).toMatchObject({
  134. type: "text",
  135. content: "first",
  136. numLines: 1,
  137. startLine: 0,
  138. totalLines: 2,
  139. });
  140. expect(asModelText(result.modelContent)).toBe("0\tfirst");
  141. });
  142. it("records explicit ranges as range views instead of partial views", async () => {
  143. const file = join(tmpDir, "range-state.txt");
  144. const fs = createMemoryFileSystem({
  145. [file]: "first\nsecond\nthird",
  146. });
  147. const readFileState: ReadFileStateMap = new Map();
  148. const context = contextWith(fs, { readFileState });
  149. await readForModel(
  150. {
  151. file_path: file,
  152. offset: 2,
  153. limit: 1,
  154. },
  155. context,
  156. );
  157. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  158. isPartialView: false,
  159. limit: 1,
  160. offset: 2,
  161. });
  162. });
  163. it("keeps empty-file output metadata on the fast path", async () => {
  164. const file = join(tmpDir, "empty.txt");
  165. const fs = createMemoryFileSystem({
  166. [file]: "",
  167. });
  168. const result = await readForModel({ file_path: file }, contextWith(fs));
  169. expect(result.output).toMatchObject({
  170. type: "text",
  171. content: "",
  172. numLines: 1,
  173. startLine: 1,
  174. totalLines: 1,
  175. });
  176. // 与严格合同同一断言;严格套件默认跳过,这里保证默认测试也覆盖空文件提示。
  177. expect(asModelText(result.modelContent)).toBe(
  178. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  179. );
  180. });
  181. it("reads past 2000 lines by default when byte and token budgets allow", async () => {
  182. const file = join(tmpDir, "many-lines.txt");
  183. const lines = Array.from({ length: 2005 }, (_, index) => `line-${index + 1}`);
  184. const fs = createMemoryFileSystem({
  185. [file]: lines.join("\n"),
  186. });
  187. const result = await readForModel({ file_path: file }, contextWith(fs));
  188. expect(result.output).toMatchObject({
  189. type: "text",
  190. numLines: 2005,
  191. totalLines: 2005,
  192. });
  193. expect(result.output).toHaveProperty("content", expect.stringContaining("line-2005"));
  194. });
  195. it("deduplicates repeated unchanged reads in the handler path", async () => {
  196. const file = join(tmpDir, "dedup.txt");
  197. const fs = createMemoryFileSystem({
  198. [file]: "same\ncontent",
  199. });
  200. const context = contextWith(fs);
  201. const first = await readForModel({ file_path: file }, context);
  202. const second = await readForModel({ file_path: file }, context);
  203. expect(first.output).toMatchObject({ type: "text", content: "same\ncontent" });
  204. expect(second.output).toEqual({ type: "file_unchanged", filePath: file });
  205. expect(asModelText(second.modelContent)).toBe(FILE_UNCHANGED_STUB);
  206. });
  207. // 修复原因:file_unchanged 的快照是当时最新记录的副本。冷恢复按它重放时,会恢复出已不在
  208. // active history 里的视图(例如那次真实读取已被 compact 摘要)。冷恢复只由真实读取恢复。
  209. it("records a read-state snapshot for content reads but not for file_unchanged", async () => {
  210. const file = join(tmpDir, "snapshot.txt");
  211. const fs = createMemoryFileSystem({ [file]: "same\ncontent" });
  212. const snapshots: unknown[] = [];
  213. const context: ToolExecutionContext = {
  214. ...contextWith(fs, { readFileState: new Map() }),
  215. recordReadFileStateMetadata: (metadata) => snapshots.push(metadata),
  216. };
  217. await readForModel({ file_path: file }, context);
  218. const second = await readForModel({ file_path: file }, context);
  219. expect(second.output).toEqual({ type: "file_unchanged", filePath: file });
  220. expect(snapshots).toEqual([expect.objectContaining({ path: file, tool: "Read" })]);
  221. });
  222. it("re-reads the whole current file for compaction without touching the read state", async () => {
  223. const file = join(tmpDir, "restore.txt");
  224. const fs = createMemoryFileSystem({ [file]: "one\ntwo" });
  225. const result = await readFileForCompactRestore({
  226. filePath: file,
  227. fileSystemPort: fs,
  228. workingDirectory: tmpDir,
  229. workspaceRoot: tmpDir,
  230. });
  231. expect(result).toMatchObject({
  232. output: { content: "one\ntwo", startLine: 1, totalLines: 2, type: "text" },
  233. readFileStateEntry: {
  234. content: "one\ntwo",
  235. isPartialView: false,
  236. limit: undefined,
  237. mtimeMs: 1,
  238. offset: undefined,
  239. path: file,
  240. revisionId: expect.any(String),
  241. sizeBytes: 7,
  242. sourceTool: "Read",
  243. },
  244. type: "text",
  245. });
  246. expect(fs.readRangeRequests).toEqual([
  247. expect.objectContaining({
  248. limitLines: undefined,
  249. maxBytes: READ_MAX_FILE_SIZE_BYTES,
  250. path: file,
  251. }),
  252. ]);
  253. });
  254. it("records a token-capped compaction re-read as a partial view", async () => {
  255. const file = join(tmpDir, "token-capped.txt");
  256. // 约 4 万 token,没有超过 Read 的文件大小上限。
  257. const content = Array.from(
  258. { length: 4_000 },
  259. (_, index) => `line ${index} ${"word ".repeat(5)}`,
  260. ).join("\n");
  261. const fs = createMemoryFileSystem({ [file]: content });
  262. const result = await readFileForCompactRestore({
  263. filePath: file,
  264. fileSystemPort: fs,
  265. workingDirectory: tmpDir,
  266. workspaceRoot: tmpDir,
  267. });
  268. expect(Buffer.byteLength(content, "utf8")).toBeLessThan(READ_MAX_FILE_SIZE_BYTES);
  269. expect(result).toMatchObject({
  270. output: { truncatedByTokenCap: true, type: "text" },
  271. readFileStateEntry: { isPartialView: true, path: file },
  272. type: "text",
  273. });
  274. });
  275. it("reports oversized files and skips paths Read would not read as text for compaction", async () => {
  276. const large = join(tmpDir, "large.txt");
  277. const image = join(tmpDir, "shot.png");
  278. const binary = join(tmpDir, "tool.exe");
  279. const fs = createMemoryFileSystem({
  280. [large]: "x".repeat(READ_MAX_FILE_SIZE_BYTES + 1),
  281. [image]: "not really an image",
  282. [binary]: "not really a binary",
  283. });
  284. const restore = (filePath: string) =>
  285. readFileForCompactRestore({
  286. filePath,
  287. fileSystemPort: fs,
  288. workingDirectory: tmpDir,
  289. workspaceRoot: tmpDir,
  290. });
  291. expect(await restore(large)).toEqual({ type: "too_large" });
  292. expect(await restore(image)).toEqual({ type: "skipped" });
  293. expect(await restore(binary)).toEqual({ type: "skipped" });
  294. await expect(restore(join(tmpDir, "missing.txt"))).rejects.toMatchObject({ code: "not_found" });
  295. });
  296. it("returns content again after Edit or Write recorded the file state", async () => {
  297. for (const sourceTool of ["Edit", "Write"] as const) {
  298. const file = join(tmpDir, `after-${sourceTool}.txt`);
  299. const fs = createMemoryFileSystem({ [file]: "alpha\ngamma" });
  300. const readFileState: ReadFileStateMap = new Map();
  301. const context = contextWith(fs, { readFileState });
  302. await readForModel({ file_path: file }, context);
  303. const key = createReadFileStatePathKey(file);
  304. // 模拟 Edit/Write 写入后的状态:同一完整视图的键,文件 mtime/size 未再变化。
  305. readFileState.set(key, { ...readFileState.get(key)!, readAt: new Date(), sourceTool });
  306. const reread = await readForModel({ file_path: file }, context);
  307. // 写入后模型没有看过新内容,重读必须返回内容,不是 Wasted call 存根。
  308. expect(reread.output).toMatchObject({ type: "text", content: "alpha\ngamma" });
  309. }
  310. });
  311. it("deduplicates only against the latest Read view of the path", async () => {
  312. const file = join(tmpDir, "latest-view.txt");
  313. const fs = createMemoryFileSystem({ [file]: "one\ntwo\nthree" });
  314. const readFileState: ReadFileStateMap = new Map();
  315. const context = contextWith(fs, { readFileState });
  316. await readForModel({ file_path: file }, context);
  317. await readForModel({ file_path: file, offset: 2, limit: 1 }, context);
  318. expect(readFileState.size).toBe(1);
  319. const full = await readForModel({ file_path: file }, context);
  320. const repeated = await readForModel({ file_path: file }, context);
  321. // 每个文件只按最近一次视图去重:中间读过别的范围后,完整读取返回内容。
  322. expect(full.output).toMatchObject({ type: "text", content: "one\ntwo\nthree" });
  323. expect(repeated.output).toEqual({ type: "file_unchanged", filePath: file });
  324. // 每个文件只存一条,每次读取覆盖。
  325. expect(readFileState.size).toBe(1);
  326. });
  327. it("maps empty Read content the same way for an empty file and a blank line", async () => {
  328. const empty = join(tmpDir, "empty-file.txt");
  329. const blank = join(tmpDir, "blank-line.txt");
  330. const fs = createMemoryFileSystem({ [empty]: "", [blank]: "a\n\nb" });
  331. const context = contextWith(fs);
  332. const emptyRead = await readForModel({ file_path: empty }, context);
  333. const blankRead = await readForModel({ file_path: blank, offset: 2, limit: 1 }, context);
  334. const pastEnd = await readForModel({ file_path: blank, offset: 5 }, context);
  335. // 空文件说内容为空;按 offset 读到的空行带行号;只有超出末尾才说 offset 太大。
  336. expect(asModelText(emptyRead.modelContent)).toBe(
  337. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  338. );
  339. expect(asModelText(blankRead.modelContent)).toBe("2\t");
  340. expect(asModelText(pastEnd.modelContent)).toBe(
  341. "<system-reminder>Warning: the file exists but is shorter than the provided offset (5). The file has 3 lines.</system-reminder>",
  342. );
  343. });
  344. it("deduplicates repeated reads when mtime only drifts inside the same millisecond", async () => {
  345. const file = join(tmpDir, "dedup-sub-ms.txt");
  346. const fs = createMemoryFileSystem({
  347. [file]: "same\ncontent",
  348. });
  349. fs.setMtime(file, 1000.2);
  350. const context = contextWith(fs);
  351. await readForModel({ file_path: file }, context);
  352. fs.setMtime(file, 1000.8);
  353. const second = await readForModel({ file_path: file }, context);
  354. expect(second.output).toEqual({ type: "file_unchanged", filePath: file });
  355. });
  356. it("re-reads when mtime advances to the next millisecond bucket", async () => {
  357. const file = join(tmpDir, "dedup-next-ms.txt");
  358. const fs = createMemoryFileSystem({
  359. [file]: "same\ncontent",
  360. });
  361. fs.setMtime(file, 1000.9);
  362. const context = contextWith(fs);
  363. await readForModel({ file_path: file }, context);
  364. fs.setMtime(file, 1001);
  365. const second = await readForModel({ file_path: file }, context);
  366. expect(second.output).toMatchObject({
  367. type: "text",
  368. content: "same\ncontent",
  369. });
  370. });
  371. it("re-reads after the file revision changes", async () => {
  372. const file = join(tmpDir, "changed.txt");
  373. const fs = createMemoryFileSystem({
  374. [file]: "before",
  375. });
  376. const context = contextWith(fs);
  377. await readForModel({ file_path: file }, context);
  378. fs.files.set(file, "after");
  379. const second = await readForModel({ file_path: file }, context);
  380. expect(second.output).toMatchObject({
  381. type: "text",
  382. content: "after",
  383. });
  384. });
  385. it("returns a missing-file message with cwd and a suggestion", async () => {
  386. const existing = join(tmpDir, "target.ts");
  387. const missing = join(tmpDir, "target.js");
  388. const fs = createMemoryFileSystem({
  389. [existing]: "export const ok = true",
  390. });
  391. await expect(
  392. readForModel(
  393. { file_path: missing },
  394. contextWith(fs, {
  395. workingDirectory: tmpDir,
  396. workspaceRoot: tmpDir,
  397. }),
  398. ),
  399. ).rejects.toMatchObject({
  400. message: `File does not exist. Note: your current working directory is ${tmpDir}. Did you mean target.ts?`,
  401. });
  402. });
  403. it("rejects unsupported binary extensions and blocking device paths before I/O", () => {
  404. expect(readInputSafeParse({ file_path: "/tmp/archive.zip" }).success).toBe(false);
  405. expect(readInputSafeParse({ file_path: "/dev/zero" }).success).toBe(false);
  406. expect(readInputSafeParse({ file_path: "/tmp/image.png" }).success).toBe(true);
  407. expect(readInputSafeParse({ file_path: "/tmp/doc.pdf" }).success).toBe(true);
  408. });
  409. it("returns tool_use_error text for Read preflight failures", async () => {
  410. const fs = createMemoryFileSystem({});
  411. const binary = await executeRead({ file_path: "/tmp/archive.zip" }, fs);
  412. const device = await executeRead({ file_path: "/dev/zero" }, fs);
  413. expect(binary.success).toBe(false);
  414. expect(binary.error?.message).toBe(
  415. "<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>",
  416. );
  417. expect(device.success).toBe(false);
  418. expect(device.error?.message).toBe(
  419. "<tool_use_error>Cannot read '/dev/zero': this device file would block or produce infinite output.</tool_use_error>",
  420. );
  421. });
  422. it("documents current non-text model-content formatting", () => {
  423. const pdf = {
  424. type: "pdf" as const,
  425. filePath: "/work/report.pdf",
  426. base64: "pdf-data",
  427. originalSize: 4,
  428. };
  429. expect(formatReadModelContent(pdf)).toEqual([
  430. { type: "text", text: "PDF file read: /work/report.pdf (4 bytes)" },
  431. {
  432. type: "file",
  433. mediaType: "application/pdf",
  434. name: "report.pdf",
  435. dataUrl: "data:application/pdf;base64,pdf-data",
  436. source: {
  437. id: "read-pdf",
  438. kind: "inline",
  439. mimeType: "application/pdf",
  440. placeholder: "report.pdf",
  441. sizeBytes: 4,
  442. },
  443. },
  444. ]);
  445. expect(
  446. formatReadModelContent({
  447. type: "image",
  448. base64: "abc123",
  449. mimeType: "image/png",
  450. originalSize: 3,
  451. dimensions: {
  452. originalWidth: 3000,
  453. originalHeight: 1000,
  454. displayWidth: 2000,
  455. displayHeight: 667,
  456. },
  457. }),
  458. ).toEqual([
  459. {
  460. type: "image",
  461. mediaType: "image/png",
  462. dataUrl: "data:image/png;base64,abc123",
  463. source: {
  464. id: "read-image",
  465. kind: "inline",
  466. mimeType: "image/png",
  467. placeholder: "Read image",
  468. sizeBytes: 3,
  469. },
  470. },
  471. ]);
  472. });
  473. });
  474. describeReadStrictContract("Read strict model-result contract", () => {
  475. it("normalizes UTF-8 BOM and CRLF while preserving requested offset and limit", async () => {
  476. const file = join(tmpDir, "windows.txt");
  477. const fs = createMemoryFileSystem({
  478. [file]: "\uFEFFfirst\r\nsecond\r\nthird",
  479. });
  480. const result = await readForModel(
  481. {
  482. file_path: file,
  483. offset: 2,
  484. limit: 1,
  485. },
  486. contextWith(fs),
  487. );
  488. expect(result.output).toMatchObject({
  489. type: "text",
  490. filePath: file,
  491. content: "second",
  492. numLines: 1,
  493. startLine: 2,
  494. totalLines: 3,
  495. });
  496. expect(asModelText(result.modelContent)).toBe("2\tsecond");
  497. });
  498. it("reads relative paths against cwd while preserving the original input path in output data", async () => {
  499. const file = join(tmpDir, "relative.txt");
  500. const fs = createMemoryFileSystem({
  501. [file]: "relative content",
  502. });
  503. const result = await readForModel(
  504. { file_path: "relative.txt" },
  505. contextWith(fs, {
  506. workingDirectory: tmpDir,
  507. workspaceRoot: tmpDir,
  508. }),
  509. );
  510. expect(result.output).toMatchObject({
  511. type: "text",
  512. filePath: "relative.txt",
  513. content: "relative content",
  514. startLine: 1,
  515. totalLines: 1,
  516. });
  517. expect(asModelText(result.modelContent)).toBe("1\trelative content");
  518. });
  519. it("maps an offset beyond EOF to the shorter-than-offset system reminder", async () => {
  520. const file = join(tmpDir, "short.txt");
  521. const fs = createMemoryFileSystem({
  522. [file]: "one\ntwo",
  523. });
  524. const result = await readForModel({ file_path: file, offset: 10 }, contextWith(fs));
  525. expect(result.output).toMatchObject({
  526. type: "text",
  527. content: "",
  528. numLines: 0,
  529. startLine: 10,
  530. totalLines: 2,
  531. });
  532. expect(asModelText(result.modelContent)).toBe(
  533. "<system-reminder>Warning: the file exists but is shorter than the provided offset (10). The file has 2 lines.</system-reminder>",
  534. );
  535. });
  536. it("matches the empty-file fast-path result", async () => {
  537. const file = join(tmpDir, "empty.txt");
  538. const fs = createMemoryFileSystem({
  539. [file]: "",
  540. });
  541. const result = await readForModel({ file_path: file }, contextWith(fs));
  542. expect(result.output).toMatchObject({
  543. type: "text",
  544. content: "",
  545. numLines: 1,
  546. startLine: 1,
  547. totalLines: 1,
  548. });
  549. expect(asModelText(result.modelContent)).toBe(
  550. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  551. );
  552. });
  553. it("maps a zero-total-lines text output to the empty-file system reminder", () => {
  554. const modelContent = formatReadModelContent({
  555. type: "text",
  556. filePath: "/tmp/empty.txt",
  557. content: "",
  558. numLines: 0,
  559. startLine: 1,
  560. totalLines: 0,
  561. });
  562. expect(asModelText(modelContent)).toBe(
  563. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  564. );
  565. });
  566. it("throws a file-size error for whole-file reads above the Read byte guard", async () => {
  567. const file = join(tmpDir, "too-large.txt");
  568. const fs = createMemoryFileSystem({
  569. [file]: "x".repeat(READ_MAX_FILE_SIZE_BYTES + 1),
  570. });
  571. await expect(readForModel({ file_path: file }, contextWith(fs))).rejects.toMatchObject({
  572. type: "tool_execution_failed",
  573. 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.`,
  574. });
  575. });
  576. it("does not apply the byte guard when an explicit line limit is provided", async () => {
  577. const file = join(tmpDir, "large-but-limited.txt");
  578. const fs = createMemoryFileSystem({
  579. [file]: `0123456789\n${"x".repeat(READ_MAX_FILE_SIZE_BYTES + 1)}`,
  580. });
  581. const result = await readForModel(
  582. {
  583. file_path: file,
  584. limit: 1,
  585. },
  586. contextWith(fs),
  587. );
  588. expect(result.output).toMatchObject({
  589. type: "text",
  590. content: "0123456789",
  591. numLines: 1,
  592. startLine: 1,
  593. totalLines: 2,
  594. });
  595. });
  596. it("returns file_unchanged for repeated reads of the same unchanged range", async () => {
  597. const file = join(tmpDir, "dedup.txt");
  598. const fs = createMemoryFileSystem({
  599. [file]: "same\ncontent",
  600. });
  601. const readFileState: ReadFileStateMap = new Map();
  602. const context = contextWith(fs, { readFileState });
  603. const first = await readForModel({ file_path: file }, context);
  604. const second = await readForModel({ file_path: file }, context);
  605. const differentRange = await readForModel(
  606. {
  607. file_path: file,
  608. offset: 2,
  609. limit: 1,
  610. },
  611. context,
  612. );
  613. expect(first.output).toMatchObject({ type: "text" });
  614. expect(second.output).toEqual({
  615. type: "file_unchanged",
  616. filePath: file,
  617. });
  618. expect(asModelText(second.modelContent)).toBe(FILE_UNCHANGED_STUB);
  619. expect(differentRange.output).toMatchObject({
  620. type: "text",
  621. content: "content",
  622. startLine: 2,
  623. });
  624. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  625. isPartialView: false,
  626. limit: 1,
  627. offset: 2,
  628. });
  629. });
  630. it("throws the directory read error returned by the line reader", async () => {
  631. const dir = join(tmpDir, "folder");
  632. const fs = createMemoryFileSystem({}, [dir]);
  633. await expect(readForModel({ file_path: dir }, contextWith(fs))).rejects.toMatchObject({
  634. message: `EISDIR: illegal operation on a directory, read '${dir}'`,
  635. });
  636. });
  637. it("reads notebooks and maps cells to model-facing text blocks", async () => {
  638. const file = join(tmpDir, "demo.ipynb");
  639. const fs = createMemoryFileSystem({
  640. [file]: JSON.stringify({
  641. metadata: { language_info: { name: "python" } },
  642. cells: [
  643. {
  644. id: "markdown-1",
  645. cell_type: "markdown",
  646. source: ["# Title\n", "body"],
  647. },
  648. {
  649. id: "code-1",
  650. cell_type: "code",
  651. execution_count: 3,
  652. source: "print('hi')",
  653. outputs: [
  654. {
  655. output_type: "stream",
  656. text: "hi\n",
  657. },
  658. ],
  659. },
  660. ],
  661. }),
  662. });
  663. const result = await readForModel({ file_path: file }, contextWith(fs));
  664. expect(result.output).toMatchObject({
  665. type: "notebook",
  666. notebookPath: file,
  667. });
  668. expect(asModelText(result.modelContent)).toContain(
  669. '<cell id="markdown-1"><cell_type>markdown</cell_type># Title\nbody</cell id="markdown-1">',
  670. );
  671. expect(asModelText(result.modelContent)).toContain(
  672. '<cell id="code-1">print(\'hi\')</cell id="code-1">',
  673. );
  674. });
  675. it("serializes PDF parts Read output for the model", () => {
  676. const content = formatReadModelContent({
  677. type: "parts",
  678. filePath: "/tmp/report.pdf",
  679. numParts: 3,
  680. originalSize: 2048,
  681. pages: [1, 2, 3].map((pageNumber) => ({
  682. type: "image" as const,
  683. pageNumber,
  684. base64: `page-${pageNumber}`,
  685. mimeType: "image/jpeg" as const,
  686. originalSize: 6,
  687. })),
  688. });
  689. expect(content[0]).toEqual({
  690. type: "text",
  691. text: "PDF pages extracted: 3 page(s) from /tmp/report.pdf (2KB)",
  692. });
  693. expect(content.slice(1).map((block) => block.source?.id)).toEqual([
  694. "read-pdf-page-1",
  695. "read-pdf-page-2",
  696. "read-pdf-page-3",
  697. ]);
  698. });
  699. it("rejects malformed PDF page ranges before I/O", () => {
  700. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "abc" }).success).toBe(false);
  701. });
  702. it("rejects oversized PDF page ranges before I/O", () => {
  703. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "1-21" }).success).toBe(false);
  704. expect(readInputSafeParse({ file_path: "/tmp/x.pdf", pages: "20-" }).success).toBe(false);
  705. });
  706. });
  707. async function readForModel(input: unknown, context: ToolExecutionContext) {
  708. const output = await readHandler(input, context);
  709. return {
  710. output,
  711. modelContent: formatReadModelContent(output),
  712. };
  713. }
  714. function formatReadModelContent(output: unknown): ModelMessageContent {
  715. const modelContent = readToolEntry.formatModelContent?.(output);
  716. if (modelContent === undefined) {
  717. throw new Error("Read tool is missing formatModelContent");
  718. }
  719. return modelContent;
  720. }
  721. function asModelText(content: ModelMessageContent | undefined): string {
  722. if (content === undefined) {
  723. throw new Error("Missing model content");
  724. }
  725. return modelMessageContentToText(content);
  726. }
  727. async function executeRead(
  728. input: unknown,
  729. fileSystemPort: FileSystemPort,
  730. options: {
  731. imageProcessorPort?: ImageProcessorPort;
  732. workingDirectory?: string;
  733. workspaceRoot?: string;
  734. } = {},
  735. ) {
  736. const sessionId = createSessionId("read-contract");
  737. const turnId = createTurnId("read-contract");
  738. const traceContext = createRootTraceContext({ sessionId, turnId });
  739. const registry = createToolRegistry();
  740. registry.register(readToolEntry);
  741. return createToolExecutor({
  742. emitEvent: async () => {},
  743. fileSystemPort,
  744. imageProcessorPort: options.imageProcessorPort,
  745. permissionService: new PermissionService(defaultPermissionConfig),
  746. registry,
  747. sessionId,
  748. traceContext,
  749. turnId,
  750. workingDirectory: options.workingDirectory ?? tmpDir,
  751. workspaceRoot: options.workspaceRoot ?? tmpDir,
  752. }).execute(
  753. {
  754. id: createToolCallId("read-contract"),
  755. input,
  756. name: "Read",
  757. },
  758. { traceContext },
  759. );
  760. }
  761. function contextWith(
  762. fileSystemPort: FileSystemPort,
  763. options: {
  764. imageProcessorPort?: ImageProcessorPort;
  765. readFileState?: ReadFileStateMap;
  766. workingDirectory?: string;
  767. workspaceRoot?: string;
  768. } = {},
  769. ): ToolExecutionContext {
  770. return {
  771. toolCallId: "tool_test",
  772. traceId: "trace_test",
  773. spanId: "span_test",
  774. abortSignal: new AbortController().signal,
  775. fileSystemPort,
  776. imageProcessorPort: options.imageProcessorPort,
  777. readFileState: options.readFileState,
  778. workingDirectory: options.workingDirectory ?? tmpDir,
  779. workspaceRoot: options.workspaceRoot ?? tmpDir,
  780. sessionId: "sess_test",
  781. turnId: "turn_test",
  782. };
  783. }
  784. interface MemoryFileSystem extends FileSystemPort {
  785. files: Map<string, string>;
  786. directories: Set<string>;
  787. mtimes: Map<string, number>;
  788. readRangeRequests: Array<Parameters<FileSystemPort["readTextFileRange"]>[0]>;
  789. setMtime(path: string, mtimeMs: number): void;
  790. }
  791. function createMemoryFileSystem(
  792. initial: Record<string, string>,
  793. directories: string[] = [],
  794. ): MemoryFileSystem {
  795. const files = new Map(Object.entries(initial));
  796. const directorySet = new Set(directories);
  797. const mtimes = new Map<string, number>();
  798. const fs: MemoryFileSystem = {
  799. files,
  800. directories: directorySet,
  801. mtimes,
  802. readRangeRequests: [],
  803. setMtime(path, mtimeMs) {
  804. mtimes.set(path, mtimeMs);
  805. },
  806. async stat(request): Promise<FileSystemStatResult> {
  807. if (directorySet.has(request.path)) {
  808. return {
  809. path: request.path,
  810. kind: "directory",
  811. sizeBytes: 0,
  812. };
  813. }
  814. const content = files.get(request.path);
  815. if (content === undefined) throw missingFile(request.path);
  816. const mtimeMs = mtimes.get(request.path) ?? 1;
  817. return {
  818. path: request.path,
  819. kind: "file",
  820. mtimeMs,
  821. sizeBytes: Buffer.byteLength(content, "utf8"),
  822. revision: revisionFor(request.path, content, mtimeMs),
  823. };
  824. },
  825. async readTextFile(request): Promise<FileSystemReadTextResult> {
  826. const content = readTextOrThrow(request.path, files, directorySet);
  827. const normalized = normalizeLineEndings(content);
  828. const mtimeMs = mtimes.get(request.path) ?? 1;
  829. return {
  830. path: request.path,
  831. content: normalized,
  832. encoding: request.encoding ?? "utf8",
  833. lineEndings: detectLineEndings(content),
  834. bytesRead: Buffer.byteLength(content, "utf8"),
  835. sizeBytes: Buffer.byteLength(content, "utf8"),
  836. truncated: false,
  837. revision: revisionFor(request.path, content, mtimeMs),
  838. };
  839. },
  840. async readBinaryFile(request) {
  841. const content = readTextOrThrow(request.path, files, directorySet);
  842. const buffer = Buffer.from(content, "utf8");
  843. const mtimeMs = mtimes.get(request.path) ?? 1;
  844. if (request.maxBytes !== undefined && buffer.byteLength > request.maxBytes) {
  845. throw createFileSystemError({
  846. code: "too_large",
  847. path: request.path,
  848. message: `File content (${buffer.byteLength} bytes) exceeds maximum allowed size (${request.maxBytes} bytes).`,
  849. });
  850. }
  851. return {
  852. path: request.path,
  853. content: buffer,
  854. bytesRead: buffer.byteLength,
  855. sizeBytes: buffer.byteLength,
  856. revision: revisionFor(request.path, content, mtimeMs),
  857. };
  858. },
  859. async readTextFileRange(request): Promise<FileSystemReadTextRangeResult> {
  860. fs.readRangeRequests.push(request);
  861. const content = readTextOrThrow(request.path, files, directorySet);
  862. const mtimeMs = mtimes.get(request.path) ?? 1;
  863. const sizeBytes = Buffer.byteLength(content, "utf8");
  864. if (request.maxBytes !== undefined && sizeBytes > request.maxBytes) {
  865. throw createFileSystemError({
  866. code: "too_large",
  867. path: request.path,
  868. 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.`,
  869. });
  870. }
  871. const normalized = normalizeLineEndings(content);
  872. const lines = normalized.length === 0 ? [] : normalized.split("\n");
  873. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  874. const limitLines =
  875. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  876. const selected =
  877. limitLines === undefined
  878. ? lines.slice(offsetLine)
  879. : lines.slice(offsetLine, offsetLine + limitLines);
  880. return {
  881. path: request.path,
  882. content: selected.join("\n"),
  883. encoding: request.encoding ?? "utf8",
  884. lineEndings: detectLineEndings(content),
  885. bytesRead: sizeBytes,
  886. sizeBytes,
  887. truncated: false,
  888. startLine: offsetLine + 1,
  889. lineCount: selected.length,
  890. totalLines: lines.length,
  891. revision: revisionFor(request.path, content, mtimeMs),
  892. };
  893. },
  894. async writeTextFile(request) {
  895. files.set(request.path, request.content);
  896. mtimes.set(request.path, (mtimes.get(request.path) ?? 1) + 1);
  897. return {
  898. path: request.path,
  899. bytesWritten: Buffer.byteLength(request.content, "utf8"),
  900. revision: revisionFor(request.path, request.content, mtimes.get(request.path) ?? 1),
  901. };
  902. },
  903. async removeFile(request) {
  904. const removed = files.delete(request.path);
  905. if (!removed && request.missingOk !== true) throw missingFile(request.path);
  906. return {
  907. path: request.path,
  908. removed,
  909. };
  910. },
  911. async listDirectory(request) {
  912. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  913. const entries = Array.from(files.keys())
  914. .filter((path) => path.startsWith(prefix))
  915. .map((path) => ({
  916. kind: "file" as const,
  917. name: path.slice(prefix.length),
  918. path,
  919. }));
  920. return {
  921. path: request.path,
  922. durationMs: 0,
  923. entries,
  924. numEntries: entries.length,
  925. };
  926. },
  927. async searchFiles(request): Promise<FileSystemSearchFilesResult> {
  928. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  929. const filesMatched = Array.from(files.keys()).filter((path) => path.startsWith(prefix));
  930. return {
  931. path: request.path,
  932. pattern: request.pattern,
  933. durationMs: 0,
  934. files: filesMatched,
  935. numFiles: filesMatched.length,
  936. truncated: false,
  937. };
  938. },
  939. async searchText(request): Promise<FileSystemSearchTextResult> {
  940. return {
  941. path: request.path,
  942. pattern: request.pattern,
  943. mode: request.outputMode ?? "files_with_matches",
  944. durationMs: 0,
  945. files: [],
  946. entries: [],
  947. numMatches: 0,
  948. truncated: false,
  949. };
  950. },
  951. };
  952. return fs;
  953. }
  954. function readTextOrThrow(
  955. path: string,
  956. files: Map<string, string>,
  957. directories: Set<string>,
  958. ): string {
  959. if (directories.has(path)) {
  960. throw createFileSystemError({
  961. code: "is_directory",
  962. path,
  963. message: `EISDIR: illegal operation on a directory, read '${path}'`,
  964. });
  965. }
  966. const content = files.get(path);
  967. if (content === undefined) throw missingFile(path);
  968. return content;
  969. }
  970. function missingFile(path: string): Error {
  971. return createFileSystemError({
  972. code: "not_found",
  973. path,
  974. message: `missing: ${path}`,
  975. });
  976. }
  977. function normalizeLineEndings(content: string): string {
  978. return content.replaceAll("\r\n", "\n");
  979. }
  980. function detectLineEndings(content: string): "LF" | "CRLF" {
  981. let crlfCount = 0;
  982. let lfCount = 0;
  983. for (let index = 0; index < content.length; index += 1) {
  984. if (content[index] !== "\n") continue;
  985. if (index > 0 && content[index - 1] === "\r") crlfCount += 1;
  986. else lfCount += 1;
  987. }
  988. return crlfCount > lfCount ? "CRLF" : "LF";
  989. }
  990. function revisionFor(path: string, content: string, mtimeMs = 1): FileSystemRevision {
  991. return {
  992. id: `rev:${path}:${content.length}:${mtimeMs}`,
  993. mtimeMs,
  994. sizeBytes: Buffer.byteLength(content, "utf8"),
  995. };
  996. }
  997. function readInputSafeParse(input: unknown): { success: boolean } {
  998. const schema = readToolEntry.runtimeInputSchema as
  999. | { safeParse: (input: unknown) => { success: boolean } }
  1000. | undefined;
  1001. if (!schema) {
  1002. throw new Error("Read tool is missing runtimeInputSchema");
  1003. }
  1004. return schema.safeParse(input);
  1005. }