tool-read.test.ts 24 KB

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