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/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}
 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) Name() string {
254	return BashToolName
255}
256
257func (b *bashTool) Info() ToolInfo {
258	return ToolInfo{
259		Name:        BashToolName,
260		Description: bashDescription(),
261		Parameters: map[string]any{
262			"command": map[string]any{
263				"type":        "string",
264				"description": "The command to execute",
265			},
266			"timeout": map[string]any{
267				"type":        "number",
268				"description": "Optional timeout in milliseconds (max 600000)",
269			},
270		},
271		Required: []string{"command"},
272	}
273}
274
275func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
276	var params BashParams
277	if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
278		return NewTextErrorResponse("invalid parameters"), nil
279	}
280
281	if params.Timeout > MaxTimeout {
282		params.Timeout = MaxTimeout
283	} else if params.Timeout <= 0 {
284		params.Timeout = DefaultTimeout
285	}
286
287	if params.Command == "" {
288		return NewTextErrorResponse("missing command"), nil
289	}
290
291	baseCmd := strings.Fields(params.Command)[0]
292	for _, banned := range bannedCommands {
293		if strings.EqualFold(baseCmd, banned) {
294			return NewTextErrorResponse(fmt.Sprintf("command '%s' is not allowed", baseCmd)), nil
295		}
296	}
297
298	isSafeReadOnly := false
299	cmdLower := strings.ToLower(params.Command)
300
301	// Get platform-appropriate safe commands
302	safeReadOnlyCommands := getSafeReadOnlyCommands()
303	for _, safe := range safeReadOnlyCommands {
304		if strings.HasPrefix(cmdLower, strings.ToLower(safe)) {
305			if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
306				isSafeReadOnly = true
307				break
308			}
309		}
310	}
311
312	sessionID, messageID := GetContextValues(ctx)
313	if sessionID == "" || messageID == "" {
314		return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
315	}
316	if !isSafeReadOnly {
317		p := b.permissions.Request(
318			permission.CreatePermissionRequest{
319				SessionID:   sessionID,
320				Path:        config.Get().WorkingDir(),
321				ToolName:    BashToolName,
322				Action:      "execute",
323				Description: fmt.Sprintf("Execute command: %s", params.Command),
324				Params: BashPermissionsParams{
325					Command: params.Command,
326				},
327			},
328		)
329		if !p {
330			return ToolResponse{}, permission.ErrorPermissionDenied
331		}
332	}
333	startTime := time.Now()
334	if params.Timeout > 0 {
335		var cancel context.CancelFunc
336		ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
337		defer cancel()
338	}
339	stdout, stderr, err := shell.
340		GetPersistentShell(config.Get().WorkingDir()).
341		Exec(ctx, params.Command)
342	interrupted := shell.IsInterrupt(err)
343	exitCode := shell.ExitCode(err)
344	if exitCode == 0 && !interrupted && err != nil {
345		return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
346	}
347
348	stdout = truncateOutput(stdout)
349	stderr = truncateOutput(stderr)
350
351	errorMessage := stderr
352	if interrupted {
353		if errorMessage != "" {
354			errorMessage += "\n"
355		}
356		errorMessage += "Command was aborted before completion"
357	} else if exitCode != 0 {
358		if errorMessage != "" {
359			errorMessage += "\n"
360		}
361		errorMessage += fmt.Sprintf("Exit code %d", exitCode)
362	}
363
364	hasBothOutputs := stdout != "" && stderr != ""
365
366	if hasBothOutputs {
367		stdout += "\n"
368	}
369
370	if errorMessage != "" {
371		stdout += "\n" + errorMessage
372	}
373
374	metadata := BashResponseMetadata{
375		StartTime: startTime.UnixMilli(),
376		EndTime:   time.Now().UnixMilli(),
377	}
378	if stdout == "" {
379		return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
380	}
381	return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
382}
383
384func truncateOutput(content string) string {
385	if len(content) <= MaxOutputLength {
386		return content
387	}
388
389	halfLength := MaxOutputLength / 2
390	start := content[:halfLength]
391	end := content[len(content)-halfLength:]
392
393	truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
394	return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
395}
396
397func countLines(s string) int {
398	if s == "" {
399		return 0
400	}
401	return len(strings.Split(s, "\n"))
402}