bash.go

  1package tools
  2
  3import (
  4	"context"
  5	"fmt"
  6	"strings"
  7	"time"
  8
  9	"github.com/charmbracelet/crush/internal/ai"
 10	"github.com/charmbracelet/crush/internal/permission"
 11	"github.com/charmbracelet/crush/internal/shell"
 12)
 13
 14type BashParams struct {
 15	Command string `json:"command" description:"The command to execute"`
 16	Timeout int    `json:"timeout,omitempty" description:"Optional timeout in milliseconds (max 600000)"`
 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}
 30
 31const (
 32	BashToolName   = "bash"
 33	DefaultTimeout = 1 * 60 * 1000  // 1 minutes in milliseconds
 34	MaxTimeout     = 10 * 60 * 1000 // 10 minutes in milliseconds
 35	BashNoOutput   = "no output"
 36)
 37
 38func NewBashTool(permissions permission.Service, workingDir string) ai.AgentTool {
 39	// Set up command blocking on the persistent shell
 40	persistentShell := shell.GetPersistentShell(workingDir)
 41	persistentShell.SetBlockFuncs(blockFuncs())
 42	return ai.NewTypedToolFunc(
 43		BashToolName,
 44		bashDescription(),
 45		func(ctx context.Context, params BashParams, call ai.ToolCall) (ai.ToolResponse, error) {
 46			if params.Timeout > MaxTimeout {
 47				params.Timeout = MaxTimeout
 48			} else if params.Timeout <= 0 {
 49				params.Timeout = DefaultTimeout
 50			}
 51
 52			if params.Command == "" {
 53				return ai.NewTextErrorResponse("missing command"), nil
 54			}
 55
 56			isSafeReadOnly := false
 57			cmdLower := strings.ToLower(params.Command)
 58
 59			for _, safe := range safeCommands {
 60				if strings.HasPrefix(cmdLower, safe) {
 61					if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
 62						isSafeReadOnly = true
 63						break
 64					}
 65				}
 66			}
 67
 68			sessionID, messageID := GetContextValues(ctx)
 69			if sessionID == "" || messageID == "" {
 70				return ai.ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a new file")
 71			}
 72			if !isSafeReadOnly {
 73				granted := permissions.Request(
 74					permission.CreatePermissionRequest{
 75						SessionID:   sessionID,
 76						Path:        workingDir,
 77						ToolCallID:  call.ID,
 78						ToolName:    BashToolName,
 79						Action:      "execute",
 80						Description: fmt.Sprintf("Execute command: %s", params.Command),
 81						Params: BashPermissionsParams{
 82							Command: params.Command,
 83						},
 84					},
 85				)
 86				if !granted {
 87					return ai.ToolResponse{}, permission.ErrorPermissionDenied
 88				}
 89			}
 90
 91			startTime := time.Now()
 92			if params.Timeout > 0 {
 93				var cancel context.CancelFunc
 94				ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
 95				defer cancel()
 96			}
 97
 98			persistentShell := shell.GetPersistentShell(workingDir)
 99			stdout, stderr, err := persistentShell.Exec(ctx, params.Command)
100
101			// Get the current working directory after command execution
102			currentWorkingDir := persistentShell.GetWorkingDir()
103			interrupted := shell.IsInterrupt(err)
104			exitCode := shell.ExitCode(err)
105			if exitCode == 0 && !interrupted && err != nil {
106				return ai.ToolResponse{}, fmt.Errorf("error executing command: %w", err)
107			}
108
109			stdout = truncateOutput(stdout)
110			stderr = truncateOutput(stderr)
111
112			errorMessage := stderr
113			if errorMessage == "" && err != nil {
114				errorMessage = err.Error()
115			}
116
117			if interrupted {
118				if errorMessage != "" {
119					errorMessage += "\n"
120				}
121				errorMessage += "Command was aborted before completion"
122			} else if exitCode != 0 {
123				if errorMessage != "" {
124					errorMessage += "\n"
125				}
126				errorMessage += fmt.Sprintf("Exit code %d", exitCode)
127			}
128
129			hasBothOutputs := stdout != "" && stderr != ""
130
131			if hasBothOutputs {
132				stdout += "\n"
133			}
134
135			if errorMessage != "" {
136				stdout += "\n" + errorMessage
137			}
138
139			metadata := BashResponseMetadata{
140				StartTime:        startTime.UnixMilli(),
141				EndTime:          time.Now().UnixMilli(),
142				Output:           stdout,
143				WorkingDirectory: currentWorkingDir,
144			}
145			if stdout == "" {
146				return ai.WithResponseMetadata(ai.NewTextResponse(BashNoOutput), metadata), nil
147			}
148			stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", currentWorkingDir)
149			return ai.WithResponseMetadata(ai.NewTextResponse(stdout), metadata), nil
150		},
151	)
152}
153
154func blockFuncs() []shell.BlockFunc {
155	return []shell.BlockFunc{
156		shell.CommandsBlocker(bannedCommands),
157		shell.ArgumentsBlocker([][]string{
158			// System package managers
159			{"apk", "add"},
160			{"apt", "install"},
161			{"apt-get", "install"},
162			{"dnf", "install"},
163			{"emerge"},
164			{"pacman", "-S"},
165			{"pkg", "install"},
166			{"yum", "install"},
167			{"zypper", "install"},
168
169			// Language-specific package managers
170			{"brew", "install"},
171			{"cargo", "install"},
172			{"gem", "install"},
173			{"go", "install"},
174			{"npm", "install", "-g"},
175			{"npm", "install", "--global"},
176			{"pip", "install", "--user"},
177			{"pip3", "install", "--user"},
178			{"pnpm", "add", "-g"},
179			{"pnpm", "add", "--global"},
180			{"yarn", "global", "add"},
181		}),
182	}
183}
184
185func bashDescription() string {
186	bannedCommandsStr := strings.Join(bannedCommands, ", ")
187	return fmt.Sprintf(`Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
188
189CROSS-PLATFORM SHELL SUPPORT:
190* This tool uses a shell interpreter (mvdan/sh) that mimics the Bash language,
191  so you should use Bash syntax in all platforms, including Windows.
192  The most common shell builtins and core utils are available in Windows as
193  well.
194* Make sure to use forward slashes (/) as path separators in commands, even on
195  Windows. Example: "ls C:/foo/bar" instead of "ls C:\foo\bar".
196
197Before executing the command, please follow these steps:
198
1991. Directory Verification:
200 - 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
201 - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
202
2032. Security Check:
204 - 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.
205 - Verify that the command is not one of the banned commands: %s.
206
2073. Command Execution:
208 - After ensuring proper quoting, execute the command.
209 - Capture the output of the command.
210
2114. Output Processing:
212 - If the output exceeds %d characters, output will be truncated before being returned to you.
213 - Prepare the output for display to the user.
214
2155. Return Result:
216 - Provide the processed output of the command.
217 - If any errors occurred during execution, include those in the output.
218 - The result will also have metadata like the cwd (current working directory) at the end, included with <cwd></cwd> tags.
219
220Usage notes:
221- The command argument is required.
222- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
223- 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.
224- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
225- 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.
226- 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.
227<good-example>
228pytest /foo/bar/tests
229</good-example>
230<bad-example>
231cd /foo/bar && pytest tests
232</bad-example>
233
234# Committing changes with git
235
236When the user asks you to create a new git commit, follow these steps carefully:
237
2381. 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!):
239 - Run a git status command to see all untracked files.
240 - Run a git diff command to see both staged and unstaged changes that will be committed.
241 - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
242
2432. 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.
244
2453. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
246
247<commit_analysis>
248- List the files that have been changed or added
249- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
250- Brainstorm the purpose or motivation behind these changes
251- Do not use tools to explore code, beyond what is available in the git context
252- Assess the impact of these changes on the overall project
253- Check for any sensitive information that shouldn't be committed
254- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
255- Ensure your language is clear, concise, and to the point
256- 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.)
257- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
258- Review the draft message to ensure it accurately reflects the changes and their purpose
259</commit_analysis>
260
2614. Create the commit with a message ending with:
262💘 Generated with Crush
263Co-Authored-By: Crush <crush@charm.land>
264
265- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
266<example>
267git commit -m "$(cat <<'EOF'
268 Commit message here.
269
270 💘 Generated with Crush
271 Co-Authored-By: 💘 Crush <crush@charm.land>
272 EOF
273 )"
274</example>
275
2765. 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.
277
2786. Finally, run git status to make sure the commit succeeded.
279
280Important notes:
281- When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
282- 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.
283- NEVER update the git config
284- DO NOT push to the remote repository
285- 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.
286- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
287- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
288- Return an empty response - the user will see the git output directly
289
290# Creating pull requests
291Use 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.
292
293IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
294
2951. 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!):
296 - Run a git status command to see all untracked files.
297 - Run a git diff command to see both staged and unstaged changes that will be committed.
298 - 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
299 - 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.)
300
3012. Create new branch if needed
302
3033. Commit changes if needed
304
3054. Push to remote with -u flag if needed
306
3075. 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:
308
309<pr_analysis>
310- List the commits since diverging from the main branch
311- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
312- Brainstorm the purpose or motivation behind these changes
313- Assess the impact of these changes on the overall project
314- Do not use tools to explore code, beyond what is available in the git context
315- Check for any sensitive information that shouldn't be committed
316- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
317- Ensure the summary accurately reflects all changes since diverging from the main branch
318- Ensure your language is clear, concise, and to the point
319- 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.)
320- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
321- Review the draft summary to ensure it accurately reflects the changes and their purpose
322</pr_analysis>
323
3246. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
325<example>
326gh pr create --title "the pr title" --body "$(cat <<'EOF'
327## Summary
328<1-3 bullet points>
329
330## Test plan
331[Checklist of TODOs for testing the pull request...]
332
333💘 Generated with Crush
334EOF
335)"
336</example>
337
338Important:
339- Return an empty response - the user will see the gh output directly
340- Never update git config`, bannedCommandsStr, MaxOutputLength)
341}