tool-bash.test.ts 16 KB

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