bash.go

  1package tools
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"strings"
  8	"time"
  9
 10	"github.com/charmbracelet/crush/internal/permission"
 11	"github.com/charmbracelet/crush/internal/shell"
 12)
 13
 14type BashParams struct {
 15	Command string `json:"command"`
 16	Timeout int    `json:"timeout"`
 17}
 18
 19type BashPermissionsParams struct {
 20	Command string `json:"command"`
 21	Timeout int    `json:"timeout"`
 22}
 23
 24type BashResponseMetadata struct {
 25	StartTime        int64  `json:"start_time"`
 26	EndTime          int64  `json:"end_time"`
 27	Output           string `json:"output"`
 28	WorkingDirectory string `json:"working_directory"`
 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	"scp",
 60	"ssh",
 61	"telnet",
 62	"w3m",
 63	"wget",
 64	"xh",
 65
 66	// System administration
 67	"doas",
 68	"su",
 69	"sudo",
 70
 71	// Package managers
 72	"apk",
 73	"apt",
 74	"apt-cache",
 75	"apt-get",
 76	"dnf",
 77	"dpkg",
 78	"emerge",
 79	"home-manager",
 80	"makepkg",
 81	"opkg",
 82	"pacman",
 83	"paru",
 84	"pkg",
 85	"pkg_add",
 86	"pkg_delete",
 87	"portage",
 88	"rpm",
 89	"yay",
 90	"yum",
 91	"zypper",
 92
 93	// System modification
 94	"at",
 95	"batch",
 96	"chkconfig",
 97	"crontab",
 98	"fdisk",
 99	"mkfs",
100	"mount",
101	"parted",
102	"service",
103	"systemctl",
104	"umount",
105
106	// Network configuration
107	"firewall-cmd",
108	"ifconfig",
109	"ip",
110	"iptables",
111	"netstat",
112	"pfctl",
113	"route",
114	"ufw",
115}
116
117func bashDescription() string {
118	bannedCommandsStr := strings.Join(bannedCommands, ", ")
119	return fmt.Sprintf(`Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
120
121CROSS-PLATFORM SHELL SUPPORT:
122* This tool uses a shell interpreter (mvdan/sh) that mimics the Bash language,
123  so you should use Bash syntax in all platforms, including Windows.
124  The most common shell builtins and core utils are available in Windows as
125  well.
126* Make sure to use forward slashes (/) as path separators in commands, even on
127  Windows. Example: "ls C:/foo/bar" instead of "ls C:\foo\bar".
128
129Before executing the command, please follow these steps:
130
1311. Directory Verification:
132 - 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
133 - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
134
1352. Security Check:
136 - 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.
137 - Verify that the command is not one of the banned commands: %s.
138
1393. Command Execution:
140 - After ensuring proper quoting, execute the command.
141 - Capture the output of the command.
142
1434. Output Processing:
144 - If the output exceeds %d characters, output will be truncated before being returned to you.
145 - Prepare the output for display to the user.
146
1475. Return Result:
148 - Provide the processed output of the command.
149 - If any errors occurred during execution, include those in the output.
150 - The result will also have metadata like the cwd (current working directory) at the end, included with <cwd></cwd> tags.
151
152Usage notes:
153- The command argument is required.
154- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
155- 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.
156- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
157- 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.
158- 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.
159<good-example>
160pytest /foo/bar/tests
161</good-example>
162<bad-example>
163cd /foo/bar && pytest tests
164</bad-example>
165
166# Committing changes with git
167
168When the user asks you to create a new git commit, follow these steps carefully:
169
1701. 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!):
171 - Run a git status command to see all untracked files.
172 - Run a git diff command to see both staged and unstaged changes that will be committed.
173 - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
174
1752. 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.
176
1773. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
178
179<commit_analysis>
180- List the files that have been changed or added
181- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
182- Brainstorm the purpose or motivation behind these changes
183- Do not use tools to explore code, beyond what is available in the git context
184- Assess the impact of these changes on the overall project
185- Check for any sensitive information that shouldn't be committed
186- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
187- Ensure your language is clear, concise, and to the point
188- 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.)
189- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
190- Review the draft message to ensure it accurately reflects the changes and their purpose
191</commit_analysis>
192
1934. Create the commit with a message ending with:
194💘 Generated with Crush
195Co-Authored-By: Crush <crush@charm.land>
196
197- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
198<example>
199git commit -m "$(cat <<'EOF'
200 Commit message here.
201
202 💘 Generated with Crush
203 Co-Authored-By: 💘 Crush <crush@charm.land>
204 EOF
205 )"
206</example>
207
2085. 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.
209
2106. Finally, run git status to make sure the commit succeeded.
211
212Important notes:
213- When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
214- 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.
215- NEVER update the git config
216- DO NOT push to the remote repository
217- 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.
218- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
219- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
220- Return an empty response - the user will see the git output directly
221
222# Creating pull requests
223Use 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.
224
225IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
226
2271. 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!):
228 - Run a git status command to see all untracked files.
229 - Run a git diff command to see both staged and unstaged changes that will be committed.
230 - 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
231 - 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.)
232
2332. Create new branch if needed
234
2353. Commit changes if needed
236
2374. Push to remote with -u flag if needed
238
2395. 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:
240
241<pr_analysis>
242- List the commits since diverging from the main branch
243- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
244- Brainstorm the purpose or motivation behind these changes
245- Assess the impact of these changes on the overall project
246- Do not use tools to explore code, beyond what is available in the git context
247- Check for any sensitive information that shouldn't be committed
248- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
249- Ensure the summary accurately reflects all changes since diverging from the main branch
250- Ensure your language is clear, concise, and to the point
251- 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.)
252- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
253- Review the draft summary to ensure it accurately reflects the changes and their purpose
254</pr_analysis>
255
2566. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
257<example>
258gh pr create --title "the pr title" --body "$(cat <<'EOF'
259## Summary
260<1-3 bullet points>
261
262## Test plan
263[Checklist of TODOs for testing the pull request...]
264
265💘 Generated with Crush
266EOF
267)"
268</example>
269
270Important:
271- Return an empty response - the user will see the gh output directly
272- Never update git config`, bannedCommandsStr, MaxOutputLength)
273}
274
275func blockFuncs() []shell.BlockFunc {
276	return []shell.BlockFunc{
277		shell.CommandsBlocker(bannedCommands),
278		shell.ArgumentsBlocker([][]string{
279			// System package managers
280			{"apk", "add"},
281			{"apt", "install"},
282			{"apt-get", "install"},
283			{"dnf", "install"},
284			{"emerge"},
285			{"pacman", "-S"},
286			{"pkg", "install"},
287			{"yum", "install"},
288			{"zypper", "install"},
289
290			// Language-specific package managers
291			{"brew", "install"},
292			{"cargo", "install"},
293			{"gem", "install"},
294			{"go", "install"},
295			{"npm", "install", "-g"},
296			{"npm", "install", "--global"},
297			{"pip", "install", "--user"},
298			{"pip3", "install", "--user"},
299			{"pnpm", "add", "-g"},
300			{"pnpm", "add", "--global"},
301			{"yarn", "global", "add"},
302		}),
303	}
304}
305
306func NewBashTool(permission permission.Service, workingDir string) BaseTool {
307	// Set up command blocking on the persistent shell
308	persistentShell := shell.GetPersistentShell(workingDir)
309	persistentShell.SetBlockFuncs(blockFuncs())
310
311	return &bashTool{
312		permissions: permission,
313		workingDir:  workingDir,
314	}
315}
316
317func (b *bashTool) Name() string {
318	return BashToolName
319}
320
321func (b *bashTool) Info() ToolInfo {
322	return ToolInfo{
323		Name:        BashToolName,
324		Description: bashDescription(),
325		Parameters: map[string]any{
326			"command": map[string]any{
327				"type":        "string",
328				"description": "The command to execute",
329			},
330			"timeout": map[string]any{
331				"type":        "number",
332				"description": "Optional timeout in milliseconds (max 600000)",
333			},
334		},
335		Required: []string{"command"},
336	}
337}
338
339func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
340	var params BashParams
341	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
342		return NewTextErrorResponse("invalid parameters"), nil
343	}
344
345	if params.Timeout > MaxTimeout {
346		params.Timeout = MaxTimeout
347	} else if params.Timeout <= 0 {
348		params.Timeout = DefaultTimeout
349	}
350
351	if params.Command == "" {
352		return NewTextErrorResponse("missing command"), nil
353	}
354
355	isSafeReadOnly := false
356	cmdLower := strings.ToLower(params.Command)
357
358	for _, safe := range safeCommands {
359		if strings.HasPrefix(cmdLower, safe) {
360			if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
361				isSafeReadOnly = true
362				break
363			}
364		}
365	}
366
367	sessionID, messageID := GetContextValues(ctx)
368	if sessionID == "" || messageID == "" {
369		return ToolResponse{}, fmt.Errorf("session ID and message ID are required for executing shell command")
370	}
371	if !isSafeReadOnly {
372		p := b.permissions.Request(
373			permission.CreatePermissionRequest{
374				SessionID:   sessionID,
375				Path:        b.workingDir,
376				ToolCallID:  call.ID,
377				ToolName:    BashToolName,
378				Action:      "execute",
379				Description: fmt.Sprintf("Execute command: %s", params.Command),
380				Params: BashPermissionsParams{
381					Command: params.Command,
382				},
383			},
384		)
385		if !p {
386			return ToolResponse{}, permission.ErrorPermissionDenied
387		}
388	}
389	startTime := time.Now()
390	if params.Timeout > 0 {
391		var cancel context.CancelFunc
392		ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
393		defer cancel()
394	}
395
396	persistentShell := shell.GetPersistentShell(b.workingDir)
397	stdout, stderr, err := persistentShell.Exec(ctx, params.Command)
398
399	// Get the current working directory after command execution
400	currentWorkingDir := persistentShell.GetWorkingDir()
401	interrupted := shell.IsInterrupt(err)
402	exitCode := shell.ExitCode(err)
403	if exitCode == 0 && !interrupted && err != nil {
404		return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
405	}
406
407	stdout = truncateOutput(stdout)
408	stderr = truncateOutput(stderr)
409
410	errorMessage := stderr
411	if errorMessage == "" && err != nil {
412		errorMessage = err.Error()
413	}
414
415	if interrupted {
416		if errorMessage != "" {
417			errorMessage += "\n"
418		}
419		errorMessage += "Command was aborted before completion"
420	} else if exitCode != 0 {
421		if errorMessage != "" {
422			errorMessage += "\n"
423		}
424		errorMessage += fmt.Sprintf("Exit code %d", exitCode)
425	}
426
427	hasBothOutputs := stdout != "" && stderr != ""
428
429	if hasBothOutputs {
430		stdout += "\n"
431	}
432
433	if errorMessage != "" {
434		stdout += "\n" + errorMessage
435	}
436
437	metadata := BashResponseMetadata{
438		StartTime:        startTime.UnixMilli(),
439		EndTime:          time.Now().UnixMilli(),
440		Output:           stdout,
441		WorkingDirectory: currentWorkingDir,
442	}
443	if stdout == "" {
444		return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
445	}
446	stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", currentWorkingDir)
447	return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
448}
449
450func truncateOutput(content string) string {
451	if len(content) <= MaxOutputLength {
452		return content
453	}
454
455	halfLength := MaxOutputLength / 2
456	start := content[:halfLength]
457	end := content[len(content)-halfLength:]
458
459	truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
460	return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
461}
462
463func countLines(s string) int {
464	if s == "" {
465		return 0
466	}
467	return len(strings.Split(s, "\n"))
468}