download.go

  1package tools
  2
  3import (
  4	"cmp"
  5	"context"
  6	_ "embed"
  7	"fmt"
  8	"io"
  9	"net/http"
 10	"os"
 11	"path/filepath"
 12	"strings"
 13	"time"
 14
 15	"charm.land/fantasy"
 16	"github.com/charmbracelet/crush/internal/filepathext"
 17	"github.com/charmbracelet/crush/internal/permission"
 18)
 19
 20type DownloadParams struct {
 21	URL      string `json:"url" description:"The URL to download from"`
 22	FilePath string `json:"file_path" description:"The local file path where the downloaded content should be saved"`
 23	Timeout  int    `json:"timeout,omitempty" description:"Optional timeout in seconds (max 600)"`
 24}
 25
 26type DownloadPermissionsParams struct {
 27	URL      string `json:"url"`
 28	FilePath string `json:"file_path"`
 29	Timeout  int    `json:"timeout,omitempty"`
 30}
 31
 32const DownloadToolName = "download"
 33
 34//go:embed download.md
 35var downloadDescription []byte
 36
 37func NewDownloadTool(permissions permission.Service, workingDir string, client *http.Client) fantasy.AgentTool {
 38	if client == nil {
 39		transport := http.DefaultTransport.(*http.Transport).Clone()
 40		transport.MaxIdleConns = 100
 41		transport.MaxIdleConnsPerHost = 10
 42		transport.IdleConnTimeout = 90 * time.Second
 43
 44		client = &http.Client{
 45			Timeout:   5 * time.Minute, // Default 5 minute timeout for downloads
 46			Transport: transport,
 47		}
 48	}
 49	return fantasy.NewParallelAgentTool(
 50		DownloadToolName,
 51		string(downloadDescription),
 52		func(ctx context.Context, params DownloadParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
 53			if params.URL == "" {
 54				return fantasy.NewTextErrorResponse("URL parameter is required"), nil
 55			}
 56
 57			if params.FilePath == "" {
 58				return fantasy.NewTextErrorResponse("file_path parameter is required"), nil
 59			}
 60
 61			if !strings.HasPrefix(params.URL, "http://") && !strings.HasPrefix(params.URL, "https://") {
 62				return fantasy.NewTextErrorResponse("URL must start with http:// or https://"), nil
 63			}
 64
 65			filePath := filepathext.SmartJoin(workingDir, params.FilePath)
 66			relPath, _ := filepath.Rel(workingDir, filePath)
 67			relPath = filepath.ToSlash(cmp.Or(relPath, filePath))
 68
 69			sessionID := GetSessionFromContext(ctx)
 70			if sessionID == "" {
 71				return fantasy.ToolResponse{}, fmt.Errorf("session ID is required for downloading files")
 72			}
 73
 74			p, err := permissions.Request(ctx,
 75				permission.CreatePermissionRequest{
 76					SessionID:   sessionID,
 77					Path:        filePath,
 78					ToolName:    DownloadToolName,
 79					Action:      "download",
 80					Description: fmt.Sprintf("Download file from URL: %s to %s", params.URL, filePath),
 81					Params:      DownloadPermissionsParams(params),
 82				},
 83			)
 84			if err != nil {
 85				return fantasy.ToolResponse{}, err
 86			}
 87			if !p {
 88				return fantasy.ToolResponse{}, permission.ErrorPermissionDenied
 89			}
 90
 91			// Handle timeout with context
 92			requestCtx := ctx
 93			if params.Timeout > 0 {
 94				maxTimeout := 600 // 10 minutes
 95				if params.Timeout > maxTimeout {
 96					params.Timeout = maxTimeout
 97				}
 98				var cancel context.CancelFunc
 99				requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
100				defer cancel()
101			}
102
103			req, err := http.NewRequestWithContext(requestCtx, "GET", params.URL, nil)
104			if err != nil {
105				return fantasy.ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
106			}
107
108			req.Header.Set("User-Agent", "crush/1.0")
109
110			resp, err := client.Do(req)
111			if err != nil {
112				return fantasy.ToolResponse{}, fmt.Errorf("failed to download from URL: %w", err)
113			}
114			defer resp.Body.Close()
115
116			if resp.StatusCode != http.StatusOK {
117				return fantasy.NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
118			}
119
120			// Create parent directories if they don't exist
121			if err := os.MkdirAll(filepath.Dir(filePath), 0o755); err != nil {
122				return fantasy.ToolResponse{}, fmt.Errorf("failed to create parent directories: %w", err)
123			}
124
125			// Create the output file
126			outFile, err := os.Create(filePath)
127			if err != nil {
128				return fantasy.ToolResponse{}, fmt.Errorf("failed to create output file: %w", err)
129			}
130			defer outFile.Close()
131
132			// Copy data without an explicit size limit.
133			// The overall download is still constrained by the HTTP client's timeout
134			// and any upstream server limits.
135			bytesWritten, err := io.Copy(outFile, resp.Body)
136			if err != nil {
137				return fantasy.ToolResponse{}, fmt.Errorf("failed to write file: %w", err)
138			}
139
140			contentType := resp.Header.Get("Content-Type")
141			responseMsg := fmt.Sprintf("Successfully downloaded %d bytes to %s", bytesWritten, relPath)
142			if contentType != "" {
143				responseMsg += fmt.Sprintf(" (Content-Type: %s)", contentType)
144			}
145
146			return fantasy.NewTextResponse(responseMsg), nil
147		})
148}