bash.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { z } from "zod"
  2. import { Tool } from "./tool"
  3. import DESCRIPTION from "./bash.txt"
  4. const MAX_OUTPUT_LENGTH = 30000
  5. const BANNED_COMMANDS = [
  6. "alias",
  7. "curl",
  8. "curlie",
  9. "wget",
  10. "axel",
  11. "aria2c",
  12. "nc",
  13. "telnet",
  14. "lynx",
  15. "w3m",
  16. "links",
  17. "httpie",
  18. "xh",
  19. "http-prompt",
  20. "chrome",
  21. "firefox",
  22. "safari",
  23. ]
  24. const DEFAULT_TIMEOUT = 1 * 60 * 1000
  25. const MAX_TIMEOUT = 10 * 60 * 1000
  26. export const BashTool = Tool.define({
  27. id: "opencode.bash",
  28. description: DESCRIPTION,
  29. parameters: z.object({
  30. command: z.string().describe("The command to execute"),
  31. timeout: z
  32. .number()
  33. .min(0)
  34. .max(MAX_TIMEOUT)
  35. .describe("Optional timeout in milliseconds")
  36. .optional()
  37. .describe("Optional timeout in milliseconds"),
  38. description: z
  39. .string()
  40. .describe(
  41. "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'",
  42. ),
  43. }),
  44. async execute(params) {
  45. const timeout = Math.min(params.timeout ?? DEFAULT_TIMEOUT, MAX_TIMEOUT)
  46. if (BANNED_COMMANDS.some((item) => params.command.startsWith(item)))
  47. throw new Error(`Command '${params.command}' is not allowed`)
  48. const process = Bun.spawn({
  49. cmd: ["bash", "-c", params.command],
  50. maxBuffer: MAX_OUTPUT_LENGTH,
  51. timeout: timeout,
  52. stdout: "pipe",
  53. stderr: "pipe",
  54. })
  55. await process.exited
  56. const stdout = await new Response(process.stdout).text()
  57. const stderr = await new Response(process.stderr).text()
  58. return {
  59. metadata: {
  60. stderr,
  61. stdout,
  62. description: params.description,
  63. },
  64. output: stdout.replaceAll(/\x1b\[[0-9;]*m/g, ""),
  65. }
  66. },
  67. })