1package tools
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log/slog"
8 "strings"
9 "time"
10
11 "github.com/charmbracelet/crush/internal/permission"
12 "github.com/charmbracelet/crush/internal/shell"
13)
14
15type BashParams struct {
16 Command string `json:"command"`
17 Timeout int `json:"timeout"`
18}
19
20type BashPermissionsParams struct {
21 Command string `json:"command"`
22 Timeout int `json:"timeout"`
23}
24
25type BashResponseMetadata struct {
26 StartTime int64 `json:"start_time"`
27 EndTime int64 `json:"end_time"`
28}
29type bashTool struct {
30 permissions permission.Service
31 workingDir string
32}
33
34const (
35 BashToolName = "bash"
36
37 DefaultTimeout = 1 * 60 * 1000 // 1 minutes in milliseconds
38 MaxTimeout = 10 * 60 * 1000 // 10 minutes in milliseconds
39 MaxOutputLength = 30000
40 BashNoOutput = "no output"
41)
42
43var bannedCommands = []string{
44 // Network/Download tools
45 "alias",
46 "aria2c",
47 "axel",
48 "chrome",
49 "curl",
50 "curlie",
51 "firefox",
52 "http-prompt",
53 "httpie",
54 "links",
55 "lynx",
56 "nc",
57 "safari",
58 "scp",
59 "ssh",
60 "telnet",
61 "w3m",
62 "wget",
63 "xh",
64
65 // System administration
66 "doas",
67 "su",
68 "sudo",
69
70 // Package managers
71 "apk",
72 "apt",
73 "apt-cache",
74 "apt-get",
75 "dnf",
76 "dpkg",
77 "emerge",
78 "home-manager",
79 "makepkg",
80 "opkg",
81 "pacman",
82 "paru",
83 "pkg",
84 "pkg_add",
85 "pkg_delete",
86 "portage",
87 "rpm",
88 "yay",
89 "yum",
90 "zypper",
91
92 // System modification
93 "at",
94 "batch",
95 "chkconfig",
96 "crontab",
97 "fdisk",
98 "mkfs",
99 "mount",
100 "parted",
101 "service",
102 "systemctl",
103 "umount",
104
105 // Network configuration
106 "firewall-cmd",
107 "ifconfig",
108 "ip",
109 "iptables",
110 "netstat",
111 "pfctl",
112 "route",
113 "ufw",
114}
115
116func bashDescription() string {
117 bannedCommandsStr := strings.Join(bannedCommands, ", ")
118 return fmt.Sprintf(`Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
119
120CROSS-PLATFORM SHELL SUPPORT:
121* This tool uses a shell interpreter (mvdan/sh) that mimics the Bash language,
122 so you should use Bash syntax in all platforms, including Windows.
123 The most common shell builtins and core utils are available in Windows as
124 well.
125* Make sure to use forward slashes (/) as path separators in commands, even on
126 Windows. Example: "ls C:/foo/bar" instead of "ls C:\foo\bar".
127
128Before executing the command, please follow these steps:
129
1301. Directory Verification:
131 - 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
132 - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory
133
1342. Security Check:
135 - 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.
136 - Verify that the command is not one of the banned commands: %s.
137
1383. Command Execution:
139 - After ensuring proper quoting, execute the command.
140 - Capture the output of the command.
141
1424. Output Processing:
143 - If the output exceeds %d characters, output will be truncated before being returned to you.
144 - Prepare the output for display to the user.
145
1465. Return Result:
147 - Provide the processed output of the command.
148 - If any errors occurred during execution, include those in the output.
149
150Usage notes:
151- The command argument is required.
152- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.
153- 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.
154- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
155- 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.
156- 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.
157<good-example>
158pytest /foo/bar/tests
159</good-example>
160<bad-example>
161cd /foo/bar && pytest tests
162</bad-example>
163
164# Committing changes with git
165
166When the user asks you to create a new git commit, follow these steps carefully:
167
1681. 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!):
169 - Run a git status command to see all untracked files.
170 - Run a git diff command to see both staged and unstaged changes that will be committed.
171 - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
172
1732. 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.
174
1753. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:
176
177<commit_analysis>
178- List the files that have been changed or added
179- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
180- Brainstorm the purpose or motivation behind these changes
181- Do not use tools to explore code, beyond what is available in the git context
182- Assess the impact of these changes on the overall project
183- Check for any sensitive information that shouldn't be committed
184- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
185- Ensure your language is clear, concise, and to the point
186- 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.)
187- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
188- Review the draft message to ensure it accurately reflects the changes and their purpose
189</commit_analysis>
190
1914. Create the commit with a message ending with:
192💘 Generated with Crush
193Co-Authored-By: Crush <crush@charm.land>
194
195- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
196<example>
197git commit -m "$(cat <<'EOF'
198 Commit message here.
199
200 💘 Generated with Crush
201 Co-Authored-By: 💘 Crush <crush@charm.land>
202 EOF
203 )"
204</example>
205
2065. 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.
207
2086. Finally, run git status to make sure the commit succeeded.
209
210Important notes:
211- When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up
212- 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.
213- NEVER update the git config
214- DO NOT push to the remote repository
215- 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.
216- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
217- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
218- Return an empty response - the user will see the git output directly
219
220# Creating pull requests
221Use 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.
222
223IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
224
2251. 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!):
226 - Run a git status command to see all untracked files.
227 - Run a git diff command to see both staged and unstaged changes that will be committed.
228 - 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
229 - 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.)
230
2312. Create new branch if needed
232
2333. Commit changes if needed
234
2354. Push to remote with -u flag if needed
236
2375. 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:
238
239<pr_analysis>
240- List the commits since diverging from the main branch
241- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
242- Brainstorm the purpose or motivation behind these changes
243- Assess the impact of these changes on the overall project
244- Do not use tools to explore code, beyond what is available in the git context
245- Check for any sensitive information that shouldn't be committed
246- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
247- Ensure the summary accurately reflects all changes since diverging from the main branch
248- Ensure your language is clear, concise, and to the point
249- 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.)
250- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
251- Review the draft summary to ensure it accurately reflects the changes and their purpose
252</pr_analysis>
253
2546. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
255<example>
256gh pr create --title "the pr title" --body "$(cat <<'EOF'
257## Summary
258<1-3 bullet points>
259
260## Test plan
261[Checklist of TODOs for testing the pull request...]
262
263💘 Generated with Crush
264EOF
265)"
266</example>
267
268Important:
269- Return an empty response - the user will see the gh output directly
270- Never update git config`, bannedCommandsStr, MaxOutputLength)
271}
272
273func blockFuncs() []shell.BlockFunc {
274 return []shell.BlockFunc{
275 shell.CommandsBlocker(bannedCommands),
276 shell.ArgumentsBlocker([][]string{
277 // System package managers
278 {"apk", "add"},
279 {"apt", "install"},
280 {"apt-get", "install"},
281 {"dnf", "install"},
282 {"emerge"},
283 {"pacman", "-S"},
284 {"pkg", "install"},
285 {"yum", "install"},
286 {"zypper", "install"},
287
288 // Language-specific package managers
289 {"brew", "install"},
290 {"cargo", "install"},
291 {"gem", "install"},
292 {"go", "install"},
293 {"npm", "install", "-g"},
294 {"npm", "install", "--global"},
295 {"pip", "install", "--user"},
296 {"pip3", "install", "--user"},
297 {"pnpm", "add", "-g"},
298 {"pnpm", "add", "--global"},
299 {"yarn", "global", "add"},
300 }),
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), ¶ms); 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 creating a new file")
368 }
369 if !isSafeReadOnly {
370 p := b.permissions.Request(
371 permission.CreatePermissionRequest{
372 SessionID: sessionID,
373 Path: b.workingDir,
374 ToolName: BashToolName,
375 Action: "execute",
376 Description: fmt.Sprintf("Execute command: %s", params.Command),
377 Params: BashPermissionsParams{
378 Command: params.Command,
379 },
380 },
381 )
382 if !p {
383 return ToolResponse{}, permission.ErrorPermissionDenied
384 }
385 }
386 startTime := time.Now()
387 if params.Timeout > 0 {
388 var cancel context.CancelFunc
389 ctx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Millisecond)
390 defer cancel()
391 }
392 stdout, stderr, err := shell.
393 GetPersistentShell(b.workingDir).
394 Exec(ctx, params.Command)
395 interrupted := shell.IsInterrupt(err)
396 exitCode := shell.ExitCode(err)
397 if exitCode == 0 && !interrupted && err != nil {
398 return ToolResponse{}, fmt.Errorf("error executing command: %w", err)
399 }
400
401 stdout = truncateOutput(stdout)
402 stderr = truncateOutput(stderr)
403
404 slog.Info("Bash command executed",
405 "command", params.Command,
406 "stdout", stdout,
407 "stderr", stderr,
408 "exit_code", exitCode,
409 "interrupted", interrupted,
410 "err", err,
411 )
412
413 errorMessage := stderr
414 if errorMessage == "" && err != nil {
415 errorMessage = err.Error()
416 }
417
418 if interrupted {
419 if errorMessage != "" {
420 errorMessage += "\n"
421 }
422 errorMessage += "Command was aborted before completion"
423 } else if exitCode != 0 {
424 if errorMessage != "" {
425 errorMessage += "\n"
426 }
427 errorMessage += fmt.Sprintf("Exit code %d", exitCode)
428 }
429
430 hasBothOutputs := stdout != "" && stderr != ""
431
432 if hasBothOutputs {
433 stdout += "\n"
434 }
435
436 if errorMessage != "" {
437 stdout += "\n" + errorMessage
438 }
439
440 metadata := BashResponseMetadata{
441 StartTime: startTime.UnixMilli(),
442 EndTime: time.Now().UnixMilli(),
443 }
444 if stdout == "" {
445 return WithResponseMetadata(NewTextResponse(BashNoOutput), metadata), nil
446 }
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}