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
 62IMPORTANT FOR WINDOWS USERS:
 63- This tool uses a POSIX shell emulator (mvdan.cc/sh/v3) that works cross-platform, including Windows
 64- On Windows, this provides bash-like functionality without requiring WSL or Git Bash
 65- Use forward slashes (/) in paths - they work on all platforms and are converted automatically
 66- Windows-specific commands (like 'dir', 'type', 'copy') are not available - use Unix equivalents ('ls', 'cat', 'cp')
 67- Environment variables use Unix syntax: $VAR instead of %%VAR%%
 68- File paths are automatically converted between Windows and Unix formats as needed
 69
 70Before executing the command, please follow these steps:
 71
 721. Directory Verification:
 73 - 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
 74 - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
 75
 762. Security Check:
 77 - 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.
 78 - Verify that the command is not one of the banned commands: %s.
 79
 803. Command Execution:
 81 - After ensuring proper quoting, execute the command.
 82 - Capture the output of the command.
 83
 844. Output Processing:
 85 - If the output exceeds %d characters, output will be truncated before being returned to you.
 86 - Prepare the output for display to the user.
 87
 885. Return Result:
 89 - Provide the processed output of the command.
 90 - If any errors occurred during execution, include those in the output.
 91
 92Usage notes:
 93- The command argument is required.
 94- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
 95- 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.
 96- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
 97- 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.
 98- 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.
 99<good-example>
100pytest /foo/bar/tests
101</good-example>
102<bad-example>
103cd /foo/bar && pytest tests
104</bad-example>
105
106# Committing changes with git
107
108When the user asks you to create a new git commit, follow these steps carefully:
109
1101. 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!):
111 - Run a git status command to see all untracked files.
112 - Run a git diff command to see both staged and unstaged changes that will be committed.
113 - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
114
1152. 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.
116
1173. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
118
119<commit_analysis>
120- List the files that have been changed or added
121- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
122- Brainstorm the purpose or motivation behind these changes
123- Do not use tools to explore code, beyond what is available in the git context
124- Assess the impact of these changes on the overall project
125- Check for any sensitive information that shouldn't be committed
126- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
127- Ensure your language is clear, concise, and to the point
128- 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.)
129- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
130- Review the draft message to ensure it accurately reflects the changes and their purpose
131</commit_analysis>
132
1334. Create the commit with a message ending with:
134💘 Generated with Crush
135Co-Authored-By: Crush <noreply@crush.charm.land>
136
137- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
138<example>
139git commit -m "$(cat <<'EOF'
140 Commit message here.
141
142 💘 Generated with Crush
143 Co-Authored-By: 💘 Crush <noreply@crush.charm.land>
144 EOF
145 )"
146</example>
147
1485. 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.
149
1506. Finally, run git status to make sure the commit succeeded.
151
152Important notes:
153- When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
154- 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.
155- NEVER update the git config
156- DO NOT push to the remote repository
157- 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.
158- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
159- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
160- Return an empty response - the user will see the git output directly
161
162# Creating pull requests
163Use 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.
164
165IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
166
1671. 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!):
168 - Run a git status command to see all untracked files.
169 - Run a git diff command to see both staged and unstaged changes that will be committed.
170 - 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
171 - 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.)
172
1732. Create new branch if needed
174
1753. Commit changes if needed
176
1774. Push to remote with -u flag if needed
178
1795. 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:
180
181<pr_analysis>
182- List the commits since diverging from the main branch
183- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
184- Brainstorm the purpose or motivation behind these changes
185- Assess the impact of these changes on the overall project
186- Do not use tools to explore code, beyond what is available in the git context
187- Check for any sensitive information that shouldn't be committed
188- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
189- Ensure the summary accurately reflects all changes since diverging from the main branch
190- Ensure your language is clear, concise, and to the point
191- 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.)
192- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
193- Review the draft summary to ensure it accurately reflects the changes and their purpose
194</pr_analysis>
195
1966. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
197<example>
198gh pr create --title "the pr title" --body "$(cat <<'EOF'
199## Summary
200<1-3 bullet points>
201
202## Test plan
203[Checklist of TODOs for testing the pull request...]
204
205💘 Generated with Crush
206EOF
207)"
208</example>
209
210Important:
211- Return an empty response - the user will see the gh output directly
212- Never update git config`, bannedCommandsStr, MaxOutputLength)
213}
214
215func NewBashTool(permission permission.Service) BaseTool {
216	return &bashTool{
217		permissions: permission,
218	}
219}
220
221func (b *bashTool) Info() ToolInfo {
222	return ToolInfo{
223		Name:        BashToolName,
224		Description: bashDescription(),
225		Parameters: map[string]any{
226			"command": map[string]any{
227				"type":        "string",
228				"description": "The command to execute",
229			},
230			"timeout": map[string]any{
231				"type":        "number",
232				"description": "Optional timeout in milliseconds (max 600000)",
233			},
234		},
235		Required: []string{"command"},
236	}
237}
238
239func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
240	var params BashParams
241	if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
242		return NewTextErrorResponse("invalid parameters"), nil
243	}
244
245	if params.Timeout > MaxTimeout {
246		params.Timeout = MaxTimeout
247	} else if params.Timeout <= 0 {
248		params.Timeout = DefaultTimeout
249	}
250
251	if params.Command == "" {
252		return NewTextErrorResponse("missing command"), nil
253	}
254
255	baseCmd := strings.Fields(params.Command)[0]
256	for _, banned := range bannedCommands {
257		if strings.EqualFold(baseCmd, banned) {
258			return NewTextErrorResponse(fmt.Sprintf("command '%s' is not allowed", baseCmd)), nil
259		}
260	}
261
262	isSafeReadOnly := false
263	cmdLower := strings.ToLower(params.Command)
264
265	for _, safe := range safeReadOnlyCommands {
266		if strings.HasPrefix(cmdLower, strings.ToLower(safe)) {
267			if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
268				isSafeReadOnly = true
269				break
270			}
271		}
272	}
273
274	sessionID, messageID := GetContextValues(ctx)
275	if sessionID == "" || messageID == "" {
276		return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
277	}
278	if !isSafeReadOnly {
279		p := b.permissions.Request(
280			permission.CreatePermissionRequest{
281				SessionID:   sessionID,
282				Path:        config.WorkingDirectory(),
283				ToolName:    BashToolName,
284				Action:      "execute",
285				Description: fmt.Sprintf("Execute command: %s", params.Command),
286				Params: BashPermissionsParams{
287					Command: params.Command,
288				},
289			},
290		)
291		if !p {
292			return ToolResponse{}, permission.ErrorPermissionDenied
293		}
294	}
295	startTime := time.Now()
296	if params.Timeout > 0 {
297		var cancel context.CancelFunc
298		ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
299		defer cancel()
300	}
301	stdout, stderr, err := shell.
302		GetPersistentShell(config.WorkingDirectory()).
303		Exec(ctx, params.Command)
304	interrupted := shell.IsInterrupt(err)
305	exitCode := shell.ExitCode(err)
306	if exitCode == 0 && !interrupted && err != nil {
307		return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
308	}
309
310	stdout = truncateOutput(stdout)
311	stderr = truncateOutput(stderr)
312
313	errorMessage := stderr
314	if interrupted {
315		if errorMessage != "" {
316			errorMessage += "\n"
317		}
318		errorMessage += "Command was aborted before completion"
319	} else if exitCode != 0 {
320		if errorMessage != "" {
321			errorMessage += "\n"
322		}
323		errorMessage += fmt.Sprintf("Exit code %d", exitCode)
324	}
325
326	hasBothOutputs := stdout != "" && stderr != ""
327
328	if hasBothOutputs {
329		stdout += "\n"
330	}
331
332	if errorMessage != "" {
333		stdout += "\n" + errorMessage
334	}
335
336	metadata := BashResponseMetadata{
337		StartTime: startTime.UnixMilli(),
338		EndTime:   time.Now().UnixMilli(),
339	}
340	if stdout == "" {
341		return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
342	}
343	return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
344}
345
346func truncateOutput(content string) string {
347	if len(content) <= MaxOutputLength {
348		return content
349	}
350
351	halfLength := MaxOutputLength / 2
352	start := content[:halfLength]
353	end := content[len(content)-halfLength:]
354
355	truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
356	return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
357}
358
359func countLines(s string) int {
360	if s == "" {
361		return 0
362	}
363	return len(strings.Split(s, "\n"))
364}