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