read-tool-contract.test.ts 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  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. // 检查移到 validateInput 后,标签由 executor 加在模型文本上,error.message 与 UI 只有原文。
  404. it("returns tool_use_error text for Read preflight failures", async () => {
  405. const fs = createMemoryFileSystem({});
  406. const binary = await executeRead({ file_path: "/tmp/archive.zip" }, fs);
  407. const device = await executeRead({ file_path: "/dev/zero" }, fs);
  408. const binaryText =
  409. "This tool cannot read binary files. The file appears to be a binary .zip file. Use a skill for this file type if one is available, or a shell command or script that can read the format.";
  410. const deviceText =
  411. "Cannot read '/dev/zero': this path names a device or process file that this tool does not read.";
  412. expect(binary.success).toBe(false);
  413. expect(binary.error?.message).toBe(binaryText);
  414. expect(binary.modelContent).toBe(`<tool_use_error>${binaryText}</tool_use_error>`);
  415. expect(device.success).toBe(false);
  416. expect(device.error?.message).toBe(deviceText);
  417. expect(device.modelContent).toBe(`<tool_use_error>${deviceText}</tool_use_error>`);
  418. });
  419. it("keeps the binary and device checks in the handler for rewritten input", async () => {
  420. const fs = createMemoryFileSystem({});
  421. expect(await readHandler({ file_path: "/dev/zero" }, contextWith(fs))).toEqual({
  422. result: false,
  423. errorCode: 9,
  424. message:
  425. "Cannot read '/dev/zero': this path names a device or process file that this tool does not read.",
  426. });
  427. expect(fs.readRangeRequests).toEqual([]);
  428. });
  429. // 规则见 docs/design/v2/tool/01-read.md「输入修正」:修正发生在 JSON Schema 校验之前,handler 读修正后的范围。
  430. it.each([
  431. ["drops a non-positive limit", { limit: -1 }, "1\ta\n2\tb\n3\tc\n4\td\n5\te"],
  432. ["drops a zero limit", { limit: 0 }, "1\ta\n2\tb\n3\tc\n4\td\n5\te"],
  433. ["drops a negative numeric-string limit", { limit: " -1 " }, "1\ta\n2\tb\n3\tc\n4\td\n5\te"],
  434. ["converts numeric strings", { offset: "2", limit: " 1 " }, "2\tb"],
  435. ["maps a numeric-string length", { length: "2" }, "1\ta\n2\tb"],
  436. ["drops a negative offset", { offset: -5, limit: 2 }, "1\ta\n2\tb"],
  437. ["unwraps one-element arrays", { offset: [2], limit: [2] }, "2\tb\n3\tc"],
  438. ["maps length to limit", { length: 2 }, "1\ta\n2\tb"],
  439. ["maps length after dropping limit", { limit: 0, length: 3 }, "1\ta\n2\tb\n3\tc"],
  440. ["keeps limit over length", { limit: 1, length: 3 }, "1\ta"],
  441. ])("%s before validation", async (_name, range, expected) => {
  442. const file = join(tmpDir, "range.txt");
  443. const fs = createMemoryFileSystem({ [file]: "a\nb\nc\nd\ne" });
  444. const result = await executeRead({ file_path: file, ...range }, fs);
  445. expect(result.success).toBe(true);
  446. expect(result.modelContent).toBe(expected);
  447. });
  448. it("leaves non-numeric strings to field validation", async () => {
  449. const file = join(tmpDir, "range.txt");
  450. const fs = createMemoryFileSystem({ [file]: "a\nb" });
  451. const result = await executeRead({ file_path: file, limit: "abc" }, fs);
  452. expect(result.success).toBe(false);
  453. expect(result.modelContent).toBe(
  454. "<tool_use_error>InputValidationError: Read failed due to the following issue:\nThe parameter `limit` type is expected as `number` but provided as `string`</tool_use_error>",
  455. );
  456. });
  457. it("documents current non-text model-content formatting", () => {
  458. const pdf = {
  459. type: "pdf" as const,
  460. filePath: "/work/report.pdf",
  461. base64: "pdf-data",
  462. originalSize: 4,
  463. };
  464. expect(formatReadModelContent(pdf)).toEqual([
  465. { type: "text", text: "PDF file read: /work/report.pdf (4 bytes)" },
  466. {
  467. type: "file",
  468. mediaType: "application/pdf",
  469. name: "report.pdf",
  470. dataUrl: "data:application/pdf;base64,pdf-data",
  471. source: {
  472. id: "read-pdf",
  473. kind: "inline",
  474. mimeType: "application/pdf",
  475. placeholder: "report.pdf",
  476. sizeBytes: 4,
  477. },
  478. },
  479. ]);
  480. expect(
  481. formatReadModelContent({
  482. type: "image",
  483. base64: "abc123",
  484. mimeType: "image/png",
  485. originalSize: 3,
  486. dimensions: {
  487. originalWidth: 3000,
  488. originalHeight: 1000,
  489. displayWidth: 2000,
  490. displayHeight: 667,
  491. },
  492. }),
  493. ).toEqual([
  494. {
  495. type: "image",
  496. mediaType: "image/png",
  497. dataUrl: "data:image/png;base64,abc123",
  498. source: {
  499. id: "read-image",
  500. kind: "inline",
  501. mimeType: "image/png",
  502. placeholder: "Read image",
  503. sizeBytes: 3,
  504. },
  505. },
  506. ]);
  507. });
  508. });
  509. describeReadStrictContract("Read strict model-result contract", () => {
  510. it("normalizes UTF-8 BOM and CRLF while preserving requested offset and limit", async () => {
  511. const file = join(tmpDir, "windows.txt");
  512. const fs = createMemoryFileSystem({
  513. [file]: "\uFEFFfirst\r\nsecond\r\nthird",
  514. });
  515. const result = await readForModel(
  516. {
  517. file_path: file,
  518. offset: 2,
  519. limit: 1,
  520. },
  521. contextWith(fs),
  522. );
  523. expect(result.output).toMatchObject({
  524. type: "text",
  525. filePath: file,
  526. content: "second",
  527. numLines: 1,
  528. startLine: 2,
  529. totalLines: 3,
  530. });
  531. expect(asModelText(result.modelContent)).toBe("2\tsecond");
  532. });
  533. it("reads relative paths against cwd while preserving the original input path in output data", async () => {
  534. const file = join(tmpDir, "relative.txt");
  535. const fs = createMemoryFileSystem({
  536. [file]: "relative content",
  537. });
  538. const result = await readForModel(
  539. { file_path: "relative.txt" },
  540. contextWith(fs, {
  541. workingDirectory: tmpDir,
  542. workspaceRoot: tmpDir,
  543. }),
  544. );
  545. expect(result.output).toMatchObject({
  546. type: "text",
  547. filePath: "relative.txt",
  548. content: "relative content",
  549. startLine: 1,
  550. totalLines: 1,
  551. });
  552. expect(asModelText(result.modelContent)).toBe("1\trelative content");
  553. });
  554. it("maps an offset beyond EOF to the shorter-than-offset system reminder", async () => {
  555. const file = join(tmpDir, "short.txt");
  556. const fs = createMemoryFileSystem({
  557. [file]: "one\ntwo",
  558. });
  559. const result = await readForModel({ file_path: file, offset: 10 }, contextWith(fs));
  560. expect(result.output).toMatchObject({
  561. type: "text",
  562. content: "",
  563. numLines: 0,
  564. startLine: 10,
  565. totalLines: 2,
  566. });
  567. expect(asModelText(result.modelContent)).toBe(
  568. "<system-reminder>Warning: the file exists but is shorter than the provided offset (10). The file has 2 lines.</system-reminder>",
  569. );
  570. });
  571. it("matches the empty-file fast-path result", async () => {
  572. const file = join(tmpDir, "empty.txt");
  573. const fs = createMemoryFileSystem({
  574. [file]: "",
  575. });
  576. const result = await readForModel({ file_path: file }, contextWith(fs));
  577. expect(result.output).toMatchObject({
  578. type: "text",
  579. content: "",
  580. numLines: 1,
  581. startLine: 1,
  582. totalLines: 1,
  583. });
  584. expect(asModelText(result.modelContent)).toBe(
  585. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  586. );
  587. });
  588. it("maps a zero-total-lines text output to the empty-file system reminder", () => {
  589. const modelContent = formatReadModelContent({
  590. type: "text",
  591. filePath: "/tmp/empty.txt",
  592. content: "",
  593. numLines: 0,
  594. startLine: 1,
  595. totalLines: 0,
  596. });
  597. expect(asModelText(modelContent)).toBe(
  598. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  599. );
  600. });
  601. it("throws a file-size error for whole-file reads above the Read byte guard", async () => {
  602. const file = join(tmpDir, "too-large.txt");
  603. const fs = createMemoryFileSystem({
  604. [file]: "x".repeat(READ_MAX_FILE_SIZE_BYTES + 1),
  605. });
  606. await expect(readForModel({ file_path: file }, contextWith(fs))).rejects.toMatchObject({
  607. type: "tool_execution_failed",
  608. 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.`,
  609. });
  610. });
  611. it("does not apply the byte guard when an explicit line limit is provided", async () => {
  612. const file = join(tmpDir, "large-but-limited.txt");
  613. const fs = createMemoryFileSystem({
  614. [file]: `0123456789\n${"x".repeat(READ_MAX_FILE_SIZE_BYTES + 1)}`,
  615. });
  616. const result = await readForModel(
  617. {
  618. file_path: file,
  619. limit: 1,
  620. },
  621. contextWith(fs),
  622. );
  623. expect(result.output).toMatchObject({
  624. type: "text",
  625. content: "0123456789",
  626. numLines: 1,
  627. startLine: 1,
  628. totalLines: 2,
  629. });
  630. });
  631. it("returns file_unchanged for repeated reads of the same unchanged range", async () => {
  632. const file = join(tmpDir, "dedup.txt");
  633. const fs = createMemoryFileSystem({
  634. [file]: "same\ncontent",
  635. });
  636. const readFileState: ReadFileStateMap = new Map();
  637. const context = contextWith(fs, { readFileState });
  638. const first = await readForModel({ file_path: file }, context);
  639. const second = await readForModel({ file_path: file }, context);
  640. const differentRange = await readForModel(
  641. {
  642. file_path: file,
  643. offset: 2,
  644. limit: 1,
  645. },
  646. context,
  647. );
  648. expect(first.output).toMatchObject({ type: "text" });
  649. expect(second.output).toEqual({
  650. type: "file_unchanged",
  651. filePath: file,
  652. });
  653. expect(asModelText(second.modelContent)).toBe(FILE_UNCHANGED_STUB);
  654. expect(differentRange.output).toMatchObject({
  655. type: "text",
  656. content: "content",
  657. startLine: 2,
  658. });
  659. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  660. isPartialView: false,
  661. limit: 1,
  662. offset: 2,
  663. });
  664. });
  665. it("throws the directory read error returned by the line reader", async () => {
  666. const dir = join(tmpDir, "folder");
  667. const fs = createMemoryFileSystem({}, [dir]);
  668. await expect(readForModel({ file_path: dir }, contextWith(fs))).rejects.toMatchObject({
  669. message: `EISDIR: illegal operation on a directory, read '${dir}'`,
  670. });
  671. });
  672. it("reads notebooks and maps cells to model-facing text blocks", async () => {
  673. const file = join(tmpDir, "demo.ipynb");
  674. const fs = createMemoryFileSystem({
  675. [file]: JSON.stringify({
  676. metadata: { language_info: { name: "python" } },
  677. cells: [
  678. {
  679. id: "markdown-1",
  680. cell_type: "markdown",
  681. source: ["# Title\n", "body"],
  682. },
  683. {
  684. id: "code-1",
  685. cell_type: "code",
  686. execution_count: 3,
  687. source: "print('hi')",
  688. outputs: [
  689. {
  690. output_type: "stream",
  691. text: "hi\n",
  692. },
  693. ],
  694. },
  695. ],
  696. }),
  697. });
  698. const result = await readForModel({ file_path: file }, contextWith(fs));
  699. expect(result.output).toMatchObject({
  700. type: "notebook",
  701. notebookPath: file,
  702. });
  703. expect(asModelText(result.modelContent)).toContain(
  704. '<cell id="markdown-1"><cell_type>markdown</cell_type># Title\nbody</cell id="markdown-1">',
  705. );
  706. expect(asModelText(result.modelContent)).toContain(
  707. '<cell id="code-1">print(\'hi\')</cell id="code-1">',
  708. );
  709. });
  710. it("serializes PDF parts Read output for the model", () => {
  711. const content = formatReadModelContent({
  712. type: "parts",
  713. filePath: "/tmp/report.pdf",
  714. numParts: 3,
  715. originalSize: 2048,
  716. pages: [1, 2, 3].map((pageNumber) => ({
  717. type: "image" as const,
  718. pageNumber,
  719. base64: `page-${pageNumber}`,
  720. mimeType: "image/jpeg" as const,
  721. originalSize: 6,
  722. })),
  723. });
  724. expect(content[0]).toEqual({
  725. type: "text",
  726. text: "PDF pages extracted: 3 page(s) from /tmp/report.pdf (2KB)",
  727. });
  728. expect(content.slice(1).map((block) => block.source?.id)).toEqual([
  729. "read-pdf-page-1",
  730. "read-pdf-page-2",
  731. "read-pdf-page-3",
  732. ]);
  733. });
  734. it("rejects malformed PDF page ranges before I/O", () => {
  735. expect(readInputValidation({ file_path: "/tmp/x.pdf", pages: "abc" })).toMatchObject({
  736. result: false,
  737. errorCode: 7,
  738. });
  739. });
  740. it("rejects oversized PDF page ranges before I/O", () => {
  741. expect(readInputValidation({ file_path: "/tmp/x.pdf", pages: "1-21" })).toMatchObject({
  742. result: false,
  743. errorCode: 8,
  744. });
  745. expect(readInputValidation({ file_path: "/tmp/x.pdf", pages: "20-" })).toMatchObject({
  746. result: false,
  747. errorCode: 8,
  748. });
  749. });
  750. });
  751. async function readForModel(input: unknown, context: ToolExecutionContext) {
  752. const output = await readHandler(input, context);
  753. return {
  754. output,
  755. modelContent: formatReadModelContent(output),
  756. };
  757. }
  758. function formatReadModelContent(output: unknown): ModelMessageContent {
  759. const modelContent = readToolEntry.formatModelContent?.(output);
  760. if (modelContent === undefined) {
  761. throw new Error("Read tool is missing formatModelContent");
  762. }
  763. return modelContent;
  764. }
  765. function asModelText(content: ModelMessageContent | undefined): string {
  766. if (content === undefined) {
  767. throw new Error("Missing model content");
  768. }
  769. return modelMessageContentToText(content);
  770. }
  771. async function executeRead(
  772. input: unknown,
  773. fileSystemPort: FileSystemPort,
  774. options: {
  775. imageProcessorPort?: ImageProcessorPort;
  776. workingDirectory?: string;
  777. workspaceRoot?: string;
  778. } = {},
  779. ) {
  780. const sessionId = createSessionId("read-contract");
  781. const turnId = createTurnId("read-contract");
  782. const traceContext = createRootTraceContext({ sessionId, turnId });
  783. const registry = createToolRegistry();
  784. registry.register(readToolEntry);
  785. return createToolExecutor({
  786. emitEvent: async () => {},
  787. fileSystemPort,
  788. imageProcessorPort: options.imageProcessorPort,
  789. permissionService: new PermissionService(defaultPermissionConfig),
  790. registry,
  791. sessionId,
  792. traceContext,
  793. turnId,
  794. workingDirectory: options.workingDirectory ?? tmpDir,
  795. workspaceRoot: options.workspaceRoot ?? tmpDir,
  796. }).execute(
  797. {
  798. id: createToolCallId("read-contract"),
  799. input,
  800. name: "Read",
  801. },
  802. { traceContext },
  803. );
  804. }
  805. function contextWith(
  806. fileSystemPort: FileSystemPort,
  807. options: {
  808. imageProcessorPort?: ImageProcessorPort;
  809. readFileState?: ReadFileStateMap;
  810. workingDirectory?: string;
  811. workspaceRoot?: string;
  812. } = {},
  813. ): ToolExecutionContext {
  814. return {
  815. toolCallId: "tool_test",
  816. traceId: "trace_test",
  817. spanId: "span_test",
  818. abortSignal: new AbortController().signal,
  819. fileSystemPort,
  820. imageProcessorPort: options.imageProcessorPort,
  821. readFileState: options.readFileState,
  822. workingDirectory: options.workingDirectory ?? tmpDir,
  823. workspaceRoot: options.workspaceRoot ?? tmpDir,
  824. sessionId: "sess_test",
  825. turnId: "turn_test",
  826. };
  827. }
  828. interface MemoryFileSystem extends FileSystemPort {
  829. files: Map<string, string>;
  830. directories: Set<string>;
  831. mtimes: Map<string, number>;
  832. readRangeRequests: Array<Parameters<FileSystemPort["readTextFileRange"]>[0]>;
  833. setMtime(path: string, mtimeMs: number): void;
  834. }
  835. function createMemoryFileSystem(
  836. initial: Record<string, string>,
  837. directories: string[] = [],
  838. ): MemoryFileSystem {
  839. const files = new Map(Object.entries(initial));
  840. const directorySet = new Set(directories);
  841. const mtimes = new Map<string, number>();
  842. const fs: MemoryFileSystem = {
  843. files,
  844. directories: directorySet,
  845. mtimes,
  846. readRangeRequests: [],
  847. setMtime(path, mtimeMs) {
  848. mtimes.set(path, mtimeMs);
  849. },
  850. async stat(request): Promise<FileSystemStatResult> {
  851. if (directorySet.has(request.path)) {
  852. return {
  853. path: request.path,
  854. kind: "directory",
  855. sizeBytes: 0,
  856. };
  857. }
  858. const content = files.get(request.path);
  859. if (content === undefined) throw missingFile(request.path);
  860. const mtimeMs = mtimes.get(request.path) ?? 1;
  861. return {
  862. path: request.path,
  863. kind: "file",
  864. mtimeMs,
  865. sizeBytes: Buffer.byteLength(content, "utf8"),
  866. revision: revisionFor(request.path, content, mtimeMs),
  867. };
  868. },
  869. async readTextFile(request): Promise<FileSystemReadTextResult> {
  870. const content = readTextOrThrow(request.path, files, directorySet);
  871. const normalized = normalizeLineEndings(content);
  872. const mtimeMs = mtimes.get(request.path) ?? 1;
  873. return {
  874. path: request.path,
  875. content: normalized,
  876. encoding: request.encoding ?? "utf8",
  877. lineEndings: detectLineEndings(content),
  878. bytesRead: Buffer.byteLength(content, "utf8"),
  879. sizeBytes: Buffer.byteLength(content, "utf8"),
  880. truncated: false,
  881. revision: revisionFor(request.path, content, mtimeMs),
  882. };
  883. },
  884. async readBinaryFile(request) {
  885. const content = readTextOrThrow(request.path, files, directorySet);
  886. const buffer = Buffer.from(content, "utf8");
  887. const mtimeMs = mtimes.get(request.path) ?? 1;
  888. if (request.maxBytes !== undefined && buffer.byteLength > request.maxBytes) {
  889. throw createFileSystemError({
  890. code: "too_large",
  891. path: request.path,
  892. message: `File content (${buffer.byteLength} bytes) exceeds maximum allowed size (${request.maxBytes} bytes).`,
  893. });
  894. }
  895. return {
  896. path: request.path,
  897. content: buffer,
  898. bytesRead: buffer.byteLength,
  899. sizeBytes: buffer.byteLength,
  900. revision: revisionFor(request.path, content, mtimeMs),
  901. };
  902. },
  903. async readTextFileRange(request): Promise<FileSystemReadTextRangeResult> {
  904. fs.readRangeRequests.push(request);
  905. const content = readTextOrThrow(request.path, files, directorySet);
  906. const mtimeMs = mtimes.get(request.path) ?? 1;
  907. const sizeBytes = Buffer.byteLength(content, "utf8");
  908. if (request.maxBytes !== undefined && sizeBytes > request.maxBytes) {
  909. throw createFileSystemError({
  910. code: "too_large",
  911. path: request.path,
  912. 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.`,
  913. });
  914. }
  915. const normalized = normalizeLineEndings(content);
  916. const lines = normalized.length === 0 ? [] : normalized.split("\n");
  917. const offsetLine = Math.max(0, Math.trunc(request.offsetLine ?? 0));
  918. const limitLines =
  919. request.limitLines === undefined ? undefined : Math.max(0, Math.trunc(request.limitLines));
  920. const selected =
  921. limitLines === undefined
  922. ? lines.slice(offsetLine)
  923. : lines.slice(offsetLine, offsetLine + limitLines);
  924. return {
  925. path: request.path,
  926. content: selected.join("\n"),
  927. encoding: request.encoding ?? "utf8",
  928. lineEndings: detectLineEndings(content),
  929. bytesRead: sizeBytes,
  930. sizeBytes,
  931. truncated: false,
  932. startLine: offsetLine + 1,
  933. lineCount: selected.length,
  934. totalLines: lines.length,
  935. revision: revisionFor(request.path, content, mtimeMs),
  936. };
  937. },
  938. async writeTextFile(request) {
  939. files.set(request.path, request.content);
  940. mtimes.set(request.path, (mtimes.get(request.path) ?? 1) + 1);
  941. return {
  942. path: request.path,
  943. bytesWritten: Buffer.byteLength(request.content, "utf8"),
  944. revision: revisionFor(request.path, request.content, mtimes.get(request.path) ?? 1),
  945. };
  946. },
  947. async removeFile(request) {
  948. const removed = files.delete(request.path);
  949. if (!removed && request.missingOk !== true) throw missingFile(request.path);
  950. return {
  951. path: request.path,
  952. removed,
  953. };
  954. },
  955. async listDirectory(request) {
  956. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  957. const entries = Array.from(files.keys())
  958. .filter((path) => path.startsWith(prefix))
  959. .map((path) => ({
  960. kind: "file" as const,
  961. name: path.slice(prefix.length),
  962. path,
  963. }));
  964. return {
  965. path: request.path,
  966. durationMs: 0,
  967. entries,
  968. numEntries: entries.length,
  969. };
  970. },
  971. async searchFiles(request): Promise<FileSystemSearchFilesResult> {
  972. const prefix = `${request.path.replace(/\/+$/u, "")}/`;
  973. const filesMatched = Array.from(files.keys()).filter((path) => path.startsWith(prefix));
  974. return {
  975. path: request.path,
  976. pattern: request.pattern,
  977. durationMs: 0,
  978. files: filesMatched,
  979. numFiles: filesMatched.length,
  980. truncated: false,
  981. };
  982. },
  983. async searchText(request): Promise<FileSystemSearchTextResult> {
  984. return {
  985. path: request.path,
  986. pattern: request.pattern,
  987. mode: request.outputMode ?? "files_with_matches",
  988. durationMs: 0,
  989. files: [],
  990. entries: [],
  991. numMatches: 0,
  992. truncated: false,
  993. };
  994. },
  995. };
  996. return fs;
  997. }
  998. function readTextOrThrow(
  999. path: string,
  1000. files: Map<string, string>,
  1001. directories: Set<string>,
  1002. ): string {
  1003. if (directories.has(path)) {
  1004. throw createFileSystemError({
  1005. code: "is_directory",
  1006. path,
  1007. message: `EISDIR: illegal operation on a directory, read '${path}'`,
  1008. });
  1009. }
  1010. const content = files.get(path);
  1011. if (content === undefined) throw missingFile(path);
  1012. return content;
  1013. }
  1014. function missingFile(path: string): Error {
  1015. return createFileSystemError({
  1016. code: "not_found",
  1017. path,
  1018. message: `missing: ${path}`,
  1019. });
  1020. }
  1021. function normalizeLineEndings(content: string): string {
  1022. return content.replaceAll("\r\n", "\n");
  1023. }
  1024. function detectLineEndings(content: string): "LF" | "CRLF" {
  1025. let crlfCount = 0;
  1026. let lfCount = 0;
  1027. for (let index = 0; index < content.length; index += 1) {
  1028. if (content[index] !== "\n") continue;
  1029. if (index > 0 && content[index - 1] === "\r") crlfCount += 1;
  1030. else lfCount += 1;
  1031. }
  1032. return crlfCount > lfCount ? "CRLF" : "LF";
  1033. }
  1034. function revisionFor(path: string, content: string, mtimeMs = 1): FileSystemRevision {
  1035. return {
  1036. id: `rev:${path}:${content.length}:${mtimeMs}`,
  1037. mtimeMs,
  1038. sizeBytes: Buffer.byteLength(content, "utf8"),
  1039. };
  1040. }
  1041. function readInputValidation(input: unknown) {
  1042. if (!readToolEntry.validateInput) {
  1043. throw new Error("Read tool is missing validateInput");
  1044. }
  1045. return readToolEntry.validateInput(input, {});
  1046. }