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			{"pacman", "-S"},
285			{"pkg", "install"},
286			{"yum", "install"},
287			{"zypper", "install"},
288
289			// Language-specific package managers
290			{"brew", "install"},
291			{"cargo", "install"},
292			{"gem", "install"},
293			{"go", "install"},
294			{"npm", "install", "-g"},
295			{"npm", "install", "--global"},
296			{"pip", "install", "--user"},
297			{"pip3", "install", "--user"},
298			{"pnpm", "add", "-g"},
299			{"pnpm", "add", "--global"},
300			{"yarn", "global", "add"},
301		}),
302	}
303}
304
305func NewBashTool(permission permission.Service, workingDir string) BaseTool {
306	// Set up command blocking on the persistent shell
307	persistentShell := shell.GetPersistentShell(workingDir)
308	persistentShell.SetBlockFuncs(blockFuncs())
309
310	return &bashTool{
311		permissions: permission,
312		workingDir:  workingDir,
313	}
314}
315
316func (b *bashTool) Name() string {
317	return BashToolName
318}
319
320func (b *bashTool) Info() ToolInfo {
321	return ToolInfo{
322		Name:        BashToolName,
323		Description: bashDescription(),
324		Parameters: map[string]any{
325			"command": map[string]any{
326				"type":        "string",
327				"description": "The command to execute",
328			},
329			"timeout": map[string]any{
330				"type":        "number",
331				"description": "Optional timeout in milliseconds (max 600000)",
332			},
333		},
334		Required: []string{"command"},
335	}
336}
337
338func (b *bashTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
339	var params BashParams
340	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
341		return NewTextErrorResponse("invalid parameters"), nil
342	}
343
344	if params.Timeout > MaxTimeout {
345		params.Timeout = MaxTimeout
346	} else if params.Timeout <= 0 {
347		params.Timeout = DefaultTimeout
348	}
349
350	if params.Command == "" {
351		return NewTextErrorResponse("missing command"), nil
352	}
353
354	isSafeReadOnly := false
355	cmdLower := strings.ToLower(params.Command)
356
357	for _, safe := range safeCommands {
358		if strings.HasPrefix(cmdLower, safe) {
359			if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
360				isSafeReadOnly = true
361				break
362			}
363		}
364	}
365
366	sessionID, messageID := GetContextValues(ctx)
367	if sessionID == "" || messageID == "" {
368		return ToolResponse{}, fmt.Errorf("session ID and message ID are required for executing shell command")
369	}
370	if !isSafeReadOnly {
371		p := b.permissions.Request(
372			permission.CreatePermissionRequest{
373				SessionID:   sessionID,
374				Path:        b.workingDir,
375				ToolCallID:  call.ID,
376				ToolName:    BashToolName,
377				Action:      "execute",
378				Description: fmt.Sprintf("Execute command: %s", params.Command),
379				Params: BashPermissionsParams{
380					Command: params.Command,
381				},
382			},
383		)
384		if !p {
385			return ToolResponse{}, permission.ErrorPermissionDenied
386		}
387	}
388	startTime := time.Now()
389	if params.Timeout > 0 {
390		var cancel context.CancelFunc
391		ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
392		defer cancel()
393	}
394
395	persistentShell := shell.GetPersistentShell(b.workingDir)
396	stdout, stderr, err := persistentShell.Exec(ctx, params.Command)
397
398	// Get the current working directory after command execution
399	currentWorkingDir := persistentShell.GetWorkingDir()
400	interrupted := shell.IsInterrupt(err)
401	exitCode := shell.ExitCode(err)
402	if exitCode == 0 && !interrupted && err != nil {
403		return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
404	}
405
406	stdout = truncateOutput(stdout)
407	stderr = truncateOutput(stderr)
408
409	errorMessage := stderr
410	if errorMessage == "" && err != nil {
411		errorMessage = err.Error()
412	}
413
414	if interrupted {
415		if errorMessage != "" {
416			errorMessage += "\n"
417		}
418		errorMessage += "Command was aborted before completion"
419	} else if exitCode != 0 {
420		if errorMessage != "" {
421			errorMessage += "\n"
422		}
423		errorMessage += fmt.Sprintf("Exit code %d", exitCode)
424	}
425
426	hasBothOutputs := stdout != "" && stderr != ""
427
428	if hasBothOutputs {
429		stdout += "\n"
430	}
431
432	if errorMessage != "" {
433		stdout += "\n" + errorMessage
434	}
435
436	metadata := BashResponseMetadata{
437		StartTime:        startTime.UnixMilli(),
438		EndTime:          time.Now().UnixMilli(),
439		Output:           stdout,
440		WorkingDirectory: currentWorkingDir,
441	}
442	if stdout == "" {
443		return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
444	}
445	stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", currentWorkingDir)
446	return WithResponseMetadata(NewTextResponse(stdout), metadata), nil
447}
448
449func truncateOutput(content string) string {
450	if len(content) <= MaxOutputLength {
451		return content
452	}
453
454	halfLength := MaxOutputLength / 2
455	start := content[:halfLength]
456	end := content[len(content)-halfLength:]
457
458	truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
459	return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
460}
461
462func countLines(s string) int {
463	if s == "" {
464		return 0
465	}
466	return len(strings.Split(s, "\n"))
467}