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