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), ¶ms); 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{
101 Command: params.Command,
102 },
103 },
104 )
105 if !p {
106 return NewTextErrorResponse("permission denied"), nil
107 }
108 }
109 shell := shell.GetPersistentShell(config.WorkingDirectory())
110 stdout, stderr, exitCode, interrupted, err := shell.Exec(ctx, params.Command, params.Timeout)
111 if err != nil {
112 return NewTextErrorResponse(fmt.Sprintf("error executing command: %s", err)), nil
113 }
114
115 stdout = truncateOutput(stdout)
116 stderr = truncateOutput(stderr)
117
118 errorMessage := stderr
119 if interrupted {
120 if errorMessage != "" {
121 errorMessage += "\n"
122 }
123 errorMessage += "Command was aborted before completion"
124 } else if exitCode != 0 {
125 if errorMessage != "" {
126 errorMessage += "\n"
127 }
128 errorMessage += fmt.Sprintf("Exit code %d", exitCode)
129 }
130
131 hasBothOutputs := stdout != "" && stderr != ""
132
133 if hasBothOutputs {
134 stdout += "\n"
135 }
136
137 if errorMessage != "" {
138 stdout += "\n" + errorMessage
139 }
140
141 if stdout == "" {
142 return NewTextResponse("no output"), nil
143 }
144 return NewTextResponse(stdout), nil
145}
146
147func truncateOutput(content string) string {
148 if len(content) <= MaxOutputLength {
149 return content
150 }
151
152 halfLength := MaxOutputLength / 2
153 start := content[:halfLength]
154 end := content[len(content)-halfLength:]
155
156 truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
157 return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
158}
159
160func countLines(s string) int {
161 if s == "" {
162 return 0
163 }
164 return len(strings.Split(s, "\n"))
165}
166
167func bashDescription() string {
168 bannedCommandsStr := strings.Join(BannedCommands, ", ")
169 return fmt.Sprintf(`Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
170
171Before executing the command, please follow these steps:
172
1731. Directory Verification:
174 - 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
175 - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
176
1772. 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
1813. Command Execution:
182 - After ensuring proper quoting, execute the command.
183 - Capture the output of the command.
184
1854. Output Processing:
186 - If the output exceeds %d characters, output will be truncated before being returned to you.
187 - Prepare the output for display to the user.
188
1895. Return Result:
190 - Provide the processed output of the command.
191 - If any errors occurred during execution, include those in the output.
192
193Usage notes:
194- The command argument is required.
195- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
196- 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.
197- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
198- 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.
199- 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.
200<good-example>
201pytest /foo/bar/tests
202</good-example>
203<bad-example>
204cd /foo/bar && pytest tests
205</bad-example>
206
207# Committing changes with git
208
209When the user asks you to create a new git commit, follow these steps carefully:
210
2111. 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!):
212 - Run a git status command to see all untracked files.
213 - Run a git diff command to see both staged and unstaged changes that will be committed.
214 - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
215
2162. 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.
217
2183. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
219
220<commit_analysis>
221- List the files that have been changed or added
222- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
223- Brainstorm the purpose or motivation behind these changes
224- Do not use tools to explore code, beyond what is available in the git context
225- Assess the impact of these changes on the overall project
226- Check for any sensitive information that shouldn't be committed
227- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
228- Ensure your language is clear, concise, and to the point
229- 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.)
230- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
231- Review the draft message to ensure it accurately reflects the changes and their purpose
232</commit_analysis>
233
2344. Create the commit with a message ending with:
235🤖 Generated with termai
236Co-Authored-By: termai <noreply@termai.io>
237
238- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
239<example>
240git commit -m "$(cat <<'EOF'
241 Commit message here.
242
243 🤖 Generated with termai
244 Co-Authored-By: termai <noreply@termai.io>
245 EOF
246 )"
247</example>
248
2495. 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.
250
2516. Finally, run git status to make sure the commit succeeded.
252
253Important notes:
254- When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
255- 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.
256- NEVER update the git config
257- DO NOT push to the remote repository
258- 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.
259- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
260- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
261- Return an empty response - the user will see the git output directly
262
263# Creating pull requests
264Use 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.
265
266IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
267
2681. 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!):
269 - Run a git status command to see all untracked files.
270 - Run a git diff command to see both staged and unstaged changes that will be committed.
271 - 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
272 - 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.)
273
2742. Create new branch if needed
275
2763. Commit changes if needed
277
2784. Push to remote with -u flag if needed
279
2805. 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:
281
282<pr_analysis>
283- List the commits since diverging from the main branch
284- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
285- Brainstorm the purpose or motivation behind these changes
286- Assess the impact of these changes on the overall project
287- Do not use tools to explore code, beyond what is available in the git context
288- Check for any sensitive information that shouldn't be committed
289- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
290- Ensure the summary accurately reflects all changes since diverging from the main branch
291- Ensure your language is clear, concise, and to the point
292- 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.)
293- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
294- Review the draft summary to ensure it accurately reflects the changes and their purpose
295</pr_analysis>
296
2976. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
298<example>
299gh pr create --title "the pr title" --body "$(cat <<'EOF'
300## Summary
301<1-3 bullet points>
302
303## Test plan
304[Checklist of TODOs for testing the pull request...]
305
306🤖 Generated with termai
307EOF
308)"
309</example>
310
311Important:
312- Return an empty response - the user will see the gh output directly
313- Never update git config`, bannedCommandsStr, MaxOutputLength)
314}
315
316func NewBashTool() BaseTool {
317 return &bashTool{}
318}