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 // maxFetchTimeoutSeconds is the maximum allowed timeout for fetch requests (2 minutes)
77 const maxFetchTimeoutSeconds = 120
78
79 // Handle timeout with context
80 requestCtx := ctx
81 if params.Timeout > 0 {
82 if params.Timeout > maxFetchTimeoutSeconds {
83 params.Timeout = maxFetchTimeoutSeconds
84 }
85 var cancel context.CancelFunc
86 requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
87 defer cancel()
88 }
89
90 req, err := http.NewRequestWithContext(requestCtx, "GET", params.URL, nil)
91 if err != nil {
92 return fantasy.ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
93 }
94
95 req.Header.Set("User-Agent", "crush/1.0")
96
97 resp, err := client.Do(req)
98 if err != nil {
99 return fantasy.ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
100 }
101 defer resp.Body.Close()
102
103 if resp.StatusCode != http.StatusOK {
104 return fantasy.NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
105 }
106
107 // maxFetchResponseSizeBytes is the maximum size of response body to read (5MB)
108 const maxFetchResponseSizeBytes = int64(5 * 1024 * 1024)
109
110 maxSize := maxFetchResponseSizeBytes
111 body, err := io.ReadAll(io.LimitReader(resp.Body, maxSize))
112 if err != nil {
113 return fantasy.NewTextErrorResponse("Failed to read response body: " + err.Error()), nil
114 }
115
116 content := string(body)
117
118 validUTF8 := utf8.ValidString(content)
119 if !validUTF8 {
120 return fantasy.NewTextErrorResponse("Response content is not valid UTF-8"), nil
121 }
122 contentType := resp.Header.Get("Content-Type")
123
124 switch format {
125 case "text":
126 if strings.Contains(contentType, "text/html") {
127 text, err := extractTextFromHTML(content)
128 if err != nil {
129 return fantasy.NewTextErrorResponse("Failed to extract text from HTML: " + err.Error()), nil
130 }
131 content = text
132 }
133
134 case "markdown":
135 if strings.Contains(contentType, "text/html") {
136 markdown, err := convertHTMLToMarkdown(content)
137 if err != nil {
138 return fantasy.NewTextErrorResponse("Failed to convert HTML to Markdown: " + err.Error()), nil
139 }
140 content = markdown
141 }
142
143 content = "```\n" + content + "\n```"
144
145 case "html":
146 // return only the body of the HTML document
147 if strings.Contains(contentType, "text/html") {
148 doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
149 if err != nil {
150 return fantasy.NewTextErrorResponse("Failed to parse HTML: " + err.Error()), nil
151 }
152 body, err := doc.Find("body").Html()
153 if err != nil {
154 return fantasy.NewTextErrorResponse("Failed to extract body from HTML: " + err.Error()), nil
155 }
156 if body == "" {
157 return fantasy.NewTextErrorResponse("No body content found in HTML"), nil
158 }
159 content = "<html>\n<body>\n" + body + "\n</body>\n</html>"
160 }
161 }
162 // truncate content if it exceeds max read size
163 if int64(len(content)) > MaxReadSize {
164 content = content[:MaxReadSize]
165 content += fmt.Sprintf("\n\n[Content truncated to %d bytes]", MaxReadSize)
166 }
167
168 return fantasy.NewTextResponse(content), nil
169 })
170}
171
172func extractTextFromHTML(html string) (string, error) {
173 doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
174 if err != nil {
175 return "", err
176 }
177
178 text := doc.Find("body").Text()
179 text = strings.Join(strings.Fields(text), " ")
180
181 return text, nil
182}
183
184func convertHTMLToMarkdown(html string) (string, error) {
185 converter := md.NewConverter("", true, nil)
186
187 markdown, err := converter.ConvertString(html)
188 if err != nil {
189 return "", err
190 }
191
192 return markdown, nil
193}