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