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