bash.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/charmbracelet/crush/internal/permission"
  9. "github.com/charmbracelet/crush/internal/shell"
  10. )
  11. type BashParams struct {
  12. Command string `json:"command"`
  13. Timeout int `json:"timeout"`
  14. }
  15. type BashPermissionsParams struct {
  16. Command string `json:"command"`
  17. Timeout int `json:"timeout"`
  18. }
  19. type BashResponseMetadata struct {
  20. StartTime int64 `json:"start_time"`
  21. EndTime int64 `json:"end_time"`
  22. Output string `json:"output"`
  23. WorkingDirectory string `json:"working_directory"`
  24. }
  25. type bashTool struct {
  26. permissions permission.Service
  27. workingDir string
  28. }
  29. const (
  30. BashToolName = "bash"
  31. DefaultTimeout = 1 * 60 * 1000 // 1 minutes in milliseconds
  32. MaxTimeout = 10 * 60 * 1000 // 10 minutes in milliseconds
  33. MaxOutputLength = 30000
  34. BashNoOutput = "no output"
  35. )
  36. var bannedCommands = []string{
  37. // Network/Download tools
  38. "alias",
  39. "aria2c",
  40. "axel",
  41. "chrome",
  42. "curl",
  43. "curlie",
  44. "firefox",
  45. "http-prompt",
  46. "httpie",
  47. "links",
  48. "lynx",
  49. "nc",
  50. "safari",
  51. "scp",
  52. "ssh",
  53. "telnet",
  54. "w3m",
  55. "wget",
  56. "xh",
  57. // System administration
  58. "doas",
  59. "su",
  60. "sudo",
  61. // Package managers
  62. "apk",
  63. "apt",
  64. "apt-cache",
  65. "apt-get",
  66. "dnf",
  67. "dpkg",
  68. "emerge",
  69. "home-manager",
  70. "makepkg",
  71. "opkg",
  72. "pacman",
  73. "paru",
  74. "pkg",
  75. "pkg_add",
  76. "pkg_delete",
  77. "portage",
  78. "rpm",
  79. "yay",
  80. "yum",
  81. "zypper",
  82. // System modification
  83. "at",
  84. "batch",
  85. "chkconfig",
  86. "crontab",
  87. "fdisk",
  88. "mkfs",
  89. "mount",
  90. "parted",
  91. "service",
  92. "systemctl",
  93. "umount",
  94. // Network configuration
  95. "firewall-cmd",
  96. "ifconfig",
  97. "ip",
  98. "iptables",
  99. "netstat",
  100. "pfctl",
  101. "route",
  102. "ufw",
  103. }
  104. func bashDescription() string {
  105. bannedCommandsStr := strings.Join(bannedCommands, ", ")
  106. return fmt.Sprintf(`Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
  107. CROSS-PLATFORM SHELL SUPPORT:
  108. * This tool uses a shell interpreter (mvdan/sh) that mimics the Bash language,
  109. so you should use Bash syntax in all platforms, including Windows.
  110. The most common shell builtins and core utils are available in Windows as
  111. well.
  112. * Make sure to use forward slashes (/) as path separators in commands, even on
  113. Windows. Example: "ls C:/foo/bar" instead of "ls C:\foo\bar".
  114. Before executing the command, please follow these steps:
  115. 1. Directory Verification:
  116. - If the command will create new directories or files, first use the LS tool to verify the parent directory exists and is the correct location
  117. - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
  118. 2. Security Check:
  119. - For security and to limit the threat of a prompt injection attack, some commands are limited or banned. If you use a disallowed command, you will receive an error message explaining the restriction. Explain the error to the User.
  120. - Verify that the command is not one of the banned commands: %s.
  121. 3. Command Execution:
  122. - After ensuring proper quoting, execute the command.
  123. - Capture the output of the command.
  124. 4. Output Processing:
  125. - If the output exceeds %d characters, output will be truncated before being returned to you.
  126. - Prepare the output for display to the user.
  127. 5. Return Result:
  128. - Provide the processed output of the command.
  129. - If any errors occurred during execution, include those in the output.
  130. - The result will also have metadata like the cwd (current working directory) at the end, included with <cwd></cwd> tags.
  131. Usage notes:
  132. - The command argument is required.
  133. - You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
  134. - VERY IMPORTANT: You MUST avoid using search commands like 'find' and 'grep'. Instead use Grep, Glob, or Agent tools to search. You MUST avoid read tools like 'cat', 'head', 'tail', and 'ls', and use FileRead and LS tools to read files.
  135. - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
  136. - IMPORTANT: All commands share the same shell session. Shell state (environment variables, virtual environments, current directory, etc.) persist between commands. For example, if you set an environment variable as part of a command, the environment variable will persist for subsequent commands.
  137. - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of 'cd'. You may use 'cd' if the User explicitly requests it.
  138. <good-example>
  139. pytest /foo/bar/tests
  140. </good-example>
  141. <bad-example>
  142. cd /foo/bar && pytest tests
  143. </bad-example>
  144. # Committing changes with git
  145. When the user asks you to create a new git commit, follow these steps carefully:
  146. 1. Start with a single message that contains exactly three tool_use blocks that do the following (it is VERY IMPORTANT that you send these tool_use blocks in a single message, otherwise it will feel slow to the user!):
  147. - Run a git status command to see all untracked files.
  148. - Run a git diff command to see both staged and unstaged changes that will be committed.
  149. - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
  150. 2. Use the git context at the start of this conversation to determine which files are relevant to your commit. Add relevant untracked files to the staging area. Do not commit files that were already modified at the start of this conversation, if they are not relevant to your commit.
  151. 3. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
  152. <commit_analysis>
  153. - List the files that have been changed or added
  154. - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
  155. - Brainstorm the purpose or motivation behind these changes
  156. - Do not use tools to explore code, beyond what is available in the git context
  157. - Assess the impact of these changes on the overall project
  158. - Check for any sensitive information that shouldn't be committed
  159. - Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
  160. - Ensure your language is clear, concise, and to the point
  161. - Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.)
  162. - Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
  163. - Review the draft message to ensure it accurately reflects the changes and their purpose
  164. </commit_analysis>
  165. 4. Create the commit with a message ending with:
  166. 💘 Generated with Crush
  167. Co-Authored-By: Crush <[email protected]>
  168. - In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
  169. <example>
  170. git commit -m "$(cat <<'EOF'
  171. Commit message here.
  172. 💘 Generated with Crush
  173. Co-Authored-By: 💘 Crush <[email protected]>
  174. EOF
  175. )"
  176. </example>
  177. 5. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
  178. 6. Finally, run git status to make sure the commit succeeded.
  179. Important notes:
  180. - When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
  181. - However, be careful not to stage files (e.g. with 'git add .') for commits that aren't part of the change, they may have untracked files they want to keep around, but not commit.
  182. - NEVER update the git config
  183. - DO NOT push to the remote repository
  184. - IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
  185. - If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
  186. - Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
  187. - Return an empty response - the user will see the git output directly
  188. # Creating pull requests
  189. Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.
  190. IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
  191. 1. Understand the current state of the branch. Remember to send a single message that contains multiple tool_use blocks (it is VERY IMPORTANT that you do this in a single message, otherwise it will feel slow to the user!):
  192. - Run a git status command to see all untracked files.
  193. - Run a git diff command to see both staged and unstaged changes that will be committed.
  194. - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote
  195. - Run a git log command and 'git diff main...HEAD' to understand the full commit history for the current branch (from the time it diverged from the 'main' branch.)
  196. 2. Create new branch if needed
  197. 3. Commit changes if needed
  198. 4. Push to remote with -u flag if needed
  199. 5. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (not just the latest commit, but all commits that will be included in the pull request!), and draft a pull request summary. Wrap your analysis process in <pr_analysis> tags:
  200. <pr_analysis>
  201. - List the commits since diverging from the main branch
  202. - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
  203. - Brainstorm the purpose or motivation behind these changes
  204. - Assess the impact of these changes on the overall project
  205. - Do not use tools to explore code, beyond what is available in the git context
  206. - Check for any sensitive information that shouldn't be committed
  207. - Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
  208. - Ensure the summary accurately reflects all changes since diverging from the main branch
  209. - Ensure your language is clear, concise, and to the point
  210. - Ensure the summary accurately reflects the changes and their purpose (ie. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.)
  211. - Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
  212. - Review the draft summary to ensure it accurately reflects the changes and their purpose
  213. </pr_analysis>
  214. 6. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
  215. <example>
  216. gh pr create --title "the pr title" --body "$(cat <<'EOF'
  217. ## Summary
  218. <1-3 bullet points>
  219. ## Test plan
  220. [Checklist of TODOs for testing the pull request...]
  221. 💘 Generated with Crush
  222. EOF
  223. )"
  224. </example>
  225. Important:
  226. - Return an empty response - the user will see the gh output directly
  227. - Never update git config`, bannedCommandsStr, MaxOutputLength)
  228. }
  229. func blockFuncs() []shell.BlockFunc {
  230. return []shell.BlockFunc{
  231. shell.CommandsBlocker(bannedCommands),
  232. shell.ArgumentsBlocker([][]string{
  233. // System package managers
  234. {"apk", "add"},
  235. {"apt", "install"},
  236. {"apt-get", "install"},
  237. {"dnf", "install"},
  238. {"emerge"},
  239. {"pacman", "-S"},
  240. {"pkg", "install"},
  241. {"yum", "install"},
  242. {"zypper", "install"},
  243. // Language-specific package managers
  244. {"brew", "install"},
  245. {"cargo", "install"},
  246. {"gem", "install"},
  247. {"go", "install"},
  248. {"npm", "install", "-g"},
  249. {"npm", "install", "--global"},
  250. {"pip", "install", "--user"},
  251. {"pip3", "install", "--user"},
  252. {"pnpm", "add", "-g"},
  253. {"pnpm", "add", "--global"},
  254. {"yarn", "global", "add"},
  255. }),
  256. }
  257. }
  258. func NewBashTool(permission permission.Service, workingDir string) BaseTool {
  259. // Set up command blocking on the persistent shell
  260. persistentShell := shell.GetPersistentShell(workingDir)
  261. persistentShell.SetBlockFuncs(blockFuncs())
  262. return &bashTool{
  263. permissions: permission,
  264. workingDir: workingDir,
  265. }
  266. }
  267. func (b *bashTool) Name() string {
  268. return BashToolName
  269. }
  270. func (b *bashTool) Info() ToolInfo {
  271. return ToolInfo{
  272. Name: BashToolName,
  273. Description: bashDescription(),
  274. Parameters: map[string]any{
  275. "command": map[string]any{
  276. "type": "string",
  277. "description": "The command to execute",
  278. },
  279. "timeout": map[string]any{
  280. "type": "number",
  281. "description": "Optional timeout in milliseconds (max 600000)",
  282. },
  283. },
  284. Required: []string{"command"},
  285. }
  286. }
  287. func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  288. var params BashParams
  289. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  290. return NewTextErrorResponse("invalid parameters"), nil
  291. }
  292. if params.Timeout > MaxTimeout {
  293. params.Timeout = MaxTimeout
  294. } else if params.Timeout <= 0 {
  295. params.Timeout = DefaultTimeout
  296. }
  297. if params.Command == "" {
  298. return NewTextErrorResponse("missing command"), nil
  299. }
  300. isSafeReadOnly := false
  301. cmdLower := strings.ToLower(params.Command)
  302. for _, safe := range safeCommands {
  303. if strings.HasPrefix(cmdLower, safe) {
  304. if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
  305. isSafeReadOnly = true
  306. break
  307. }
  308. }
  309. }
  310. sessionID, messageID := GetContextValues(ctx)
  311. if sessionID == "" || messageID == "" {
  312. return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
  313. }
  314. if !isSafeReadOnly {
  315. p := b.permissions.Request(
  316. permission.CreatePermissionRequest{
  317. SessionID: sessionID,
  318. Path: b.workingDir,
  319. ToolCallID: call.ID,
  320. ToolName: BashToolName,
  321. Action: "execute",
  322. Description: fmt.Sprintf("Execute command: %s", params.Command),
  323. Params: BashPermissionsParams{
  324. Command: params.Command,
  325. },
  326. },
  327. )
  328. if !p {
  329. return ToolResponse{}, permission.ErrorPermissionDenied
  330. }
  331. }
  332. startTime := time.Now()
  333. if params.Timeout > 0 {
  334. var cancel context.CancelFunc
  335. ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
  336. defer cancel()
  337. }
  338. persistentShell := shell.GetPersistentShell(b.workingDir)
  339. stdout, stderr, err := persistentShell.Exec(ctx, params.Command)
  340. // Get the current working directory after command execution
  341. currentWorkingDir := persistentShell.GetWorkingDir()
  342. interrupted := shell.IsInterrupt(err)
  343. exitCode := shell.ExitCode(err)
  344. if exitCode == 0 && !interrupted && err != nil {
  345. return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
  346. }
  347. stdout = truncateOutput(stdout)
  348. stderr = truncateOutput(stderr)
  349. errorMessage := stderr
  350. if errorMessage == "" && err != nil {
  351. errorMessage = err.Error()
  352. }
  353. if interrupted {
  354. if errorMessage != "" {
  355. errorMessage += "\n"
  356. }
  357. errorMessage += "Command was aborted before completion"
  358. } else if exitCode != 0 {
  359. if errorMessage != "" {
  360. errorMessage += "\n"
  361. }
  362. errorMessage += fmt.Sprintf("Exit code %d", exitCode)
  363. }
  364. hasBothOutputs := stdout != "" && stderr != ""
  365. if hasBothOutputs {
  366. stdout += "\n"
  367. }
  368. if errorMessage != "" {
  369. stdout += "\n" + errorMessage
  370. }
  371. metadata := BashResponseMetadata{
  372. StartTime: startTime.UnixMilli(),
  373. EndTime: time.Now().UnixMilli(),
  374. Output: stdout,
  375. WorkingDirectory: currentWorkingDir,
  376. }
  377. if stdout == "" {
  378. return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
  379. }
  380. stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", currentWorkingDir)
  381. return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
  382. }
  383. func truncateOutput(content string) string {
  384. if len(content) <= MaxOutputLength {
  385. return content
  386. }
  387. halfLength := MaxOutputLength / 2
  388. start := content[:halfLength]
  389. end := content[len(content)-halfLength:]
  390. truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
  391. return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
  392. }
  393. func countLines(s string) int {
  394. if s == "" {
  395. return 0
  396. }
  397. return len(strings.Split(s, "\n"))
  398. }