1package tools
2
3import (
4 "context"
5 _ "embed"
6 "fmt"
7 "net/http"
8 "os"
9 "strings"
10 "time"
11
12 "charm.land/fantasy"
13)
14
15//go:embed web_fetch.md
16var webFetchToolDescription []byte
17
18// NewWebFetchTool creates a simple web fetch tool for sub-agents (no permissions needed).
19func NewWebFetchTool(workingDir string, client *http.Client) fantasy.AgentTool {
20 if client == nil {
21 client = &http.Client{
22 Timeout: 30 * time.Second,
23 Transport: &http.Transport{
24 MaxIdleConns: 100,
25 MaxIdleConnsPerHost: 10,
26 IdleConnTimeout: 90 * time.Second,
27 },
28 }
29 }
30
31 return fantasy.NewAgentTool(
32 WebFetchToolName,
33 string(webFetchToolDescription),
34 func(ctx context.Context, params WebFetchParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
35 if params.URL == "" {
36 return fantasy.NewTextErrorResponse("url is required"), nil
37 }
38
39 content, err := FetchURLAndConvert(ctx, client, params.URL)
40 if err != nil {
41 return fantasy.NewTextErrorResponse(fmt.Sprintf("Failed to fetch URL: %s", err)), nil
42 }
43
44 hasLargeContent := len(content) > LargeContentThreshold
45 var result strings.Builder
46
47 if hasLargeContent {
48 tempFile, err := os.CreateTemp(workingDir, "page-*.md")
49 if err != nil {
50 return fantasy.NewTextErrorResponse(fmt.Sprintf("Failed to create temporary file: %s", err)), nil
51 }
52 tempFilePath := tempFile.Name()
53
54 if _, err := tempFile.WriteString(content); err != nil {
55 _ = tempFile.Close() // Best effort close
56 return fantasy.NewTextErrorResponse(fmt.Sprintf("Failed to write content to file: %s", err)), nil
57 }
58 if err := tempFile.Close(); err != nil {
59 return fantasy.NewTextErrorResponse(fmt.Sprintf("Failed to close temporary file: %s", err)), nil
60 }
61
62 result.WriteString(fmt.Sprintf("Fetched content from %s (large page)\n\n", params.URL))
63 result.WriteString(fmt.Sprintf("Content saved to: %s\n\n", tempFilePath))
64 result.WriteString("Use the view and grep tools to analyze this file.")
65 } else {
66 result.WriteString(fmt.Sprintf("Fetched content from %s:\n\n", params.URL))
67 result.WriteString(content)
68 }
69
70 return fantasy.NewTextResponse(result.String()), nil
71 })
72}