tool-bash.test.ts 17 KB

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