bash.go

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