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