tool-bash.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import fs from "fs/promises"
  2. import { realpathSync } from "node:fs"
  3. import path from "path"
  4. import { describe, expect, test } from "bun:test"
  5. import { Effect, Layer } from "effect"
  6. import { ChildProcess } from "effect/unstable/process"
  7. import { FSUtil } from "@opencode-ai/core/fs-util"
  8. import { Config } from "@opencode-ai/core/config"
  9. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  10. import { LayerNode } from "@opencode-ai/core/effect/layer-node"
  11. import { Location } from "@opencode-ai/core/location"
  12. import { LocationMutation } from "@opencode-ai/core/location-mutation"
  13. import { PermissionV2 } from "@opencode-ai/core/permission"
  14. import { AppProcess } from "@opencode-ai/core/process"
  15. import { AbsolutePath } from "@opencode-ai/core/schema"
  16. import { SessionV2 } from "@opencode-ai/core/session"
  17. import { BashTool } from "@opencode-ai/core/tool/bash"
  18. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  19. import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
  20. import { location } from "./fixture/location"
  21. import { tmpdir } from "./fixture/tmpdir"
  22. import { testEffect } from "./lib/effect"
  23. import { toolIdentity, executeTool, settleTool, toolDefinitions } from "./lib/tool"
  24. const sessionID = SessionV2.ID.make("ses_bash_tool_test")
  25. const assertions: PermissionV2.AssertInput[] = []
  26. const runs: Array<{
  27. readonly command: string
  28. readonly cwd?: string
  29. readonly shell?: string | boolean
  30. readonly options?: AppProcess.RunOptions
  31. }> = []
  32. let denyAction: string | undefined
  33. let result: AppProcess.RunResult = {
  34. command: "mock",
  35. exitCode: 0,
  36. output: Buffer.from("hello\n"),
  37. stdout: Buffer.from("hello\n"),
  38. stderr: Buffer.alloc(0),
  39. outputTruncated: false,
  40. stdoutTruncated: false,
  41. stderrTruncated: false,
  42. }
  43. let runFailure: AppProcess.AppProcessError | undefined
  44. let afterPermission = (_input: PermissionV2.AssertInput): Effect.Effect<void> => Effect.void
  45. const permission = Layer.succeed(
  46. PermissionV2.Service,
  47. PermissionV2.Service.of({
  48. assert: (input) =>
  49. Effect.sync(() => assertions.push(input)).pipe(
  50. Effect.andThen(Effect.suspend(() => afterPermission(input))),
  51. Effect.andThen(
  52. input.action === denyAction ? Effect.fail(new PermissionV2.DeniedError({ rules: [] })) : Effect.void,
  53. ),
  54. ),
  55. ask: () => Effect.die("unused"),
  56. reply: () => Effect.die("unused"),
  57. get: () => Effect.die("unused"),
  58. forSession: () => Effect.die("unused"),
  59. list: () => Effect.die("unused"),
  60. }),
  61. )
  62. const appProcess = Layer.succeed(
  63. AppProcess.Service,
  64. AppProcess.Service.of({
  65. run: (command: ChildProcess.Command, options?: AppProcess.RunOptions) =>
  66. Effect.suspend(() => {
  67. if (command._tag !== "StandardCommand") throw new Error("expected standard command")
  68. runs.push({ command: command.command, cwd: command.options.cwd, shell: command.options.shell, options })
  69. return runFailure ? Effect.fail(runFailure) : Effect.succeed(result)
  70. }),
  71. } as unknown as AppProcess.Interface),
  72. )
  73. const config = Layer.succeed(
  74. Config.Service,
  75. Config.Service.of({
  76. entries: () => Effect.succeed([]),
  77. }),
  78. )
  79. const reset = () => {
  80. assertions.length = 0
  81. runs.length = 0
  82. denyAction = undefined
  83. runFailure = undefined
  84. afterPermission = () => Effect.void
  85. result = {
  86. command: "mock",
  87. exitCode: 0,
  88. output: Buffer.from("hello\n"),
  89. stdout: Buffer.from("hello\n"),
  90. stderr: Buffer.alloc(0),
  91. outputTruncated: false,
  92. stdoutTruncated: false,
  93. stderrTruncated: false,
  94. }
  95. }
  96. const withTool = <A, E, R>(
  97. directory: string,
  98. body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>,
  99. processLayer: Layer.Layer<AppProcess.Service> = appProcess,
  100. ) => {
  101. const activeLocation = Layer.succeed(
  102. Location.Service,
  103. Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
  104. )
  105. return Effect.gen(function* () {
  106. return yield* body(yield* ToolRegistry.Service)
  107. }).pipe(
  108. Effect.provide(
  109. AppNodeBuilder.build(LayerNode.group([ToolRegistry.node, ToolRegistry.toolsNode, LocationMutation.node, BashTool.node]), [
  110. [Location.node, activeLocation],
  111. [PermissionV2.node, permission],
  112. [AppProcess.node, processLayer],
  113. [Config.node, config],
  114. [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
  115. ]),
  116. ),
  117. )
  118. }
  119. const call = (input: typeof BashTool.Input.Type, id = "call-bash") => ({
  120. sessionID,
  121. ...toolIdentity,
  122. call: { type: "tool-call" as const, id, name: "bash", input },
  123. })
  124. const it = testEffect(Layer.empty)
  125. describe("BashTool", () => {
  126. it.live("registers and returns structured successful output from the active Location", () =>
  127. Effect.acquireUseRelease(
  128. Effect.promise(() => tmpdir()),
  129. (tmp) => {
  130. reset()
  131. return withTool(tmp.path, (registry) =>
  132. Effect.gen(function* () {
  133. const definitions = yield* toolDefinitions(registry)
  134. expect(definitions.map((tool) => tool.name)).toEqual(["bash"])
  135. expect(definitions[0]?.inputSchema).not.toHaveProperty("properties.background")
  136. expect(definitions[0]?.inputSchema).not.toHaveProperty("properties.description")
  137. expect(definitions[0]?.outputSchema).not.toHaveProperty("properties.output")
  138. expect(definitions[0]?.outputSchema).not.toHaveProperty("properties.command")
  139. expect(definitions[0]?.outputSchema).not.toHaveProperty("properties.cwd")
  140. expect(yield* toolDefinitions(registry, [{ action: "bash", resource: "*", effect: "deny" }])).toEqual([])
  141. expect(yield* settleTool(registry, call({ command: "pwd" }))).toEqual({
  142. result: {
  143. type: "content",
  144. value: [
  145. { type: "text", text: "hello\n" },
  146. { type: "text", text: "Command exited with code 0." },
  147. ],
  148. },
  149. output: {
  150. structured: {
  151. exit: 0,
  152. truncated: false,
  153. },
  154. content: [
  155. { type: "text", text: "hello\n" },
  156. { type: "text", text: "Command exited with code 0." },
  157. ],
  158. },
  159. })
  160. expect(runs).toMatchObject([{ command: "pwd", cwd: realpathSync(tmp.path) }])
  161. expect(runs[0]?.options).toMatchObject({
  162. combineOutput: true,
  163. maxOutputBytes: BashTool.MAX_CAPTURE_BYTES,
  164. })
  165. expect(assertions).toMatchObject([{ sessionID, action: "bash", resources: ["pwd"], save: ["pwd"] }])
  166. }),
  167. )
  168. },
  169. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  170. ),
  171. )
  172. it.live("resolves a relative workdir from the active Location", () =>
  173. Effect.acquireUseRelease(
  174. Effect.promise(() => tmpdir()),
  175. (tmp) => {
  176. reset()
  177. return Effect.promise(() => fs.mkdir(path.join(tmp.path, "src"))).pipe(
  178. Effect.andThen(
  179. withTool(tmp.path, (registry) => executeTool(registry, call({ command: "pwd", workdir: "src" }))),
  180. ),
  181. Effect.andThen(
  182. Effect.sync(() => expect(runs).toMatchObject([{ cwd: realpathSync(path.join(tmp.path, "src")) }])),
  183. ),
  184. )
  185. },
  186. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  187. ),
  188. )
  189. it.live("rejects a workdir that stops being a directory during approval", () =>
  190. Effect.acquireUseRelease(
  191. Effect.promise(() => tmpdir()),
  192. (tmp) => {
  193. reset()
  194. const workdir = path.join(tmp.path, "src")
  195. afterPermission = (input) =>
  196. input.action === "bash"
  197. ? Effect.promise(async () => {
  198. await fs.rm(workdir, { recursive: true })
  199. await fs.writeFile(workdir, "not a directory")
  200. }).pipe(Effect.orDie)
  201. : Effect.void
  202. return Effect.promise(() => fs.mkdir(workdir)).pipe(
  203. Effect.andThen(
  204. withTool(tmp.path, (registry) => executeTool(registry, call({ command: "pwd", workdir: "src" }))),
  205. ),
  206. Effect.andThen(
  207. Effect.sync(() => {
  208. expect(runs).toEqual([])
  209. expect(assertions.map((input) => input.action)).toEqual(["bash"])
  210. }),
  211. ),
  212. )
  213. },
  214. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  215. ),
  216. )
  217. if (process.platform !== "win32") {
  218. it.live("executes a real shell command through AppProcess", () =>
  219. Effect.acquireUseRelease(
  220. Effect.promise(() => tmpdir()),
  221. (tmp) => {
  222. reset()
  223. return withTool(
  224. tmp.path,
  225. (registry) => settleTool(registry, call({ command: "printf core-bash" })),
  226. LayerNode.compile(AppProcess.node),
  227. ).pipe(
  228. Effect.andThen((settled) =>
  229. Effect.sync(() => {
  230. expect(settled.result).toEqual({
  231. type: "content",
  232. value: [
  233. { type: "text", text: "core-bash" },
  234. { type: "text", text: "Command exited with code 0." },
  235. ],
  236. })
  237. expect(settled.output?.structured).toMatchObject({
  238. exit: 0,
  239. })
  240. expect(settled.output?.structured).not.toHaveProperty("output")
  241. }),
  242. ),
  243. )
  244. },
  245. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  246. ),
  247. )
  248. }
  249. it.live("approves an explicit external workdir before bash execution", () =>
  250. Effect.acquireUseRelease(
  251. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  252. ([active, outside]) => {
  253. reset()
  254. return withTool(active.path, (registry) =>
  255. executeTool(registry, call({ command: "pwd", workdir: outside.path })),
  256. ).pipe(
  257. Effect.andThen(
  258. Effect.sync(() => {
  259. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "bash"])
  260. expect(assertions[0]).toMatchObject({
  261. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  262. })
  263. expect(runs).toHaveLength(1)
  264. }),
  265. ),
  266. )
  267. },
  268. ([active, outside]) =>
  269. Effect.promise(() =>
  270. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  271. ),
  272. ),
  273. )
  274. it.live("does not execute after external-directory or bash denial", () =>
  275. Effect.acquireUseRelease(
  276. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  277. ([active, outside]) =>
  278. Effect.gen(function* () {
  279. reset()
  280. denyAction = "external_directory"
  281. yield* withTool(active.path, (registry) =>
  282. executeTool(registry, call({ command: "pwd", workdir: outside.path })),
  283. )
  284. expect(assertions.map((item) => item.action)).toEqual(["external_directory"])
  285. expect(runs).toEqual([])
  286. reset()
  287. denyAction = "bash"
  288. yield* withTool(active.path, (registry) => executeTool(registry, call({ command: "pwd" })))
  289. expect(assertions.map((item) => item.action)).toEqual(["bash"])
  290. expect(runs).toEqual([])
  291. }),
  292. ([active, outside]) =>
  293. Effect.promise(() =>
  294. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  295. ),
  296. ),
  297. )
  298. it.live("reports external command arguments as advisory warnings without enforcing approval", () =>
  299. Effect.acquireUseRelease(
  300. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  301. ([active, outside]) => {
  302. reset()
  303. denyAction = "external_directory"
  304. const target = path.join(outside.path, "secret.txt")
  305. return withTool(active.path, (registry) => settleTool(registry, call({ command: `cat ${target}` }))).pipe(
  306. Effect.andThen((settled) =>
  307. Effect.sync(() => {
  308. expect(assertions.map((item) => item.action)).toEqual(["bash"])
  309. expect(runs).toHaveLength(1)
  310. expect(settled.output?.structured).toMatchObject({
  311. truncated: false,
  312. })
  313. expect(settled.output?.structured).not.toHaveProperty("warnings")
  314. expect(settled.output?.content[1]).toMatchObject({
  315. type: "text",
  316. text: expect.stringContaining("Warnings:"),
  317. })
  318. }),
  319. ),
  320. )
  321. },
  322. ([active, outside]) =>
  323. Effect.promise(() =>
  324. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  325. ),
  326. ),
  327. )
  328. it.live("keeps non-zero exits useful", () =>
  329. Effect.acquireUseRelease(
  330. Effect.promise(() => tmpdir()),
  331. (tmp) => {
  332. reset()
  333. result = { ...result, exitCode: 7, output: Buffer.from("HEAD full output TAIL") }
  334. return withTool(tmp.path, (registry) => settleTool(registry, call({ command: "false" }, "call-overflow"))).pipe(
  335. Effect.andThen((settled) =>
  336. Effect.sync(() => {
  337. expect(settled.output?.content[1]).toMatchObject({
  338. type: "text",
  339. text: expect.stringContaining("Command exited with code 7"),
  340. })
  341. expect(settled.output?.structured).toMatchObject({
  342. exit: 7,
  343. truncated: false,
  344. })
  345. expect(settled.output?.content[0]).toEqual({ type: "text", text: "HEAD full output TAIL" })
  346. }),
  347. ),
  348. )
  349. },
  350. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  351. ),
  352. )
  353. it.live("surfaces bounded process-capture truncation", () =>
  354. Effect.acquireUseRelease(
  355. Effect.promise(() => tmpdir()),
  356. (tmp) => {
  357. reset()
  358. result = { ...result, outputTruncated: true }
  359. return withTool(tmp.path, (registry) => settleTool(registry, call({ command: "verbose" }))).pipe(
  360. Effect.andThen((settled) =>
  361. Effect.sync(() => {
  362. expect(settled.output?.structured).toMatchObject({ truncated: true })
  363. expect(settled.output?.content[0]).toMatchObject({
  364. type: "text",
  365. text: expect.stringContaining("output capture truncated"),
  366. })
  367. expect(settled.output?.structured).not.toHaveProperty("resource")
  368. }),
  369. ),
  370. )
  371. },
  372. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  373. ),
  374. )
  375. it.live("returns a useful timeout settlement", () =>
  376. Effect.acquireUseRelease(
  377. Effect.promise(() => tmpdir()),
  378. (tmp) => {
  379. reset()
  380. runFailure = new AppProcess.AppProcessError({ command: "sleep", cause: new Error("Timed out") })
  381. return withTool(tmp.path, (registry) => settleTool(registry, call({ command: "sleep 60", timeout: 10 }))).pipe(
  382. Effect.andThen((settled) =>
  383. Effect.sync(() => {
  384. expect(settled.output?.content[1]).toMatchObject({
  385. type: "text",
  386. text: expect.stringContaining("Command timed out"),
  387. })
  388. expect(settled.output?.structured).toMatchObject({
  389. timeout: true,
  390. truncated: false,
  391. })
  392. }),
  393. ),
  394. )
  395. },
  396. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  397. ),
  398. )
  399. })
  400. test("keeps locked deferred parity TODOs visible", async () => {
  401. const source = await fs.readFile(new URL("../src/tool/bash.ts", import.meta.url), "utf8")
  402. for (const todo of [
  403. "Port tree-sitter bash / PowerShell parser-based approval reduction.",
  404. "Port BashArity reusable command-prefix approvals.",
  405. "Replace token-based command-argument external-directory advisories with parser-based detection.",
  406. "Restore PowerShell and cmd-specific invocation/path handling on Windows.",
  407. "Add plugin shell.env environment augmentation once V2 plugin hooks exist.",
  408. "Add durable/live progress metadata streaming for long-running commands once V2 tool invocation progress context is wired.",
  409. "Persist background job status and define restart recovery before exposing remote observation.",
  410. "Revisit process-group cleanup and platform coverage with shell-specific tests if current AppProcess semantics do not fully cover it.",
  411. "Revisit binary output handling if stdout/stderr decoding is text-only.",
  412. "Stream full shell output into managed storage while retaining only a bounded in-memory preview.",
  413. ]) {
  414. expect(source).toContain(`TODO: ${todo}`)
  415. }
  416. })