bash.go

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