read.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import { describe, expect, test } from "bun:test"
  2. import path from "path"
  3. import { ReadTool } from "../../src/tool/read"
  4. import { Instance } from "../../src/project/instance"
  5. import { tmpdir } from "../fixture/fixture"
  6. import { PermissionNext } from "../../src/permission/next"
  7. import { Agent } from "../../src/agent/agent"
  8. const FIXTURES_DIR = path.join(import.meta.dir, "fixtures")
  9. const ctx = {
  10. sessionID: "test",
  11. messageID: "",
  12. callID: "",
  13. agent: "build",
  14. abort: AbortSignal.any([]),
  15. messages: [],
  16. metadata: () => {},
  17. ask: async () => {},
  18. }
  19. describe("tool.read external_directory permission", () => {
  20. test("allows reading absolute path inside project directory", async () => {
  21. await using tmp = await tmpdir({
  22. init: async (dir) => {
  23. await Bun.write(path.join(dir, "test.txt"), "hello world")
  24. },
  25. })
  26. await Instance.provide({
  27. directory: tmp.path,
  28. fn: async () => {
  29. const read = await ReadTool.init()
  30. const result = await read.execute({ filePath: path.join(tmp.path, "test.txt") }, ctx)
  31. expect(result.output).toContain("hello world")
  32. },
  33. })
  34. })
  35. test("allows reading file in subdirectory inside project directory", async () => {
  36. await using tmp = await tmpdir({
  37. init: async (dir) => {
  38. await Bun.write(path.join(dir, "subdir", "test.txt"), "nested content")
  39. },
  40. })
  41. await Instance.provide({
  42. directory: tmp.path,
  43. fn: async () => {
  44. const read = await ReadTool.init()
  45. const result = await read.execute({ filePath: path.join(tmp.path, "subdir", "test.txt") }, ctx)
  46. expect(result.output).toContain("nested content")
  47. },
  48. })
  49. })
  50. test("asks for external_directory permission when reading absolute path outside project", async () => {
  51. await using outerTmp = await tmpdir({
  52. init: async (dir) => {
  53. await Bun.write(path.join(dir, "secret.txt"), "secret data")
  54. },
  55. })
  56. await using tmp = await tmpdir({ git: true })
  57. await Instance.provide({
  58. directory: tmp.path,
  59. fn: async () => {
  60. const read = await ReadTool.init()
  61. const requests: Array<Omit<PermissionNext.Request, "id" | "sessionID" | "tool">> = []
  62. const testCtx = {
  63. ...ctx,
  64. ask: async (req: Omit<PermissionNext.Request, "id" | "sessionID" | "tool">) => {
  65. requests.push(req)
  66. },
  67. }
  68. await read.execute({ filePath: path.join(outerTmp.path, "secret.txt") }, testCtx)
  69. const extDirReq = requests.find((r) => r.permission === "external_directory")
  70. expect(extDirReq).toBeDefined()
  71. expect(extDirReq!.patterns.some((p) => p.includes(outerTmp.path))).toBe(true)
  72. },
  73. })
  74. })
  75. test("asks for directory-scoped external_directory permission when reading external directory", async () => {
  76. await using outerTmp = await tmpdir({
  77. init: async (dir) => {
  78. await Bun.write(path.join(dir, "external", "a.txt"), "a")
  79. },
  80. })
  81. await using tmp = await tmpdir({ git: true })
  82. await Instance.provide({
  83. directory: tmp.path,
  84. fn: async () => {
  85. const read = await ReadTool.init()
  86. const requests: Array<Omit<PermissionNext.Request, "id" | "sessionID" | "tool">> = []
  87. const testCtx = {
  88. ...ctx,
  89. ask: async (req: Omit<PermissionNext.Request, "id" | "sessionID" | "tool">) => {
  90. requests.push(req)
  91. },
  92. }
  93. await read.execute({ filePath: path.join(outerTmp.path, "external") }, testCtx)
  94. const extDirReq = requests.find((r) => r.permission === "external_directory")
  95. expect(extDirReq).toBeDefined()
  96. expect(extDirReq!.patterns).toContain(path.join(outerTmp.path, "external", "*"))
  97. },
  98. })
  99. })
  100. test("asks for external_directory permission when reading relative path outside project", async () => {
  101. await using tmp = await tmpdir({ git: true })
  102. await Instance.provide({
  103. directory: tmp.path,
  104. fn: async () => {
  105. const read = await ReadTool.init()
  106. const requests: Array<Omit<PermissionNext.Request, "id" | "sessionID" | "tool">> = []
  107. const testCtx = {
  108. ...ctx,
  109. ask: async (req: Omit<PermissionNext.Request, "id" | "sessionID" | "tool">) => {
  110. requests.push(req)
  111. },
  112. }
  113. // This will fail because file doesn't exist, but we can check if permission was asked
  114. await read.execute({ filePath: "../outside.txt" }, testCtx).catch(() => {})
  115. const extDirReq = requests.find((r) => r.permission === "external_directory")
  116. expect(extDirReq).toBeDefined()
  117. },
  118. })
  119. })
  120. test("does not ask for external_directory permission when reading inside project", async () => {
  121. await using tmp = await tmpdir({
  122. git: true,
  123. init: async (dir) => {
  124. await Bun.write(path.join(dir, "internal.txt"), "internal content")
  125. },
  126. })
  127. await Instance.provide({
  128. directory: tmp.path,
  129. fn: async () => {
  130. const read = await ReadTool.init()
  131. const requests: Array<Omit<PermissionNext.Request, "id" | "sessionID" | "tool">> = []
  132. const testCtx = {
  133. ...ctx,
  134. ask: async (req: Omit<PermissionNext.Request, "id" | "sessionID" | "tool">) => {
  135. requests.push(req)
  136. },
  137. }
  138. await read.execute({ filePath: path.join(tmp.path, "internal.txt") }, testCtx)
  139. const extDirReq = requests.find((r) => r.permission === "external_directory")
  140. expect(extDirReq).toBeUndefined()
  141. },
  142. })
  143. })
  144. })
  145. describe("tool.read env file permissions", () => {
  146. const cases: [string, boolean][] = [
  147. [".env", true],
  148. [".env.local", true],
  149. [".env.production", true],
  150. [".env.development.local", true],
  151. [".env.example", false],
  152. [".envrc", false],
  153. ["environment.ts", false],
  154. ]
  155. describe.each(["build", "plan"])("agent=%s", (agentName) => {
  156. test.each(cases)("%s asks=%s", async (filename, shouldAsk) => {
  157. await using tmp = await tmpdir({
  158. init: (dir) => Bun.write(path.join(dir, filename), "content"),
  159. })
  160. await Instance.provide({
  161. directory: tmp.path,
  162. fn: async () => {
  163. const agent = await Agent.get(agentName)
  164. let askedForEnv = false
  165. const ctxWithPermissions = {
  166. ...ctx,
  167. ask: async (req: Omit<PermissionNext.Request, "id" | "sessionID" | "tool">) => {
  168. for (const pattern of req.patterns) {
  169. const rule = PermissionNext.evaluate(req.permission, pattern, agent.permission)
  170. if (rule.action === "ask" && req.permission === "read") {
  171. askedForEnv = true
  172. }
  173. if (rule.action === "deny") {
  174. throw new PermissionNext.DeniedError(agent.permission)
  175. }
  176. }
  177. },
  178. }
  179. const read = await ReadTool.init()
  180. await read.execute({ filePath: path.join(tmp.path, filename) }, ctxWithPermissions)
  181. expect(askedForEnv).toBe(shouldAsk)
  182. },
  183. })
  184. })
  185. })
  186. })
  187. describe("tool.read truncation", () => {
  188. test("truncates large file by bytes and sets truncated metadata", async () => {
  189. await using tmp = await tmpdir({
  190. init: async (dir) => {
  191. const base = await Bun.file(path.join(FIXTURES_DIR, "models-api.json")).text()
  192. const target = 60 * 1024
  193. const content = base.length >= target ? base : base.repeat(Math.ceil(target / base.length))
  194. await Bun.write(path.join(dir, "large.json"), content)
  195. },
  196. })
  197. await Instance.provide({
  198. directory: tmp.path,
  199. fn: async () => {
  200. const read = await ReadTool.init()
  201. const result = await read.execute({ filePath: path.join(tmp.path, "large.json") }, ctx)
  202. expect(result.metadata.truncated).toBe(true)
  203. expect(result.output).toContain("Output truncated at")
  204. expect(result.output).toContain("bytes")
  205. },
  206. })
  207. })
  208. test("truncates by line count when limit is specified", async () => {
  209. await using tmp = await tmpdir({
  210. init: async (dir) => {
  211. const lines = Array.from({ length: 100 }, (_, i) => `line${i}`).join("\n")
  212. await Bun.write(path.join(dir, "many-lines.txt"), lines)
  213. },
  214. })
  215. await Instance.provide({
  216. directory: tmp.path,
  217. fn: async () => {
  218. const read = await ReadTool.init()
  219. const result = await read.execute({ filePath: path.join(tmp.path, "many-lines.txt"), limit: 10 }, ctx)
  220. expect(result.metadata.truncated).toBe(true)
  221. expect(result.output).toContain("File has more lines")
  222. expect(result.output).toContain("line0")
  223. expect(result.output).toContain("line9")
  224. expect(result.output).not.toContain("line10")
  225. },
  226. })
  227. })
  228. test("does not truncate small file", async () => {
  229. await using tmp = await tmpdir({
  230. init: async (dir) => {
  231. await Bun.write(path.join(dir, "small.txt"), "hello world")
  232. },
  233. })
  234. await Instance.provide({
  235. directory: tmp.path,
  236. fn: async () => {
  237. const read = await ReadTool.init()
  238. const result = await read.execute({ filePath: path.join(tmp.path, "small.txt") }, ctx)
  239. expect(result.metadata.truncated).toBe(false)
  240. expect(result.output).toContain("End of file")
  241. },
  242. })
  243. })
  244. test("respects offset parameter", async () => {
  245. await using tmp = await tmpdir({
  246. init: async (dir) => {
  247. const lines = Array.from({ length: 20 }, (_, i) => `line${i + 1}`).join("\n")
  248. await Bun.write(path.join(dir, "offset.txt"), lines)
  249. },
  250. })
  251. await Instance.provide({
  252. directory: tmp.path,
  253. fn: async () => {
  254. const read = await ReadTool.init()
  255. const result = await read.execute({ filePath: path.join(tmp.path, "offset.txt"), offset: 10, limit: 5 }, ctx)
  256. expect(result.output).toContain("line10")
  257. expect(result.output).toContain("line14")
  258. expect(result.output).not.toContain("line0")
  259. expect(result.output).not.toContain("line15")
  260. },
  261. })
  262. })
  263. test("throws when offset is beyond end of file", async () => {
  264. await using tmp = await tmpdir({
  265. init: async (dir) => {
  266. const lines = Array.from({ length: 3 }, (_, i) => `line${i + 1}`).join("\n")
  267. await Bun.write(path.join(dir, "short.txt"), lines)
  268. },
  269. })
  270. await Instance.provide({
  271. directory: tmp.path,
  272. fn: async () => {
  273. const read = await ReadTool.init()
  274. await expect(
  275. read.execute({ filePath: path.join(tmp.path, "short.txt"), offset: 4, limit: 5 }, ctx),
  276. ).rejects.toThrow("Offset 4 is out of range for this file (3 lines)")
  277. },
  278. })
  279. })
  280. test("does not mark final directory page as truncated", async () => {
  281. await using tmp = await tmpdir({
  282. init: async (dir) => {
  283. await Promise.all(
  284. Array.from({ length: 10 }, (_, i) => Bun.write(path.join(dir, "dir", `file-${i + 1}.txt`), `line${i}`)),
  285. )
  286. },
  287. })
  288. await Instance.provide({
  289. directory: tmp.path,
  290. fn: async () => {
  291. const read = await ReadTool.init()
  292. const result = await read.execute({ filePath: path.join(tmp.path, "dir"), offset: 6, limit: 5 }, ctx)
  293. expect(result.metadata.truncated).toBe(false)
  294. expect(result.output).not.toContain("Showing 5 of 10 entries")
  295. },
  296. })
  297. })
  298. test("truncates long lines", async () => {
  299. await using tmp = await tmpdir({
  300. init: async (dir) => {
  301. const longLine = "x".repeat(3000)
  302. await Bun.write(path.join(dir, "long-line.txt"), longLine)
  303. },
  304. })
  305. await Instance.provide({
  306. directory: tmp.path,
  307. fn: async () => {
  308. const read = await ReadTool.init()
  309. const result = await read.execute({ filePath: path.join(tmp.path, "long-line.txt") }, ctx)
  310. expect(result.output).toContain("...")
  311. expect(result.output.length).toBeLessThan(3000)
  312. },
  313. })
  314. })
  315. test("image files set truncated to false", async () => {
  316. await using tmp = await tmpdir({
  317. init: async (dir) => {
  318. // 1x1 red PNG
  319. const png = Buffer.from(
  320. "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==",
  321. "base64",
  322. )
  323. await Bun.write(path.join(dir, "image.png"), png)
  324. },
  325. })
  326. await Instance.provide({
  327. directory: tmp.path,
  328. fn: async () => {
  329. const read = await ReadTool.init()
  330. const result = await read.execute({ filePath: path.join(tmp.path, "image.png") }, ctx)
  331. expect(result.metadata.truncated).toBe(false)
  332. expect(result.attachments).toBeDefined()
  333. expect(result.attachments?.length).toBe(1)
  334. },
  335. })
  336. })
  337. test("large image files are properly attached without error", async () => {
  338. await Instance.provide({
  339. directory: FIXTURES_DIR,
  340. fn: async () => {
  341. const read = await ReadTool.init()
  342. const result = await read.execute({ filePath: path.join(FIXTURES_DIR, "large-image.png") }, ctx)
  343. expect(result.metadata.truncated).toBe(false)
  344. expect(result.attachments).toBeDefined()
  345. expect(result.attachments?.length).toBe(1)
  346. expect(result.attachments?.[0].type).toBe("file")
  347. },
  348. })
  349. })
  350. test(".fbs files (FlatBuffers schema) are read as text, not images", async () => {
  351. await using tmp = await tmpdir({
  352. init: async (dir) => {
  353. // FlatBuffers schema content
  354. const fbsContent = `namespace MyGame;
  355. table Monster {
  356. pos:Vec3;
  357. name:string;
  358. inventory:[ubyte];
  359. }
  360. root_type Monster;`
  361. await Bun.write(path.join(dir, "schema.fbs"), fbsContent)
  362. },
  363. })
  364. await Instance.provide({
  365. directory: tmp.path,
  366. fn: async () => {
  367. const read = await ReadTool.init()
  368. const result = await read.execute({ filePath: path.join(tmp.path, "schema.fbs") }, ctx)
  369. // Should be read as text, not as image
  370. expect(result.attachments).toBeUndefined()
  371. expect(result.output).toContain("namespace MyGame")
  372. expect(result.output).toContain("table Monster")
  373. },
  374. })
  375. })
  376. })
  377. describe("tool.read loaded instructions", () => {
  378. test("loads AGENTS.md from parent directory and includes in metadata", async () => {
  379. await using tmp = await tmpdir({
  380. init: async (dir) => {
  381. await Bun.write(path.join(dir, "subdir", "AGENTS.md"), "# Test Instructions\nDo something special.")
  382. await Bun.write(path.join(dir, "subdir", "nested", "test.txt"), "test content")
  383. },
  384. })
  385. await Instance.provide({
  386. directory: tmp.path,
  387. fn: async () => {
  388. const read = await ReadTool.init()
  389. const result = await read.execute({ filePath: path.join(tmp.path, "subdir", "nested", "test.txt") }, ctx)
  390. expect(result.output).toContain("test content")
  391. expect(result.output).toContain("system-reminder")
  392. expect(result.output).toContain("Test Instructions")
  393. expect(result.metadata.loaded).toBeDefined()
  394. expect(result.metadata.loaded).toContain(path.join(tmp.path, "subdir", "AGENTS.md"))
  395. },
  396. })
  397. })
  398. })