bash.go 15 KB

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