@@ -0,0 +1,223 @@
14+ "github.com/charmbracelet/crush/internal/permission"
17+type DownloadParams struct {
18+ URL string `json:"url"`
19+ FilePath string `json:"file_path"`
20+ Timeout int `json:"timeout,omitempty"`
23+type DownloadPermissionsParams struct {
24+ URL string `json:"url"`
25+ FilePath string `json:"file_path"`
26+ Timeout int `json:"timeout,omitempty"`
29+type downloadTool struct {
31+ permissions permission.Service
36+ DownloadToolName = "download"
37+ downloadToolDescription = `Downloads binary data from a URL and saves it to a local file.
39+WHEN TO USE THIS TOOL:
40+- Use when you need to download files, images, or other binary data from URLs
41+- Helpful for downloading assets, documents, or any file type
42+- Useful for saving remote content locally for processing or storage
45+- Provide the URL to download from
46+- Specify the local file path where the content should be saved
47+- Optionally set a timeout for the request
50+- Downloads any file type (binary or text)
51+- Automatically creates parent directories if they don't exist
52+- Handles large files efficiently with streaming
53+- Sets reasonable timeouts to prevent hanging
54+- Validates input parameters before making requests
57+- Maximum file size is 100MB
58+- Only supports HTTP and HTTPS protocols
59+- Cannot handle authentication or cookies
60+- Some websites may block automated requests
61+- Will overwrite existing files without warning
64+- Use absolute paths or paths relative to the working directory
65+- Set appropriate timeouts for large files or slow connections`
68+func NewDownloadTool(permissions permission.Service, workingDir string) BaseTool {
69+ return &downloadTool{
70+ client: &http.Client{
71+ Timeout: 5 * time.Minute, // Default 5 minute timeout for downloads
72+ Transport: &http.Transport{
74+ MaxIdleConnsPerHost: 10,
75+ IdleConnTimeout: 90 * time.Second,
78+ permissions: permissions,
79+ workingDir: workingDir,
83+func (t *downloadTool) Name() string {
84+ return DownloadToolName
87+func (t *downloadTool) Info() ToolInfo {
89+ Name: DownloadToolName,
90+ Description: downloadToolDescription,
91+ Parameters: map[string]any{
92+ "url": map[string]any{
94+ "description": "The URL to download from",
96+ "file_path": map[string]any{
98+ "description": "The local file path where the downloaded content should be saved",
100+ "timeout": map[string]any{
102+ "description": "Optional timeout in seconds (max 600)",
105+ Required: []string{"url", "file_path"},
109+func (t *downloadTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
110+ var params DownloadParams
111+ if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
112+ return NewTextErrorResponse("Failed to parse download parameters: " + err.Error()), nil
115+ if params.URL == "" {
116+ return NewTextErrorResponse("URL parameter is required"), nil
119+ if params.FilePath == "" {
120+ return NewTextErrorResponse("file_path parameter is required"), nil
123+ if !strings.HasPrefix(params.URL, "http://") && !strings.HasPrefix(params.URL, "https://") {
124+ return NewTextErrorResponse("URL must start with http:// or https://"), nil
127+ // Convert relative path to absolute path
129+ if filepath.IsAbs(params.FilePath) {
130+ filePath = params.FilePath
132+ filePath = filepath.Join(t.workingDir, params.FilePath)
135+ sessionID, messageID := GetContextValues(ctx)
136+ if sessionID == "" || messageID == "" {
137+ return ToolResponse{}, fmt.Errorf("session ID and message ID are required for downloading files")
140+ p := t.permissions.Request(
141+ permission.CreatePermissionRequest{
142+ SessionID: sessionID,
144+ ToolName: DownloadToolName,
146+ Description: fmt.Sprintf("Download file from URL: %s to %s", params.URL, filePath),
147+ Params: DownloadPermissionsParams(params),
152+ return ToolResponse{}, permission.ErrorPermissionDenied
155+ // Handle timeout with context
157+ if params.Timeout > 0 {
158+ maxTimeout := 600 // 10 minutes
159+ if params.Timeout > maxTimeout {
160+ params.Timeout = maxTimeout
162+ var cancel context.CancelFunc
163+ requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
167+ req, err := http.NewRequestWithContext(requestCtx, "GET", params.URL, nil)
169+ return ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
172+ req.Header.Set("User-Agent", "crush/1.0")
174+ resp, err := t.client.Do(req)
176+ return ToolResponse{}, fmt.Errorf("failed to download from URL: %w", err)
178+ defer resp.Body.Close()
180+ if resp.StatusCode != http.StatusOK {
181+ return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
184+ // Check content length if available
185+ maxSize := int64(100 * 1024 * 1024) // 100MB
186+ if resp.ContentLength > maxSize {
187+ return NewTextErrorResponse(fmt.Sprintf("File too large: %d bytes (max %d bytes)", resp.ContentLength, maxSize)), nil
190+ // Create parent directories if they don't exist
191+ if err := os.MkdirAll(filepath.Dir(filePath), 0o755); err != nil {
192+ return ToolResponse{}, fmt.Errorf("failed to create parent directories: %w", err)
195+ // Create the output file
196+ outFile, err := os.Create(filePath)
198+ return ToolResponse{}, fmt.Errorf("failed to create output file: %w", err)
200+ defer outFile.Close()
202+ // Copy data with size limit
203+ limitedReader := io.LimitReader(resp.Body, maxSize)
204+ bytesWritten, err := io.Copy(outFile, limitedReader)
206+ return ToolResponse{}, fmt.Errorf("failed to write file: %w", err)
209+ // Check if we hit the size limit
210+ if bytesWritten == maxSize {
211+ // Clean up the file since it might be incomplete
213+ return NewTextErrorResponse(fmt.Sprintf("File too large: exceeded %d bytes limit", maxSize)), nil
216+ contentType := resp.Header.Get("Content-Type")
217+ responseMsg := fmt.Sprintf("Successfully downloaded %d bytes to %s", bytesWritten, filePath)
218+ if contentType != "" {
219+ responseMsg += fmt.Sprintf(" (Content-Type: %s)", contentType)
222+ return NewTextResponse(responseMsg), nil