14 md "github.com/JohannesKaufmann/html-to-markdown"
15 "github.com/PuerkitoBio/goquery"
16 "github.com/charmbracelet/crush/internal/permission"
19const FetchToolName = "fetch"
22var fetchDescription []byte
24func NewFetchTool(permissions permission.Service, workingDir string, client *http.Client) fantasy.AgentTool {
26 client = &http.Client{
27 Timeout: 30 * time.Second,
28 Transport: &http.Transport{
30 MaxIdleConnsPerHost: 10,
31 IdleConnTimeout: 90 * time.Second,
36 return fantasy.NewParallelAgentTool(
38 string(fetchDescription),
39 func(ctx context.Context, params FetchParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
41 return fantasy.NewTextErrorResponse("URL parameter is required"), nil
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
49 if !strings.HasPrefix(params.URL, "http://") && !strings.HasPrefix(params.URL, "https://") {
50 return fantasy.NewTextErrorResponse("URL must start with http:// or https://"), nil
53 sessionID := GetSessionFromContext(ctx)
55 return fantasy.ToolResponse{}, fmt.Errorf("session ID is required for creating a new file")
58 p := permissions.Request(
59 permission.CreatePermissionRequest{
63 ToolName: FetchToolName,
65 Description: fmt.Sprintf("Fetch content from URL: %s", params.URL),
66 Params: FetchPermissionsParams(params),
71 return fantasy.ToolResponse{}, permission.ErrorPermissionDenied
74 // Handle timeout with context
76 if params.Timeout > 0 {
77 maxTimeout := 120 // 2 minutes
78 if params.Timeout > maxTimeout {
79 params.Timeout = maxTimeout
81 var cancel context.CancelFunc
82 requestCtx, cancel = context.WithTimeout(ctx, time.Duration(params.Timeout)*time.Second)
86 req, err := http.NewRequestWithContext(requestCtx, "GET", params.URL, nil)
88 return fantasy.ToolResponse{}, fmt.Errorf("failed to create request: %w", err)
91 req.Header.Set("User-Agent", "crush/1.0")
93 resp, err := client.Do(req)
95 return fantasy.ToolResponse{}, fmt.Errorf("failed to fetch URL: %w", err)
97 defer resp.Body.Close()
99 if resp.StatusCode != http.StatusOK {
100 return fantasy.NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
103 maxSize := int64(5 * 1024 * 1024) // 5MB
104 body, err := io.ReadAll(io.LimitReader(resp.Body, maxSize))
106 return fantasy.NewTextErrorResponse("Failed to read response body: " + err.Error()), nil
109 content := string(body)
111 isValidUt8 := utf8.ValidString(content)
113 return fantasy.NewTextErrorResponse("Response content is not valid UTF-8"), nil
115 contentType := resp.Header.Get("Content-Type")
119 if strings.Contains(contentType, "text/html") {
120 text, err := extractTextFromHTML(content)
122 return fantasy.NewTextErrorResponse("Failed to extract text from HTML: " + err.Error()), nil
128 if strings.Contains(contentType, "text/html") {
129 markdown, err := convertHTMLToMarkdown(content)
131 return fantasy.NewTextErrorResponse("Failed to convert HTML to Markdown: " + err.Error()), nil
136 content = "```\n" + content + "\n```"
139 // return only the body of the HTML document
140 if strings.Contains(contentType, "text/html") {
141 doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
143 return fantasy.NewTextErrorResponse("Failed to parse HTML: " + err.Error()), nil
145 body, err := doc.Find("body").Html()
147 return fantasy.NewTextErrorResponse("Failed to extract body from HTML: " + err.Error()), nil
150 return fantasy.NewTextErrorResponse("No body content found in HTML"), nil
152 content = "<html>\n<body>\n" + body + "\n</body>\n</html>"
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)
162 return fantasy.NewTextResponse(content), nil
166func extractTextFromHTML(html string) (string, error) {
167 doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
172 text := doc.Find("body").Text()
173 text = strings.Join(strings.Fields(text), " ")
178func convertHTMLToMarkdown(html string) (string, error) {
179 converter := md.NewConverter("", true, nil)
181 markdown, err := converter.ConvertString(html)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list