fetch.go

  1package tools
  2
  3import (
  4	"context"
  5	_ "embed"
  6	"fmt"
  7	"io"
  8	"net/http"
  9	"strings"
 10	"time"
 11	"unicode/utf8"
 12
 13	"charm.land/fantasy"
 14	md "github.com/JohannesKaufmann/html-to-markdown"
 15	"github.com/PuerkitoBio/goquery"
 16	"github.com/charmbracelet/crush/internal/permission"
 17)
 18
 19const FetchToolName = "fetch"
 20
 21//go:embed fetch.md
 22var fetchDescription []byte
 23
 24func NewFetchTool(permissions permission.Service, workingDir string, client *http.Client) fantasy.AgentTool {
 25	if client == nil {
 26		client = &http.Client{
 27			Timeout: 30 * time.Second,
 28			Transport: &http.Transport{
 29				MaxIdleConns:        100,
 30				MaxIdleConnsPerHost: 10,
 31				IdleConnTimeout:     90 * time.Second,
 32			},
 33		}
 34	}
 35
 36	return fantasy.NewParallelAgentTool(
 37		FetchToolName,
 38		string(fetchDescription),
 39		func(ctx context.Context, params FetchParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
 40			if params.URL == "" {
 41				return fantasy.NewTextErrorResponse("URL parameter is required"), nil
 42			}
 43
 44			format := strings.ToLower(params.Format)
 45			if format != "text" && format != "markdown" && format != "html" {
 46				return fantasy.NewTextErrorResponse("Format must be one of: text, markdown, html"), nil
 47			}
 48
 49			if !strings.HasPrefix(params.URL, "http://") && !strings.HasPrefix(params.URL, "https://") {
 50				return fantasy.NewTextErrorResponse("URL must start with http:// or https://"), nil
 51			}
 52
 53			sessionID := GetSessionFromContext(ctx)
 54			if sessionID == "" {
 55				return fantasy.ToolResponse{}, fmt.Errorf("session ID is required for creating a new file")
 56			}
 57
 58			p, err := permissions.Request(ctx,
 59				permission.CreatePermissionRequest{
 60					SessionID:   sessionID,
 61					Path:        workingDir,
 62					ToolCallID:  call.ID,
 63					ToolName:    FetchToolName,
 64					Action:      "fetch",
 65					Description: fmt.Sprintf("Fetch content from URL: %s", params.URL),
 66					Params:      FetchPermissionsParams(params),
 67				},
 68			)
 69			if err != nil {
 70				return fantasy.ToolResponse{}, err
 71			}
 72			if !p {
 73				return fantasy.ToolResponse{}, permission.ErrorPermissionDenied
 74			}
 75
 76			// Handle timeout with context
 77			requestCtx := ctx
 78			if params.Timeout > 0 {
 79				maxTimeout := 120 // 2 minutes
 80				if params.Timeout > maxTimeout {
 81					params.Timeout = maxTimeout
 82				}
 83				var cancel context.CancelFunc
 84				requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
 85				defer cancel()
 86			}
 87
 88			req, err := http.NewRequestWithContext(requestCtx, "GET", params.URL, nil)
 89			if err != nil {
 90				return fantasy.ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
 91			}
 92
 93			req.Header.Set("User-Agent", "crush/1.0")
 94
 95			resp, err := client.Do(req)
 96			if err != nil {
 97				return fantasy.ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
 98			}
 99			defer resp.Body.Close()
100
101			if resp.StatusCode != http.StatusOK {
102				return fantasy.NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
103			}
104
105			maxSize := int64(5 * 1024 * 1024) // 5MB
106			body, err := io.ReadAll(io.LimitReader(resp.Body, maxSize))
107			if err != nil {
108				return fantasy.NewTextErrorResponse("Failed to read response body: " + err.Error()), nil
109			}
110
111			content := string(body)
112
113			isValidUt8 := utf8.ValidString(content)
114			if !isValidUt8 {
115				return fantasy.NewTextErrorResponse("Response content is not valid UTF-8"), nil
116			}
117			contentType := resp.Header.Get("Content-Type")
118
119			switch format {
120			case "text":
121				if strings.Contains(contentType, "text/html") {
122					text, err := extractTextFromHTML(content)
123					if err != nil {
124						return fantasy.NewTextErrorResponse("Failed to extract text from HTML: " + err.Error()), nil
125					}
126					content = text
127				}
128
129			case "markdown":
130				if strings.Contains(contentType, "text/html") {
131					markdown, err := convertHTMLToMarkdown(content)
132					if err != nil {
133						return fantasy.NewTextErrorResponse("Failed to convert HTML to Markdown: " + err.Error()), nil
134					}
135					content = markdown
136				}
137
138				content = "```\n" + content + "\n```"
139
140			case "html":
141				// return only the body of the HTML document
142				if strings.Contains(contentType, "text/html") {
143					doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
144					if err != nil {
145						return fantasy.NewTextErrorResponse("Failed to parse HTML: " + err.Error()), nil
146					}
147					body, err := doc.Find("body").Html()
148					if err != nil {
149						return fantasy.NewTextErrorResponse("Failed to extract body from HTML: " + err.Error()), nil
150					}
151					if body == "" {
152						return fantasy.NewTextErrorResponse("No body content found in HTML"), nil
153					}
154					content = "<html>\n<body>\n" + body + "\n</body>\n</html>"
155				}
156			}
157			// calculate byte size of content
158			contentSize := int64(len(content))
159			if contentSize > MaxReadSize {
160				content = content[:MaxReadSize]
161				content += fmt.Sprintf("\n\n[Content truncated to %d bytes]", MaxReadSize)
162			}
163
164			return fantasy.NewTextResponse(content), nil
165		})
166}
167
168func extractTextFromHTML(html string) (string, error) {
169	doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
170	if err != nil {
171		return "", err
172	}
173
174	text := doc.Find("body").Text()
175	text = strings.Join(strings.Fields(text), " ")
176
177	return text, nil
178}
179
180func convertHTMLToMarkdown(html string) (string, error) {
181	converter := md.NewConverter("", true, nil)
182
183	markdown, err := converter.ConvertString(html)
184	if err != nil {
185		return "", err
186	}
187
188	return markdown, nil
189}