bash.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. // Get full command text including redirects if present
  86. let commandText = node.parent?.type === "redirected_statement" ? node.parent.text : node.text
  87. const command = []
  88. for (let i = 0; i < node.childCount; i++) {
  89. const child = node.child(i)
  90. if (!child) continue
  91. if (
  92. child.type !== "command_name" &&
  93. child.type !== "word" &&
  94. child.type !== "string" &&
  95. child.type !== "raw_string" &&
  96. child.type !== "concatenation"
  97. ) {
  98. continue
  99. }
  100. command.push(child.text)
  101. }
  102. // not an exhaustive list, but covers most common cases
  103. if (["cd", "rm", "cp", "mv", "mkdir", "touch", "chmod", "chown", "cat"].includes(command[0])) {
  104. for (const arg of command.slice(1)) {
  105. if (arg.startsWith("-") || (command[0] === "chmod" && arg.startsWith("+"))) continue
  106. const resolved = await $`realpath ${arg}`
  107. .cwd(cwd)
  108. .quiet()
  109. .nothrow()
  110. .text()
  111. .then((x) => x.trim())
  112. log.info("resolved path", { arg, resolved })
  113. if (resolved) {
  114. // Git Bash on Windows returns Unix-style paths like /c/Users/...
  115. const normalized =
  116. process.platform === "win32" && resolved.match(/^\/[a-z]\//)
  117. ? resolved.replace(/^\/([a-z])\//, (_, drive) => `${drive.toUpperCase()}:\\`).replace(/\//g, "\\")
  118. : resolved
  119. if (!Instance.containsPath(normalized)) directories.add(normalized)
  120. }
  121. }
  122. }
  123. // cd covered by above check
  124. if (command.length && command[0] !== "cd") {
  125. patterns.add(commandText)
  126. always.add(BashArity.prefix(command).join(" ") + " *")
  127. }
  128. }
  129. if (directories.size > 0) {
  130. await ctx.ask({
  131. permission: "external_directory",
  132. patterns: Array.from(directories),
  133. always: Array.from(directories).map((x) => path.dirname(x) + "*"),
  134. metadata: {},
  135. })
  136. }
  137. if (patterns.size > 0) {
  138. await ctx.ask({
  139. permission: "bash",
  140. patterns: Array.from(patterns),
  141. always: Array.from(always),
  142. metadata: {},
  143. })
  144. }
  145. const proc = spawn(params.command, {
  146. shell,
  147. cwd,
  148. env: {
  149. ...process.env,
  150. },
  151. stdio: ["ignore", "pipe", "pipe"],
  152. detached: process.platform !== "win32",
  153. })
  154. let output = ""
  155. // Initialize metadata with empty output
  156. ctx.metadata({
  157. metadata: {
  158. output: "",
  159. description: params.description,
  160. },
  161. })
  162. const append = (chunk: Buffer) => {
  163. output += chunk.toString()
  164. ctx.metadata({
  165. metadata: {
  166. // truncate the metadata to avoid GIANT blobs of data (has nothing to do w/ what agent can access)
  167. output: output.length > MAX_METADATA_LENGTH ? output.slice(0, MAX_METADATA_LENGTH) + "\n\n..." : output,
  168. description: params.description,
  169. },
  170. })
  171. }
  172. proc.stdout?.on("data", append)
  173. proc.stderr?.on("data", append)
  174. let timedOut = false
  175. let aborted = false
  176. let exited = false
  177. const kill = () => Shell.killTree(proc, { exited: () => exited })
  178. if (ctx.abort.aborted) {
  179. aborted = true
  180. await kill()
  181. }
  182. const abortHandler = () => {
  183. aborted = true
  184. void kill()
  185. }
  186. ctx.abort.addEventListener("abort", abortHandler, { once: true })
  187. const timeoutTimer = setTimeout(() => {
  188. timedOut = true
  189. void kill()
  190. }, timeout + 100)
  191. await new Promise<void>((resolve, reject) => {
  192. const cleanup = () => {
  193. clearTimeout(timeoutTimer)
  194. ctx.abort.removeEventListener("abort", abortHandler)
  195. }
  196. proc.once("exit", () => {
  197. exited = true
  198. cleanup()
  199. resolve()
  200. })
  201. proc.once("error", (error) => {
  202. exited = true
  203. cleanup()
  204. reject(error)
  205. })
  206. })
  207. const resultMetadata: string[] = []
  208. if (timedOut) {
  209. resultMetadata.push(`bash tool terminated command after exceeding timeout ${timeout} ms`)
  210. }
  211. if (aborted) {
  212. resultMetadata.push("User aborted the command")
  213. }
  214. if (resultMetadata.length > 0) {
  215. output += "\n\n<bash_metadata>\n" + resultMetadata.join("\n") + "\n</bash_metadata>"
  216. }
  217. return {
  218. title: params.description,
  219. metadata: {
  220. output: output.length > MAX_METADATA_LENGTH ? output.slice(0, MAX_METADATA_LENGTH) + "\n\n..." : output,
  221. exit: proc.exitCode,
  222. description: params.description,
  223. },
  224. output,
  225. }
  226. },
  227. }
  228. })