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