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