bash.go

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