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