bash.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import { z } from "zod"
  2. import { Tool } from "./tool"
  3. import DESCRIPTION from "./bash.txt"
  4. import { App } from "../app/app"
  5. import { Permission } from "../permission"
  6. import { Config } from "../config/config"
  7. import { Filesystem } from "../util/filesystem"
  8. import { lazy } from "../util/lazy"
  9. import { Log } from "../util/log"
  10. import { Wildcard } from "../util/wildcard"
  11. import { $ } from "bun"
  12. const MAX_OUTPUT_LENGTH = 30000
  13. const DEFAULT_TIMEOUT = 1 * 60 * 1000
  14. const MAX_TIMEOUT = 10 * 60 * 1000
  15. const log = Log.create({ service: "bash-tool" })
  16. const parser = lazy(async () => {
  17. const { default: Parser } = await import("tree-sitter")
  18. const Bash = await import("tree-sitter-bash")
  19. const p = new Parser()
  20. p.setLanguage(Bash.language as any)
  21. return p
  22. })
  23. export const BashTool = Tool.define("bash", {
  24. description: DESCRIPTION,
  25. parameters: z.object({
  26. command: z.string().describe("The command to execute"),
  27. timeout: z.number().describe("Optional timeout in milliseconds").optional(),
  28. description: z
  29. .string()
  30. .describe(
  31. "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'",
  32. ),
  33. }),
  34. async execute(params, ctx) {
  35. const timeout = Math.min(params.timeout ?? DEFAULT_TIMEOUT, MAX_TIMEOUT)
  36. const app = App.info()
  37. const cfg = await Config.get()
  38. const tree = await parser().then((p) => p.parse(params.command))
  39. const permissions = (() => {
  40. const value = cfg.permission?.bash
  41. if (!value)
  42. return {
  43. "*": "allow",
  44. }
  45. if (typeof value === "string")
  46. return {
  47. "*": value,
  48. }
  49. return value
  50. })()
  51. let needsAsk = false
  52. for (const node of tree.rootNode.descendantsOfType("command")) {
  53. const command = []
  54. for (let i = 0; i < node.childCount; i++) {
  55. const child = node.child(i)
  56. if (!child) continue
  57. if (
  58. child.type !== "command_name" &&
  59. child.type !== "word" &&
  60. child.type !== "string" &&
  61. child.type !== "raw_string" &&
  62. child.type !== "concatenation"
  63. ) {
  64. continue
  65. }
  66. command.push(child.text)
  67. }
  68. // not an exhaustive list, but covers most common cases
  69. if (["cd", "rm", "cp", "mv", "mkdir", "touch", "chmod", "chown"].includes(command[0])) {
  70. for (const arg of command.slice(1)) {
  71. if (arg.startsWith("-") || (command[0] === "chmod" && arg.startsWith("+"))) continue
  72. const resolved = await $`realpath ${arg}`
  73. .quiet()
  74. .nothrow()
  75. .text()
  76. .then((x) => x.trim())
  77. log.info("resolved path", { arg, resolved })
  78. if (resolved && !Filesystem.contains(app.path.cwd, resolved)) {
  79. throw new Error(
  80. `This command references paths outside of ${app.path.cwd} so it is not allowed to be executed.`,
  81. )
  82. }
  83. }
  84. }
  85. // always allow cd if it passes above check
  86. if (!needsAsk && command[0] !== "cd") {
  87. const ask = (() => {
  88. for (const [pattern, value] of Object.entries(permissions)) {
  89. const match = Wildcard.match(node.text, pattern)
  90. log.info("checking", { text: node.text.trim(), pattern, match })
  91. if (match) return value
  92. }
  93. return "ask"
  94. })()
  95. if (ask === "ask") needsAsk = true
  96. }
  97. }
  98. if (needsAsk) {
  99. await Permission.ask({
  100. type: "bash",
  101. sessionID: ctx.sessionID,
  102. messageID: ctx.messageID,
  103. callID: ctx.callID,
  104. title: params.command,
  105. metadata: {
  106. command: params.command,
  107. },
  108. })
  109. }
  110. const process = Bun.spawn({
  111. cmd: ["bash", "-c", params.command],
  112. cwd: app.path.cwd,
  113. maxBuffer: MAX_OUTPUT_LENGTH,
  114. signal: ctx.abort,
  115. timeout: timeout,
  116. stdout: "pipe",
  117. stderr: "pipe",
  118. })
  119. await process.exited
  120. const stdout = await new Response(process.stdout).text()
  121. const stderr = await new Response(process.stderr).text()
  122. return {
  123. title: params.command,
  124. metadata: {
  125. stderr,
  126. stdout,
  127. exit: process.exitCode,
  128. description: params.description,
  129. },
  130. output: [`<stdout>`, stdout ?? "", `</stdout>`, `<stderr>`, stderr ?? "", `</stderr>`].join("\n"),
  131. }
  132. },
  133. })