bash.go

  1package tools
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"runtime"
  8	"strings"
  9	"time"
 10
 11	"github.com/charmbracelet/crush/internal/config"
 12	"github.com/charmbracelet/crush/internal/llm/tools/shell"
 13	"github.com/charmbracelet/crush/internal/permission"
 14)
 15
 16type BashParams struct {
 17	Command string `json:"command"`
 18	Timeout int    `json:"timeout"`
 19}
 20
 21type BashPermissionsParams struct {
 22	Command string `json:"command"`
 23	Timeout int    `json:"timeout"`
 24}
 25
 26type BashResponseMetadata struct {
 27	StartTime int64 `json:"start_time"`
 28	EndTime   int64 `json:"end_time"`
 29}
 30type bashTool struct {
 31	permissions permission.Service
 32}
 33
 34const (
 35	BashToolName = "bash"
 36
 37	DefaultTimeout  = 1 * 60 * 1000  // 1 minutes in milliseconds
 38	MaxTimeout      = 10 * 60 * 1000 // 10 minutes in milliseconds
 39	MaxOutputLength = 30000
 40	BashNoOutput    = "no output"
 41)
 42
 43var bannedCommands = []string{
 44	"alias", "curl", "curlie", "wget", "axel", "aria2c",
 45	"nc", "telnet", "lynx", "w3m", "links", "httpie", "xh",
 46	"http-prompt", "chrome", "firefox", "safari",
 47}
 48
 49// getSafeReadOnlyCommands returns platform-appropriate safe commands
 50func getSafeReadOnlyCommands() []string {
 51	// Base commands that work on all platforms
 52	baseCommands := []string{
 53		// Cross-platform commands
 54		"echo", "hostname", "whoami",
 55		
 56		// Git commands (cross-platform)
 57		"git status", "git log", "git diff", "git show", "git branch", "git tag", "git remote", "git ls-files", "git ls-remote",
 58		"git rev-parse", "git config --get", "git config --list", "git describe", "git blame", "git grep", "git shortlog",
 59
 60		// Go commands (cross-platform)
 61		"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",
 62	}
 63
 64	if runtime.GOOS == "windows" {
 65		// Windows-specific commands
 66		windowsCommands := []string{
 67			"dir", "type", "where", "ver", "systeminfo", "tasklist", "ipconfig", "ping", "nslookup",
 68			"Get-Process", "Get-Location", "Get-ChildItem", "Get-Content", "Get-Date", "Get-Host", "Get-ComputerInfo",
 69		}
 70		return append(baseCommands, windowsCommands...)
 71	} else {
 72		// Unix/Linux commands (including WSL, since WSL reports as Linux)
 73		unixCommands := []string{
 74			"ls", "pwd", "date", "cal", "uptime", "id", "groups", "env", "printenv", "set", "unset", "which", "type", "whereis",
 75			"whatis", "uname", "df", "du", "free", "top", "ps", "kill", "killall", "nice", "nohup", "time", "timeout",
 76		}
 77		return append(baseCommands, unixCommands...)
 78	}
 79}
 80
 81func bashDescription() string {
 82	bannedCommandsStr := strings.Join(bannedCommands, ", ")
 83	return fmt.Sprintf(`Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
 84
 85CROSS-PLATFORM SHELL SUPPORT:
 86- Unix/Linux/macOS: Uses native bash/sh shell
 87- Windows: Intelligent shell selection:
 88  * Windows commands (dir, type, copy, etc.) use cmd.exe
 89  * PowerShell commands (Get-, Set-, etc.) use PowerShell
 90  * Unix-style commands (ls, cat, etc.) use POSIX emulation
 91- WSL: Automatically treated as Linux (which is correct)
 92- Automatic detection: Chooses the best shell based on command and platform
 93- Persistent state: Working directory and environment variables persist between commands
 94
 95WINDOWS-SPECIFIC FEATURES:
 96- Native Windows commands: dir, type, copy, move, del, md, rd, cls, where, tasklist, etc.
 97- PowerShell support: Get-Process, Set-Location, and other PowerShell cmdlets
 98- Windows path handling: Supports both forward slashes (/) and backslashes (\)
 99- Drive letters: Properly handles C:\, D:\, etc.
100- Environment variables: Supports both Unix ($VAR) and Windows (%%VAR%%) syntax
101
102Before executing the command, please follow these steps:
103
1041. Directory Verification:
105 - 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
106 - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
107
1082. Security Check:
109 - 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.
110 - Verify that the command is not one of the banned commands: %s.
111
1123. Command Execution:
113 - After ensuring proper quoting, execute the command.
114 - Capture the output of the command.
115
1164. Output Processing:
117 - If the output exceeds %d characters, output will be truncated before being returned to you.
118 - Prepare the output for display to the user.
119
1205. Return Result:
121 - Provide the processed output of the command.
122 - If any errors occurred during execution, include those in the output.
123
124Usage notes:
125- The command argument is required.
126- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
127- 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.
128- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
129- 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.
130- 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.
131<good-example>
132pytest /foo/bar/tests
133</good-example>
134<bad-example>
135cd /foo/bar && pytest tests
136</bad-example>
137
138# Committing changes with git
139
140When the user asks you to create a new git commit, follow these steps carefully:
141
1421. 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!):
143 - Run a git status command to see all untracked files.
144 - Run a git diff command to see both staged and unstaged changes that will be committed.
145 - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
146
1472. 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.
148
1493. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
150
151<commit_analysis>
152- List the files that have been changed or added
153- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
154- Brainstorm the purpose or motivation behind these changes
155- Do not use tools to explore code, beyond what is available in the git context
156- Assess the impact of these changes on the overall project
157- Check for any sensitive information that shouldn't be committed
158- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
159- Ensure your language is clear, concise, and to the point
160- 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.)
161- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
162- Review the draft message to ensure it accurately reflects the changes and their purpose
163</commit_analysis>
164
1654. Create the commit with a message ending with:
166💘 Generated with Crush
167Co-Authored-By: Crush <noreply@crush.charm.land>
168
169- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
170<example>
171git commit -m "$(cat <<'EOF'
172 Commit message here.
173
174 💘 Generated with Crush
175 Co-Authored-By: 💘 Crush <noreply@crush.charm.land>
176 EOF
177 )"
178</example>
179
1805. 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.
181
1826. Finally, run git status to make sure the commit succeeded.
183
184Important notes:
185- When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
186- 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.
187- NEVER update the git config
188- DO NOT push to the remote repository
189- 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.
190- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
191- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
192- Return an empty response - the user will see the git output directly
193
194# Creating pull requests
195Use 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.
196
197IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
198
1991. 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!):
200 - Run a git status command to see all untracked files.
201 - Run a git diff command to see both staged and unstaged changes that will be committed.
202 - 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
203 - 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.)
204
2052. Create new branch if needed
206
2073. Commit changes if needed
208
2094. Push to remote with -u flag if needed
210
2115. 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:
212
213<pr_analysis>
214- List the commits since diverging from the main branch
215- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
216- Brainstorm the purpose or motivation behind these changes
217- Assess the impact of these changes on the overall project
218- Do not use tools to explore code, beyond what is available in the git context
219- Check for any sensitive information that shouldn't be committed
220- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
221- Ensure the summary accurately reflects all changes since diverging from the main branch
222- Ensure your language is clear, concise, and to the point
223- 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.)
224- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
225- Review the draft summary to ensure it accurately reflects the changes and their purpose
226</pr_analysis>
227
2286. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
229<example>
230gh pr create --title "the pr title" --body "$(cat <<'EOF'
231## Summary
232<1-3 bullet points>
233
234## Test plan
235[Checklist of TODOs for testing the pull request...]
236
237💘 Generated with Crush
238EOF
239)"
240</example>
241
242Important:
243- Return an empty response - the user will see the gh output directly
244- Never update git config`, bannedCommandsStr, MaxOutputLength)
245}
246
247func NewBashTool(permission permission.Service) BaseTool {
248	return &bashTool{
249		permissions: permission,
250	}
251}
252
253func (b *bashTool) Info() ToolInfo {
254	return ToolInfo{
255		Name:        BashToolName,
256		Description: bashDescription(),
257		Parameters: map[string]any{
258			"command": map[string]any{
259				"type":        "string",
260				"description": "The command to execute",
261			},
262			"timeout": map[string]any{
263				"type":        "number",
264				"description": "Optional timeout in milliseconds (max 600000)",
265			},
266		},
267		Required: []string{"command"},
268	}
269}
270
271func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
272	var params BashParams
273	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
274		return NewTextErrorResponse("invalid parameters"), nil
275	}
276
277	if params.Timeout > MaxTimeout {
278		params.Timeout = MaxTimeout
279	} else if params.Timeout <= 0 {
280		params.Timeout = DefaultTimeout
281	}
282
283	if params.Command == "" {
284		return NewTextErrorResponse("missing command"), nil
285	}
286
287	baseCmd := strings.Fields(params.Command)[0]
288	for _, banned := range bannedCommands {
289		if strings.EqualFold(baseCmd, banned) {
290			return NewTextErrorResponse(fmt.Sprintf("command '%s' is not allowed", baseCmd)), nil
291		}
292	}
293
294	isSafeReadOnly := false
295	cmdLower := strings.ToLower(params.Command)
296
297	// Get platform-appropriate safe commands
298	safeReadOnlyCommands := getSafeReadOnlyCommands()
299	for _, safe := range safeReadOnlyCommands {
300		if strings.HasPrefix(cmdLower, strings.ToLower(safe)) {
301			if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
302				isSafeReadOnly = true
303				break
304			}
305		}
306	}
307
308	sessionID, messageID := GetContextValues(ctx)
309	if sessionID == "" || messageID == "" {
310		return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
311	}
312	if !isSafeReadOnly {
313		p := b.permissions.Request(
314			permission.CreatePermissionRequest{
315				SessionID:   sessionID,
316				Path:        config.WorkingDirectory(),
317				ToolName:    BashToolName,
318				Action:      "execute",
319				Description: fmt.Sprintf("Execute command: %s", params.Command),
320				Params: BashPermissionsParams{
321					Command: params.Command,
322				},
323			},
324		)
325		if !p {
326			return ToolResponse{}, permission.ErrorPermissionDenied
327		}
328	}
329	startTime := time.Now()
330	if params.Timeout > 0 {
331		var cancel context.CancelFunc
332		ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
333		defer cancel()
334	}
335	stdout, stderr, err := shell.
336		GetPersistentShell(config.WorkingDirectory()).
337		Exec(ctx, params.Command)
338	interrupted := shell.IsInterrupt(err)
339	exitCode := shell.ExitCode(err)
340	if exitCode == 0 && !interrupted && err != nil {
341		return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
342	}
343
344	stdout = truncateOutput(stdout)
345	stderr = truncateOutput(stderr)
346
347	errorMessage := stderr
348	if interrupted {
349		if errorMessage != "" {
350			errorMessage += "\n"
351		}
352		errorMessage += "Command was aborted before completion"
353	} else if exitCode != 0 {
354		if errorMessage != "" {
355			errorMessage += "\n"
356		}
357		errorMessage += fmt.Sprintf("Exit code %d", exitCode)
358	}
359
360	hasBothOutputs := stdout != "" && stderr != ""
361
362	if hasBothOutputs {
363		stdout += "\n"
364	}
365
366	if errorMessage != "" {
367		stdout += "\n" + errorMessage
368	}
369
370	metadata := BashResponseMetadata{
371		StartTime: startTime.UnixMilli(),
372		EndTime:   time.Now().UnixMilli(),
373	}
374	if stdout == "" {
375		return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
376	}
377	return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
378}
379
380func truncateOutput(content string) string {
381	if len(content) <= MaxOutputLength {
382		return content
383	}
384
385	halfLength := MaxOutputLength / 2
386	start := content[:halfLength]
387	end := content[len(content)-halfLength:]
388
389	truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
390	return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
391}
392
393func countLines(s string) int {
394	if s == "" {
395		return 0
396	}
397	return len(strings.Split(s, "\n"))
398}