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 bannedCommands = []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 // File deletion (use delete tool instead for proper LSP integration)
142 "rm",
143}
144
145func bashDescription(attribution *config.Attribution, modelName string) string {
146 bannedCommandsStr := strings.Join(bannedCommands, ", ")
147 var out bytes.Buffer
148 if err := bashDescriptionTpl.Execute(&out, bashDescriptionData{
149 BannedCommands: bannedCommandsStr,
150 MaxOutputLength: MaxOutputLength,
151 Attribution: *attribution,
152 ModelName: modelName,
153 }); err != nil {
154 // this should never happen.
155 panic("failed to execute bash description template: " + err.Error())
156 }
157 return out.String()
158}
159
160func blockFuncs() []shell.BlockFunc {
161 return []shell.BlockFunc{
162 shell.CommandsBlocker(bannedCommands),
163
164 // System package managers
165 shell.ArgumentsBlocker("apk", []string{"add"}, nil),
166 shell.ArgumentsBlocker("apt", []string{"install"}, nil),
167 shell.ArgumentsBlocker("apt-get", []string{"install"}, nil),
168 shell.ArgumentsBlocker("dnf", []string{"install"}, nil),
169 shell.ArgumentsBlocker("pacman", nil, []string{"-S"}),
170 shell.ArgumentsBlocker("pkg", []string{"install"}, nil),
171 shell.ArgumentsBlocker("yum", []string{"install"}, nil),
172 shell.ArgumentsBlocker("zypper", []string{"install"}, nil),
173
174 // Language-specific package managers
175 shell.ArgumentsBlocker("brew", []string{"install"}, nil),
176 shell.ArgumentsBlocker("cargo", []string{"install"}, nil),
177 shell.ArgumentsBlocker("gem", []string{"install"}, nil),
178 shell.ArgumentsBlocker("go", []string{"install"}, nil),
179 shell.ArgumentsBlocker("npm", []string{"install"}, []string{"--global"}),
180 shell.ArgumentsBlocker("npm", []string{"install"}, []string{"-g"}),
181 shell.ArgumentsBlocker("pip", []string{"install"}, []string{"--user"}),
182 shell.ArgumentsBlocker("pip3", []string{"install"}, []string{"--user"}),
183 shell.ArgumentsBlocker("pnpm", []string{"add"}, []string{"--global"}),
184 shell.ArgumentsBlocker("pnpm", []string{"add"}, []string{"-g"}),
185 shell.ArgumentsBlocker("yarn", []string{"global", "add"}, nil),
186
187 // `go test -exec` can run arbitrary commands
188 shell.ArgumentsBlocker("go", []string{"test"}, []string{"-exec"}),
189 }
190}
191
192func NewBashTool(permissions permission.Service, workingDir string, attribution *config.Attribution, modelName string) fantasy.AgentTool {
193 return fantasy.NewAgentTool(
194 BashToolName,
195 string(bashDescription(attribution, modelName)),
196 func(ctx context.Context, params BashParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
197 if params.Command == "" {
198 return fantasy.NewTextErrorResponse("missing command"), nil
199 }
200
201 // Determine working directory
202 execWorkingDir := cmp.Or(params.WorkingDir, workingDir)
203
204 isSafeReadOnly := false
205 cmdLower := strings.ToLower(params.Command)
206
207 for _, safe := range safeCommands {
208 if strings.HasPrefix(cmdLower, safe) {
209 if len(cmdLower) == len(safe) || cmdLower[len(safe)] == ' ' || cmdLower[len(safe)] == '-' {
210 isSafeReadOnly = true
211 break
212 }
213 }
214 }
215
216 sessionID := GetSessionFromContext(ctx)
217 if sessionID == "" {
218 return fantasy.ToolResponse{}, fmt.Errorf("session ID is required for executing shell command")
219 }
220 if !isSafeReadOnly {
221 p, err := permissions.Request(ctx,
222 permission.CreatePermissionRequest{
223 SessionID: sessionID,
224 Path: execWorkingDir,
225 ToolCallID: call.ID,
226 ToolName: BashToolName,
227 Action: "execute",
228 Description: fmt.Sprintf("Execute command: %s", params.Command),
229 Params: BashPermissionsParams(params),
230 },
231 )
232 if err != nil {
233 return fantasy.ToolResponse{}, err
234 }
235 if !p {
236 return fantasy.ToolResponse{}, permission.ErrorPermissionDenied
237 }
238 }
239
240 // If explicitly requested as background, start immediately with detached context
241 if params.RunInBackground {
242 startTime := time.Now()
243 bgManager := shell.GetBackgroundShellManager()
244 bgManager.Cleanup()
245 // Use background context so it continues after tool returns
246 bgShell, err := bgManager.Start(context.Background(), execWorkingDir, blockFuncs(), params.Command, params.Description)
247 if err != nil {
248 return fantasy.ToolResponse{}, fmt.Errorf("error starting background shell: %w", err)
249 }
250
251 // Wait a short time to detect fast failures (blocked commands, syntax errors, etc.)
252 time.Sleep(1 * time.Second)
253 stdout, stderr, done, execErr := bgShell.GetOutput()
254
255 if done {
256 // Command failed or completed very quickly
257 bgManager.Remove(bgShell.ID)
258
259 interrupted := shell.IsInterrupt(execErr)
260 exitCode := shell.ExitCode(execErr)
261 if exitCode == 0 && !interrupted && execErr != nil {
262 return fantasy.ToolResponse{}, fmt.Errorf("[Job %s] error executing command: %w", bgShell.ID, execErr)
263 }
264
265 stdout = formatOutput(stdout, stderr, execErr)
266
267 metadata := BashResponseMetadata{
268 StartTime: startTime.UnixMilli(),
269 EndTime: time.Now().UnixMilli(),
270 Output: stdout,
271 Description: params.Description,
272 Background: params.RunInBackground,
273 WorkingDirectory: bgShell.WorkingDir,
274 }
275 if stdout == "" {
276 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(BashNoOutput), metadata), nil
277 }
278 stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", normalizeWorkingDir(bgShell.WorkingDir))
279 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(stdout), metadata), nil
280 }
281
282 // Still running after fast-failure check - return as background job
283 metadata := BashResponseMetadata{
284 StartTime: startTime.UnixMilli(),
285 EndTime: time.Now().UnixMilli(),
286 Description: params.Description,
287 WorkingDirectory: bgShell.WorkingDir,
288 Background: true,
289 ShellID: bgShell.ID,
290 }
291 response := fmt.Sprintf("Background shell started with ID: %s\n\nUse job_output tool to view output or job_kill to terminate.", bgShell.ID)
292 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(response), metadata), nil
293 }
294
295 // Start synchronous execution with auto-background support
296 startTime := time.Now()
297
298 // Start with detached context so it can survive if moved to background
299 bgManager := shell.GetBackgroundShellManager()
300 bgManager.Cleanup()
301 bgShell, err := bgManager.Start(context.Background(), execWorkingDir, blockFuncs(), params.Command, params.Description)
302 if err != nil {
303 return fantasy.ToolResponse{}, fmt.Errorf("error starting shell: %w", err)
304 }
305
306 // Wait for either completion, auto-background threshold, or context cancellation
307 ticker := time.NewTicker(100 * time.Millisecond)
308 defer ticker.Stop()
309 timeout := time.After(AutoBackgroundThreshold)
310
311 var stdout, stderr string
312 var done bool
313 var execErr error
314
315 waitLoop:
316 for {
317 select {
318 case <-ticker.C:
319 stdout, stderr, done, execErr = bgShell.GetOutput()
320 if done {
321 break waitLoop
322 }
323 case <-timeout:
324 stdout, stderr, done, execErr = bgShell.GetOutput()
325 break waitLoop
326 case <-ctx.Done():
327 // Incoming context was cancelled before we moved to background
328 // Kill the shell and return error
329 bgManager.Kill(bgShell.ID)
330 return fantasy.ToolResponse{}, ctx.Err()
331 }
332 }
333
334 if done {
335 // Command completed within threshold - return synchronously
336 // Remove from background manager since we're returning directly
337 // Don't call Kill() as it cancels the context and corrupts the exit code
338 bgManager.Remove(bgShell.ID)
339
340 interrupted := shell.IsInterrupt(execErr)
341 exitCode := shell.ExitCode(execErr)
342 if exitCode == 0 && !interrupted && execErr != nil {
343 return fantasy.ToolResponse{}, fmt.Errorf("[Job %s] error executing command: %w", bgShell.ID, execErr)
344 }
345
346 stdout = formatOutput(stdout, stderr, execErr)
347
348 metadata := BashResponseMetadata{
349 StartTime: startTime.UnixMilli(),
350 EndTime: time.Now().UnixMilli(),
351 Output: stdout,
352 Description: params.Description,
353 Background: params.RunInBackground,
354 WorkingDirectory: bgShell.WorkingDir,
355 }
356 if stdout == "" {
357 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(BashNoOutput), metadata), nil
358 }
359 stdout += fmt.Sprintf("\n\n<cwd>%s</cwd>", normalizeWorkingDir(bgShell.WorkingDir))
360 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(stdout), metadata), nil
361 }
362
363 // Still running - keep as background job
364 metadata := BashResponseMetadata{
365 StartTime: startTime.UnixMilli(),
366 EndTime: time.Now().UnixMilli(),
367 Description: params.Description,
368 WorkingDirectory: bgShell.WorkingDir,
369 Background: true,
370 ShellID: bgShell.ID,
371 }
372 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)
373 return fantasy.WithResponseMetadata(fantasy.NewTextResponse(response), metadata), nil
374 })
375}
376
377// formatOutput formats the output of a completed command with error handling
378func formatOutput(stdout, stderr string, execErr error) string {
379 interrupted := shell.IsInterrupt(execErr)
380 exitCode := shell.ExitCode(execErr)
381
382 stdout = truncateOutput(stdout)
383 stderr = truncateOutput(stderr)
384
385 errorMessage := stderr
386 if errorMessage == "" && execErr != nil {
387 errorMessage = execErr.Error()
388 }
389
390 if interrupted {
391 if errorMessage != "" {
392 errorMessage += "\n"
393 }
394 errorMessage += "Command was aborted before completion"
395 } else if exitCode != 0 {
396 if errorMessage != "" {
397 errorMessage += "\n"
398 }
399 errorMessage += fmt.Sprintf("Exit code %d", exitCode)
400 }
401
402 hasBothOutputs := stdout != "" && stderr != ""
403
404 if hasBothOutputs {
405 stdout += "\n"
406 }
407
408 if errorMessage != "" {
409 stdout += "\n" + errorMessage
410 }
411
412 return stdout
413}
414
415func truncateOutput(content string) string {
416 if len(content) <= MaxOutputLength {
417 return content
418 }
419
420 halfLength := MaxOutputLength / 2
421 start := content[:halfLength]
422 end := content[len(content)-halfLength:]
423
424 truncatedLinesCount := countLines(content[halfLength : len(content)-halfLength])
425 return fmt.Sprintf("%s\n\n... [%d lines truncated] ...\n\n%s", start, truncatedLinesCount, end)
426}
427
428func countLines(s string) int {
429 if s == "" {
430 return 0
431 }
432 return len(strings.Split(s, "\n"))
433}
434
435func normalizeWorkingDir(path string) string {
436 if runtime.GOOS == "windows" {
437 cwd, err := os.Getwd()
438 if err != nil {
439 cwd = "C:"
440 }
441 path = strings.ReplaceAll(path, filepath.VolumeName(cwd), "")
442 }
443
444 return filepath.ToSlash(path)
445}