Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(agent): preserve web evidence when page fetches fail

langcaiyea3da5cb57ab2
diff --git a/internal/agent/tools/web_fetch.go b/internal/agent/tools/web_fetch.go
index 507afc62b..deb8f6426 100644
--- a/internal/agent/tools/web_fetch.go
+++ b/internal/agent/tools/web_fetch.go
@@ -4,661 +4,285 @@ import (
"context"
"encoding/json"
"fmt"
- "io"
- "net"
- "net/http"
"net/url"
- "regexp"
"strings"
"sync"
- "time"
-
- "github.com/PuerkitoBio/goquery"
- "github.com/chromedp/chromedp"
+ webfetch "github.com/Tencent/WeKnora/internal/infrastructure/web_fetch"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
-const (
- webFetchTimeout = 60 * time.Second // timeout for web fetch
- webFetchMaxChars = 100000 // maximum number of characters to fetch
-)
-
var webFetchTool = BaseTool{
name: ToolWebFetch,
- description: `Fetch detailed web content from previously discovered short wN web page IDs and analyze it with an LLM.
+ description: `Fetch detailed content from web pages returned by web_search and analyze it with an LLM.
## Usage
- Receive one or more {url: "wN", prompt} combinations; the field name stays url, but its value is the short page ID
-- Fetch web page content and convert to Markdown text
-- Use prompt to call small model for analysis and summary (if model is available)
-- Return summary result and original content fragment
+- Fetch each page independently and return a structured status for every URL
+- Successful pages remain usable when other pages fail
## When to Use
-- **MANDATORY**: After web_search returns results, if content is truncated or incomplete, use web_fetch to get full page content
-- When web_search snippet is insufficient for answering the question`,
+- Use when a search snippet is insufficient or a claim needs full-page verification
+- web_search titles, URLs, and snippets remain usable evidence if fetching fails
+- Do not repeatedly fetch a non-retryable URL or expand searches after all fetches fail
+- When page verification is unavailable, answer from search summaries, disclose that limitation, and lower confidence for dynamic facts`,
schema: utils.GenerateSchema[WebFetchInput](),
}
-// WebFetchInput defines the input parameters for web fetch tool
+// WebFetchInput defines the input parameters for web fetch tool.
type WebFetchInput struct {
Items []WebFetchItem `json:"items" jsonschema:"Batch fetch tasks, each containing a short wN web page ID and prompt"`
}
-// WebFetchItem represents a single web fetch task
+// WebFetchItem represents a single web fetch task.
type WebFetchItem struct {
URL string `json:"url" jsonschema:"Short wN web page ID from web_search results"`
Prompt string `json:"prompt" jsonschema:"Prompt for analyzing the fetched web page content"`
}
-// webFetchParams is the parameters for the web fetch tool
-type webFetchParams struct {
- URL string
- Prompt string
-}
-
-// validatedParams holds validated input plus DNS-pinned host/IP for SSRF protection.
-// PinnedIP is the single IP we resolved at validation time; chromedp and HTTP both use it.
-type validatedParams struct {
- URL string
- Prompt string
- Host string
- Port string
- PinnedIP net.IP
+type webContentFetcher interface {
+ Fetch(context.Context, string) (string, error)
}
-// webFetchItemResult is the result for a web fetch item
type webFetchItemResult struct {
output string
data map[string]interface{}
- err error
+ status string
}
-// WebFetchTool fetches web page content and summarizes it using an LLM
+// WebFetchTool fetches web page content and summarizes it using an LLM.
type WebFetchTool struct {
BaseTool
- client *http.Client
+ fetcher webContentFetcher
chatModel chat.Chat
}
-// NewWebFetchTool creates a new web_fetch tool instance
+// NewWebFetchTool creates a new web_fetch tool instance.
func NewWebFetchTool(chatModel chat.Chat) *WebFetchTool {
- // Use SSRF-safe HTTP client to prevent redirect-based SSRF attacks
- ssrfConfig := utils.DefaultSSRFSafeHTTPClientConfig()
- ssrfConfig.Timeout = webFetchTimeout
+ return newWebFetchTool(chatModel, webfetch.NewFetcher())
+}
+func newWebFetchTool(chatModel chat.Chat, fetcher webContentFetcher) *WebFetchTool {
return &WebFetchTool{
BaseTool: webFetchTool,
- client: utils.NewSSRFSafeHTTPClient(ssrfConfig),
+ fetcher: fetcher,
chatModel: chatModel,
}
}
-// Execute 执行 web_fetch 工具
+// Execute runs web_fetch and preserves successful items when a batch partially fails.
func (t *WebFetchTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
logger.Infof(ctx, "[Tool][WebFetch] Execute started")
-
- // Parse args from json.RawMessage
var input WebFetchInput
if err := json.Unmarshal(args, &input); err != nil {
- logger.Errorf(ctx, "[Tool][WebFetch] Failed to parse args: %v", err)
- return &types.ToolResult{
- Success: false,
- Error: fmt.Sprintf("Failed to parse args: %v", err),
- }, err
+ return &types.ToolResult{Success: false, Error: fmt.Sprintf("failed to parse args: %v", err)}, err
}
-
if len(input.Items) == 0 {
- logger.Errorf(ctx, "[Tool][WebFetch] 参数缺失: items")
- return &types.ToolResult{
- Success: false,
- Error: "missing required parameter: items",
- }, nil
+ return &types.ToolResult{Success: false, Error: "missing required parameter: items"}, nil
}
results := make([]*webFetchItemResult, len(input.Items))
-
- var wg sync.WaitGroup
- wg.Add(len(input.Items))
-
- for idx := range input.Items {
- i := idx
- item := input.Items[i]
-
- params := webFetchParams{
- URL: item.URL,
- Prompt: item.Prompt,
- }
-
- go func(index int, p webFetchParams) {
- defer wg.Done()
-
- // Normalize URL before validation so we pin the host we actually fetch (e.g. raw.githubusercontent.com)
- finalURL := t.normalizeGitHubURL(p.URL)
- vp, err := t.validateAndResolve(webFetchParams{URL: finalURL, Prompt: p.Prompt})
- if err != nil {
- results[index] = &webFetchItemResult{
- err: err,
- data: map[string]interface{}{
- "url": p.URL,
- "prompt": p.Prompt,
- "error": err.Error(),
- },
- output: fmt.Sprintf("URL: %s\nError: %v\n\n", p.URL, err),
- }
- return
- }
-
- output, data, err := t.executeFetch(ctx, vp, p.URL)
- results[index] = &webFetchItemResult{
- output: output,
- data: data,
- err: err,
- }
- }(i, params)
- }
-
- wg.Wait()
-
- var builder strings.Builder
- builder.WriteString("=== Web Fetch Results ===\n\n")
-
- aggregated := make([]map[string]interface{}, 0, len(results))
- success := true
- var firstErr error
-
- for idx, res := range results {
- if res == nil {
- success = false
- if firstErr == nil {
- firstErr = fmt.Errorf("fetch item %d returned nil", idx)
- }
- builder.WriteString(fmt.Sprintf("#%d: No result (internal error)\n\n", idx+1))
+ seenURLs := make(map[string]struct{}, len(input.Items))
+ var waitGroup sync.WaitGroup
+ for index, item := range input.Items {
+ canonicalURL := canonicalFetchURL(item.URL)
+ if _, duplicate := seenURLs[canonicalURL]; duplicate {
+ results[index] = duplicateWebFetchResult(item)
continue
}
+ seenURLs[canonicalURL] = struct{}{}
+ waitGroup.Add(1)
+ go func(resultIndex int, fetchItem WebFetchItem) {
+ defer waitGroup.Done()
+ results[resultIndex] = t.fetchItem(ctx, fetchItem)
+ }(index, item)
+ }
+ waitGroup.Wait()
- builder.WriteString(fmt.Sprintf("#%d:\n%s", idx+1, res.output))
- if !strings.HasSuffix(res.output, "\n") {
- builder.WriteString("\n")
- }
- builder.WriteString("\n")
-
- if res.data != nil {
- aggregated = append(aggregated, res.data)
- }
+ return buildWebFetchToolResult(ctx, results), nil
+}
- if res.err != nil {
- success = false
- if firstErr == nil {
- firstErr = res.err
- }
- }
+func (t *WebFetchTool) fetchItem(ctx context.Context, item WebFetchItem) *webFetchItemResult {
+ displayURL := strings.TrimSpace(item.URL)
+ if strings.TrimSpace(item.Prompt) == "" {
+ return failedWebFetchResult(displayURL, false, "invalid_arguments", "prompt is required")
}
- // Add guidance for next steps
- builder.WriteString("\n=== Next Steps ===\n")
- if len(aggregated) > 0 {
- builder.WriteString("- ✅ Full page content has been fetched and analyzed.\n")
- builder.WriteString("- Evaluate if the content is sufficient to answer the question completely.\n")
- builder.WriteString("- Synthesize information from all fetched pages for comprehensive answers.\n")
- if !success {
- builder.WriteString("- ⚠️ Some URLs failed to fetch. Use available content or try alternative sources.\n")
- }
- } else {
- builder.WriteString("- ❌ No content was successfully fetched. Consider:\n")
- builder.WriteString(" - Verify URLs are accessible\n")
- builder.WriteString(" - Try alternative sources from web_search results\n")
- builder.WriteString(" - Check if information can be found in knowledge base instead\n")
+ fetchURL := normalizeGitHubURL(displayURL)
+ content, err := t.fetcher.Fetch(ctx, fetchURL)
+ if err != nil {
+ code, retryable, message := webfetch.ErrorDetails(err)
+ logger.Warnf(ctx, "[Tool][WebFetch] fetch failed url=%s code=%s retryable=%v err=%v", displayURL, code, retryable, err)
+ return failedWebFetchResult(displayURL, retryable, string(code), message)
}
data := map[string]interface{}{
- "results": aggregated,
- "count": len(aggregated),
- "display_type": "web_fetch_results",
+ "url": displayURL,
+ "status": "success",
+ "retryable": false,
+ "prompt": item.Prompt,
+ "raw_content": content,
+ "content_length": len(content),
+ "evidence_type": "fetched_page",
+ "summary_status": "not_requested",
+ }
+ summary, summaryErr := t.processWithLLM(ctx, item, content)
+ if summaryErr != nil {
+ data["summary_status"] = "failed"
+ data["summary_error_code"] = "summary_failed"
+ data["summary_error_message"] = summaryErr.Error()
+ logger.Warnf(ctx, "[Tool][WebFetch] summary failed url=%s err=%v", displayURL, summaryErr)
+ } else if summary != "" {
+ data["summary_status"] = "success"
+ data["summary"] = summary
}
- logger.Infof(ctx, "[Tool][WebFetch] Completed with success=%v, items=%d", success, len(aggregated))
-
- return &types.ToolResult{
- Success: success,
- Output: builder.String(),
- Data: data,
- Error: func() string {
- if firstErr != nil {
- return firstErr.Error()
- }
- return ""
- }(),
- }, nil
-}
-
-// parseParams parses the parameters for a web fetch item
-func (t *WebFetchTool) parseParams(item interface{}) webFetchParams {
- params := webFetchParams{}
- if m, ok := item.(map[string]interface{}); ok {
- if v, ok := m["url"].(string); ok {
- params.URL = strings.TrimSpace(v)
- }
- if v, ok := m["prompt"].(string); ok {
- params.Prompt = strings.TrimSpace(v)
- }
+ return &webFetchItemResult{
+ output: buildWebFetchOutput(item, content, summary, summaryErr),
+ data: data,
+ status: "success",
}
- return params
}
-// validateAndResolve validates parameters and resolves the host to a single public IP (DNS pinning).
-// The returned PinnedIP is used for both chromedp (host-resolver-rules) and HTTP to prevent DNS rebinding.
-func (t *WebFetchTool) validateAndResolve(p webFetchParams) (*validatedParams, error) {
- if p.URL == "" {
- return nil, fmt.Errorf("url is required")
- }
- if p.Prompt == "" {
- return nil, fmt.Errorf("prompt is required")
- }
- if !strings.HasPrefix(p.URL, "http://") && !strings.HasPrefix(p.URL, "https://") {
- return nil, fmt.Errorf("invalid URL format")
+func failedWebFetchResult(rawURL string, retryable bool, code, message string) *webFetchItemResult {
+ data := map[string]interface{}{
+ "url": rawURL,
+ "status": "failed",
+ "retryable": retryable,
+ "error_code": code,
+ "error_message": message,
+ }
+ return &webFetchItemResult{
+ output: fmt.Sprintf("URL: %s\nStatus: failed\nRetryable: %t\nError code: %s\nError: %s\n",
+ rawURL, retryable, code, message),
+ data: data,
+ status: "failed",
}
+}
- // SSRF protection: validate URL is safe (uses centralised entry-point with whitelist support)
- if err := utils.ValidateURLForSSRF(p.URL); err != nil {
- return nil, fmt.Errorf("URL rejected for security reasons: %v", err)
+func duplicateWebFetchResult(item WebFetchItem) *webFetchItemResult {
+ message := "duplicate URL skipped in this batch"
+ return &webFetchItemResult{
+ output: fmt.Sprintf("URL: %s\nStatus: skipped\nRetryable: false\nReason: %s\n", item.URL, message),
+ data: map[string]interface{}{
+ "url": item.URL,
+ "status": "skipped",
+ "retryable": false,
+ "error_code": "duplicate_url",
+ "error_message": message,
+ },
+ status: "skipped",
}
+}
- u, err := url.Parse(p.URL)
- if err != nil {
- return nil, fmt.Errorf("invalid URL: %w", err)
- }
- hostname := u.Hostname()
- port := u.Port()
- if port == "" {
- if u.Scheme == "https" {
- port = "443"
- } else {
- port = "80"
+func buildWebFetchToolResult(ctx context.Context, results []*webFetchItemResult) *types.ToolResult {
+ var builder strings.Builder
+ builder.WriteString("=== Web Fetch Results ===\n\n")
+ aggregated := make([]map[string]interface{}, 0, len(results))
+ successCount, failedCount, skippedCount := 0, 0, 0
+ for index, result := range results {
+ if result == nil {
+ result = failedWebFetchResult("", false, "internal_error", "fetch item returned no result")
}
- }
-
- // Resolve and pin to the first safe IP (same resolver as isSSRFSafeURL; we pin so chromedp cannot re-resolve).
- // Whitelisted hosts may resolve to private/restricted IPs, so we allow any IP for them.
- ips, err := net.DefaultResolver.LookupIP(context.Background(), "ip", hostname)
- if err != nil || len(ips) == 0 {
- return nil, fmt.Errorf("DNS lookup failed for %s: %w", hostname, err)
- }
- isWhitelisted := utils.IsSSRFWhitelisted(hostname)
- var pinnedIP net.IP
- for _, ip := range ips {
- if isWhitelisted || utils.IsPublicIP(ip) {
- pinnedIP = ip
- break
+ builder.WriteString(fmt.Sprintf("#%d:\n%s\n", index+1, result.output))
+ aggregated = append(aggregated, result.data)
+ switch result.status {
+ case "success":
+ successCount++
+ case "failed":
+ failedCount++
+ case "skipped":
+ skippedCount++
}
}
- if pinnedIP == nil {
- return nil, fmt.Errorf("no public IP available for host %s", hostname)
- }
-
- return &validatedParams{
- URL: p.URL,
- Prompt: p.Prompt,
- Host: hostname,
- Port: port,
- PinnedIP: pinnedIP,
- }, nil
-}
-
-// executeFetch executes a web fetch item. displayURL is the URL shown to the user (e.g. original); vp.URL is the normalized URL we fetch.
-func (t *WebFetchTool) executeFetch(
- ctx context.Context,
- vp *validatedParams,
- displayURL string,
-) (string, map[string]interface{}, error) {
- logger.Infof(ctx, "[Tool][WebFetch] Fetching URL: %s", displayURL)
- htmlContent, method, err := t.fetchHTMLContent(ctx, vp)
- if err != nil {
- logger.Errorf(ctx, "[Tool][WebFetch] 获取页面失败 url=%s err=%v", vp.URL, err)
- return fmt.Sprintf("URL: %s\nError: %v\n", displayURL, err),
- map[string]interface{}{
- "url": displayURL,
- "prompt": vp.Prompt,
- "error": err.Error(),
- }, err
- }
-
- textContent := t.convertHTMLToText(htmlContent)
-
- resultData := map[string]interface{}{
- "url": displayURL,
- "prompt": vp.Prompt,
- "raw_content": textContent,
- "content_length": len(textContent),
- "method": method,
- }
- params := webFetchParams{URL: displayURL, Prompt: vp.Prompt}
- var summary string
- var summaryErr error
- summary, summaryErr = t.processWithLLM(ctx, params, textContent)
- if summaryErr != nil {
- logger.Warnf(ctx, "[Tool][WebFetch] LLM 处理失败 url=%s err=%v", displayURL, summaryErr)
- } else if summary != "" {
- resultData["summary"] = summary
+ allFailed := successCount == 0 && failedCount > 0
+ builder.WriteString("=== Next Steps ===\n")
+ switch {
+ case allFailed:
+ builder.WriteString("- All page fetches failed. Stop expanding web searches and answer from existing web_search titles, URLs, and snippets.\n")
+ builder.WriteString("- Explicitly state that page content was not verified. Treat prices, inventory, and other dynamic facts as uncertain.\n")
+ case failedCount > 0:
+ builder.WriteString("- Use successful page content together with existing search snippets; failed URLs do not invalidate successful evidence.\n")
+ builder.WriteString("- Do not retry non-retryable failures. If evidence is sufficient, answer now.\n")
+ default:
+ builder.WriteString("- Synthesize the fetched evidence and answer when it is sufficient.\n")
}
- output := t.buildOutputText(params, textContent, summary, summaryErr)
-
- return output, resultData, summaryErr
-}
-
-// normalizeGitHubURL normalizes a GitHub URL
-func (t *WebFetchTool) normalizeGitHubURL(source string) string {
- if strings.Contains(source, "github.com") && strings.Contains(source, "/blob/") {
- source = strings.Replace(source, "github.com", "raw.githubusercontent.com", 1)
- source = strings.Replace(source, "/blob/", "/", 1)
+ logger.Infof(ctx, "[Tool][WebFetch] completed success=%d failed=%d skipped=%d", successCount, failedCount, skippedCount)
+ return &types.ToolResult{
+ Success: true,
+ Output: builder.String(),
+ Data: map[string]interface{}{
+ "results": aggregated,
+ "count": len(aggregated),
+ "successful_count": successCount,
+ "failed_count": failedCount,
+ "skipped_count": skippedCount,
+ "all_failed": allFailed,
+ "display_type": "web_fetch_results",
+ },
}
- return source
}
-// processWithLLM processes the content with an LLM
-func (t *WebFetchTool) processWithLLM(ctx context.Context, params webFetchParams, content string) (string, error) {
+func (t *WebFetchTool) processWithLLM(ctx context.Context, item WebFetchItem, content string) (string, error) {
if t.chatModel == nil {
- return "", fmt.Errorf("chat model not available for web_fetch")
+ return "", fmt.Errorf("chat model not available for web_fetch summary")
}
-
- systemMessage := "You are an intelligent assistant skilled at reading web page content. Answer the user's request based on the provided web page text. Never fabricate information that does not appear in the text."
- userTemplate := `User request:
-%s
-
-Web page content:
-%s`
-
messages := []chat.Message{
{
Role: "system",
- Content: systemMessage,
+ Content: "Answer the request from the supplied web page text. Never fabricate information that is absent from the page.",
},
{
Role: "user",
- Content: fmt.Sprintf(userTemplate, params.Prompt, content),
+ Content: fmt.Sprintf("User request:\n%s\n\nWeb page content:\n%s", item.Prompt, content),
},
}
-
modelCtx := types.WithLLMCallMetadata(ctx, "web_fetch_summary", "")
- response, err := t.chatModel.Chat(modelCtx, messages, &chat.ChatOptions{
- Temperature: 0.3,
- MaxTokens: 1024,
- })
+ response, err := t.chatModel.Chat(modelCtx, messages, &chat.ChatOptions{Temperature: 0.3, MaxTokens: 1024})
if err != nil {
return "", err
}
-
return strings.TrimSpace(response.Content), nil
}
-// buildOutputText builds the output text for a web fetch item
-func (t *WebFetchTool) buildOutputText(params webFetchParams, content string, summary string, summaryErr error) string {
+func buildWebFetchOutput(item WebFetchItem, content, summary string, summaryErr error) string {
var builder strings.Builder
- builder.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
- builder.WriteString(fmt.Sprintf("Prompt: %s\n", params.Prompt))
-
- if summaryErr == nil && summary != "" {
+ builder.WriteString(fmt.Sprintf("URL: %s\nStatus: success\nPrompt: %s\n", item.URL, item.Prompt))
+ if summary != "" {
builder.WriteString("Summary:\n")
builder.WriteString(summary)
builder.WriteString("\n")
- } else {
- builder.WriteString("Content Preview:\n")
- builder.WriteString(content)
- builder.WriteString("\n")
- }
-
- return builder.String()
-}
-
-// fetchHTMLContent fetches the HTML content for a web fetch item using pinned IP (DNS pinning).
-func (t *WebFetchTool) fetchHTMLContent(ctx context.Context, vp *validatedParams) (string, string, error) {
- html, err := t.fetchWithChromedp(ctx, vp)
- if err == nil && strings.TrimSpace(html) != "" {
- return html, "chromedp", nil
- }
-
- if err != nil {
- logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取失败 url=%s err=%v,尝试直接请求", vp.URL, err)
- }
-
- html, httpErr := t.fetchWithHTTP(ctx, vp)
- if httpErr != nil {
- if err != nil {
- return "", "", fmt.Errorf("chromedp error: %v; http error: %w", err, httpErr)
- }
- return "", "", httpErr
- }
-
- return html, "http", nil
-}
-
-// fetchWithChromedp fetches the HTML content with Chromedp. Uses host-resolver-rules to pin host to vp.PinnedIP (DNS rebinding protection).
-func (t *WebFetchTool) fetchWithChromedp(ctx context.Context, vp *validatedParams) (string, error) {
- logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取开始 url=%s", vp.URL)
-
- // DNS pinning: force Chrome to use the IP we resolved at validation time, not a second resolution.
- hostRule := fmt.Sprintf("MAP %s %s", vp.Host, vp.PinnedIP.String())
- opts := append(
- chromedp.DefaultExecAllocatorOptions[:],
- chromedp.Flag("host-resolver-rules", hostRule),
- chromedp.Flag("headless", true),
- chromedp.Flag("disable-setuid-sandbox", true),
- chromedp.Flag("disable-dev-shm-usage", true),
- chromedp.Flag("disable-gpu", true),
- chromedp.Flag("disable-blink-features", "AutomationControlled"),
- chromedp.Flag("disable-features", "VizDisplayCompositor"),
- chromedp.UserAgent(
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
- ),
- )
-
- allocCtx, cancel := chromedp.NewExecAllocator(ctx, opts...)
- defer cancel()
-
- ctx, cancel = chromedp.NewContext(allocCtx)
- defer cancel()
-
- ctx, cancel = context.WithTimeout(ctx, webFetchTimeout)
- defer cancel()
-
- var html string
- err := chromedp.Run(ctx,
- chromedp.Navigate(vp.URL),
- chromedp.WaitReady("body", chromedp.ByQuery),
- chromedp.OuterHTML("html", &html),
- )
- if err != nil {
- return "", fmt.Errorf("chromedp run failed: %w", err)
+ return builder.String()
}
-
- logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取成功 url=%s", vp.URL)
- return html, nil
-}
-
-// fetchWithHTTP fetches the HTML content with HTTP using pinned IP (same as chromedp path).
-func (t *WebFetchTool) fetchWithHTTP(ctx context.Context, vp *validatedParams) (string, error) {
- resp, err := t.fetchWithTimeout(ctx, vp)
- if err != nil {
- return "", err
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != http.StatusOK {
- return "", fmt.Errorf("request failed with status %d %s", resp.StatusCode, resp.Status)
- }
-
- limitedReader := io.LimitReader(resp.Body, webFetchMaxChars*2)
- htmlBytes, err := io.ReadAll(limitedReader)
- if err != nil {
- return "", fmt.Errorf("failed to read response body: %w", err)
+ if summaryErr != nil {
+ builder.WriteString(fmt.Sprintf("Summary status: failed (%s); fetched page content remains usable.\n", summaryErr))
}
-
- return string(htmlBytes), nil
+ builder.WriteString("Content Preview:\n")
+ builder.WriteString(content)
+ builder.WriteString("\n")
+ return builder.String()
}
-// fetchWithTimeout fetches the HTML content with a timeout. Uses pinned IP and original Host header (DNS pinning).
-func (t *WebFetchTool) fetchWithTimeout(ctx context.Context, vp *validatedParams) (*http.Response, error) {
- // Connect to pinned IP so we do not re-resolve; set Host so the server gets the right virtual host.
- hostPort := net.JoinHostPort(vp.PinnedIP.String(), vp.Port)
- rawURL := vp.URL
- u, _ := url.Parse(rawURL)
- u.Host = hostPort
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
- if err != nil {
- return nil, fmt.Errorf("failed to create request: %w", err)
+func canonicalFetchURL(rawURL string) string {
+ trimmed := strings.TrimSpace(rawURL)
+ parsedURL, err := url.Parse(trimmed)
+ if err != nil || parsedURL.Host == "" {
+ return trimmed
}
- // Preserve original host for TLS SNI and Host header (required for virtual hosting).
- req.Host = net.JoinHostPort(vp.Host, vp.Port)
-
- req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; WebFetchTool/1.0)")
- req.Header.Set(
- "Accept",
- "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
- )
- req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
- req.Header.Set("Cache-Control", "no-cache")
-
- return t.client.Do(req)
+ parsedURL.Fragment = ""
+ parsedURL.Host = strings.ToLower(parsedURL.Host)
+ return parsedURL.String()
}
-// convertHTMLToText converts the HTML content to text
-func (t *WebFetchTool) convertHTMLToText(html string) string {
- doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
- if err != nil {
- return t.basicTextExtraction(html)
+func normalizeGitHubURL(source string) string {
+ if strings.Contains(source, "github.com") && strings.Contains(source, "/blob/") {
+ source = strings.Replace(source, "github.com", "raw.githubusercontent.com", 1)
+ source = strings.Replace(source, "/blob/", "/", 1)
}
-
- doc.Find("script, style, nav, footer, header").Remove()
-
- var markdown strings.Builder
- doc.Find("body").Each(func(i int, body *goquery.Selection) {
- t.processNode(body, &markdown)
- })
-
- result := markdown.String()
- result = regexp.MustCompile(`\n{3,}`).ReplaceAllString(result, "\n\n")
- return strings.TrimSpace(result)
-}
-
-// processNode processes a node in the HTML content
-func (t *WebFetchTool) processNode(s *goquery.Selection, markdown *strings.Builder) {
- s.Contents().Each(func(i int, node *goquery.Selection) {
- nodeName := goquery.NodeName(node)
-
- switch nodeName {
- case "h1", "h2", "h3", "h4", "h5", "h6":
- headerLevel := int(nodeName[1] - '0')
- markdown.WriteString("\n")
- markdown.WriteString(strings.Repeat("#", headerLevel))
- markdown.WriteString(" ")
- markdown.WriteString(strings.TrimSpace(node.Text()))
- markdown.WriteString("\n\n")
- case "p":
- t.processNode(node, markdown)
- markdown.WriteString("\n\n")
- case "a":
- href, exists := node.Attr("href")
- text := strings.TrimSpace(node.Text())
- if exists && text != "" {
- markdown.WriteString("[")
- markdown.WriteString(text)
- markdown.WriteString("](")
- markdown.WriteString(href)
- markdown.WriteString(")")
- } else if text != "" {
- markdown.WriteString(text)
- }
- case "img":
- src, _ := node.Attr("src")
- alt, _ := node.Attr("alt")
- if src != "" {
- markdown.WriteString("![")
- markdown.WriteString(alt)
- markdown.WriteString("](")
- markdown.WriteString(src)
- markdown.WriteString(")\n\n")
- }
- case "ul", "ol":
- markdown.WriteString("\n")
- isOrdered := nodeName == "ol"
- node.Find("li").Each(func(idx int, li *goquery.Selection) {
- if isOrdered {
- fmt.Fprintf(markdown, "%d. ", idx+1)
- } else {
- markdown.WriteString("- ")
- }
- markdown.WriteString(strings.TrimSpace(li.Text()))
- markdown.WriteString("\n")
- })
- markdown.WriteString("\n")
- case "br":
- markdown.WriteString("\n")
- case "code":
- parent := node.Parent()
- if goquery.NodeName(parent) == "pre" {
- markdown.WriteString("\n```\n")
- markdown.WriteString(node.Text())
- markdown.WriteString("\n```\n\n")
- } else {
- markdown.WriteString("`")
- markdown.WriteString(node.Text())
- markdown.WriteString("`")
- }
- case "blockquote":
- lines := strings.Split(strings.TrimSpace(node.Text()), "\n")
- for _, line := range lines {
- markdown.WriteString("> ")
- markdown.WriteString(strings.TrimSpace(line))
- markdown.WriteString("\n")
- }
- markdown.WriteString("\n")
- case "strong", "b":
- markdown.WriteString("**")
- markdown.WriteString(strings.TrimSpace(node.Text()))
- markdown.WriteString("**")
- case "em", "i":
- markdown.WriteString("*")
- markdown.WriteString(strings.TrimSpace(node.Text()))
- markdown.WriteString("*")
- case "hr":
- markdown.WriteString("\n---\n\n")
- case "table":
- markdown.WriteString("\n")
- node.Find("tr").Each(func(idx int, tr *goquery.Selection) {
- tr.Find("th, td").Each(func(i int, cell *goquery.Selection) {
- markdown.WriteString("| ")
- markdown.WriteString(strings.TrimSpace(cell.Text()))
- markdown.WriteString(" ")
- })
- markdown.WriteString("|\n")
- if idx == 0 {
- tr.Find("th").Each(func(i int, _ *goquery.Selection) {
- markdown.WriteString("|---")
- })
- markdown.WriteString("|\n")
- }
- })
- markdown.WriteString("\n")
- case "#text":
- text := node.Text()
- if strings.TrimSpace(text) != "" {
- markdown.WriteString(text)
- }
- default:
- t.processNode(node, markdown)
- }
- })
-}
-
-// basicTextExtraction extracts the text from the HTML content
-func (t *WebFetchTool) basicTextExtraction(html string) string {
- re := regexp.MustCompile(`<[^>]*>`)
- text := re.ReplaceAllString(html, " ")
- text = regexp.MustCompile(`\s+`).ReplaceAllString(text, " ")
- return strings.TrimSpace(text)
+ return source
}
diff --git a/internal/agent/tools/web_fetch_test.go b/internal/agent/tools/web_fetch_test.go
new file mode 100644
index 000000000..1fcd6d786
--- /dev/null
+++ b/internal/agent/tools/web_fetch_test.go
@@ -0,0 +1,131 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "sync"
+ "testing"
+
+ webfetch "github.com/Tencent/WeKnora/internal/infrastructure/web_fetch"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type stubWebContentFetcher struct {
+ mu sync.Mutex
+ contents map[string]string
+ errors map[string]error
+ callCount map[string]int
+}
+
+func (fetcher *stubWebContentFetcher) Fetch(_ context.Context, rawURL string) (string, error) {
+ fetcher.mu.Lock()
+ defer fetcher.mu.Unlock()
+ fetcher.callCount[rawURL]++
+ if err := fetcher.errors[rawURL]; err != nil {
+ return "", err
+ }
+ return fetcher.contents[rawURL], nil
+}
+
+func TestWebFetchToolSingleURLSuccessSurvivesSummaryFailure(t *testing.T) {
+ const rawURL = "https://example.com/specs"
+ fetcher := newStubWebContentFetcher(map[string]string{rawURL: "official specifications"}, nil)
+ tool := newWebFetchTool(nil, fetcher)
+
+ result, err := tool.Execute(context.Background(), webFetchArgs(
+ WebFetchItem{URL: rawURL, Prompt: "extract specifications"},
+ ))
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.Equal(t, 1, result.Data["successful_count"])
+ items := result.Data["results"].([]map[string]interface{})
+ assert.Equal(t, "success", items[0]["status"])
+ assert.Equal(t, "failed", items[0]["summary_status"])
+ assert.Equal(t, "official specifications", items[0]["raw_content"])
+}
+
+func TestWebFetchToolPreservesPartialSuccess(t *testing.T) {
+ const successURL = "https://example.com/success"
+ const failedURL = "https://example.com/forbidden"
+ fetcher := newStubWebContentFetcher(
+ map[string]string{successURL: "verified page content"},
+ map[string]error{failedURL: fetchFailure(webfetch.ErrorHTTP403, false, "access denied")},
+ )
+ tool := newWebFetchTool(nil, fetcher)
+
+ result, err := tool.Execute(context.Background(), webFetchArgs(
+ WebFetchItem{URL: successURL, Prompt: "extract facts"},
+ WebFetchItem{URL: failedURL, Prompt: "extract facts"},
+ ))
+
+ require.NoError(t, err)
+ require.True(t, result.Success)
+ assert.Equal(t, 1, result.Data["successful_count"])
+ assert.Equal(t, 1, result.Data["failed_count"])
+ assert.Equal(t, false, result.Data["all_failed"])
+ items := result.Data["results"].([]map[string]interface{})
+ assert.Equal(t, "success", items[0]["status"])
+ assert.Equal(t, "failed", items[1]["status"])
+ assert.Equal(t, "http_403", items[1]["error_code"])
+ assert.Equal(t, false, items[1]["retryable"])
+}
+
+func TestWebFetchToolAllFailuresReturnStructuredFallback(t *testing.T) {
+ const firstURL = "https://example.com/dns"
+ const secondURL = "https://example.com/rate-limit"
+ fetcher := newStubWebContentFetcher(nil, map[string]error{
+ firstURL: fetchFailure(webfetch.ErrorDNS, true, "DNS lookup failed"),
+ secondURL: fetchFailure(webfetch.ErrorHTTP429, true, "rate limited"),
+ })
+ tool := newWebFetchTool(nil, fetcher)
+
+ result, err := tool.Execute(context.Background(), webFetchArgs(
+ WebFetchItem{URL: firstURL, Prompt: "extract facts"},
+ WebFetchItem{URL: secondURL, Prompt: "extract facts"},
+ ))
+
+ require.NoError(t, err)
+ require.True(t, result.Success, "structured fetch failures must not fail the whole tool call")
+ assert.Equal(t, true, result.Data["all_failed"])
+ assert.Equal(t, 0, result.Data["successful_count"])
+ assert.Contains(t, result.Output, "answer from existing web_search titles, URLs, and snippets")
+}
+
+func TestWebFetchToolDeduplicatesURLsWithinBatch(t *testing.T) {
+ const rawURL = "https://example.com/page#section"
+ const duplicateURL = "https://example.com/page"
+ fetcher := newStubWebContentFetcher(map[string]string{rawURL: "page content"}, nil)
+ tool := newWebFetchTool(nil, fetcher)
+
+ result, err := tool.Execute(context.Background(), webFetchArgs(
+ WebFetchItem{URL: rawURL, Prompt: "extract facts"},
+ WebFetchItem{URL: duplicateURL, Prompt: "extract facts"},
+ ))
+
+ require.NoError(t, err)
+ assert.Equal(t, 1, fetcher.callCount[rawURL])
+ assert.Equal(t, 0, fetcher.callCount[duplicateURL])
+ assert.Equal(t, 1, result.Data["skipped_count"])
+ items := result.Data["results"].([]map[string]interface{})
+ assert.Equal(t, "duplicate_url", items[1]["error_code"])
+}
+
+func newStubWebContentFetcher(contents map[string]string, failures map[string]error) *stubWebContentFetcher {
+ return &stubWebContentFetcher{
+ contents: contents,
+ errors: failures,
+ callCount: make(map[string]int),
+ }
+}
+
+func fetchFailure(code webfetch.ErrorCode, retryable bool, message string) error {
+ return &webfetch.FetchError{Code: code, Retryable: retryable, Err: errors.New(message)}
+}
+
+func webFetchArgs(items ...WebFetchItem) json.RawMessage {
+ encoded, _ := json.Marshal(WebFetchInput{Items: items})
+ return encoded
+}
diff --git a/internal/agent/tools/web_search.go b/internal/agent/tools/web_search.go
index 008789c05..1846e0a17 100644
--- a/internal/agent/tools/web_search.go
+++ b/internal/agent/tools/web_search.go
@@ -57,13 +57,14 @@ var webSearchTool = BaseTool{
}
` + "`" + `
-## Tips
+## Evidence and Fallback
- Results are automatically compressed using RAG to extract relevant content
- Search results are stored in a temporary knowledge base for the session
-- Use this tool when knowledge bases don't have the information you need
-- Results include a short wN page ID, title, snippet, and content snippet (may be truncated)
-- **CRITICAL**: If content is truncated or you need full details, pass that wN value to **web_fetch** to fetch complete page content
+- Titles, URLs, snippets, and content snippets are usable search-summary evidence
+- Use web_fetch only when the snippet is insufficient or full-page verification is important
+- If web_fetch fails, keep the search evidence, disclose that page content was not verified, and lower confidence for dynamic facts
+- Do not repeat equivalent searches merely because a page could not be fetched
- Maximum %d results will be returned per search`,
schema: utils.GenerateSchema[WebSearchInput](),
}
@@ -250,12 +251,14 @@ func (t *WebSearchTool) Execute(ctx context.Context, args json.RawMessage) (*typ
output += "\n"
resultData := map[string]interface{}{
- "result_index": i + 1,
- "title": result.Title,
- "url": result.URL,
- "snippet": result.Snippet,
- "content": result.Content,
- "source": result.Source,
+ "result_index": i + 1,
+ "title": result.Title,
+ "url": result.URL,
+ "snippet": result.Snippet,
+ "content": result.Content,
+ "source": result.Source,
+ "evidence_type": "search_summary",
+ "page_verified": false,
}
if result.PublishedAt != nil {
resultData["published_at"] = result.PublishedAt.Format(time.RFC3339)
@@ -266,9 +269,9 @@ func (t *WebSearchTool) Execute(ctx context.Context, args json.RawMessage) (*typ
// Add guidance for next steps
output += "\n=== Next Steps ===\n"
if len(webResults) > 0 {
- output += "- ⚠️ Content may be truncated (showing first 500 chars). Use web_fetch to get full page content.\n"
- output += "- Extract URLs from results above and use web_fetch with appropriate prompts to get detailed information.\n"
- output += "- Synthesize information from multiple sources for comprehensive answers.\n"
+ output += "- Titles, URLs, snippets, and content snippets are usable search-summary evidence.\n"
+ output += "- If the evidence is sufficient, answer now. Use web_fetch only for claims that need full-page verification.\n"
+ output += "- If fetching fails, retain these results, disclose that page content was not verified, and avoid presenting dynamic facts as certain.\n"
} else {
output += "- No web search results found. Consider:\n"
output += " - Try different search queries or keywords\n"
diff --git a/internal/infrastructure/web_fetch/fetcher.go b/internal/infrastructure/web_fetch/fetcher.go
index dd45de903..476e1ff7a 100644
--- a/internal/infrastructure/web_fetch/fetcher.go
+++ b/internal/infrastructure/web_fetch/fetcher.go
@@ -1,11 +1,14 @@
// Package web_fetch provides a public URL content fetcher with SSRF protection.
-// It extracts core logic from the agent WebFetchTool so it can be used by the chat pipeline.
package web_fetch
import (
"context"
+ "crypto/tls"
+ "crypto/x509"
+ "errors"
"fmt"
"io"
+ "net"
"net/http"
"net/url"
"strings"
@@ -18,39 +21,148 @@ import (
const (
fetchTimeout = 15 * time.Second
- maxBodySize = 100 * 1024 // 100KB
+ maxBodySize = 100 * 1024
)
-// FetchURLContent fetches a URL and returns its text content (HTML converted to clean text).
-// Includes SSRF validation, redirect re-validation, dial-time guards, and content size limits.
-func FetchURLContent(ctx context.Context, rawURL string) (string, error) {
- if rawURL == "" {
- return "", fmt.Errorf("url is empty")
+// ErrorCode identifies the stage and class of a fetch failure.
+type ErrorCode string
+
+const (
+ ErrorInvalidURL ErrorCode = "invalid_url"
+ ErrorDNS ErrorCode = "dns_failed"
+ ErrorTimeout ErrorCode = "connection_timeout"
+ ErrorTLS ErrorCode = "tls_failed"
+ ErrorHTTP403 ErrorCode = "http_403"
+ ErrorHTTP429 ErrorCode = "http_429"
+ ErrorHTTP5xx ErrorCode = "http_5xx"
+ ErrorHTTPStatus ErrorCode = "http_status"
+ ErrorSSRFRejected ErrorCode = "ssrf_rejected"
+ ErrorRedirectRejected ErrorCode = "redirect_rejected"
+ ErrorRead ErrorCode = "read_failed"
+ ErrorHTMLParse ErrorCode = "html_parse_failed"
+ ErrorEmptyContent ErrorCode = "empty_content"
+ ErrorConnection ErrorCode = "connection_failed"
+)
+
+// FetchError carries stable, machine-readable failure details.
+type FetchError struct {
+ Code ErrorCode
+ Retryable bool
+ Err error
+}
+
+func (e *FetchError) Error() string {
+ if e == nil {
+ return ""
+ }
+ if e.Err == nil {
+ return string(e.Code)
}
+ return e.Err.Error()
+}
+
+func (e *FetchError) Unwrap() error {
+ if e == nil {
+ return nil
+ }
+ return e.Err
+}
- if err := utils.ValidateURLForSSRF(rawURL); err != nil {
- return "", fmt.Errorf("URL rejected: %w", err)
+// ErrorDetails returns stable fields suitable for tool responses and logs.
+func ErrorDetails(err error) (ErrorCode, bool, string) {
+ if err == nil {
+ return "", false, ""
}
+ var fetchErr *FetchError
+ if errors.As(err, &fetchErr) {
+ return fetchErr.Code, fetchErr.Retryable, fetchErr.Error()
+ }
+ return ErrorConnection, true, err.Error()
+}
+
+// Fetcher fetches and extracts public web pages through an SSRF-safe client.
+type Fetcher struct {
+ client *http.Client
+ timeout time.Duration
+ maxBodySize int64
+ validateURL func(string) error
+}
- u, err := url.Parse(rawURL)
+// NewFetcher creates a production fetcher with DNS and redirect SSRF guards.
+func NewFetcher() *Fetcher {
+ return &Fetcher{
+ client: utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
+ Timeout: fetchTimeout,
+ MaxRedirects: 10,
+ }),
+ timeout: fetchTimeout,
+ maxBodySize: maxBodySize,
+ validateURL: utils.ValidateURLForSSRF,
+ }
+}
+
+// FetchURLContent preserves the existing package-level API.
+func FetchURLContent(ctx context.Context, rawURL string) (string, error) {
+ return NewFetcher().Fetch(ctx, rawURL)
+}
+
+// Fetch downloads a page and returns clean text content.
+func (f *Fetcher) Fetch(ctx context.Context, rawURL string) (string, error) {
+ if strings.TrimSpace(rawURL) == "" {
+ return "", newFetchError(ErrorInvalidURL, false, "url is empty")
+ }
+ parsedURL, err := url.Parse(rawURL)
if err != nil {
- return "", fmt.Errorf("invalid URL: %w", err)
+ return "", newFetchError(ErrorInvalidURL, false, "invalid URL: %v", err)
+ }
+ if (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") || parsedURL.Hostname() == "" {
+ return "", newFetchError(ErrorInvalidURL, false, "invalid URL format")
+ }
+ if err := f.validateURL(rawURL); err != nil {
+ return "", classifyValidationError(err)
}
- hostname := u.Hostname()
- ctx, cancel := context.WithTimeout(ctx, fetchTimeout)
+ requestCtx, cancel := context.WithTimeout(ctx, f.timeout)
defer cancel()
+ req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, rawURL, nil)
+ if err != nil {
+ return "", newFetchError(ErrorInvalidURL, false, "invalid URL: %v", err)
+ }
+ setBrowserHeaders(req, parsedURL)
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
+ resp, err := f.client.Do(req)
+ if err != nil {
+ return "", classifyRequestError(err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ return "", classifyHTTPStatus(resp.StatusCode, resp.Status)
+ }
+
+ body, err := io.ReadAll(io.LimitReader(resp.Body, f.maxBodySize))
+ if err != nil {
+ return "", newFetchError(ErrorRead, true, "read failed: %v", err)
+ }
+ if len(body) == 0 {
+ return "", newFetchError(ErrorEmptyContent, false, "page body is empty")
+ }
+
+ content, err := htmlToText(string(body))
if err != nil {
return "", err
}
+ if strings.TrimSpace(content) == "" {
+ return "", newFetchError(ErrorEmptyContent, false, "page contains no readable text")
+ }
- // Browser-like headers to reduce 403 rejections.
- req.Header.Set("User-Agent",
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
- req.Header.Set("Accept",
- "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
+ logger.Infof(ctx, "[WebFetch] fetched %s → %d chars", rawURL, len(content))
+ return content, nil
+}
+
+func setBrowserHeaders(req *http.Request, parsedURL *url.URL) {
+ req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
+ req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
req.Header.Set("Accept-Encoding", "identity")
req.Header.Set("Cache-Control", "no-cache")
@@ -63,68 +175,115 @@ func FetchURLContent(ctx context.Context, rawURL string) (string, error) {
req.Header.Set("Sec-Fetch-Site", "none")
req.Header.Set("Sec-Fetch-User", "?1")
req.Header.Set("Upgrade-Insecure-Requests", "1")
- req.Header.Set("Referer", u.Scheme+"://"+hostname+"/")
+ req.Header.Set("Referer", parsedURL.Scheme+"://"+parsedURL.Hostname()+"/")
+}
- client := utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
- Timeout: fetchTimeout,
- MaxRedirects: 10,
- })
- resp, err := client.Do(req)
- if err != nil {
- return "", fmt.Errorf("fetch failed: %w", err)
+func classifyHTTPStatus(statusCode int, status string) error {
+ switch {
+ case statusCode == http.StatusForbidden:
+ return newFetchError(ErrorHTTP403, false, "HTTP %s", status)
+ case statusCode == http.StatusTooManyRequests:
+ return newFetchError(ErrorHTTP429, true, "HTTP %s", status)
+ case statusCode >= http.StatusInternalServerError:
+ return newFetchError(ErrorHTTP5xx, true, "HTTP %s", status)
+ default:
+ return newFetchError(ErrorHTTPStatus, false, "HTTP %s", status)
}
- defer resp.Body.Close()
+}
- if resp.StatusCode != http.StatusOK {
- return "", fmt.Errorf("HTTP %d %s", resp.StatusCode, resp.Status)
+func classifyValidationError(err error) error {
+ message := strings.ToLower(err.Error())
+ if strings.Contains(message, "dns resolution failed") || strings.Contains(message, "dns lookup failed") {
+ return newFetchError(ErrorDNS, true, "DNS lookup failed: %v", err)
}
+ return newFetchError(ErrorSSRFRejected, false, "URL rejected: %v", err)
+}
- body, err := io.ReadAll(io.LimitReader(resp.Body, maxBodySize))
- if err != nil {
- return "", fmt.Errorf("read failed: %w", err)
+func classifyRequestError(err error) error {
+ if errors.Is(err, context.DeadlineExceeded) {
+ return newFetchError(ErrorTimeout, true, "fetch timed out: %v", err)
+ }
+ var dnsErr *net.DNSError
+ if errors.As(err, &dnsErr) {
+ return newFetchError(ErrorDNS, true, "DNS lookup failed: %v", err)
+ }
+ var netErr net.Error
+ if errors.As(err, &netErr) && netErr.Timeout() {
+ return newFetchError(ErrorTimeout, true, "fetch timed out: %v", err)
+ }
+ var unknownAuthority x509.UnknownAuthorityError
+ var certificateInvalid x509.CertificateInvalidError
+ var hostnameError x509.HostnameError
+ var recordHeaderError tls.RecordHeaderError
+ if errors.As(err, &unknownAuthority) || errors.As(err, &certificateInvalid) ||
+ errors.As(err, &hostnameError) || errors.As(err, &recordHeaderError) {
+ return newFetchError(ErrorTLS, false, "TLS validation failed: %v", err)
+ }
+ if errors.Is(err, utils.ErrSSRFRedirectBlocked) {
+ return newFetchError(ErrorRedirectRejected, false, "redirect rejected: %v", err)
+ }
+ var urlErr *url.Error
+ if errors.As(err, &urlErr) {
+ redirectMessage := strings.ToLower(urlErr.Err.Error())
+ if strings.Contains(redirectMessage, "redirect") || strings.Contains(redirectMessage, "stopped after") {
+ return newFetchError(ErrorRedirectRejected, false, "redirect rejected: %v", err)
+ }
}
- text := htmlToText(string(body))
- logger.Infof(ctx, "[WebFetch] fetched %s → %d chars", rawURL, len(text))
- return text, nil
+ message := strings.ToLower(err.Error())
+ if strings.Contains(message, "connection blocked:") {
+ return newFetchError(ErrorSSRFRejected, false, "URL rejected: %v", err)
+ }
+ if strings.Contains(message, "certificate") || strings.Contains(message, "tls") {
+ return newFetchError(ErrorTLS, false, "TLS validation failed: %v", err)
+ }
+ return newFetchError(ErrorConnection, true, "fetch failed: %v", err)
}
-// htmlToText extracts clean text from HTML, removing scripts/styles/nav.
-func htmlToText(html string) string {
+func newFetchError(code ErrorCode, retryable bool, format string, args ...interface{}) error {
+ return &FetchError{Code: code, Retryable: retryable, Err: fmt.Errorf(format, args...)}
+}
+
+func htmlToText(html string) (string, error) {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
- return stripTags(html)
+ fallback := stripTags(html)
+ if fallback == "" {
+ return "", newFetchError(ErrorHTMLParse, false, "HTML parse failed: %v", err)
+ }
+ return fallback, nil
}
doc.Find("script, style, nav, footer, header, iframe, noscript, svg, img").Remove()
- var sb strings.Builder
- doc.Find("body").Each(func(i int, s *goquery.Selection) {
- sb.WriteString(s.Text())
+ var builder strings.Builder
+ doc.Find("body").Each(func(_ int, selection *goquery.Selection) {
+ builder.WriteString(selection.Text())
})
- text := sb.String()
-
- lines := strings.Split(text, "\n")
- var cleaned []string
+ lines := strings.Split(builder.String(), "\n")
+ cleaned := make([]string, 0, len(lines))
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
cleaned = append(cleaned, line)
}
}
- return strings.Join(cleaned, "\n")
+ return strings.Join(cleaned, "\n"), nil
}
-func stripTags(s string) string {
- var sb strings.Builder
+func stripTags(html string) string {
+ var builder strings.Builder
inTag := false
- for _, r := range s {
- if r == '<' {
+ for _, char := range html {
+ switch char {
+ case '<':
inTag = true
- } else if r == '>' {
+ case '>':
inTag = false
- } else if !inTag {
- sb.WriteRune(r)
+ default:
+ if !inTag {
+ builder.WriteRune(char)
+ }
}
}
- return sb.String()
+ return strings.TrimSpace(builder.String())
}
diff --git a/internal/infrastructure/web_fetch/fetcher_test.go b/internal/infrastructure/web_fetch/fetcher_test.go
new file mode 100644
index 000000000..6ec0abe85
--- /dev/null
+++ b/internal/infrastructure/web_fetch/fetcher_test.go
@@ -0,0 +1,135 @@
+package web_fetch
+
+import (
+ "context"
+ "crypto/x509"
+ "errors"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
+ return function(request)
+}
+
+func TestFetcherFetchSuccess(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
+ _, _ = writer.Write([]byte("<html><body><main>official specifications</main></body></html>"))
+ }))
+ defer server.Close()
+
+ fetcher := newTestFetcher(server.Client())
+ content, err := fetcher.Fetch(context.Background(), server.URL)
+
+ require.NoError(t, err)
+ assert.Contains(t, content, "official specifications")
+}
+
+func TestFetcherClassifiesHTTPStatus(t *testing.T) {
+ tests := []struct {
+ name string
+ status int
+ code ErrorCode
+ retryable bool
+ }{
+ {name: "forbidden", status: http.StatusForbidden, code: ErrorHTTP403, retryable: false},
+ {name: "rate limited", status: http.StatusTooManyRequests, code: ErrorHTTP429, retryable: true},
+ {name: "server error", status: http.StatusServiceUnavailable, code: ErrorHTTP5xx, retryable: true},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
+ writer.WriteHeader(test.status)
+ }))
+ defer server.Close()
+
+ _, err := newTestFetcher(server.Client()).Fetch(context.Background(), server.URL)
+ code, retryable, _ := ErrorDetails(err)
+ assert.Equal(t, test.code, code)
+ assert.Equal(t, test.retryable, retryable)
+ })
+ }
+}
+
+func TestFetcherClassifiesNetworkFailures(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ code ErrorCode
+ retryable bool
+ }{
+ {name: "dns", err: &net.DNSError{Err: "no such host", Name: "invalid.example"}, code: ErrorDNS, retryable: true},
+ {name: "timeout", err: context.DeadlineExceeded, code: ErrorTimeout, retryable: true},
+ {name: "tls", err: x509.HostnameError{Host: "example.com"}, code: ErrorTLS, retryable: false},
+ {name: "redirect", err: errors.New("redirect blocked by SSRF private address"), code: ErrorRedirectRejected, retryable: false},
+ {name: "dial-time SSRF", err: errors.New("connection blocked: host resolves to restricted IP"), code: ErrorSSRFRejected, retryable: false},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
+ return nil, test.err
+ })}
+ _, err := newTestFetcher(client).Fetch(context.Background(), "https://example.com")
+ code, retryable, _ := ErrorDetails(err)
+ assert.Equal(t, test.code, code)
+ assert.Equal(t, test.retryable, retryable)
+ })
+ }
+}
+
+func TestFetcherClassifiesDNSFailureDuringSSRFValidation(t *testing.T) {
+ fetcher := newTestFetcher(&http.Client{})
+ fetcher.validateURL = func(string) error {
+ return errors.New("SSRF validation failed: DNS resolution failed for hostname unavailable.example")
+ }
+
+ _, err := fetcher.Fetch(context.Background(), "https://unavailable.example")
+ code, retryable, _ := ErrorDetails(err)
+
+ assert.Equal(t, ErrorDNS, code)
+ assert.True(t, retryable)
+}
+
+func TestFetcherRejectsEmptyContent(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
+ _, _ = writer.Write([]byte("<html><body><script>ignored()</script></body></html>"))
+ }))
+ defer server.Close()
+
+ _, err := newTestFetcher(server.Client()).Fetch(context.Background(), server.URL)
+ code, retryable, _ := ErrorDetails(err)
+ assert.Equal(t, ErrorEmptyContent, code)
+ assert.False(t, retryable)
+}
+
+func TestFetcherClassifiesInvalidAndSSRFURLs(t *testing.T) {
+ fetcher := NewFetcher()
+ _, invalidErr := fetcher.Fetch(context.Background(), "not-a-url")
+ invalidCode, invalidRetryable, _ := ErrorDetails(invalidErr)
+ assert.Equal(t, ErrorInvalidURL, invalidCode)
+ assert.False(t, invalidRetryable)
+
+ _, ssrfErr := fetcher.Fetch(context.Background(), "http://127.0.0.1:1/private")
+ ssrfCode, ssrfRetryable, _ := ErrorDetails(ssrfErr)
+ assert.Equal(t, ErrorSSRFRejected, ssrfCode)
+ assert.False(t, ssrfRetryable)
+}
+
+func newTestFetcher(client *http.Client) *Fetcher {
+ return &Fetcher{
+ client: client,
+ timeout: time.Second,
+ maxBodySize: maxBodySize,
+ validateURL: func(string) error { return nil },
+ }
+}
diff --git a/internal/modelcontext/model_output.go b/internal/modelcontext/model_output.go
index ca01792f0..5804f37f0 100644
--- a/internal/modelcontext/model_output.go
+++ b/internal/modelcontext/model_output.go
@@ -348,9 +348,13 @@ func (r *sourceRegistry) modelWebSearchOutput(rows []map[string]interface{}, fal
}
handle := r.RegisterWeb(rawURL, stringValue(row, "title"))
fmt.Fprintf(&b, " <page id=\"%s\" title=\"%s\">\n", handle, escapeAttr(stringValue(row, "title")))
+ b.WriteString(" <evidence type=\"search_summary\" verified=\"false\" />\n")
if snippet := stringValue(row, "snippet"); snippet != "" {
fmt.Fprintf(&b, " <match>%s</match>\n", escapeText(snippet))
}
+ if content := stringValue(row, "content"); content != "" && content != stringValue(row, "snippet") {
+ fmt.Fprintf(&b, " <content>%s</content>\n", escapeText(content))
+ }
if published := stringValue(row, "published_at"); published != "" {
fmt.Fprintf(&b, " <published>%s</published>\n", escapeText(published))
}
@@ -370,7 +374,7 @@ func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fall
}
var b strings.Builder
b.WriteString("<retrieval type=\"web\" mode=\"fetch\">\n")
- count := 0
+ count, successCount, failedCount := 0, 0, 0
for _, row := range rows {
rawURL := stringValue(row, "url")
if rawURL == "" {
@@ -378,16 +382,39 @@ func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fall
}
title := stringValue(row, "title")
handle := r.RegisterWeb(rawURL, title)
- fmt.Fprintf(&b, " <page id=\"%s\"", handle)
+ status := stringValue(row, "status")
+ if status == "" {
+ status = "success"
+ }
+ fmt.Fprintf(&b, " <page id=\"%s\" status=\"%s\"", handle, escapeAttr(status))
if title != "" {
fmt.Fprintf(&b, " title=\"%s\"", escapeAttr(title))
}
- b.WriteString(" view=\"full\">\n")
- if summary := stringValue(row, "summary"); summary != "" {
- fmt.Fprintf(&b, " <summary>%s</summary>\n", escapeText(summary))
- }
- if content := stringValue(row, "raw_content"); content != "" {
- fmt.Fprintf(&b, " <content>%s</content>\n", escapeText(content))
+ if status == "success" {
+ b.WriteString(" view=\"full\">\n")
+ successCount++
+ if summary := stringValue(row, "summary"); summary != "" {
+ fmt.Fprintf(&b, " <summary>%s</summary>\n", escapeText(summary))
+ }
+ if summaryStatus := stringValue(row, "summary_status"); summaryStatus == "failed" {
+ fmt.Fprintf(&b, " <summary_error code=\"%s\">%s</summary_error>\n",
+ escapeAttr(stringValue(row, "summary_error_code")), escapeText(stringValue(row, "summary_error_message")))
+ }
+ if content := stringValue(row, "raw_content"); content != "" {
+ fmt.Fprintf(&b, " <content>%s</content>\n", escapeText(content))
+ }
+ } else {
+ fmt.Fprintf(&b, " retryable=\"%t\"", boolValue(row, "retryable"))
+ if errorCode := stringValue(row, "error_code"); errorCode != "" {
+ fmt.Fprintf(&b, " error_code=\"%s\"", escapeAttr(errorCode))
+ }
+ b.WriteString(">\n")
+ if errorMessage := stringValue(row, "error_message"); errorMessage != "" {
+ fmt.Fprintf(&b, " <error>%s</error>\n", escapeText(errorMessage))
+ }
+ if status == "failed" {
+ failedCount++
+ }
}
b.WriteString(" </page>\n")
count++
@@ -396,6 +423,16 @@ func (r *sourceRegistry) modelWebFetchOutput(rows []map[string]interface{}, fall
if count == 0 {
return r.CompactKnownText(fallback)
}
+ if failedCount > 0 {
+ b.WriteString("\n\n=== Next Steps ===\n")
+ if successCount == 0 {
+ b.WriteString("- All page fetches failed. Stop expanding web searches and answer from existing web_search titles, URLs, and snippets.\n")
+ b.WriteString("- Explicitly state that page content was not verified and treat dynamic facts as uncertain.")
+ } else {
+ b.WriteString("- Use successful page content together with existing search snippets; failed URLs do not invalidate successful evidence.\n")
+ b.WriteString("- Do not retry non-retryable failures. If evidence is sufficient, answer now.")
+ }
+ }
return b.String()
}
diff --git a/internal/modelcontext/sources_test.go b/internal/modelcontext/sources_test.go
index afb207cf0..6dac9b7fd 100644
--- a/internal/modelcontext/sources_test.go
+++ b/internal/modelcontext/sources_test.go
@@ -272,6 +272,7 @@ func TestModelOutputWebAliasExpandsToWebCitation(t *testing.T) {
},
})
require.Contains(t, output, `<page id="w1" title="Example">`)
+ require.Contains(t, output, `<evidence type="search_summary" verified="false" />`)
require.NotContains(t, output, "https://example.com/a")
require.Equal(t,
`<web url="https://example.com/a" title="Example" />`,
@@ -279,6 +280,106 @@ func TestModelOutputWebAliasExpandsToWebCitation(t *testing.T) {
)
}
+func TestModelOutputWebSearchRetainsContentOnlyEvidence(t *testing.T) {
+ registry := NewRegistry()
+ output := registry.ModelOutput(&types.ToolResult{
+ Success: true,
+ Data: map[string]interface{}{
+ "display_type": "web_search_results",
+ "results": []map[string]interface{}{
+ {
+ "title": "Content-only provider",
+ "url": "https://example.com/content",
+ "content": "search evidence from provider content",
+ },
+ },
+ },
+ })
+
+ require.Contains(t, output, `<content>search evidence from provider content</content>`)
+ require.Contains(t, output, `<evidence type="search_summary" verified="false" />`)
+}
+
+func TestModelOutputWebFetchPreservesPartialFailureStatus(t *testing.T) {
+ registry := NewRegistry()
+ registry.RegisterWeb("https://example.com/verified", "Verified")
+ registry.RegisterWeb("https://example.com/forbidden", "Forbidden")
+
+ output := registry.ModelOutput(&types.ToolResult{
+ Success: true,
+ Data: map[string]interface{}{
+ "display_type": "web_fetch_results",
+ "results": []map[string]interface{}{
+ {
+ "url": "https://example.com/verified",
+ "status": "success",
+ "raw_content": "verified page content",
+ },
+ {
+ "url": "https://example.com/forbidden",
+ "status": "failed",
+ "retryable": false,
+ "error_code": "http_403",
+ "error_message": "access denied",
+ },
+ },
+ },
+ })
+
+ require.Contains(t, output, `<page id="w1" status="success" view="full">`)
+ require.Contains(t, output, "verified page content")
+ require.Contains(t, output, `<page id="w2" status="failed" retryable="false" error_code="http_403">`)
+ require.Contains(t, output, `<error>access denied</error>`)
+ require.Contains(t, output, "failed URLs do not invalidate successful evidence")
+ require.NotContains(t, output, "https://example.com")
+}
+
+func TestModelOutputWebFetchAllFailuresIncludeSearchFallback(t *testing.T) {
+ registry := NewRegistry()
+ output := registry.ModelOutput(&types.ToolResult{
+ Success: true,
+ Data: map[string]interface{}{
+ "display_type": "web_fetch_results",
+ "results": []map[string]interface{}{
+ {
+ "url": "https://example.com/dns",
+ "status": "failed",
+ "retryable": true,
+ "error_code": "dns_failed",
+ "error_message": "DNS lookup failed",
+ },
+ },
+ },
+ })
+
+ require.Contains(t, output, `status="failed" retryable="true" error_code="dns_failed"`)
+ require.Contains(t, output, "Stop expanding web searches")
+ require.Contains(t, output, "page content was not verified")
+}
+
+func TestModelOutputWebFetchKeepsContentWhenSummaryFails(t *testing.T) {
+ registry := NewRegistry()
+ output := registry.ModelOutput(&types.ToolResult{
+ Success: true,
+ Data: map[string]interface{}{
+ "display_type": "web_fetch_results",
+ "results": []map[string]interface{}{
+ {
+ "url": "https://example.com/specs",
+ "status": "success",
+ "summary_status": "failed",
+ "summary_error_code": "summary_failed",
+ "summary_error_message": "model unavailable",
+ "raw_content": "official specifications",
+ },
+ },
+ },
+ })
+
+ require.Contains(t, output, `<summary_error code="summary_failed">model unavailable</summary_error>`)
+ require.Contains(t, output, `<content>official specifications</content>`)
+}
+
func TestModelOutputDocumentInfoUsesDocumentAndFAQAliases(t *testing.T) {
registry := newSourceRegistry()
result := &types.ToolResult{