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