bash.go

  1package tools
  2
  3import (
  4	"bytes"
  5	"cmp"
  6	"context"
  7	_ "embed"
  8	"fmt"
  9	"html/template"
 10	"os"
 11	"path/filepath"
 12	"runtime"
 13	"strings"
 14	"time"
 15
 16	"charm.land/fantasy"
 17	"github.com/charmbracelet/crush/internal/config"
 18	"github.com/charmbracelet/crush/internal/permission"
 19	"github.com/charmbracelet/crush/internal/shell"
 20)
 21
 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}
 28
 29type BashPermissionsParams struct {
 30	Description     string `json:"description"`
 31	Command         string `json:"command"`
 32	WorkingDir      string `json:"working_dir"`
 33	RunInBackground bool   `json:"run_in_background"`
 34}
 35
 36type BashResponseMetadata struct {
 37	StartTime        int64  `json:"start_time"`
 38	EndTime          int64  `json:"end_time"`
 39	Output           string `json:"output"`
 40	Description      string `json:"description"`
 41	WorkingDirectory string `json:"working_directory"`
 42	Background       bool   `json:"background,omitempty"`
 43	ShellID          string `json:"shell_id,omitempty"`
 44}
 45
 46const (
 47	BashToolName = "bash"
 48
 49	AutoBackgroundThreshold = 1 * time.Minute // Commands taking longer automatically become background jobs
 50	MaxOutputLength         = 30000
 51	BashNoOutput            = "no output"
 52)
 53
 54//go:embed bash.tpl
 55var bashDescriptionTmpl []byte
 56
 57var bashDescriptionTpl = template.Must(
 58	template.New("bashDescription").
 59		Parse(string(bashDescriptionTmpl)),
 60)
 61
 62type bashDescriptionData struct {
 63	BannedCommands  string
 64	MaxOutputLength int
 65	Attribution     config.Attribution
 66	ModelName       string
 67}
 68
 69var defaultBannedCommands = []string{
 70	// Network/Download tools
 71	"alias",
 72	"aria2c",
 73	"axel",
 74	"chrome",
 75	"curl",
 76	"curlie",
 77	"firefox",
 78	"http-prompt",
 79	"httpie",
 80	"links",
 81	"lynx",
 82	"nc",
 83	"safari",
 84	"scp",
 85	"ssh",
 86	"telnet",
 87	"w3m",
 88	"wget",
 89	"xh",
 90
 91	// System administration
 92	"doas",
 93	"su",
 94	"sudo",
 95
 96	// Package managers
 97	"apk",
 98	"apt",
 99	"apt-cache",
100	"apt-get",
101	"dnf",
102	"dpkg",
103	"emerge",
104	"home-manager",
105	"makepkg",
106	"opkg",
107	"pacman",
108	"paru",
109	"pkg",
110	"pkg_add",
111	"pkg_delete",
112	"portage",
113	"rpm",
114	"yay",
115	"yum",
116	"zypper",
117
118	// System modification
119	"at",
120	"batch",
121	"chkconfig",
122	"crontab",
123	"fdisk",
124	"mkfs",
125	"mount",
126	"parted",
127	"service",
128	"systemctl",
129	"umount",
130
131	// Network configuration
132	"firewall-cmd",
133	"ifconfig",
134	"ip",
135	"iptables",
136	"netstat",
137	"pfctl",
138	"route",
139	"ufw",
140}
141
142func bashDescription(attribution *config.Attribution, modelName string) string {
143	bannedCommandsStr := strings.Join(defaultBannedCommands, ", ")
144	var out bytes.Buffer
145	if err := bashDescriptionTpl.Execute(&out, bashDescriptionData{
146		BannedCommands:  bannedCommandsStr,
147		MaxOutputLength: MaxOutputLength,
148		Attribution:     *attribution,
149		ModelName:       modelName,
150	}); err != nil {
151		// this should never happen.
152		panic("failed to execute bash description template: " + err.Error())
153	}
154	return out.String()
155}
156
157func blockFuncs(bannedCommands []string) []shell.BlockFunc {
158	return []shell.BlockFunc{
159		shell.CommandsBlocker(bannedCommands),
160
161		// System package managers
162		shell.ArgumentsBlocker("apk", []string{"add"}, nil),
163		shell.ArgumentsBlocker("apt", []string{"install"}, nil),
164		shell.ArgumentsBlocker("apt-get", []string{"install"}, nil),
165		shell.ArgumentsBlocker("dnf", []string{"install"}, nil),
166		shell.ArgumentsBlocker("pacman", nil, []string{"-S"}),
167		shell.ArgumentsBlocker("pkg", []string{"install"}, nil),
168		shell.ArgumentsBlocker("yum", []string{"install"}, nil),
169		shell.ArgumentsBlocker("zypper", []string{"install"}, nil),
170
171		// Language-specific package managers
172		shell.ArgumentsBlocker("brew", []string{"install"}, nil),
173		shell.ArgumentsBlocker("cargo", []string{"install"}, nil),
174		shell.ArgumentsBlocker("gem", []string{"install"}, nil),
175		shell.ArgumentsBlocker("go", []string{"install"}, nil),
176		shell.ArgumentsBlocker("npm", []string{"install"}, []string{"--global"}),
177		shell.ArgumentsBlocker("npm", []string{"install"}, []string{"-g"}),
178		shell.ArgumentsBlocker("pip", []string{"install"}, []string{"--user"}),
179		shell.ArgumentsBlocker("pip3", []string{"install"}, []string{"--user"}),
180		shell.ArgumentsBlocker("pnpm", []string{"add"}, []string{"--global"}),
181		shell.ArgumentsBlocker("pnpm", []string{"add"}, []string{"-g"}),
182		shell.ArgumentsBlocker("yarn", []string{"global", "add"}, nil),
183
184		// `go test -exec` can run arbitrary commands
185		shell.ArgumentsBlocker("go", []string{"test"}, []string{"-exec"}),
186	}
187}
188
189func resolveBannedCommandsList(cfg config.ToolBash) []string {
190	bannedCommands := cfg.BannedCommands
191	if !cfg.DisableDefaults {
192		if len(bannedCommands) == 0 {
193			return defaultBannedCommands
194		}
195		bannedCommands = append(bannedCommands, defaultBannedCommands...)
196	}
197	return bannedCommands
198}
199
200func resolveBlockFuncs(cfg config.ToolBash) []shell.BlockFunc {
201	return blockFuncs(resolveBannedCommandsList(cfg))
202}
203
204func NewBashTool(
205	permissions permission.Service,
206	workingDir string, attribution *config.Attribution,
207	modelName string,
208	bashConfig config.ToolBash,
209) fantasy.AgentTool {
210	return fantasy.NewAgentTool(
211		BashToolName,
212		string(bashDescription(attribution, modelName)),
213		func(ctx context.Context, params BashParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
214			if params.Command == "" {
215				return fantasy.NewTextErrorResponse("missing command"), nil
216			}
217
218			// Determine working directory
219			execWorkingDir := cmp.Or(params.WorkingDir, workingDir)
220
221			isSafeReadOnly := false
222			cmdLower := strings.ToLower(params.Command)
223
224			for _, safe := range safeCommands {
225				if strings.HasPrefix(cmdLower, safe) {
226					if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
227						isSafeReadOnly = true
228						break
229					}
230				}
231			}
232
233			sessionID := GetSessionFromContext(ctx)
234			if sessionID == "" {
235				return fantasy.ToolResponse{}, fmt.Errorf("session ID is required for executing shell command")
236			}
237			if !isSafeReadOnly {
238				p := permissions.Request(
239					permission.CreatePermissionRequest{
240						SessionID:   sessionID,
241						Path:        execWorkingDir,
242						ToolCallID:  call.ID,
243						ToolName:    BashToolName,
244						Action:      "execute",
245						Description: fmt.Sprintf("Execute command: %s", params.Command),
246						Params:      BashPermissionsParams(params),
247					},
248				)
249				if !p {
250					return fantasy.ToolResponse{}, permission.ErrorPermissionDenied
251				}
252			}
253
254			// If explicitly requested as background, start immediately with detached context
255			if params.RunInBackground {
256				startTime := time.Now()
257				bgManager := shell.GetBackgroundShellManager()
258				bgManager.Cleanup()
259				// Use background context so it continues after tool returns
260				bgShell, err := bgManager.Start(context.Background(), execWorkingDir, resolveBlockFuncs(bashConfig), params.Command, params.Description)
261				if err != nil {
262					return fantasy.ToolResponse{}, fmt.Errorf("error starting background shell: %w", err)
263				}
264
265				// Wait a short time to detect fast failures (blocked commands, syntax errors, etc.)
266				time.Sleep(1 * time.Second)
267				stdout, stderr, done, execErr := bgShell.GetOutput()
268
269				if done {
270					// Command failed or completed very quickly
271					bgManager.Remove(bgShell.ID)
272
273					interrupted := shell.IsInterrupt(execErr)
274					exitCode := shell.ExitCode(execErr)
275					if exitCode == 0 && !interrupted && execErr != nil {
276						return fantasy.ToolResponse{}, fmt.Errorf("[Job %s] error executing command: %w", bgShell.ID, execErr)
277					}
278
279					stdout = formatOutput(stdout, stderr, execErr)
280
281					metadata := BashResponseMetadata{
282						StartTime:        startTime.UnixMilli(),
283						EndTime:          time.Now().UnixMilli(),
284						Output:           stdout,
285						Description:      params.Description,
286						Background:       params.RunInBackground,
287						WorkingDirectory: bgShell.WorkingDir,
288					}
289					if stdout == "" {
290						return fantasy.WithResponseMetadata(fantasy.NewTextResponse(BashNoOutput), metadata), nil
291					}
292					stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", normalizeWorkingDir(bgShell.WorkingDir))
293					return fantasy.WithResponseMetadata(fantasy.NewTextResponse(stdout), metadata), nil
294				}
295
296				// Still running after fast-failure check - return as background job
297				metadata := BashResponseMetadata{
298					StartTime:        startTime.UnixMilli(),
299					EndTime:          time.Now().UnixMilli(),
300					Description:      params.Description,
301					WorkingDirectory: bgShell.WorkingDir,
302					Background:       true,
303					ShellID:          bgShell.ID,
304				}
305				response := fmt.Sprintf("Background shell started with ID: %s\n\nUse job_output tool to view output or job_kill to terminate.", bgShell.ID)
306				return fantasy.WithResponseMetadata(fantasy.NewTextResponse(response), metadata), nil
307			}
308
309			// Start synchronous execution with auto-background support
310			startTime := time.Now()
311
312			// Start with detached context so it can survive if moved to background
313			bgManager := shell.GetBackgroundShellManager()
314			bgManager.Cleanup()
315			bgShell, err := bgManager.Start(context.Background(), execWorkingDir, blockFuncs(defaultBannedCommands), params.Command, params.Description)
316			if err != nil {
317				return fantasy.ToolResponse{}, fmt.Errorf("error starting shell: %w", err)
318			}
319
320			// Wait for either completion, auto-background threshold, or context cancellation
321			ticker := time.NewTicker(100 * time.Millisecond)
322			defer ticker.Stop()
323			timeout := time.After(AutoBackgroundThreshold)
324
325			var stdout, stderr string
326			var done bool
327			var execErr error
328
329		waitLoop:
330			for {
331				select {
332				case <-ticker.C:
333					stdout, stderr, done, execErr = bgShell.GetOutput()
334					if done {
335						break waitLoop
336					}
337				case <-timeout:
338					stdout, stderr, done, execErr = bgShell.GetOutput()
339					break waitLoop
340				case <-ctx.Done():
341					// Incoming context was cancelled before we moved to background
342					// Kill the shell and return error
343					bgManager.Kill(bgShell.ID)
344					return fantasy.ToolResponse{}, ctx.Err()
345				}
346			}
347
348			if done {
349				// Command completed within threshold - return synchronously
350				// Remove from background manager since we're returning directly
351				// Don't call Kill() as it cancels the context and corrupts the exit code
352				bgManager.Remove(bgShell.ID)
353
354				interrupted := shell.IsInterrupt(execErr)
355				exitCode := shell.ExitCode(execErr)
356				if exitCode == 0 && !interrupted && execErr != nil {
357					return fantasy.ToolResponse{}, fmt.Errorf("[Job %s] error executing command: %w", bgShell.ID, execErr)
358				}
359
360				stdout = formatOutput(stdout, stderr, execErr)
361
362				metadata := BashResponseMetadata{
363					StartTime:        startTime.UnixMilli(),
364					EndTime:          time.Now().UnixMilli(),
365					Output:           stdout,
366					Description:      params.Description,
367					Background:       params.RunInBackground,
368					WorkingDirectory: bgShell.WorkingDir,
369				}
370				if stdout == "" {
371					return fantasy.WithResponseMetadata(fantasy.NewTextResponse(BashNoOutput), metadata), nil
372				}
373				stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", normalizeWorkingDir(bgShell.WorkingDir))
374				return fantasy.WithResponseMetadata(fantasy.NewTextResponse(stdout), metadata), nil
375			}
376
377			// Still running - keep as background job
378			metadata := BashResponseMetadata{
379				StartTime:        startTime.UnixMilli(),
380				EndTime:          time.Now().UnixMilli(),
381				Description:      params.Description,
382				WorkingDirectory: bgShell.WorkingDir,
383				Background:       true,
384				ShellID:          bgShell.ID,
385			}
386			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)
387			return fantasy.WithResponseMetadata(fantasy.NewTextResponse(response), metadata), nil
388		})
389}
390
391// formatOutput formats the output of a completed command with error handling
392func formatOutput(stdout, stderr string, execErr error) string {
393	interrupted := shell.IsInterrupt(execErr)
394	exitCode := shell.ExitCode(execErr)
395
396	stdout = truncateOutput(stdout)
397	stderr = truncateOutput(stderr)
398
399	errorMessage := stderr
400	if errorMessage == "" && execErr != nil {
401		errorMessage = execErr.Error()
402	}
403
404	if interrupted {
405		if errorMessage != "" {
406			errorMessage += "\n"
407		}
408		errorMessage += "Command was aborted before completion"
409	} else if exitCode != 0 {
410		if errorMessage != "" {
411			errorMessage += "\n"
412		}
413		errorMessage += fmt.Sprintf("Exit code %d", exitCode)
414	}
415
416	hasBothOutputs := stdout != "" && stderr != ""
417
418	if hasBothOutputs {
419		stdout += "\n"
420	}
421
422	if errorMessage != "" {
423		stdout += "\n" + errorMessage
424	}
425
426	return stdout
427}
428
429func truncateOutput(content string) string {
430	if len(content) <= MaxOutputLength {
431		return content
432	}
433
434	halfLength := MaxOutputLength / 2
435	start := content[:halfLength]
436	end := content[len(content)-halfLength:]
437
438	truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
439	return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
440}
441
442func countLines(s string) int {
443	if s == "" {
444		return 0
445	}
446	return len(strings.Split(s, "\n"))
447}
448
449func normalizeWorkingDir(path string) string {
450	if runtime.GOOS == "windows" {
451		cwd, err := os.Getwd()
452		if err != nil {
453			cwd = "C:"
454		}
455		path = strings.ReplaceAll(path, filepath.VolumeName(cwd), "")
456	}
457
458	return filepath.ToSlash(path)
459}