16 "github.com/charmbracelet/crush/internal/config"
17 "github.com/charmbracelet/crush/internal/fsext"
18 "github.com/charmbracelet/crush/internal/permission"
19 "github.com/charmbracelet/crush/internal/shell"
22type BashParams struct {
23 Description string `json:"description" description:"A brief description of what the command does, try to keep it under 30 characters or so"`
24 Command string `json:"command" description:"The command to execute"`
25 WorkingDir string `json:"working_dir,omitempty" description:"The working directory to execute the command in (defaults to current directory)"`
26 RunInBackground bool `json:"run_in_background,omitempty" description:"Set to true (boolean) to run this command in the background. Use job_output to read the output later."`
27 AutoBackgroundAfter int `json:"auto_background_after,omitempty" description:"Seconds to wait before automatically moving the command to a background job (default: 60)"`
30type BashPermissionsParams struct {
31 Description string `json:"description"`
32 Command string `json:"command"`
33 WorkingDir string `json:"working_dir"`
34 RunInBackground bool `json:"run_in_background"`
35 AutoBackgroundAfter int `json:"auto_background_after"`
38type BashResponseMetadata struct {
39 StartTime int64 `json:"start_time"`
40 EndTime int64 `json:"end_time"`
41 Output string `json:"output"`
42 Description string `json:"description"`
43 WorkingDirectory string `json:"working_directory"`
44 Background bool `json:"background,omitempty"`
45 ShellID string `json:"shell_id,omitempty"`
51 DefaultAutoBackgroundAfter = 60 // Commands taking longer automatically become background jobs
52 MaxOutputLength = 30000
53 BashNoOutput = "no output"
57var bashDescriptionTmpl []byte
59var bashDescriptionTpl = template.Must(
60 template.New("bashDescription").
61 Parse(string(bashDescriptionTmpl)),
64type bashDescriptionData struct {
67 Attribution config.Attribution
71var bannedCommands = []string{
72 // Network/Download tools
93 // System administration
120 // System modification
133 // Network configuration
144func bashDescription(attribution *config.Attribution, modelName string) string {
145 bannedCommandsStr := strings.Join(bannedCommands, ", ")
147 if err := bashDescriptionTpl.Execute(&out, bashDescriptionData{
148 BannedCommands: bannedCommandsStr,
149 MaxOutputLength: MaxOutputLength,
150 Attribution: *attribution,
151 ModelName: modelName,
153 // this should never happen.
154 panic("failed to execute bash description template: " + err.Error())
159func blockFuncs() []shell.BlockFunc {
160 return []shell.BlockFunc{
161 shell.CommandsBlocker(bannedCommands),
163 // System package managers
164 shell.ArgumentsBlocker("apk", []string{"add"}, nil),
165 shell.ArgumentsBlocker("apt", []string{"install"}, nil),
166 shell.ArgumentsBlocker("apt-get", []string{"install"}, nil),
167 shell.ArgumentsBlocker("dnf", []string{"install"}, nil),
168 shell.ArgumentsBlocker("pacman", nil, []string{"-S"}),
169 shell.ArgumentsBlocker("pkg", []string{"install"}, nil),
170 shell.ArgumentsBlocker("yum", []string{"install"}, nil),
171 shell.ArgumentsBlocker("zypper", []string{"install"}, nil),
173 // Language-specific package managers
174 shell.ArgumentsBlocker("brew", []string{"install"}, nil),
175 shell.ArgumentsBlocker("cargo", []string{"install"}, nil),
176 shell.ArgumentsBlocker("gem", []string{"install"}, nil),
177 shell.ArgumentsBlocker("go", []string{"install"}, nil),
178 shell.ArgumentsBlocker("npm", []string{"install"}, []string{"--global"}),
179 shell.ArgumentsBlocker("npm", []string{"install"}, []string{"-g"}),
180 shell.ArgumentsBlocker("pip", []string{"install"}, []string{"--user"}),
181 shell.ArgumentsBlocker("pip3", []string{"install"}, []string{"--user"}),
182 shell.ArgumentsBlocker("pnpm", []string{"add"}, []string{"--global"}),
183 shell.ArgumentsBlocker("pnpm", []string{"add"}, []string{"-g"}),
184 shell.ArgumentsBlocker("yarn", []string{"global", "add"}, nil),
186 // `go test -exec` can run arbitrary commands
187 shell.ArgumentsBlocker("go", []string{"test"}, []string{"-exec"}),
191func NewBashTool(permissions permission.Service, workingDir string, attribution *config.Attribution, modelName string) fantasy.AgentTool {
192 return fantasy.NewAgentTool(
194 string(bashDescription(attribution, modelName)),
195 func(ctx context.Context, params BashParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
196 if params.Command == "" {
197 return fantasy.NewTextErrorResponse("missing command"), nil
200 // Determine working directory
201 execWorkingDir := cmp.Or(params.WorkingDir, workingDir)
203 isSafeReadOnly := false
204 cmdLower := strings.ToLower(params.Command)
206 for _, safe := range safeCommands {
207 if strings.HasPrefix(cmdLower, safe) {
208 if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
209 isSafeReadOnly = true
215 sessionID := GetSessionFromContext(ctx)
217 return fantasy.ToolResponse{}, fmt.Errorf("session ID is required for executing shell command")
220 p, err := permissions.Request(ctx,
221 permission.CreatePermissionRequest{
222 SessionID: sessionID,
223 Path: execWorkingDir,
225 ToolName: BashToolName,
227 Description: fmt.Sprintf("Execute command: %s", params.Command),
228 Params: BashPermissionsParams(params),
232 return fantasy.ToolResponse{}, err
235 return NewPermissionDeniedResponse(), nil
239 // If explicitly requested as background, start immediately with detached context
240 if params.RunInBackground {
241 startTime := time.Now()
242 bgManager := shell.GetBackgroundShellManager()
244 // Use background context so it continues after tool returns
245 bgShell, err := bgManager.Start(context.Background(), execWorkingDir, blockFuncs(), params.Command, params.Description)
247 return fantasy.ToolResponse{}, fmt.Errorf("error starting background shell: %w", err)
250 // Wait a short time to detect fast failures (blocked commands, syntax errors, etc.)
251 time.Sleep(1 * time.Second)
252 stdout, stderr, done, execErr := bgShell.GetOutput()
255 // Command failed or completed very quickly
256 bgManager.Remove(bgShell.ID)
258 interrupted := shell.IsInterrupt(execErr)
259 exitCode := shell.ExitCode(execErr)
260 if exitCode == 0 && !interrupted && execErr != nil {
261 return fantasy.ToolResponse{}, fmt.Errorf("[Job %s] error executing command: %w", bgShell.ID, execErr)
264 stdout = formatOutput(stdout, stderr, execErr)
266 metadata := BashResponseMetadata{
267 StartTime: startTime.UnixMilli(),
268 EndTime: time.Now().UnixMilli(),
270 Description: params.Description,
271 Background: params.RunInBackground,
272 WorkingDirectory: bgShell.WorkingDir,
275 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(BashNoOutput), metadata), nil
277 stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", normalizeWorkingDir(bgShell.WorkingDir))
278 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(stdout), metadata), nil
281 // Still running after fast-failure check - return as background job
282 metadata := BashResponseMetadata{
283 StartTime: startTime.UnixMilli(),
284 EndTime: time.Now().UnixMilli(),
285 Description: params.Description,
286 WorkingDirectory: bgShell.WorkingDir,
290 response := fmt.Sprintf("Background shell started with ID: %s\n\nUse job_output tool to view output or job_kill to terminate.", bgShell.ID)
291 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(response), metadata), nil
294 // Start synchronous execution with auto-background support
295 startTime := time.Now()
297 // Start with detached context so it can survive if moved to background
298 bgManager := shell.GetBackgroundShellManager()
300 bgShell, err := bgManager.Start(context.Background(), execWorkingDir, blockFuncs(), params.Command, params.Description)
302 return fantasy.ToolResponse{}, fmt.Errorf("error starting shell: %w", err)
305 // Wait for either completion, auto-background threshold, or context cancellation
306 ticker := time.NewTicker(100 * time.Millisecond)
309 autoBackgroundAfter := cmp.Or(params.AutoBackgroundAfter, DefaultAutoBackgroundAfter)
310 autoBackgroundThreshold := time.Duration(autoBackgroundAfter) * time.Second
311 timeout := time.After(autoBackgroundThreshold)
313 var stdout, stderr string
321 stdout, stderr, done, execErr = bgShell.GetOutput()
326 stdout, stderr, done, execErr = bgShell.GetOutput()
329 // Incoming context was cancelled before we moved to background
330 // Kill the shell and return error
331 bgManager.Kill(bgShell.ID)
332 return fantasy.ToolResponse{}, ctx.Err()
337 // Command completed within threshold - return synchronously
338 // Remove from background manager since we're returning directly
339 // Don't call Kill() as it cancels the context and corrupts the exit code
340 bgManager.Remove(bgShell.ID)
342 interrupted := shell.IsInterrupt(execErr)
343 exitCode := shell.ExitCode(execErr)
344 if exitCode == 0 && !interrupted && execErr != nil {
345 return fantasy.ToolResponse{}, fmt.Errorf("[Job %s] error executing command: %w", bgShell.ID, execErr)
348 stdout = formatOutput(stdout, stderr, execErr)
350 metadata := BashResponseMetadata{
351 StartTime: startTime.UnixMilli(),
352 EndTime: time.Now().UnixMilli(),
354 Description: params.Description,
355 Background: params.RunInBackground,
356 WorkingDirectory: bgShell.WorkingDir,
359 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(BashNoOutput), metadata), nil
361 stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", normalizeWorkingDir(bgShell.WorkingDir))
362 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(stdout), metadata), nil
365 // Still running - keep as background job
366 metadata := BashResponseMetadata{
367 StartTime: startTime.UnixMilli(),
368 EndTime: time.Now().UnixMilli(),
369 Description: params.Description,
370 WorkingDirectory: bgShell.WorkingDir,
374 response := fmt.Sprintf("Command is taking longer than expected and has been moved to background.\n\nBackground shell ID: %s\n\nUse job_output tool to view output or job_kill to terminate.", bgShell.ID)
375 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(response), metadata), nil
379// formatOutput formats the output of a completed command with error handling
380func formatOutput(stdout, stderr string, execErr error) string {
381 interrupted := shell.IsInterrupt(execErr)
382 exitCode := shell.ExitCode(execErr)
384 stdout = truncateOutput(stdout)
385 stderr = truncateOutput(stderr)
387 errorMessage := stderr
388 if errorMessage == "" && execErr != nil {
389 errorMessage = execErr.Error()
393 if errorMessage != "" {
396 errorMessage += "Command was aborted before completion"
397 } else if exitCode != 0 {
398 if errorMessage != "" {
401 errorMessage += fmt.Sprintf("Exit code %d", exitCode)
404 hasBothOutputs := stdout != "" && stderr != ""
410 if errorMessage != "" {
411 stdout += "\n" + errorMessage
417func truncateOutput(content string) string {
418 if len(content) <= MaxOutputLength {
422 halfLength := MaxOutputLength / 2
423 start := content[:halfLength]
424 end := content[len(content)-halfLength:]
426 truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
427 return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
430func countLines(s string) int {
434 return len(strings.Split(s, "\n"))
437func normalizeWorkingDir(path string) string {
438 if runtime.GOOS == "windows" {
439 path = strings.ReplaceAll(path, fsext.WindowsWorkingDirDrive(), "")
441 return filepath.ToSlash(path)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list