bash.go

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