bash.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/charmbracelet/crush/internal/config"
  9. "github.com/charmbracelet/crush/internal/llm/tools/shell"
  10. "github.com/charmbracelet/crush/internal/permission"
  11. )
  12. type BashParams struct {
  13. Command string `json:"command"`
  14. Timeout int `json:"timeout"`
  15. }
  16. type BashPermissionsParams struct {
  17. Command string `json:"command"`
  18. Timeout int `json:"timeout"`
  19. }
  20. type BashResponseMetadata struct {
  21. StartTime int64 `json:"start_time"`
  22. EndTime int64 `json:"end_time"`
  23. }
  24. type bashTool struct {
  25. permissions permission.Service
  26. }
  27. const (
  28. BashToolName = "bash"
  29. DefaultTimeout = 1 * 60 * 1000 // 1 minutes in milliseconds
  30. MaxTimeout = 10 * 60 * 1000 // 10 minutes in milliseconds
  31. MaxOutputLength = 30000
  32. BashNoOutput = "no output"
  33. )
  34. var bannedCommands = []string{
  35. "alias", "curl", "curlie", "wget", "axel", "aria2c",
  36. "nc", "telnet", "lynx", "w3m", "links", "httpie", "xh",
  37. "http-prompt", "chrome", "firefox", "safari",
  38. }
  39. var safeReadOnlyCommands = []string{
  40. "ls", "echo", "pwd", "date", "cal", "uptime", "whoami", "id", "groups", "env", "printenv", "set", "unset", "which", "type", "whereis",
  41. "whatis", "uname", "hostname", "df", "du", "free", "top", "ps", "kill", "killall", "nice", "nohup", "time", "timeout",
  42. "git status", "git log", "git diff", "git show", "git branch", "git tag", "git remote", "git ls-files", "git ls-remote",
  43. "git rev-parse", "git config --get", "git config --list", "git describe", "git blame", "git grep", "git shortlog",
  44. "go version", "go help", "go list", "go env", "go doc", "go vet", "go fmt", "go mod", "go test", "go build", "go run", "go install", "go clean",
  45. }
  46. func bashDescription() string {
  47. bannedCommandsStr := strings.Join(bannedCommands, ", ")
  48. return fmt.Sprintf(`Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
  49. Before executing the command, please follow these steps:
  50. 1. Directory Verification:
  51. - 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
  52. - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
  53. 2. Security Check:
  54. - 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.
  55. - Verify that the command is not one of the banned commands: %s.
  56. 3. Command Execution:
  57. - After ensuring proper quoting, execute the command.
  58. - Capture the output of the command.
  59. 4. Output Processing:
  60. - If the output exceeds %d characters, output will be truncated before being returned to you.
  61. - Prepare the output for display to the user.
  62. 5. Return Result:
  63. - Provide the processed output of the command.
  64. - If any errors occurred during execution, include those in the output.
  65. Usage notes:
  66. - The command argument is required.
  67. - You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
  68. - 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.
  69. - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
  70. - 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.
  71. - 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.
  72. <good-example>
  73. pytest /foo/bar/tests
  74. </good-example>
  75. <bad-example>
  76. cd /foo/bar && pytest tests
  77. </bad-example>
  78. # Committing changes with git
  79. When the user asks you to create a new git commit, follow these steps carefully:
  80. 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!):
  81. - Run a git status command to see all untracked files.
  82. - Run a git diff command to see both staged and unstaged changes that will be committed.
  83. - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
  84. 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.
  85. 3. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
  86. <commit_analysis>
  87. - List the files that have been changed or added
  88. - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
  89. - Brainstorm the purpose or motivation behind these changes
  90. - Do not use tools to explore code, beyond what is available in the git context
  91. - Assess the impact of these changes on the overall project
  92. - Check for any sensitive information that shouldn't be committed
  93. - Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
  94. - Ensure your language is clear, concise, and to the point
  95. - 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.)
  96. - Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
  97. - Review the draft message to ensure it accurately reflects the changes and their purpose
  98. </commit_analysis>
  99. 4. Create the commit with a message ending with:
  100. 💘 Generated with Crush
  101. Co-Authored-By: Crush <[email protected]>
  102. - In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
  103. <example>
  104. git commit -m "$(cat <<'EOF'
  105. Commit message here.
  106. 💘 Generated with Crush
  107. Co-Authored-By: 💘 Crush <[email protected]>
  108. EOF
  109. )"
  110. </example>
  111. 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.
  112. 6. Finally, run git status to make sure the commit succeeded.
  113. Important notes:
  114. - When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
  115. - 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.
  116. - NEVER update the git config
  117. - DO NOT push to the remote repository
  118. - 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.
  119. - If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
  120. - Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
  121. - Return an empty response - the user will see the git output directly
  122. # Creating pull requests
  123. 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.
  124. IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
  125. 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!):
  126. - Run a git status command to see all untracked files.
  127. - Run a git diff command to see both staged and unstaged changes that will be committed.
  128. - 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
  129. - 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.)
  130. 2. Create new branch if needed
  131. 3. Commit changes if needed
  132. 4. Push to remote with -u flag if needed
  133. 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:
  134. <pr_analysis>
  135. - List the commits since diverging from the main branch
  136. - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
  137. - Brainstorm the purpose or motivation behind these changes
  138. - Assess the impact of these changes on the overall project
  139. - Do not use tools to explore code, beyond what is available in the git context
  140. - Check for any sensitive information that shouldn't be committed
  141. - Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
  142. - Ensure the summary accurately reflects all changes since diverging from the main branch
  143. - Ensure your language is clear, concise, and to the point
  144. - 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.)
  145. - Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
  146. - Review the draft summary to ensure it accurately reflects the changes and their purpose
  147. </pr_analysis>
  148. 6. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
  149. <example>
  150. gh pr create --title "the pr title" --body "$(cat <<'EOF'
  151. ## Summary
  152. <1-3 bullet points>
  153. ## Test plan
  154. [Checklist of TODOs for testing the pull request...]
  155. 💘 Generated with Crush
  156. EOF
  157. )"
  158. </example>
  159. Important:
  160. - Return an empty response - the user will see the gh output directly
  161. - Never update git config`, bannedCommandsStr, MaxOutputLength)
  162. }
  163. func NewBashTool(permission permission.Service) BaseTool {
  164. return &bashTool{
  165. permissions: permission,
  166. }
  167. }
  168. func (b *bashTool) Info() ToolInfo {
  169. return ToolInfo{
  170. Name: BashToolName,
  171. Description: bashDescription(),
  172. Parameters: map[string]any{
  173. "command": map[string]any{
  174. "type": "string",
  175. "description": "The command to execute",
  176. },
  177. "timeout": map[string]any{
  178. "type": "number",
  179. "description": "Optional timeout in milliseconds (max 600000)",
  180. },
  181. },
  182. Required: []string{"command"},
  183. }
  184. }
  185. func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  186. var params BashParams
  187. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  188. return NewTextErrorResponse("invalid parameters"), nil
  189. }
  190. if params.Timeout > MaxTimeout {
  191. params.Timeout = MaxTimeout
  192. } else if params.Timeout <= 0 {
  193. params.Timeout = DefaultTimeout
  194. }
  195. if params.Command == "" {
  196. return NewTextErrorResponse("missing command"), nil
  197. }
  198. baseCmd := strings.Fields(params.Command)[0]
  199. for _, banned := range bannedCommands {
  200. if strings.EqualFold(baseCmd, banned) {
  201. return NewTextErrorResponse(fmt.Sprintf("command '%s' is not allowed", baseCmd)), nil
  202. }
  203. }
  204. isSafeReadOnly := false
  205. cmdLower := strings.ToLower(params.Command)
  206. for _, safe := range safeReadOnlyCommands {
  207. if strings.HasPrefix(cmdLower, strings.ToLower(safe)) {
  208. if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
  209. isSafeReadOnly = true
  210. break
  211. }
  212. }
  213. }
  214. sessionID, messageID := GetContextValues(ctx)
  215. if sessionID == "" || messageID == "" {
  216. return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
  217. }
  218. if !isSafeReadOnly {
  219. p := b.permissions.Request(
  220. permission.CreatePermissionRequest{
  221. SessionID: sessionID,
  222. Path: config.WorkingDirectory(),
  223. ToolName: BashToolName,
  224. Action: "execute",
  225. Description: fmt.Sprintf("Execute command: %s", params.Command),
  226. Params: BashPermissionsParams{
  227. Command: params.Command,
  228. },
  229. },
  230. )
  231. if !p {
  232. return ToolResponse{}, permission.ErrorPermissionDenied
  233. }
  234. }
  235. startTime := time.Now()
  236. if params.Timeout > 0 {
  237. var cancel context.CancelFunc
  238. ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
  239. defer cancel()
  240. }
  241. stdout, stderr, err := shell.
  242. GetPersistentShell(config.WorkingDirectory()).
  243. Exec(ctx, params.Command)
  244. interrupted := shell.IsInterrupt(err)
  245. exitCode := shell.ExitCode(err)
  246. if exitCode == 0 && !interrupted && err != nil {
  247. return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
  248. }
  249. stdout = truncateOutput(stdout)
  250. stderr = truncateOutput(stderr)
  251. errorMessage := stderr
  252. if interrupted {
  253. if errorMessage != "" {
  254. errorMessage += "\n"
  255. }
  256. errorMessage += "Command was aborted before completion"
  257. } else if exitCode != 0 {
  258. if errorMessage != "" {
  259. errorMessage += "\n"
  260. }
  261. errorMessage += fmt.Sprintf("Exit code %d", exitCode)
  262. }
  263. hasBothOutputs := stdout != "" && stderr != ""
  264. if hasBothOutputs {
  265. stdout += "\n"
  266. }
  267. if errorMessage != "" {
  268. stdout += "\n" + errorMessage
  269. }
  270. metadata := BashResponseMetadata{
  271. StartTime: startTime.UnixMilli(),
  272. EndTime: time.Now().UnixMilli(),
  273. }
  274. if stdout == "" {
  275. return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
  276. }
  277. return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
  278. }
  279. func truncateOutput(content string) string {
  280. if len(content) <= MaxOutputLength {
  281. return content
  282. }
  283. halfLength := MaxOutputLength / 2
  284. start := content[:halfLength]
  285. end := content[len(content)-halfLength:]
  286. truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
  287. return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
  288. }
  289. func countLines(s string) int {
  290. if s == "" {
  291. return 0
  292. }
  293. return len(strings.Split(s, "\n"))
  294. }