tool-bash.test.ts 16 KB

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