Files
harness/tools/web/webfetch.go
T
sausheong 9a013f6f4b Raise WebFetchTool's output cap to ~1M tokens
MaxOutputLength was 50,000 chars, truncating fetched pages to a few
paragraphs well before hitting any model's context window. Match Sonnet
5's 1M-token context using this codebase's 4-chars/token estimate
(session.Session.EstimateTokens), and raise the raw HTTP read cap
(maxFetchSize) to 8MB so plain-text/JSON responses that don't shrink
during HTML->markdown conversion aren't cut short before the output cap
even applies.
2026-09-22 17:45:40 +08:00

134 lines
3.9 KiB
Go

package web
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
"github.com/sausheong/harness/tool"
)
const (
maxFetchSize = 8 * 1024 * 1024 // 8MB raw read; headroom over MaxOutputLength since HTML->markdown shrinks most pages but plain text/JSON responses pass through near 1:1
fetchTimeout = 30 * time.Second
// MaxOutputLength caps fetched content at roughly 1M tokens, matching
// Sonnet 5's context window, using this codebase's own token estimate
// of 4 chars/token (see session.Session.EstimateTokens).
MaxOutputLength = 4_000_000
)
// WebFetchTool fetches a URL and returns its content as markdown.
type WebFetchTool struct{}
type webFetchInput struct {
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
func (t *WebFetchTool) Name() string { return "web_fetch" }
func (t *WebFetchTool) Description() string {
return "Fetch the content of a web page at the given URL. Returns the page content converted to readable markdown text. Use this to read documentation, articles, API responses, or any web content."
}
func (t *WebFetchTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "The URL to fetch (must start with http:// or https://)"
},
"headers": {
"type": "object",
"description": "Optional HTTP headers to include in the request",
"additionalProperties": { "type": "string" }
}
},
"required": ["url"]
}`)
}
// IsConcurrencySafe returns true — web_fetch is a pure read.
func (t *WebFetchTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
func (t *WebFetchTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in webFetchInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
}
if in.URL == "" {
return tool.ToolResult{Error: "url is required"}, nil
}
if !strings.HasPrefix(in.URL, "http://") && !strings.HasPrefix(in.URL, "https://") {
return tool.ToolResult{Error: "url must start with http:// or https://"}, nil
}
if err := ValidateURLNotInternal(in.URL); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
ctx, cancel := context.WithTimeout(ctx, fetchTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, in.URL, nil)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid URL: %v", err)}, nil
}
req.Header.Set("User-Agent", "harness/1.0 (Go agent framework)")
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,application/json;q=0.7,*/*;q=0.5")
for k, v := range in.Headers {
req.Header.Set(k, v)
}
client := SafeHTTPClient(fetchTimeout)
resp, err := client.Do(req)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("fetch failed: %v", err)}, nil
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return tool.ToolResult{Error: fmt.Sprintf("HTTP %d: %s", resp.StatusCode, resp.Status)}, nil
}
body, err := io.ReadAll(io.LimitReader(resp.Body, maxFetchSize))
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("read body failed: %v", err)}, nil
}
contentType := resp.Header.Get("Content-Type")
content := string(body)
// Convert HTML to markdown for readability
if strings.Contains(contentType, "text/html") || strings.Contains(contentType, "application/xhtml") {
md, err := htmltomarkdown.ConvertString(content)
if err == nil {
content = md
}
}
// Truncate very long content
if len(content) > MaxOutputLength {
content = content[:MaxOutputLength] + "\n\n[Content truncated — exceeded maximum length]"
}
return tool.ToolResult{
Output: content,
Metadata: map[string]any{
"url": in.URL,
"status": resp.StatusCode,
"content_type": contentType,
"length": len(body),
},
}, nil
}