tool-read.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import { beforeEach, describe, expect } from "bun:test"
  2. import { Effect, Exit, Layer, PlatformError } from "effect"
  3. import { Config } from "@opencode-ai/core/config"
  4. import { ConfigAttachments } from "@opencode-ai/core/config/attachments"
  5. import { FileSystem } from "@opencode-ai/core/filesystem"
  6. import { FSUtil } from "@opencode-ai/core/fs-util"
  7. import { Location } from "@opencode-ai/core/location"
  8. import { Image } from "@opencode-ai/core/image"
  9. import { PermissionV2 } from "@opencode-ai/core/permission"
  10. import { SessionV2 } from "@opencode-ai/core/session"
  11. import { AbsolutePath } from "@opencode-ai/core/schema"
  12. import { Global } from "@opencode-ai/core/global"
  13. import { location } from "./fixture/location"
  14. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  15. import { ReadTool } from "@opencode-ai/core/tool/read"
  16. import { ReadToolFileSystem } from "@opencode-ai/core/tool/read-filesystem"
  17. import { testEffect } from "./lib/effect"
  18. import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool"
  19. const assertions: PermissionV2.AssertInput[] = []
  20. const missingPath = "__missing_read_target__.txt"
  21. const missingAbsolutePath = `${process.cwd()}/${missingPath}`
  22. const readCalls: {
  23. input: AbsolutePath
  24. page: ReadToolFileSystem.PageInput
  25. }[] = []
  26. const listCalls: ReadToolFileSystem.PageInput[] = []
  27. let resolvedType: "file" | "directory" = "file"
  28. let resolveFailure: unknown
  29. let readResult: FileSystem.Content | ReadToolFileSystem.TextPage = {
  30. uri: "file:///README.md",
  31. name: "README.md",
  32. content: "hello",
  33. encoding: "utf8",
  34. mime: "text/plain",
  35. }
  36. let readFailure: unknown
  37. let configEntries: Config.Entry[] = []
  38. const reader = Layer.succeed(
  39. ReadToolFileSystem.Service,
  40. ReadToolFileSystem.Service.of({
  41. inspect: () => (resolveFailure === undefined ? Effect.succeed(resolvedType) : Effect.die(resolveFailure)),
  42. read: (input, _resource, page = {}) => {
  43. readCalls.push({ input, page })
  44. if (readFailure !== undefined) return Effect.die(readFailure)
  45. return Effect.succeed(readResult)
  46. },
  47. list: (_path, input = {}) =>
  48. Effect.sync(() => {
  49. listCalls.push(input)
  50. return new ReadToolFileSystem.ListPage({ entries: [], truncated: false })
  51. }),
  52. }),
  53. )
  54. let allow = true
  55. const permission = Layer.succeed(
  56. PermissionV2.Service,
  57. PermissionV2.Service.of({
  58. assert: (input) =>
  59. Effect.sync(() => {
  60. assertions.push(input)
  61. }).pipe(Effect.andThen(allow ? Effect.void : Effect.fail(new PermissionV2.DeniedError({ rules: [] })))),
  62. ask: () => Effect.die("unused"),
  63. reply: () => Effect.die("unused"),
  64. get: () => Effect.die("unused"),
  65. forSession: () => Effect.die("unused"),
  66. list: () => Effect.die("unused"),
  67. }),
  68. )
  69. const registry = ToolRegistry.defaultLayer.pipe(Layer.provide(permission))
  70. const config = Layer.succeed(Config.Service, Config.Service.of({ entries: () => Effect.succeed(configEntries) }))
  71. const image = Image.layer.pipe(Layer.provide(config))
  72. const testFileSystem = Layer.effect(
  73. FSUtil.Service,
  74. FSUtil.Service.use((fs) =>
  75. Effect.succeed(
  76. FSUtil.Service.of({
  77. ...fs,
  78. realPath: (path) =>
  79. path === missingAbsolutePath
  80. ? Effect.fail(
  81. PlatformError.systemError({
  82. _tag: "NotFound",
  83. module: "FileSystem",
  84. method: "realPath",
  85. pathOrDescriptor: path,
  86. }),
  87. )
  88. : Effect.succeed(path),
  89. }),
  90. ),
  91. ),
  92. ).pipe(Layer.provide(FSUtil.defaultLayer))
  93. const infrastructure = Layer.mergeAll(
  94. testFileSystem,
  95. Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make(process.cwd()) }))),
  96. Global.layerWith({ data: Global.Path.data }),
  97. )
  98. const unavailableImage = Layer.succeed(
  99. Image.Service,
  100. Image.Service.of({ normalize: () => Effect.fail(new Image.ResizerUnavailableError()) }),
  101. )
  102. const read = ReadTool.layer.pipe(
  103. Layer.provide(registry),
  104. Layer.provide(reader),
  105. Layer.provide(permission),
  106. Layer.provide(config),
  107. Layer.provide(image),
  108. Layer.provide(infrastructure),
  109. )
  110. const it = testEffect(Layer.mergeAll(registry, reader, permission, config, image, infrastructure, read))
  111. const unavailableRead = ReadTool.layer.pipe(
  112. Layer.provide(registry),
  113. Layer.provide(reader),
  114. Layer.provide(permission),
  115. Layer.provide(config),
  116. Layer.provide(unavailableImage),
  117. Layer.provide(infrastructure),
  118. )
  119. const itWithoutResizer = testEffect(
  120. Layer.mergeAll(registry, reader, permission, config, unavailableImage, infrastructure, unavailableRead),
  121. )
  122. const sessionID = SessionV2.ID.make("ses_read_tool_test")
  123. describe("ReadTool", () => {
  124. beforeEach(() => {
  125. assertions.length = 0
  126. readCalls.length = 0
  127. listCalls.length = 0
  128. allow = true
  129. resolvedType = "file"
  130. resolveFailure = undefined
  131. readResult = {
  132. uri: "file:///README.md",
  133. name: "README.md",
  134. content: "hello",
  135. encoding: "utf8",
  136. mime: "text/plain",
  137. }
  138. readFailure = undefined
  139. configEntries = []
  140. })
  141. it.effect("registers, authorizes, and reads through the location filesystem", () =>
  142. Effect.gen(function* () {
  143. const registry = yield* ToolRegistry.Service
  144. expect(yield* toolDefinitions(registry)).toMatchObject([{ name: "read" }])
  145. expect(yield* toolDefinitions(registry, [{ action: "read", resource: "*", effect: "deny" }])).toEqual([])
  146. expect(
  147. yield* executeTool(registry, {
  148. sessionID,
  149. ...toolIdentity,
  150. call: { type: "tool-call", id: "call-read", name: "read", input: { path: "README.md" } },
  151. }),
  152. ).toEqual({
  153. type: "json",
  154. value: {
  155. uri: "file:///README.md",
  156. name: "README.md",
  157. content: "hello",
  158. encoding: "utf8",
  159. mime: "text/plain",
  160. },
  161. })
  162. expect(assertions).toMatchObject([{ sessionID, action: "read", resources: ["README.md"], save: ["*"] }])
  163. expect(readCalls).toEqual([{ input: AbsolutePath.make(`${process.cwd()}/README.md`), page: {} }])
  164. }),
  165. )
  166. it.effect("returns a small PNG as native media instead of durable base64 text", () =>
  167. Effect.gen(function* () {
  168. const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
  169. readResult = {
  170. uri: "file:///pixel.png",
  171. name: "pixel.png",
  172. content: png,
  173. encoding: "base64",
  174. mime: "image/png",
  175. }
  176. const registry = yield* ToolRegistry.Service
  177. expect(
  178. yield* executeTool(registry, {
  179. sessionID,
  180. ...toolIdentity,
  181. call: { type: "tool-call", id: "call-image", name: "read", input: { path: "pixel.png" } },
  182. }),
  183. ).toEqual({
  184. type: "content",
  185. value: [
  186. { type: "text", text: "Image read successfully" },
  187. { type: "file", uri: `data:image/png;base64,${png}`, mime: "image/png", name: "pixel.png" },
  188. ],
  189. })
  190. expect(readCalls).toEqual([{ input: AbsolutePath.make(`${process.cwd()}/pixel.png`), page: {} }])
  191. const settled = yield* settleTool(registry, {
  192. sessionID,
  193. ...toolIdentity,
  194. call: { type: "tool-call", id: "call-image-settle", name: "read", input: { path: "pixel.png" } },
  195. })
  196. expect(settled.output?.structured).toMatchObject({
  197. uri: "file:///pixel.png",
  198. name: "pixel.png",
  199. mime: "image/png",
  200. encoding: "base64",
  201. })
  202. expect(settled.output?.content).toMatchObject([
  203. { type: "text", text: "Image read successfully" },
  204. { type: "file", mime: "image/png", uri: `data:image/png;base64,${png}` },
  205. ])
  206. }),
  207. )
  208. it.effect("preserves a PNG above the generic text limit as native media", () =>
  209. Effect.gen(function* () {
  210. const photon = yield* Effect.promise(() => import("@silvia-odwyer/photon-node"))
  211. const pixels = Uint8Array.from({ length: 256 * 256 * 4 }, (_, index) => (index * 73 + (index >> 3)) % 256)
  212. const source = new photon.PhotonImage(pixels, 256, 256)
  213. const png = Buffer.from(source.get_bytes()).toString("base64")
  214. source.free()
  215. expect(Buffer.byteLength(png)).toBeGreaterThan(50 * 1024)
  216. readResult = {
  217. uri: "file:///large.png",
  218. name: "large.png",
  219. content: png,
  220. encoding: "base64",
  221. mime: "image/png",
  222. }
  223. const registry = yield* ToolRegistry.Service
  224. const settled = yield* settleTool(registry, {
  225. sessionID,
  226. ...toolIdentity,
  227. call: { type: "tool-call", id: "call-large-image", name: "read", input: { path: "large.png" } },
  228. })
  229. expect(settled.outputPaths).toBeUndefined()
  230. expect(settled.output?.structured).toMatchObject({
  231. uri: "file:///large.png",
  232. name: "large.png",
  233. mime: "image/png",
  234. encoding: "base64",
  235. })
  236. expect(settled.result).toEqual({
  237. type: "content",
  238. value: [
  239. { type: "text", text: "Image read successfully" },
  240. { type: "file", uri: `data:image/png;base64,${png}`, mime: "image/png", name: "large.png" },
  241. ],
  242. })
  243. }),
  244. )
  245. itWithoutResizer.effect("returns the original image when the resizer is unavailable", () =>
  246. Effect.gen(function* () {
  247. const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
  248. readResult = {
  249. uri: "file:///pixel.png",
  250. name: "pixel.png",
  251. content: png,
  252. encoding: "base64",
  253. mime: "image/png",
  254. }
  255. const registry = yield* ToolRegistry.Service
  256. expect(
  257. yield* executeTool(registry, {
  258. sessionID,
  259. ...toolIdentity,
  260. call: { type: "tool-call", id: "call-image-fallback", name: "read", input: { path: "pixel.png" } },
  261. }),
  262. ).toMatchObject({
  263. type: "content",
  264. value: [{ type: "text" }, { type: "file", uri: `data:image/png;base64,${png}`, mime: "image/png" }],
  265. })
  266. }),
  267. )
  268. it.effect("rejects invalid image data returned by the filesystem", () =>
  269. Effect.gen(function* () {
  270. readResult = {
  271. uri: "file:///truncated.png",
  272. name: "truncated.png",
  273. content: "iVBORw0KGgo=",
  274. encoding: "base64",
  275. mime: "image/png",
  276. }
  277. const registry = yield* ToolRegistry.Service
  278. expect(
  279. yield* executeTool(registry, {
  280. sessionID,
  281. ...toolIdentity,
  282. call: { type: "tool-call", id: "call-truncated-image", name: "read", input: { path: "truncated.png" } },
  283. }),
  284. ).toEqual({ type: "error", value: "Image could not be decoded: truncated.png" })
  285. }),
  286. )
  287. it.effect("rejects oversized images when resizing is disabled", () =>
  288. Effect.gen(function* () {
  289. const photon = yield* Effect.promise(() => import("@silvia-odwyer/photon-node"))
  290. const source = new photon.PhotonImage(new Uint8Array(Array.from({ length: 16 * 4 }, () => 255)), 16, 1)
  291. const base64 = Buffer.from(source.get_bytes()).toString("base64")
  292. source.free()
  293. readResult = {
  294. uri: "file:///wide.png",
  295. name: "wide.png",
  296. content: base64,
  297. encoding: "base64",
  298. mime: "image/png",
  299. }
  300. configEntries = [
  301. new Config.Document({
  302. type: "document",
  303. info: new Config.Info({
  304. attachments: new ConfigAttachments.Info({
  305. image: new ConfigAttachments.Image({ auto_resize: false, max_width: 4 }),
  306. }),
  307. }),
  308. }),
  309. ]
  310. const registry = yield* ToolRegistry.Service
  311. const result = yield* executeTool(registry, {
  312. sessionID,
  313. ...toolIdentity,
  314. call: { type: "tool-call", id: "call-wide-image", name: "read", input: { path: "wide.png" } },
  315. })
  316. expect(result.type).toBe("error")
  317. if (result.type === "error") expect(result.value).toContain("exceeding configured limits 4x2000")
  318. }),
  319. )
  320. it.effect("resizes images to configured dimensions before returning media", () =>
  321. Effect.gen(function* () {
  322. const photon = yield* Effect.promise(() => import("@silvia-odwyer/photon-node"))
  323. const source = new photon.PhotonImage(new Uint8Array(Array.from({ length: 16 * 4 }, () => 255)), 16, 1)
  324. const base64 = Buffer.from(source.get_bytes()).toString("base64")
  325. source.free()
  326. readResult = {
  327. uri: "file:///wide.png",
  328. name: "wide.png",
  329. content: base64,
  330. encoding: "base64",
  331. mime: "image/png",
  332. }
  333. configEntries = [
  334. new Config.Document({
  335. type: "document",
  336. info: new Config.Info({
  337. attachments: new ConfigAttachments.Info({ image: new ConfigAttachments.Image({ max_width: 4 }) }),
  338. }),
  339. }),
  340. ]
  341. const registry = yield* ToolRegistry.Service
  342. const result = yield* executeTool(registry, {
  343. sessionID,
  344. ...toolIdentity,
  345. call: { type: "tool-call", id: "call-resize-image", name: "read", input: { path: "wide.png" } },
  346. })
  347. expect(result.type).toBe("content")
  348. if (result.type !== "content") return
  349. const media = result.value[1]
  350. expect(media?.type).toBe("file")
  351. if (media?.type !== "file") return
  352. const resized = photon.PhotonImage.new_from_byteslice(Buffer.from(media.uri.split(",")[1] ?? "", "base64"))
  353. expect(resized.get_width()).toBeLessThanOrEqual(4)
  354. expect(resized.get_height()).toBeLessThanOrEqual(2_000)
  355. resized.free()
  356. }),
  357. )
  358. it.effect("enforces max base64 bytes after resize attempts", () =>
  359. Effect.gen(function* () {
  360. const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
  361. readResult = {
  362. uri: "file:///pixel.png",
  363. name: "pixel.png",
  364. content: png,
  365. encoding: "base64",
  366. mime: "image/png",
  367. }
  368. configEntries = [
  369. new Config.Document({
  370. type: "document",
  371. info: new Config.Info({
  372. attachments: new ConfigAttachments.Info({
  373. image: new ConfigAttachments.Image({ max_base64_bytes: 1 }),
  374. }),
  375. }),
  376. }),
  377. ]
  378. const registry = yield* ToolRegistry.Service
  379. const result = yield* executeTool(registry, {
  380. sessionID,
  381. ...toolIdentity,
  382. call: { type: "tool-call", id: "call-max-bytes", name: "read", input: { path: "pixel.png" } },
  383. })
  384. expect(result.type).toBe("error")
  385. if (result.type === "error") expect(result.value).toContain("/1 bytes")
  386. }),
  387. )
  388. it.effect("returns supported image contents despite a misleading binary extension", () =>
  389. Effect.gen(function* () {
  390. const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
  391. readResult = {
  392. uri: "file:///pixel.bin",
  393. name: "pixel.bin",
  394. content: png,
  395. encoding: "base64",
  396. mime: "image/png",
  397. }
  398. const registry = yield* ToolRegistry.Service
  399. expect(
  400. yield* executeTool(registry, {
  401. sessionID,
  402. ...toolIdentity,
  403. call: { type: "tool-call", id: "call-disguised-image", name: "read", input: { path: "pixel.bin" } },
  404. }),
  405. ).toMatchObject({
  406. type: "content",
  407. value: [{ type: "text" }, { type: "file", mime: "image/png", name: "pixel.bin" }],
  408. })
  409. }),
  410. )
  411. it.effect("preserves unexpected filesystem defects", () =>
  412. Effect.gen(function* () {
  413. readFailure = new ReadToolFileSystem.BinaryFileError("archive.dat")
  414. const registry = yield* ToolRegistry.Service
  415. expect(
  416. Exit.isFailure(
  417. yield* executeTool(registry, {
  418. sessionID,
  419. ...toolIdentity,
  420. call: {
  421. type: "tool-call",
  422. id: "call-binary",
  423. name: "read",
  424. input: { path: "archive.dat", offset: 2, limit: 1 },
  425. },
  426. }).pipe(Effect.exit),
  427. ),
  428. ).toBe(true)
  429. expect(readCalls).toEqual([
  430. { input: AbsolutePath.make(`${process.cwd()}/archive.dat`), page: { offset: 2, limit: 1 } },
  431. ])
  432. }),
  433. )
  434. it.effect("does not read when permission is denied", () =>
  435. Effect.gen(function* () {
  436. allow = false
  437. const registry = yield* ToolRegistry.Service
  438. expect(
  439. yield* executeTool(registry, {
  440. sessionID,
  441. ...toolIdentity,
  442. call: { type: "tool-call", id: "call-read", name: "read", input: { path: "README.md" } },
  443. }),
  444. ).toEqual({ type: "error", value: "Unable to read README.md" })
  445. expect(readCalls).toEqual([])
  446. }),
  447. )
  448. it.effect("returns missing paths as model-visible tool failures", () =>
  449. Effect.gen(function* () {
  450. const registry = yield* ToolRegistry.Service
  451. expect(
  452. yield* executeTool(registry, {
  453. sessionID,
  454. ...toolIdentity,
  455. call: { type: "tool-call", id: "call-missing-path", name: "read", input: { path: missingPath } },
  456. }),
  457. ).toEqual({ type: "error", value: `Unable to read ${missingPath}` })
  458. expect(assertions).toEqual([])
  459. expect(readCalls).toEqual([])
  460. }),
  461. )
  462. it.effect("lists a bounded directory page through read", () =>
  463. Effect.gen(function* () {
  464. resolvedType = "directory"
  465. const registry = yield* ToolRegistry.Service
  466. expect(
  467. yield* executeTool(registry, {
  468. sessionID,
  469. ...toolIdentity,
  470. call: {
  471. type: "tool-call",
  472. id: "call-read-directory",
  473. name: "read",
  474. input: { path: "src", offset: 2, limit: 10 },
  475. },
  476. }),
  477. ).toEqual({ type: "json", value: { entries: [], truncated: false } })
  478. expect(assertions).toMatchObject([{ sessionID, action: "read", resources: ["src"], save: ["*"] }])
  479. expect(listCalls).toEqual([{ offset: 2, limit: 10 }])
  480. }),
  481. )
  482. it.effect("does not list a directory when permission is denied", () =>
  483. Effect.gen(function* () {
  484. allow = false
  485. resolvedType = "directory"
  486. const registry = yield* ToolRegistry.Service
  487. expect(
  488. yield* executeTool(registry, {
  489. sessionID,
  490. ...toolIdentity,
  491. call: { type: "tool-call", id: "call-read-directory-denied", name: "read", input: { path: "src" } },
  492. }),
  493. ).toEqual({ type: "error", value: "Unable to read src" })
  494. expect(listCalls).toEqual([])
  495. }),
  496. )
  497. it.effect("preserves unexpected resolution defects", () =>
  498. Effect.gen(function* () {
  499. const registry = yield* ToolRegistry.Service
  500. resolveFailure = new Error("missing")
  501. expect(
  502. Exit.isFailure(
  503. yield* executeTool(registry, {
  504. sessionID,
  505. ...toolIdentity,
  506. call: { type: "tool-call", id: "call-missing", name: "read", input: { path: "missing.txt" } },
  507. }).pipe(Effect.exit),
  508. ),
  509. ).toBe(true)
  510. expect(readCalls).toEqual([])
  511. }),
  512. )
  513. it.effect("forwards pagination and returns bounded text pages with continuation", () =>
  514. Effect.gen(function* () {
  515. readResult = new ReadToolFileSystem.TextPage({
  516. type: "text-page",
  517. content: "hello",
  518. mime: "text/plain",
  519. offset: 2,
  520. truncated: true,
  521. next: 3,
  522. })
  523. const registry = yield* ToolRegistry.Service
  524. expect(
  525. yield* executeTool(registry, {
  526. sessionID,
  527. ...toolIdentity,
  528. call: {
  529. type: "tool-call",
  530. id: "call-large",
  531. name: "read",
  532. input: { path: "large.txt", offset: 2, limit: 1 },
  533. },
  534. }),
  535. ).toEqual({
  536. type: "json",
  537. value: { type: "text-page", content: "hello", mime: "text/plain", offset: 2, truncated: true, next: 3 },
  538. })
  539. expect(readCalls).toEqual([
  540. { input: AbsolutePath.make(`${process.cwd()}/large.txt`), page: { offset: 2, limit: 1 } },
  541. ])
  542. }),
  543. )
  544. it.effect("rejects unsupported binary discovered by a direct read", () =>
  545. Effect.gen(function* () {
  546. readResult = {
  547. uri: "file:///late-binary",
  548. name: "late-binary",
  549. content: "AAECAw==",
  550. encoding: "base64",
  551. mime: "application/octet-stream",
  552. }
  553. const registry = yield* ToolRegistry.Service
  554. expect(
  555. yield* executeTool(registry, {
  556. sessionID,
  557. ...toolIdentity,
  558. call: { type: "tool-call", id: "call-direct-binary", name: "read", input: { path: "late-binary" } },
  559. }),
  560. ).toEqual({ type: "error", value: "Cannot read binary file: late-binary" })
  561. }),
  562. )
  563. })