bash.go 14 KB

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