Initial commit: Go agentic harness extracted from Felix
This commit is contained in:
commit
1f2c471ff9
89 files changed
+19388
No files matched your search
@@ -0,0 +1,76 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// privateNetworks defines CIDR ranges considered internal/private.
|
||||
var privateNetworks = []string{
|
||||
"127.0.0.0/8", // loopback
|
||||
"10.0.0.0/8", // RFC 1918
|
||||
"172.16.0.0/12", // RFC 1918
|
||||
"192.168.0.0/16", // RFC 1918
|
||||
"169.254.0.0/16", // link-local
|
||||
"::1/128", // IPv6 loopback
|
||||
"fc00::/7", // IPv6 unique local
|
||||
"fe80::/10", // IPv6 link-local
|
||||
}
|
||||
|
||||
var parsedPrivateNets []*net.IPNet
|
||||
|
||||
func init() {
|
||||
for _, cidr := range privateNetworks {
|
||||
_, ipNet, err := net.ParseCIDR(cidr)
|
||||
if err == nil {
|
||||
parsedPrivateNets = append(parsedPrivateNets, ipNet)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// isPrivateIP returns true if the IP address is in a private/internal range.
|
||||
func isPrivateIP(ip net.IP) bool {
|
||||
for _, n := range parsedPrivateNets {
|
||||
if n.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ValidateURLNotInternal checks that a URL does not point to an internal/private
|
||||
// network address. This prevents SSRF attacks that could access cloud metadata
|
||||
// endpoints, localhost services, or internal network resources.
|
||||
func ValidateURLNotInternal(rawURL string) error {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid URL: %w", err)
|
||||
}
|
||||
|
||||
host := u.Hostname()
|
||||
if host == "" {
|
||||
return fmt.Errorf("URL has no host")
|
||||
}
|
||||
|
||||
// Block common metadata hostnames
|
||||
lower := strings.ToLower(host)
|
||||
if lower == "metadata.google.internal" || lower == "metadata" {
|
||||
return fmt.Errorf("access to internal metadata endpoint is blocked")
|
||||
}
|
||||
|
||||
// Resolve hostname to IP addresses
|
||||
ips, err := net.LookupIP(host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot resolve hostname %q — blocking to prevent SSRF", host)
|
||||
}
|
||||
|
||||
for _, ip := range ips {
|
||||
if isPrivateIP(ip) {
|
||||
return fmt.Errorf("access to internal address %s (%s) is blocked", host, ip)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateURLNotInternal_BlocksLoopback(t *testing.T) {
|
||||
cases := []string{
|
||||
"http://127.0.0.1/",
|
||||
"http://localhost/",
|
||||
"http://[::1]/",
|
||||
"http://10.0.0.1/",
|
||||
"http://172.16.0.1/",
|
||||
"http://192.168.1.1/",
|
||||
"http://169.254.169.254/", // AWS/GCP/Azure metadata IP
|
||||
"http://metadata.google.internal/", // GCP metadata host
|
||||
}
|
||||
for _, u := range cases {
|
||||
t.Run(u, func(t *testing.T) {
|
||||
err := ValidateURLNotInternal(u)
|
||||
assert.Error(t, err, "url %s should be blocked as internal", u)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateURLNotInternal_AllowsPublic(t *testing.T) {
|
||||
for _, u := range []string{
|
||||
"https://example.com/",
|
||||
"https://api.github.com/repos/foo/bar",
|
||||
"http://1.1.1.1/",
|
||||
} {
|
||||
err := ValidateURLNotInternal(u)
|
||||
assert.NoError(t, err, "public url %s should be allowed", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateURLNotInternal_RejectsBadScheme(t *testing.T) {
|
||||
// file:// URLs lack a host, so SSRF guard rejects on parse — either
|
||||
// "no host" or a scheme/http complaint is acceptable; what matters is
|
||||
// it does not silently allow the URL.
|
||||
err := ValidateURLNotInternal("file:///etc/passwd")
|
||||
assert.Error(t, err, "non-http schemes must be rejected")
|
||||
_ = strings.TrimSpace(err.Error())
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
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 = 5 * 1024 * 1024 // 5MB
|
||||
fetchTimeout = 30 * time.Second
|
||||
MaxOutputLength = 50000 // truncate very long pages
|
||||
)
|
||||
|
||||
// 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", "Felix/1.0 (AI Agent Gateway)")
|
||||
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 := &http.Client{
|
||||
Timeout: fetchTimeout,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return fmt.Errorf("too many redirects (max 10)")
|
||||
}
|
||||
// Re-validate each redirect destination against SSRF blocklist
|
||||
if err := ValidateURLNotInternal(req.URL.String()); err != nil {
|
||||
return fmt.Errorf("redirect blocked: %w", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
const searchTimeout = 15 * time.Second
|
||||
|
||||
// WebSearchTool searches the web and returns results via a configurable
|
||||
// backend. The default backend (when Backend is nil) scrapes DuckDuckGo's
|
||||
// HTML interface — no API key required, but fragile to upstream HTML
|
||||
// changes. Production users who care about reliability should configure a
|
||||
// stable backend (Brave, Tavily) or self-host SearXNG.
|
||||
type WebSearchTool struct {
|
||||
// Backend is the active search strategy. Constructed at registration
|
||||
// time from config; nil means "use the default DDG scraper" so a
|
||||
// no-config install still works.
|
||||
Backend WebSearchBackend
|
||||
}
|
||||
|
||||
type webSearchInput struct {
|
||||
Query string `json:"query"`
|
||||
MaxResults int `json:"max_results,omitempty"`
|
||||
}
|
||||
|
||||
func (t *WebSearchTool) Name() string { return "web_search" }
|
||||
|
||||
func (t *WebSearchTool) Description() string {
|
||||
return "Search the web for information. Returns search results with titles, URLs, and snippets. Use this when you need current information, documentation, or to find web resources."
|
||||
}
|
||||
|
||||
func (t *WebSearchTool) Parameters() json.RawMessage {
|
||||
return json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "The search query"
|
||||
},
|
||||
"max_results": {
|
||||
"type": "integer",
|
||||
"description": "Maximum number of results to return (default: 5, max: 10)"
|
||||
}
|
||||
},
|
||||
"required": ["query"]
|
||||
}`)
|
||||
}
|
||||
|
||||
// IsConcurrencySafe returns true — web_search is a pure read.
|
||||
func (t *WebSearchTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
|
||||
|
||||
// SetBackend swaps the active backend. Called from the config hot-reload
|
||||
// path so settings-page edits take effect on the next agent turn without
|
||||
// a restart. Concurrency-safe with Execute calls because only the
|
||||
// pointer is replaced — the old backend remains usable until any
|
||||
// in-flight Execute returns.
|
||||
func (t *WebSearchTool) SetBackend(b WebSearchBackend) {
|
||||
t.Backend = b
|
||||
}
|
||||
|
||||
func (t *WebSearchTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var in webSearchInput
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
||||
}
|
||||
|
||||
if in.Query == "" {
|
||||
return tool.ToolResult{Error: "query is required"}, nil
|
||||
}
|
||||
|
||||
maxResults := in.MaxResults
|
||||
if maxResults <= 0 {
|
||||
maxResults = 5
|
||||
}
|
||||
if maxResults > 10 {
|
||||
maxResults = 10
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, searchTimeout)
|
||||
defer cancel()
|
||||
|
||||
backend := t.Backend
|
||||
if backend == nil {
|
||||
backend = newDDGBackend()
|
||||
}
|
||||
results, err := backend.Search(ctx, in.Query, maxResults)
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("search failed (%s): %v", backend.Name(), err)}, nil
|
||||
}
|
||||
|
||||
if len(results) == 0 {
|
||||
return tool.ToolResult{Output: "No results found for: " + in.Query}, nil
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
for i, r := range results {
|
||||
fmt.Fprintf(&sb, "%d. **%s**\n %s\n %s\n\n", i+1, r.Title, r.URL, r.Snippet)
|
||||
}
|
||||
|
||||
return tool.ToolResult{
|
||||
Output: sb.String(),
|
||||
Metadata: map[string]any{
|
||||
"query": in.Query,
|
||||
"num_results": len(results),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
type searchResult struct {
|
||||
Title string
|
||||
URL string
|
||||
Snippet string
|
||||
}
|
||||
|
||||
// duckDuckGoSearch performs a search using DuckDuckGo's HTML interface
|
||||
// and extracts results. No API key required.
|
||||
func duckDuckGoSearch(ctx context.Context, query string, maxResults int) ([]searchResult, error) {
|
||||
searchURL := "https://html.duckduckgo.com/html/?q=" + url.QueryEscape(query)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, searchURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", "Felix/1.0 (AI Agent Gateway)")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("search returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 1*1024*1024))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return parseDDGResults(string(body), maxResults), nil
|
||||
}
|
||||
|
||||
// parseDDGResults extracts search results from DuckDuckGo's HTML response.
|
||||
func parseDDGResults(html string, maxResults int) []searchResult {
|
||||
var results []searchResult
|
||||
|
||||
// DuckDuckGo HTML results are in <a class="result__a" ...> tags
|
||||
// with snippets in <a class="result__snippet" ...> tags
|
||||
remaining := html
|
||||
for len(results) < maxResults {
|
||||
// Find result link
|
||||
linkIdx := strings.Index(remaining, `class="result__a"`)
|
||||
if linkIdx == -1 {
|
||||
break
|
||||
}
|
||||
remaining = remaining[linkIdx:]
|
||||
|
||||
// Extract href
|
||||
href := extractAttr(remaining, "href")
|
||||
// Extract title text
|
||||
title := extractTagText(remaining, "a")
|
||||
|
||||
// Find snippet
|
||||
snippetIdx := strings.Index(remaining, `class="result__snippet"`)
|
||||
snippet := ""
|
||||
if snippetIdx != -1 {
|
||||
snippet = extractTagText(remaining[snippetIdx:], "a")
|
||||
}
|
||||
|
||||
// Clean up the URL — DDG wraps URLs in a redirect
|
||||
cleanURL := cleanDDGURL(href)
|
||||
|
||||
if cleanURL != "" && title != "" {
|
||||
results = append(results, searchResult{
|
||||
Title: cleanHTMLText(title),
|
||||
URL: cleanURL,
|
||||
Snippet: cleanHTMLText(snippet),
|
||||
})
|
||||
}
|
||||
|
||||
// Move past this result
|
||||
nextIdx := strings.Index(remaining[1:], `class="result__a"`)
|
||||
if nextIdx == -1 {
|
||||
break
|
||||
}
|
||||
remaining = remaining[nextIdx+1:]
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// extractAttr extracts the value of the first href attribute found.
|
||||
func extractAttr(html, attr string) string {
|
||||
needle := attr + `="`
|
||||
idx := strings.Index(html, needle)
|
||||
if idx == -1 {
|
||||
return ""
|
||||
}
|
||||
start := idx + len(needle)
|
||||
end := strings.Index(html[start:], `"`)
|
||||
if end == -1 {
|
||||
return ""
|
||||
}
|
||||
return html[start : start+end]
|
||||
}
|
||||
|
||||
// extractTagText extracts text content from the first occurrence of a tag.
|
||||
func extractTagText(html, tag string) string {
|
||||
start := strings.Index(html, ">")
|
||||
if start == -1 {
|
||||
return ""
|
||||
}
|
||||
start++
|
||||
endTag := "</" + tag + ">"
|
||||
end := strings.Index(html[start:], endTag)
|
||||
if end == -1 {
|
||||
return ""
|
||||
}
|
||||
return html[start : start+end]
|
||||
}
|
||||
|
||||
// cleanDDGURL extracts the actual URL from DuckDuckGo's redirect wrapper.
|
||||
func cleanDDGURL(rawURL string) string {
|
||||
// DDG wraps URLs like: //duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com&rut=...
|
||||
if strings.Contains(rawURL, "uddg=") {
|
||||
parsed, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return rawURL
|
||||
}
|
||||
uddg := parsed.Query().Get("uddg")
|
||||
if uddg != "" {
|
||||
return uddg
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(rawURL, "//") {
|
||||
return "https:" + rawURL
|
||||
}
|
||||
return rawURL
|
||||
}
|
||||
|
||||
// cleanHTMLText removes HTML tags and decodes common entities.
|
||||
func cleanHTMLText(s string) string {
|
||||
// Strip HTML tags
|
||||
var out strings.Builder
|
||||
inTag := false
|
||||
for _, r := range s {
|
||||
if r == '<' {
|
||||
inTag = true
|
||||
continue
|
||||
}
|
||||
if r == '>' {
|
||||
inTag = false
|
||||
continue
|
||||
}
|
||||
if !inTag {
|
||||
out.WriteRune(r)
|
||||
}
|
||||
}
|
||||
result := out.String()
|
||||
result = strings.ReplaceAll(result, "&", "&")
|
||||
result = strings.ReplaceAll(result, "<", "<")
|
||||
result = strings.ReplaceAll(result, ">", ">")
|
||||
result = strings.ReplaceAll(result, """, `"`)
|
||||
result = strings.ReplaceAll(result, "'", "'")
|
||||
result = strings.ReplaceAll(result, " ", " ")
|
||||
return strings.TrimSpace(result)
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// WebSearchBackend is the strategy interface used by WebSearchTool.
|
||||
// Implementations turn (query, maxResults) into ranked results.
|
||||
//
|
||||
// The interface deliberately does not include configuration — backends
|
||||
// are constructed with their config (API key, base URL, etc.) at
|
||||
// registration time and remain immutable thereafter. This keeps the tool
|
||||
// dispatch path zero-allocation in the hot loop.
|
||||
type WebSearchBackend interface {
|
||||
Name() string
|
||||
Search(ctx context.Context, query string, maxResults int) ([]searchResult, error)
|
||||
}
|
||||
|
||||
// ddgBackend is the default backend — scrapes html.duckduckgo.com.
|
||||
// Fragile (DDG can change their HTML), no API key required, the original
|
||||
// pre-S1 behavior. Kept as the no-config default so a fresh install with
|
||||
// no env vars still has working search.
|
||||
type ddgBackend struct{}
|
||||
|
||||
func newDDGBackend() WebSearchBackend { return &ddgBackend{} }
|
||||
func (b *ddgBackend) Name() string { return "duckduckgo" }
|
||||
func (b *ddgBackend) Search(ctx context.Context, q string, n int) ([]searchResult, error) {
|
||||
return duckDuckGoSearch(ctx, q, n)
|
||||
}
|
||||
|
||||
// braveBackend uses the Brave Search REST API.
|
||||
// Docs: https://api.search.brave.com/app/documentation/web-search/get-started
|
||||
// Auth: header X-Subscription-Token: <key>
|
||||
type braveBackend struct {
|
||||
apiKey string
|
||||
}
|
||||
|
||||
func newBraveBackend(apiKey string) WebSearchBackend { return &braveBackend{apiKey: apiKey} }
|
||||
func (b *braveBackend) Name() string { return "brave" }
|
||||
func (b *braveBackend) Search(ctx context.Context, q string, n int) ([]searchResult, error) {
|
||||
if b.apiKey == "" {
|
||||
return nil, fmt.Errorf("brave backend: no API key configured")
|
||||
}
|
||||
if n > 20 {
|
||||
n = 20
|
||||
}
|
||||
u := "https://api.search.brave.com/res/v1/web/search?q=" + url.QueryEscape(q) +
|
||||
fmt.Sprintf("&count=%d", n)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("X-Subscription-Token", b.apiKey)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return nil, fmt.Errorf("brave returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
var parsed struct {
|
||||
Web struct {
|
||||
Results []struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Description string `json:"description"`
|
||||
} `json:"results"`
|
||||
} `json:"web"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&parsed); err != nil {
|
||||
return nil, fmt.Errorf("brave decode: %w", err)
|
||||
}
|
||||
out := make([]searchResult, 0, len(parsed.Web.Results))
|
||||
for _, r := range parsed.Web.Results {
|
||||
out = append(out, searchResult{
|
||||
Title: cleanHTMLText(r.Title),
|
||||
URL: r.URL,
|
||||
Snippet: cleanHTMLText(r.Description),
|
||||
})
|
||||
}
|
||||
if n > 0 && len(out) > n {
|
||||
out = out[:n]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// tavilyBackend uses the Tavily Search API.
|
||||
// Docs: https://docs.tavily.com/docs/rest-api/api-reference
|
||||
// Auth: JSON body field "api_key"; POST to /search.
|
||||
type tavilyBackend struct {
|
||||
apiKey string
|
||||
}
|
||||
|
||||
func newTavilyBackend(apiKey string) WebSearchBackend { return &tavilyBackend{apiKey: apiKey} }
|
||||
func (b *tavilyBackend) Name() string { return "tavily" }
|
||||
func (b *tavilyBackend) Search(ctx context.Context, q string, n int) ([]searchResult, error) {
|
||||
if b.apiKey == "" {
|
||||
return nil, fmt.Errorf("tavily backend: no API key configured")
|
||||
}
|
||||
if n > 20 {
|
||||
n = 20
|
||||
}
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"api_key": b.apiKey,
|
||||
"query": q,
|
||||
"max_results": n,
|
||||
})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.tavily.com/search", strings.NewReader(string(body)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return nil, fmt.Errorf("tavily returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
|
||||
}
|
||||
var parsed struct {
|
||||
Results []struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Content string `json:"content"`
|
||||
} `json:"results"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&parsed); err != nil {
|
||||
return nil, fmt.Errorf("tavily decode: %w", err)
|
||||
}
|
||||
out := make([]searchResult, 0, len(parsed.Results))
|
||||
for _, r := range parsed.Results {
|
||||
out = append(out, searchResult{
|
||||
Title: r.Title,
|
||||
URL: r.URL,
|
||||
Snippet: r.Content,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// searxngBackend talks to a self-hosted SearXNG instance — the
|
||||
// self-sufficiency-aligned option. JSON output must be enabled on the
|
||||
// SearXNG server (`enabled_engines` and `formats: [json]` in settings.yml).
|
||||
type searxngBackend struct {
|
||||
baseURL string // e.g. "http://localhost:8080"
|
||||
}
|
||||
|
||||
func newSearxngBackend(baseURL string) WebSearchBackend {
|
||||
return &searxngBackend{baseURL: strings.TrimRight(baseURL, "/")}
|
||||
}
|
||||
func (b *searxngBackend) Name() string { return "searxng" }
|
||||
func (b *searxngBackend) Search(ctx context.Context, q string, n int) ([]searchResult, error) {
|
||||
if b.baseURL == "" {
|
||||
return nil, fmt.Errorf("searxng backend: no base URL configured")
|
||||
}
|
||||
u := b.baseURL + "/search?format=json&q=" + url.QueryEscape(q)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("searxng returned HTTP %d", resp.StatusCode)
|
||||
}
|
||||
var parsed struct {
|
||||
Results []struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Content string `json:"content"`
|
||||
} `json:"results"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&parsed); err != nil {
|
||||
return nil, fmt.Errorf("searxng decode: %w", err)
|
||||
}
|
||||
out := make([]searchResult, 0, len(parsed.Results))
|
||||
for _, r := range parsed.Results {
|
||||
out = append(out, searchResult{
|
||||
Title: r.Title,
|
||||
URL: r.URL,
|
||||
Snippet: r.Content,
|
||||
})
|
||||
}
|
||||
if n > 0 && len(out) > n {
|
||||
out = out[:n]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// WebSearchConfig selects the backend at registration time. Empty Backend
|
||||
// or Backend == "duckduckgo" yields the default DDG scraper (no API key).
|
||||
// "brave" + APIKey, "tavily" + APIKey, and "searxng" + BaseURL each
|
||||
// activate their respective backends.
|
||||
type WebSearchConfig struct {
|
||||
Backend string // "duckduckgo" (default) | "brave" | "tavily" | "searxng"
|
||||
APIKey string // for brave / tavily
|
||||
BaseURL string // for searxng
|
||||
}
|
||||
|
||||
// NewWebSearchBackend resolves a WebSearchConfig into a concrete backend.
|
||||
// Returns the DDG fallback when the config is empty or names an unknown
|
||||
// backend; never returns nil. Logging the fallback is the caller's
|
||||
// responsibility (registerWebSearch in the gateway wires that).
|
||||
func NewWebSearchBackend(cfg WebSearchConfig) WebSearchBackend {
|
||||
switch strings.ToLower(strings.TrimSpace(cfg.Backend)) {
|
||||
case "", "duckduckgo", "ddg":
|
||||
return newDDGBackend()
|
||||
case "brave":
|
||||
return newBraveBackend(cfg.APIKey)
|
||||
case "tavily":
|
||||
return newTavilyBackend(cfg.APIKey)
|
||||
case "searxng":
|
||||
return newSearxngBackend(cfg.BaseURL)
|
||||
default:
|
||||
return newDDGBackend()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user