bash.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import z from "zod"
  2. import { spawn } from "child_process"
  3. import { Tool } from "./tool"
  4. import path from "path"
  5. import DESCRIPTION from "./bash.txt"
  6. import { Log } from "../util/log"
  7. import { Instance } from "../project/instance"
  8. import { lazy } from "@/util/lazy"
  9. import { Language } from "web-tree-sitter"
  10. import { $ } from "bun"
  11. import { Filesystem } from "@/util/filesystem"
  12. import { fileURLToPath } from "url"
  13. import { Flag } from "@/flag/flag.ts"
  14. import { Shell } from "@/shell/shell"
  15. import { BashArity } from "@/permission/arity"
  16. import { Truncate } from "./truncation"
  17. const MAX_METADATA_LENGTH = 30_000
  18. const DEFAULT_TIMEOUT = Flag.OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS || 2 * 60 * 1000
  19. export const log = Log.create({ service: "bash-tool" })
  20. const resolveWasm = (asset: string) => {
  21. if (asset.startsWith("file://")) return fileURLToPath(asset)
  22. if (asset.startsWith("/") || /^[a-z]:/i.test(asset)) return asset
  23. const url = new URL(asset, import.meta.url)
  24. return fileURLToPath(url)
  25. }
  26. const parser = lazy(async () => {
  27. const { Parser } = await import("web-tree-sitter")
  28. const { default: treeWasm } = await import("web-tree-sitter/tree-sitter.wasm" as string, {
  29. with: { type: "wasm" },
  30. })
  31. const treePath = resolveWasm(treeWasm)
  32. await Parser.init({
  33. locateFile() {
  34. return treePath
  35. },
  36. })
  37. const { default: bashWasm } = await import("tree-sitter-bash/tree-sitter-bash.wasm" as string, {
  38. with: { type: "wasm" },
  39. })
  40. const bashPath = resolveWasm(bashWasm)
  41. const bashLanguage = await Language.load(bashPath)
  42. const p = new Parser()
  43. p.setLanguage(bashLanguage)
  44. return p
  45. })
  46. // TODO: we may wanna rename this tool so it works better on other shells
  47. export const BashTool = Tool.define("bash", async () => {
  48. const shell = Shell.acceptable()
  49. log.info("bash tool using shell", { shell })
  50. return {
  51. description: DESCRIPTION.replaceAll("${directory}", Instance.directory)
  52. .replaceAll("${maxLines}", String(Truncate.MAX_LINES))
  53. .replaceAll("${maxBytes}", String(Truncate.MAX_BYTES)),
  54. parameters: z.object({
  55. command: z.string().describe("The command to execute"),
  56. timeout: z.number().describe("Optional timeout in milliseconds").optional(),
  57. workdir: z
  58. .string()
  59. .describe(
  60. `The working directory to run the command in. Defaults to ${Instance.directory}. Use this instead of 'cd' commands.`,
  61. )
  62. .optional(),
  63. description: z
  64. .string()
  65. .describe(
  66. "Clear, concise description of what this command does in 5-10 words. Examples:\nInput: ls\nOutput: Lists files in current directory\n\nInput: git status\nOutput: Shows working tree status\n\nInput: npm install\nOutput: Installs package dependencies\n\nInput: mkdir foo\nOutput: Creates directory 'foo'",
  67. ),
  68. }),
  69. async execute(params, ctx) {
  70. const cwd = params.workdir || Instance.directory
  71. if (params.timeout !== undefined && params.timeout < 0) {
  72. throw new Error(`Invalid timeout value: ${params.timeout}. Timeout must be a positive number.`)
  73. }
  74. const timeout = params.timeout ?? DEFAULT_TIMEOUT
  75. const tree = await parser().then((p) => p.parse(params.command))
  76. if (!tree) {
  77. throw new Error("Failed to parse command")
  78. }
  79. const directories = new Set<string>()
  80. if (!Instance.containsPath(cwd)) directories.add(cwd)
  81. const patterns = new Set<string>()
  82. const always = new Set<string>()
  83. for (const node of tree.rootNode.descendantsOfType("command")) {
  84. if (!node) continue
  85. const command = []
  86. for (let i = 0; i < node.childCount; i++) {
  87. const child = node.child(i)
  88. if (!child) continue
  89. if (
  90. child.type !== "command_name" &&
  91. child.type !== "word" &&
  92. child.type !== "string" &&
  93. child.type !== "raw_string" &&
  94. child.type !== "concatenation"
  95. ) {
  96. continue
  97. }
  98. command.push(child.text)
  99. }
  100. // not an exhaustive list, but covers most common cases
  101. if (["cd", "rm", "cp", "mv", "mkdir", "touch", "chmod", "chown", "cat"].includes(command[0])) {
  102. for (const arg of command.slice(1)) {
  103. if (arg.startsWith("-") || (command[0] === "chmod" && arg.startsWith("+"))) continue
  104. const resolved = await $`realpath ${arg}`
  105. .cwd(cwd)
  106. .quiet()
  107. .nothrow()
  108. .text()
  109. .then((x) => x.trim())
  110. log.info("resolved path", { arg, resolved })
  111. if (resolved) {
  112. // Git Bash on Windows returns Unix-style paths like /c/Users/...
  113. const normalized =
  114. process.platform === "win32" && resolved.match(/^\/[a-z]\//)
  115. ? resolved.replace(/^\/([a-z])\//, (_, drive) => `${drive.toUpperCase()}:\\`).replace(/\//g, "\\")
  116. : resolved
  117. if (!Instance.containsPath(normalized)) directories.add(normalized)
  118. }
  119. }
  120. }
  121. // cd covered by above check
  122. if (command.length && command[0] !== "cd") {
  123. patterns.add(command.join(" "))
  124. always.add(BashArity.prefix(command).join(" ") + "*")
  125. }
  126. }
  127. if (directories.size > 0) {
  128. await ctx.ask({
  129. permission: "external_directory",
  130. patterns: Array.from(directories),
  131. always: Array.from(directories).map((x) => path.dirname(x) + "*"),
  132. metadata: {},
  133. })
  134. }
  135. if (patterns.size > 0) {
  136. await ctx.ask({
  137. permission: "bash",
  138. patterns: Array.from(patterns),
  139. always: Array.from(always),
  140. metadata: {},
  141. })
  142. }
  143. const proc = spawn(params.command, {
  144. shell,
  145. cwd,
  146. env: {
  147. ...process.env,
  148. },
  149. stdio: ["ignore", "pipe", "pipe"],
  150. detached: process.platform !== "win32",
  151. })
  152. let output = ""
  153. // Initialize metadata with empty output
  154. ctx.metadata({
  155. metadata: {
  156. output: "",
  157. description: params.description,
  158. },
  159. })
  160. const append = (chunk: Buffer) => {
  161. output += chunk.toString()
  162. ctx.metadata({
  163. metadata: {
  164. // truncate the metadata to avoid GIANT blobs of data (has nothing to do w/ what agent can access)
  165. output: output.length > MAX_METADATA_LENGTH ? output.slice(0, MAX_METADATA_LENGTH) + "\n\n..." : output,
  166. description: params.description,
  167. },
  168. })
  169. }
  170. proc.stdout?.on("data", append)
  171. proc.stderr?.on("data", append)
  172. let timedOut = false
  173. let aborted = false
  174. let exited = false
  175. const kill = () => Shell.killTree(proc, { exited: () => exited })
  176. if (ctx.abort.aborted) {
  177. aborted = true
  178. await kill()
  179. }
  180. const abortHandler = () => {
  181. aborted = true
  182. void kill()
  183. }
  184. ctx.abort.addEventListener("abort", abortHandler, { once: true })
  185. const timeoutTimer = setTimeout(() => {
  186. timedOut = true
  187. void kill()
  188. }, timeout + 100)
  189. await new Promise<void>((resolve, reject) => {
  190. const cleanup = () => {
  191. clearTimeout(timeoutTimer)
  192. ctx.abort.removeEventListener("abort", abortHandler)
  193. }
  194. proc.once("exit", () => {
  195. exited = true
  196. cleanup()
  197. resolve()
  198. })
  199. proc.once("error", (error) => {
  200. exited = true
  201. cleanup()
  202. reject(error)
  203. })
  204. })
  205. const resultMetadata: string[] = []
  206. if (timedOut) {
  207. resultMetadata.push(`bash tool terminated command after exceeding timeout ${timeout} ms`)
  208. }
  209. if (aborted) {
  210. resultMetadata.push("User aborted the command")
  211. }
  212. if (resultMetadata.length > 0) {
  213. output += "\n\n<bash_metadata>\n" + resultMetadata.join("\n") + "\n</bash_metadata>"
  214. }
  215. return {
  216. title: params.description,
  217. metadata: {
  218. output: output.length > MAX_METADATA_LENGTH ? output.slice(0, MAX_METADATA_LENGTH) + "\n\n..." : output,
  219. exit: proc.exitCode,
  220. description: params.description,
  221. },
  222. output,
  223. }
  224. },
  225. }
  226. })