tool-write.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect } from "bun:test"
  4. import { Effect, Layer } from "effect"
  5. import { FileMutation } from "@opencode-ai/core/file-mutation"
  6. import { Formatter } from "@opencode-ai/core/formatter"
  7. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  8. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  9. import { FSUtil } from "@opencode-ai/util/fs-util"
  10. import { Location } from "@opencode-ai/core/location"
  11. import { LocationMutation } from "@opencode-ai/core/location-mutation"
  12. import { Permission } from "@opencode-ai/core/permission"
  13. import { AbsolutePath } from "@opencode-ai/core/schema"
  14. import { Session } from "@opencode-ai/core/session"
  15. import { Tool } from "@opencode-ai/core/tool"
  16. import { WriteTool } from "@opencode-ai/core/tool/plugin/write"
  17. import { location } from "./fixture/location"
  18. import { tmpdir } from "./fixture/tmpdir"
  19. import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
  20. import { testEffect } from "./lib/effect"
  21. import { toolIdentity, executeTool, registerToolPlugin, toolDefinitions } from "./lib/tool"
  22. const writeToolNode = makeLocationNode({
  23. name: "test/write-tool-plugin",
  24. layer: Layer.effectDiscard(registerToolPlugin(WriteTool.Plugin)),
  25. deps: [Tool.node, LocationMutation.node, FileMutation.node, Formatter.node, FSUtil.node, Permission.node],
  26. })
  27. const sessionID = Session.ID.make("ses_write_tool_test")
  28. const assertions: Permission.AssertInput[] = []
  29. const writes: string[] = []
  30. let formatFile = (_target: string): Effect.Effect<boolean> => Effect.succeed(false)
  31. let denyAction: string | undefined
  32. const permission = Layer.succeed(
  33. Permission.Service,
  34. Permission.Service.of({
  35. assert: (input) =>
  36. Effect.sync(() => assertions.push(input)).pipe(
  37. Effect.andThen(
  38. input.action === denyAction
  39. ? Effect.fail(
  40. new Permission.BlockedError({
  41. rules: [],
  42. permission: input.action,
  43. resources: input.resources,
  44. }),
  45. )
  46. : Effect.void,
  47. ),
  48. ),
  49. ask: () => Effect.die("unused"),
  50. reply: () => Effect.die("unused"),
  51. get: () => Effect.die("unused"),
  52. forSession: () => Effect.die("unused"),
  53. list: () => Effect.die("unused"),
  54. }),
  55. )
  56. const formatter = Layer.mock(Formatter.Service, {
  57. file: (target) => formatFile(target),
  58. })
  59. const reset = () => {
  60. assertions.length = 0
  61. writes.length = 0
  62. formatFile = () => Effect.succeed(false)
  63. denyAction = undefined
  64. }
  65. const filesystem = Layer.effect(
  66. FSUtil.Service,
  67. Effect.gen(function* () {
  68. const fs = yield* FSUtil.Service
  69. return FSUtil.Service.of({
  70. ...fs,
  71. writeWithDirs: (target, content, mode) =>
  72. Effect.sync(() => writes.push(target)).pipe(Effect.andThen(fs.writeWithDirs(target, content, mode))),
  73. })
  74. }),
  75. ).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
  76. const withTool = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) => {
  77. const activeLocation = Layer.succeed(
  78. Location.Service,
  79. Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
  80. )
  81. return Effect.gen(function* () {
  82. return yield* body(yield* Tool.Service)
  83. }).pipe(
  84. Effect.provide(
  85. AppNodeBuilder.build(
  86. LayerNode.group([
  87. Tool.node,
  88. Tool.node,
  89. LocationMutation.node,
  90. FileMutation.node,
  91. writeToolNode,
  92. ]),
  93. [
  94. [FSUtil.node, filesystem],
  95. [Location.node, activeLocation],
  96. [Formatter.node, formatter],
  97. [Permission.node, permission],
  98. ],
  99. ),
  100. ),
  101. )
  102. }
  103. const call = (input: typeof WriteTool.Input.Type, id = "call-write") => ({
  104. sessionID,
  105. ...toolIdentity,
  106. call: { type: "tool-call" as const, id, name: "write", input },
  107. })
  108. const it = testEffect(Layer.empty)
  109. describe("WriteTool", () => {
  110. it.live("registers and creates a relative file through FileMutation once", () =>
  111. Effect.acquireUseRelease(
  112. Effect.promise(() => tmpdir()),
  113. (tmp) => {
  114. reset()
  115. return withTool(tmp.path, (registry) =>
  116. Effect.gen(function* () {
  117. expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["write", "execute"])
  118. const settled = yield* executeTool(registry, call({ path: "src/new.txt", content: "created" }))
  119. expect(settled).toEqual({
  120. status: "completed",
  121. output: {
  122. operation: "write",
  123. target: path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt"),
  124. resource: "src/new.txt",
  125. existed: false,
  126. },
  127. content: [{ type: "text", text: "Created file successfully: src/new.txt" }],
  128. })
  129. expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "src", "new.txt"), "utf8"))).toBe(
  130. "created",
  131. )
  132. expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["src/new.txt"], save: ["*"] }])
  133. expect(assertions[0]?.metadata).toMatchObject({
  134. files: [
  135. {
  136. file: "src/new.txt",
  137. status: "added",
  138. additions: 1,
  139. deletions: 0,
  140. patch: expect.stringContaining("+created"),
  141. },
  142. ],
  143. })
  144. expect(writes).toEqual([path.join(yield* Effect.promise(() => fs.realpath(tmp.path)), "src", "new.txt")])
  145. }),
  146. )
  147. },
  148. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  149. ),
  150. )
  151. it.live("formats the committed file", () =>
  152. Effect.acquireUseRelease(
  153. Effect.promise(() => tmpdir()),
  154. (tmp) => {
  155. reset()
  156. const target = path.join(tmp.path, "formatted.txt")
  157. formatFile = (file) =>
  158. Effect.promise(async () => {
  159. await fs.writeFile(file, (await fs.readFile(file, "utf8")).toUpperCase())
  160. return true
  161. })
  162. return withTool(tmp.path, (registry) =>
  163. Effect.gen(function* () {
  164. expect(yield* executeTool(registry, call({ path: "formatted.txt", content: "format me" }))).toMatchObject({
  165. status: "completed",
  166. })
  167. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("FORMAT ME")
  168. }),
  169. )
  170. },
  171. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  172. ),
  173. )
  174. it.live("overwrites a relative existing file and reports that it wrote the file", () =>
  175. Effect.acquireUseRelease(
  176. Effect.promise(() => tmpdir()),
  177. (tmp) => {
  178. reset()
  179. return Effect.promise(() => fs.writeFile(path.join(tmp.path, "existing.txt"), "before")).pipe(
  180. Effect.andThen(
  181. withTool(tmp.path, (registry) => executeTool(registry, call({ path: "existing.txt", content: "after" }))),
  182. ),
  183. Effect.andThen((settled) =>
  184. Effect.gen(function* () {
  185. expect(settled.status).toBe("completed")
  186. if (settled.status !== "completed") return
  187. expect(settled.content).toEqual([{ type: "text", text: "Wrote file successfully: existing.txt" }])
  188. expect(settled.output).toMatchObject({ resource: "existing.txt", existed: true })
  189. expect(assertions[0]?.metadata).toMatchObject({
  190. files: [
  191. {
  192. file: "existing.txt",
  193. status: "modified",
  194. additions: 1,
  195. deletions: 1,
  196. patch: expect.stringMatching(/-before[\s\S]*\+after/),
  197. },
  198. ],
  199. })
  200. expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "existing.txt"), "utf8"))).toBe(
  201. "after",
  202. )
  203. expect(writes).toHaveLength(1)
  204. }),
  205. ),
  206. )
  207. },
  208. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  209. ),
  210. )
  211. it.live("preserves exactly one BOM when overwriting existing files", () =>
  212. Effect.acquireUseRelease(
  213. Effect.promise(() => tmpdir()),
  214. (tmp) => {
  215. reset()
  216. const preserved = path.join(tmp.path, "preserved.txt")
  217. const deduplicated = path.join(tmp.path, "deduplicated.txt")
  218. formatFile = (target) =>
  219. Effect.promise(async () => {
  220. await fs.writeFile(target, `\uFEFF\uFEFF\uFEFF${(await fs.readFile(target, "utf8")).replace(/^\uFEFF+/, "")}`)
  221. return true
  222. })
  223. return Effect.promise(() =>
  224. Promise.all([fs.writeFile(preserved, "\uFEFFbefore"), fs.writeFile(deduplicated, "\uFEFFbefore")]),
  225. ).pipe(
  226. Effect.andThen(
  227. withTool(tmp.path, (registry) =>
  228. Effect.gen(function* () {
  229. yield* executeTool(registry, call({ path: "preserved.txt", content: "after" }, "call-preserved"))
  230. yield* executeTool(
  231. registry,
  232. call({ path: "deduplicated.txt", content: "\uFEFFafter" }, "call-deduplicated"),
  233. )
  234. expect(yield* Effect.promise(() => fs.readFile(preserved, "utf8"))).toBe("\uFEFFafter")
  235. expect(yield* Effect.promise(() => fs.readFile(deduplicated, "utf8"))).toBe("\uFEFFafter")
  236. }),
  237. ),
  238. ),
  239. )
  240. },
  241. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  242. ),
  243. )
  244. it.live("accepts an absolute file path inside the active Location", () =>
  245. Effect.acquireUseRelease(
  246. Effect.promise(() => tmpdir()),
  247. (tmp) => {
  248. reset()
  249. const target = path.join(tmp.path, "absolute.txt")
  250. return withTool(tmp.path, (registry) => executeTool(registry, call({ path: target, content: "inside" }))).pipe(
  251. Effect.andThen((result) =>
  252. Effect.gen(function* () {
  253. expect(result).toMatchObject({
  254. status: "completed",
  255. content: [{ type: "text", text: "Created file successfully: absolute.txt" }],
  256. })
  257. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  258. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("inside")
  259. }),
  260. ),
  261. )
  262. },
  263. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  264. ),
  265. )
  266. it.live("writes an external symlink target with only its in-location permission", () =>
  267. Effect.acquireUseRelease(
  268. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  269. ([active, outside]) => {
  270. reset()
  271. if (process.platform === "win32") return Effect.void
  272. const target = path.join(outside.path, "external.txt")
  273. const link = path.join(active.path, "link.txt")
  274. return Effect.promise(async () => {
  275. await fs.writeFile(target, "before")
  276. await fs.symlink(target, link)
  277. }).pipe(
  278. Effect.andThen(
  279. withTool(active.path, (registry) => executeTool(registry, call({ path: "link.txt", content: "after" }))),
  280. ),
  281. Effect.andThen((result) =>
  282. Effect.sync(() => {
  283. expect(result.status).toBe("completed")
  284. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  285. expect(assertions[0]?.resources).toEqual(["link.txt"])
  286. }),
  287. ),
  288. Effect.andThen(Effect.promise(() => fs.readFile(target, "utf8"))),
  289. Effect.tap((content) => Effect.sync(() => expect(content).toBe("after"))),
  290. )
  291. },
  292. ([active, outside]) =>
  293. Effect.promise(() =>
  294. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  295. ),
  296. ),
  297. )
  298. it.live("approves an explicit external absolute path before edit", () =>
  299. Effect.acquireUseRelease(
  300. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  301. ([active, outside]) => {
  302. reset()
  303. const target = path.join(outside.path, "external.txt")
  304. return withTool(active.path, (registry) =>
  305. executeTool(registry, call({ path: target, content: "external" })),
  306. ).pipe(
  307. Effect.andThen((settled) =>
  308. Effect.gen(function* () {
  309. const canonicalTarget = path.join(yield* Effect.promise(() => fs.realpath(outside.path)), "external.txt")
  310. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  311. expect(assertions[0]).toMatchObject({
  312. resources: [
  313. path.join(yield* Effect.promise(() => fs.realpath(outside.path)), "*").replaceAll("\\", "/"),
  314. ],
  315. })
  316. expect(assertions[1]).toMatchObject({ resources: [canonicalTarget.replaceAll("\\", "/")], save: ["*"] })
  317. expect(settled).toMatchObject({
  318. status: "completed",
  319. output: {
  320. target: canonicalTarget,
  321. resource: canonicalTarget.replaceAll("\\", "/"),
  322. existed: false,
  323. },
  324. })
  325. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("external")
  326. expect(writes).toEqual([canonicalTarget])
  327. }),
  328. ),
  329. )
  330. },
  331. ([active, outside]) =>
  332. Effect.promise(() =>
  333. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  334. ),
  335. ),
  336. )
  337. it.live("saves external directory approval at the nearest project directory", () =>
  338. Effect.acquireUseRelease(
  339. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  340. ([active, outside]) => {
  341. reset()
  342. const repo = path.join(outside.path, "repo")
  343. const nested = path.join(repo, "packages", "app")
  344. const target = path.join(nested, "external.txt")
  345. return Effect.promise(() =>
  346. Promise.all([fs.mkdir(path.join(repo, ".git"), { recursive: true }), fs.mkdir(nested, { recursive: true })]),
  347. ).pipe(
  348. Effect.andThen(
  349. withTool(active.path, (registry) => executeTool(registry, call({ path: target, content: "external" }))),
  350. ),
  351. Effect.andThen(
  352. Effect.gen(function* () {
  353. const canonicalRepo = yield* Effect.promise(() => fs.realpath(repo))
  354. const canonicalNested = yield* Effect.promise(() => fs.realpath(nested))
  355. expect(assertions[0]).toMatchObject({
  356. action: "external_directory",
  357. resources: [path.join(canonicalNested, "*").replaceAll("\\", "/")],
  358. save: [path.join(canonicalRepo, "*").replaceAll("\\", "/")],
  359. })
  360. }),
  361. ),
  362. )
  363. },
  364. ([active, outside]) =>
  365. Effect.promise(() =>
  366. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  367. ),
  368. ),
  369. )
  370. it.live("does not write when external_directory or edit approval is denied", () =>
  371. Effect.acquireUseRelease(
  372. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  373. ([active, outside]) =>
  374. Effect.gen(function* () {
  375. const external = path.join(outside.path, "denied.txt")
  376. reset()
  377. denyAction = "external_directory"
  378. expect(
  379. yield* withTool(active.path, (registry) =>
  380. executeTool(registry, call({ path: external, content: "blocked" })),
  381. ),
  382. ).toEqual({
  383. status: "error",
  384. error: { type: "permission.rejected", message: "Permission denied: external_directory" },
  385. })
  386. expect(assertions.map((input) => input.action)).toEqual(["external_directory"])
  387. expect(writes).toEqual([])
  388. reset()
  389. denyAction = "edit"
  390. expect(
  391. yield* withTool(active.path, (registry) =>
  392. executeTool(registry, call({ path: "denied.txt", content: "blocked" })),
  393. ),
  394. ).toEqual({
  395. status: "error",
  396. error: { type: "permission.rejected", message: "Permission denied: edit" },
  397. })
  398. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  399. expect(writes).toEqual([])
  400. }),
  401. ([active, outside]) =>
  402. Effect.promise(() =>
  403. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  404. ),
  405. ),
  406. )
  407. })