fetch.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. md "github.com/JohannesKaufmann/html-to-markdown"
  11. "github.com/PuerkitoBio/goquery"
  12. "github.com/kujtimiihoxha/termai/internal/config"
  13. "github.com/kujtimiihoxha/termai/internal/permission"
  14. )
  15. type FetchParams struct {
  16. URL string `json:"url"`
  17. Format string `json:"format"`
  18. Timeout int `json:"timeout,omitempty"`
  19. }
  20. type FetchPermissionsParams struct {
  21. URL string `json:"url"`
  22. Format string `json:"format"`
  23. Timeout int `json:"timeout,omitempty"`
  24. }
  25. type fetchTool struct {
  26. client *http.Client
  27. permissions permission.Service
  28. }
  29. const (
  30. FetchToolName = "fetch"
  31. fetchToolDescription = `Fetches content from a URL and returns it in the specified format.
  32. WHEN TO USE THIS TOOL:
  33. - Use when you need to download content from a URL
  34. - Helpful for retrieving documentation, API responses, or web content
  35. - Useful for getting external information to assist with tasks
  36. HOW TO USE:
  37. - Provide the URL to fetch content from
  38. - Specify the desired output format (text, markdown, or html)
  39. - Optionally set a timeout for the request
  40. FEATURES:
  41. - Supports three output formats: text, markdown, and html
  42. - Automatically handles HTTP redirects
  43. - Sets reasonable timeouts to prevent hanging
  44. - Validates input parameters before making requests
  45. LIMITATIONS:
  46. - Maximum response size is 5MB
  47. - Only supports HTTP and HTTPS protocols
  48. - Cannot handle authentication or cookies
  49. - Some websites may block automated requests
  50. TIPS:
  51. - Use text format for plain text content or simple API responses
  52. - Use markdown format for content that should be rendered with formatting
  53. - Use html format when you need the raw HTML structure
  54. - Set appropriate timeouts for potentially slow websites`
  55. )
  56. func NewFetchTool(permissions permission.Service) BaseTool {
  57. return &fetchTool{
  58. client: &http.Client{
  59. Timeout: 30 * time.Second,
  60. },
  61. permissions: permissions,
  62. }
  63. }
  64. func (t *fetchTool) Info() ToolInfo {
  65. return ToolInfo{
  66. Name: FetchToolName,
  67. Description: fetchToolDescription,
  68. Parameters: map[string]any{
  69. "url": map[string]any{
  70. "type": "string",
  71. "description": "The URL to fetch content from",
  72. },
  73. "format": map[string]any{
  74. "type": "string",
  75. "description": "The format to return the content in (text, markdown, or html)",
  76. },
  77. "timeout": map[string]any{
  78. "type": "number",
  79. "description": "Optional timeout in seconds (max 120)",
  80. },
  81. },
  82. Required: []string{"url", "format"},
  83. }
  84. }
  85. func (t *fetchTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  86. var params FetchParams
  87. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  88. return NewTextErrorResponse("Failed to parse fetch parameters: " + err.Error()), nil
  89. }
  90. if params.URL == "" {
  91. return NewTextErrorResponse("URL parameter is required"), nil
  92. }
  93. format := strings.ToLower(params.Format)
  94. if format != "text" && format != "markdown" && format != "html" {
  95. return NewTextErrorResponse("Format must be one of: text, markdown, html"), nil
  96. }
  97. if !strings.HasPrefix(params.URL, "http://") && !strings.HasPrefix(params.URL, "https://") {
  98. return NewTextErrorResponse("URL must start with http:// or https://"), nil
  99. }
  100. p := t.permissions.Request(
  101. permission.CreatePermissionRequest{
  102. Path: config.WorkingDirectory(),
  103. ToolName: FetchToolName,
  104. Action: "fetch",
  105. Description: fmt.Sprintf("Fetch content from URL: %s", params.URL),
  106. Params: FetchPermissionsParams{
  107. URL: params.URL,
  108. Format: params.Format,
  109. Timeout: params.Timeout,
  110. },
  111. },
  112. )
  113. if !p {
  114. return NewTextErrorResponse("Permission denied to fetch from URL: " + params.URL), nil
  115. }
  116. client := t.client
  117. if params.Timeout > 0 {
  118. maxTimeout := 120 // 2 minutes
  119. if params.Timeout > maxTimeout {
  120. params.Timeout = maxTimeout
  121. }
  122. client = &http.Client{
  123. Timeout: time.Duration(params.Timeout) * time.Second,
  124. }
  125. }
  126. req, err := http.NewRequestWithContext(ctx, "GET", params.URL, nil)
  127. if err != nil {
  128. return NewTextErrorResponse("Failed to create request: " + err.Error()), nil
  129. }
  130. req.Header.Set("User-Agent", "termai/1.0")
  131. resp, err := client.Do(req)
  132. if err != nil {
  133. return NewTextErrorResponse("Failed to execute request: " + err.Error()), nil
  134. }
  135. defer resp.Body.Close()
  136. if resp.StatusCode != http.StatusOK {
  137. return NewTextErrorResponse(fmt.Sprintf("Request failed with status code: %d", resp.StatusCode)), nil
  138. }
  139. maxSize := int64(5 * 1024 * 1024) // 5MB
  140. body, err := io.ReadAll(io.LimitReader(resp.Body, maxSize))
  141. if err != nil {
  142. return NewTextErrorResponse("Failed to read response body: " + err.Error()), nil
  143. }
  144. content := string(body)
  145. contentType := resp.Header.Get("Content-Type")
  146. switch format {
  147. case "text":
  148. if strings.Contains(contentType, "text/html") {
  149. text, err := extractTextFromHTML(content)
  150. if err != nil {
  151. return NewTextErrorResponse("Failed to extract text from HTML: " + err.Error()), nil
  152. }
  153. return NewTextResponse(text), nil
  154. }
  155. return NewTextResponse(content), nil
  156. case "markdown":
  157. if strings.Contains(contentType, "text/html") {
  158. markdown, err := convertHTMLToMarkdown(content)
  159. if err != nil {
  160. return NewTextErrorResponse("Failed to convert HTML to Markdown: " + err.Error()), nil
  161. }
  162. return NewTextResponse(markdown), nil
  163. }
  164. return NewTextResponse("```\n" + content + "\n```"), nil
  165. case "html":
  166. return NewTextResponse(content), nil
  167. default:
  168. return NewTextResponse(content), nil
  169. }
  170. }
  171. func extractTextFromHTML(html string) (string, error) {
  172. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  173. if err != nil {
  174. return "", err
  175. }
  176. text := doc.Text()
  177. text = strings.Join(strings.Fields(text), " ")
  178. return text, nil
  179. }
  180. func convertHTMLToMarkdown(html string) (string, error) {
  181. converter := md.NewConverter("", true, nil)
  182. markdown, err := converter.ConvertString(html)
  183. if err != nil {
  184. return "", err
  185. }
  186. return markdown, nil
  187. }