Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat(search): introduce internal analytics engine for web search

Dmitry Ng5a4f1f54dc41
diff --git a/.env.example b/.env.example
index a8b715af..5d3f4bd8 100644
--- a/.env.example
+++ b/.env.example
@@ -210,6 +210,11 @@ SEARXNG_SAFESEARCH=0
SEARXNG_TIME_RANGE=
SEARXNG_TIMEOUT=
+## Web search internal analytics engine (optional fallback for the web_search tool)
+WEB_SEARCH_INTERNAL_ENABLED=false
+WEB_SEARCH_INTERNAL_MAX_SITES=5
+WEB_SEARCH_INTERNAL_MAX_SITE_BYTES=10240
+
## Langfuse observability settings
LANGFUSE_BASE_URL=
LANGFUSE_PROJECT_ID=
diff --git a/CLAUDE.md b/CLAUDE.md
index dfff9812..b92e1953 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -134,6 +134,17 @@ State is managed primarily through Apollo Client (GraphQL) with real-time update
7. Add the provider icon in `frontend/src/components/icons/<name>.tsx` and register it in `frontend/src/components/icons/provider-icon.tsx`.
8. Update the GraphQL schema/types and frontend settings page if needed.
+### Adding a New Search Engine
+
+Search engines are primitives under `backend/pkg/tools/searchers/`, orchestrated by the single `web_search` tool (`backend/pkg/tools/web_search.go`). Agents never call an engine directly — they call `web_search` with an intent `mode`.
+
+1. Create `backend/pkg/tools/searchers/<name>.go` implementing the `searchers.Searcher` interface: `New<Name>(cfg, …)` constructor, `IsAvailable()`, `Engine()`, and a `Handle(ctx, Request)` that returns **typed** errors (`searchers.Retryable` / `searchers.Fatal` / `searchers.ErrNotConfigured`, or `searchers.ClassifyHTTPStatus`). Never swallow an error into a result string. `searchers` must not import `pkg/tools`.
+2. Add the engine's config field(s) to `pkg/config/config.go`, plus `.env.example`, `docker-compose.yml`, and `config_test.go` defaults.
+3. Construct the engine in `buildSearchEngines` and place its id in the relevant `fallbackStrategy` chains in `web_search.go` — that table is the only place engine priority per mode lives.
+4. Attribution: if the engine needs a **new** `SearchengineType` value (not one that already exists), add a goose migration in `backend/migrations/sql/`, a `SearchengineType<Name>` constant in `pkg/database/models.go`, and reconcile `pkg/server/models/searchlogs.go`. Reusing an existing value needs no migration.
+5. Add `<name>_test.go` in `searchers/` (the shared MITM proxy harness is in `proxy_test.go`); add orchestrator coverage in `web_search_test.go` if behavior changes.
+6. No frontend change is needed: the frontend treats `SearchLog.engine` as an opaque string and displays whatever the orchestrator logs.
+
### Code Generation
When modifying `backend/pkg/graph/schema.graphqls`, re-run the gqlgen command to regenerate resolver stubs. When modifying REST handler annotations, re-run swag to update Swagger docs. When modifying `frontend/src/graphql/*.graphql` query files, re-run `pnpm run graphql:generate` to update TypeScript types.
diff --git a/README.md b/README.md
index 945f4960..44e6cf11 100644
--- a/README.md
+++ b/README.md
@@ -105,7 +105,7 @@ flowchart TB
llm["🧠 llm-provider
(OpenAI/Anthropic/Ollama/Bedrock/Gemini/Custom)"]
search["🔍 search-systems
- (Google/DuckDuckGo/Tavily/Traversaal/Perplexity/Sploitus/Searxng)"]
+ (Google/DuckDuckGo/Tavily/Firecrawl/Traversaal/Perplexity/Sploitus/Searxng)"]
langfuse["📊 langfuse-ui
(LLM Observability Dashboard)"]
grafana["📈 grafana
@@ -636,8 +636,8 @@ The installer requires appropriate privileges to interact with the Docker API fo
The installer will:
1. **System Checks**: Verify Docker, network connectivity, and system requirements
2. **Environment Setup**: Create and configure `.env` file with optimal defaults
-3. **Provider Configuration**: Set up LLM providers (OpenAI, Anthropic, Gemini, Bedrock, Ollama, Custom)
-4. **Search Engines**: Configure DuckDuckGo, Google, Tavily, Firecrawl, Traversaal, Perplexity, Sploitus, Searxng
+3. **Provider Configuration**: Set up LLM providers (OpenAI, Anthropic, Gemini, Bedrock, Ollama, DeepSeek, GLM, Kimi, Qwen, MiniMax, Custom)
+4. **Search Engines**: Configure DuckDuckGo, Google, Tavily, Firecrawl, Traversaal, Perplexity, Sploitus, Searxng, and the optional internal browser-analytics fallback engine
5. **Security Hardening**: Generate secure credentials and configure SSL certificates
6. **Deployment**: Start PentAGI with docker-compose
@@ -655,7 +655,7 @@ The PentAGI web console already manages several settings areas after the server
The following configuration areas still need to be set on the server through environment variables, compose files, or mounted config files:
- **LLM credentials and connection details**: API keys, endpoints, auth modes, and provider-specific connection settings for OpenAI, Anthropic, Bedrock, Ollama, custom providers, and similar backends; config-path settings apply only where supported, such as `OLLAMA_SERVER_CONFIG_PATH` and `LLM_SERVER_CONFIG_PATH`.
-- **Search provider credentials and options**: Settings such as `DUCKDUCKGO_*`, `GOOGLE_*`, `TAVILY_API_KEY`, `FIRECRAWL_API_KEY`, `FIRECRAWL_API_URL`, `TRAVERSAAL_API_KEY`, `PERPLEXITY_*`, `SEARXNG_*`, and `SPLOITUS_ENABLED`.
+- **Search provider credentials and options**: Settings such as `DUCKDUCKGO_*`, `GOOGLE_*`, `TAVILY_API_KEY`, `FIRECRAWL_API_KEY`, `FIRECRAWL_API_URL`, `TRAVERSAAL_API_KEY`, `PERPLEXITY_*`, `SEARXNG_*`, `SPLOITUS_ENABLED`, and the optional `WEB_SEARCH_INTERNAL_*` browser-analytics fallback settings.
- **Third-party integrations**: Langfuse, Graphiti, and similar external services remain server-side configuration.
- **MCP server management**: MCP settings pages are not currently exposed as a live web-console feature.
@@ -718,6 +718,7 @@ BEDROCK_DEFAULT_AUTH=true # Option 1: Use AWS SDK default
# GLM_API_KEY=your_glm_key # GLM (Zhipu AI)
# KIMI_API_KEY=your_kimi_key # Kimi (Moonshot AI, ultra-long context)
# QWEN_API_KEY=your_qwen_key # Qwen (Alibaba Cloud, multimodal)
+# MINIMAX_API_KEY=your_minimax_key # MiniMax
# Optional: Local LLM provider (zero-cost inference)
OLLAMA_SERVER_URL=http://localhost:11434
@@ -733,6 +734,7 @@ GOOGLE_API_KEY=your_google_key
GOOGLE_CX_KEY=your_google_cx
TAVILY_API_KEY=your_tavily_key
FIRECRAWL_API_KEY=your_firecrawl_key
+FIRECRAWL_API_URL=
TRAVERSAAL_API_KEY=your_traversaal_key
PERPLEXITY_API_KEY=your_perplexity_key
PERPLEXITY_MODEL=sonar-pro
@@ -746,6 +748,12 @@ SEARXNG_SAFESEARCH=0
SEARXNG_TIME_RANGE=
SEARXNG_TIMEOUT=
+# Optional: internal browser-analytics fallback engine for web_search (off by default;
+# scrapes and summarizes pages instead of calling a paid analytic API)
+WEB_SEARCH_INTERNAL_ENABLED=false
+WEB_SEARCH_INTERNAL_MAX_SITES=5
+WEB_SEARCH_INTERNAL_MAX_SITE_BYTES=10240
+
## Graphiti knowledge graph settings
GRAPHITI_ENABLED=true
GRAPHITI_TIMEOUT=30
@@ -3625,6 +3633,7 @@ go run cmd/ftester/main.go browser
### Search Functions
- **browser**: Access websites and capture screenshots
+- **web_search**: Unified search orchestrator that agents actually call — pass a `query` and a `mode` (`links`, `answer`, `research`, `exploit`) and it auto-selects, retries, and falls back across the engines below, so you never name an engine explicitly
- **google**: Search the web using Google Custom Search
- **duckduckgo**: Search the web using DuckDuckGo
- **tavily**: Search using Tavily AI search engine
@@ -3633,6 +3642,7 @@ go run cmd/ftester/main.go browser
- **perplexity**: Search using Perplexity AI
- **sploitus**: Search for security exploits, vulnerabilities (CVEs), and pentesting tools
- **searxng**: Search using Searxng meta search engine (aggregates results from multiple engines)
+- **internal** *(ftester-only debug function, not an agent tool)*: Opt-in browser-analytics fallback engine that discovers links, scrapes each page, and summarizes the result; requires `WEB_SEARCH_INTERNAL_ENABLED=true`, a configured scraper, and at least one available link engine
### Vector Database Functions
- **search_in_memory**: Search for information in vector database
@@ -3803,8 +3813,9 @@ To access detailed logs:
The main utility accepts several options:
- `-env <path>` - Path to environment file (optional, default: `.env`)
-- `-provider <type>` - Provider type to use (default: `custom`, options: `openai`, `anthropic`, `ollama`, `bedrock`, `gemini`, `custom`)
-- `-flow <id>` - Flow ID for testing (0 means using mocks, default: `0`)
+- `-provider <type>` - Provider type to use (default: `custom`, options: `openai`, `anthropic`, `gemini`, `bedrock`, `ollama`, `deepseek`, `glm`, `kimi`, `qwen`, `minimax`, `custom`)
+- `-flow <id>` - Flow ID for testing functions that require it (0 means using mocks, default: `0`)
+- `-user <id>` - User ID for testing functions that require it (default: `0`; `1` is the default admin user)
- `-task <id>` - Task ID for agent context (optional)
- `-subtask <id>` - Subtask ID for agent context (optional)
diff --git a/backend/cmd/ftester/mocks/tools.go b/backend/cmd/ftester/mocks/tools.go
index 6d95c01c..1904e1e3 100644
--- a/backend/cmd/ftester/mocks/tools.go
+++ b/backend/cmd/ftester/mocks/tools.go
@@ -136,6 +136,42 @@ func MockResponse(funcName string, args json.RawMessage) (string, error) {
resultObj = builder.String()
+ case tools.WebSearchToolName:
+ var searchArgs tools.WebSearchAction
+ if err := json.Unmarshal(args, &searchArgs); err != nil {
+ return "", fmt.Errorf("error unmarshaling web_search arguments: %w", err)
+ }
+
+ mode := strings.ToLower(strings.TrimSpace(searchArgs.Mode.String()))
+ if mode == "" {
+ mode = "answer"
+ }
+ n := searchArgs.MaxResults.Int()
+ if n < 1 || n > 3 {
+ n = 3
+ }
+
+ terminal.PrintMock("web_search:")
+ terminal.PrintKeyValue("Query", searchArgs.Query)
+ terminal.PrintKeyValue("Mode", mode)
+
+ var builder strings.Builder
+ builder.WriteString(fmt.Sprintf("# Mock web_search result (mode=%s)\n\n", mode))
+ builder.WriteString(fmt.Sprintf("The web_search orchestrator would pick the best available engine for mode '%s', retry transient failures, and fall back across providers automatically.\n\n", mode))
+ switch mode {
+ case "links":
+ builder.WriteString("# Links\n\n")
+ for i := 1; i <= n; i++ {
+ builder.WriteString(fmt.Sprintf("## %d. Mock result %d\n\n* URL https://example.com/web_search/result%d\n\n### Snippet\n\nBrief snippet about '%s'.\n\n", i, i, i, searchArgs.Query))
+ }
+ case "exploit":
+ builder.WriteString(fmt.Sprintf("# Exploits\n\n## 1. Mock exploit for '%s'\n\n* URL https://sploitus.com/exploit/mock\n* CVSS 9.8\n\n", searchArgs.Query))
+ default: // answer / research
+ builder.WriteString(fmt.Sprintf("# Answer\n\nThis is a synthesized mock answer to '%s' that web_search would return in mode '%s', combining multiple sources.\n", searchArgs.Query, mode))
+ }
+
+ resultObj = builder.String()
+
case tools.FirecrawlToolName:
var searchArgs tools.SearchAction
if err := json.Unmarshal(args, &searchArgs); err != nil {
diff --git a/backend/cmd/ftester/worker/args.go b/backend/cmd/ftester/worker/args.go
index 7308676c..3feb85b8 100644
--- a/backend/cmd/ftester/worker/args.go
+++ b/backend/cmd/ftester/worker/args.go
@@ -45,6 +45,23 @@ var describeFuncInfo = FunctionInfo{
},
}
+// internalFuncInfo describes the ftester-only "internal" engine (the internal
+// browser-analytics engine — the opt-in alternative to Tavily). It is NOT a registered
+// agent tool (agents call web_search), so — like "describe" — it is special-cased here
+// instead of coming from the tool registry. It takes the same SearchAction arguments as
+// the other search engines.
+var internalFuncInfo = FunctionInfo{
+ Name: "internal",
+ Description: "Internal browser-analytics engine (ftester debug): discovers links, scrapes each page, " +
+ "and summarizes the result — the opt-in alternative to Tavily. Requires WEB_SEARCH_INTERNAL_ENABLED=true, " +
+ "a configured scraper, and at least one available link engine.",
+ Arguments: []ArgumentInfo{
+ {Name: "query", Type: "string", Description: "Search query (English)", Required: true},
+ {Name: "max_results", Type: "integer", Description: "Maximum number of results (1-10; default 5)", Required: true},
+ {Name: "message", Type: "string", Description: "Engagement-log message", Required: true},
+ },
+}
+
// GetAvailableFunctions returns all available functions with their descriptions
func GetAvailableFunctions() []FunctionInfo {
funcInfos := []FunctionInfo{}
@@ -63,7 +80,7 @@ func GetAvailableFunctions() []FunctionInfo {
}
// Add custom ftester functions
- funcInfos = append(funcInfos, describeFuncInfo)
+ funcInfos = append(funcInfos, describeFuncInfo, internalFuncInfo)
return funcInfos
}
@@ -74,6 +91,9 @@ func GetFunctionInfo(funcName string) (FunctionInfo, error) {
if funcName == "describe" {
return describeFuncInfo, nil
}
+ if funcName == "internal" {
+ return internalFuncInfo, nil
+ }
definitions := tools.GetRegistryDefinitions()
@@ -311,6 +331,8 @@ func getStructTypeForFunction(funcName string) (reflect.Type, error) {
tools.PerplexityToolName: &tools.SearchAction{},
tools.SearxngToolName: &tools.SearchAction{},
tools.SploitusToolName: &tools.SploitusAction{},
+ tools.WebSearchToolName: &tools.WebSearchAction{},
+ "internal": &tools.SearchAction{}, // internal analytics engine (ftester-only, debug)
tools.MemoristToolName: &tools.MemoristAction{},
tools.SearchInMemoryToolName: &tools.SearchInMemoryAction{},
tools.SearchGuideToolName: &tools.SearchGuideAction{},
diff --git a/backend/cmd/ftester/worker/executor.go b/backend/cmd/ftester/worker/executor.go
index ed232e45..feac6751 100644
--- a/backend/cmd/ftester/worker/executor.go
+++ b/backend/cmd/ftester/worker/executor.go
@@ -15,6 +15,7 @@ import (
"pentagi/pkg/providers/embeddings"
"pentagi/pkg/terminal"
"pentagi/pkg/tools"
+ "pentagi/pkg/tools/searchers"
"github.com/sirupsen/logrus"
"github.com/vxcontrol/cloud/anonymizer"
@@ -37,6 +38,49 @@ func (at *agentTool) IsAvailable() bool {
return at.handler != nil
}
+// searcherTool adapts a single searchers.Searcher to the tools.Tool interface so the
+// ftester can exercise one engine against its real API by name (e.g. `ftester -flow N
+// tavily`). Production agents never take this path — they call web_search, which
+// orchestrates the engines — but per-engine access is valuable for debugging a single
+// provider's live integration and response parsing in isolation.
+type searcherTool struct {
+ searcher searchers.Searcher
+}
+
+func (s *searcherTool) IsAvailable() bool { return s.searcher.IsAvailable() }
+
+func (s *searcherTool) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+ req, err := searchRequestFromArgs(name, args)
+ if err != nil {
+ return "", err
+ }
+ return s.searcher.Handle(ctx, req)
+}
+
+// searchRequestFromArgs builds the engine-agnostic searchers.Request from a single
+// engine's LLM-facing arguments. Sploitus carries extra exploit fields; every other
+// engine uses SearchAction.
+func searchRequestFromArgs(name string, args json.RawMessage) (searchers.Request, error) {
+ if name == tools.SploitusToolName {
+ var a tools.SploitusAction
+ if err := json.Unmarshal(args, &a); err != nil {
+ return searchers.Request{}, fmt.Errorf("failed to unmarshal %s args: %w", name, err)
+ }
+ return searchers.Request{
+ Query: a.Query,
+ MaxResults: a.MaxResults.Int(),
+ ExploitType: a.ExploitType.String(),
+ Sort: a.Sort.String(),
+ }, nil
+ }
+
+ var a tools.SearchAction
+ if err := json.Unmarshal(args, &a); err != nil {
+ return searchers.Request{}, fmt.Errorf("failed to unmarshal %s args: %w", name, err)
+ }
+ return searchers.Request{Query: a.Query, MaxResults: a.MaxResults.Int()}, nil
+}
+
// toolExecutor holds the necessary data for creating and managing tools
type toolExecutor struct {
flowExecutor tools.FlowToolsExecutor
@@ -168,81 +212,55 @@ func (te *toolExecutor) GetTool(ctx context.Context, funcName string) (tools.Too
te.proxies.GetScreenshotProvider(),
), nil
- case tools.GoogleToolName:
- return tools.NewGoogleTool(
+ case tools.WebSearchToolName:
+ // The unified web_search orchestrator, as production agents use it. A nil page
+ // fetcher disables the optional internal analytics engine, which is out of
+ // scope for the function tester.
+ return tools.NewWebSearchTool(
te.cfg,
te.flowID,
te.taskID,
te.subtaskID,
te.proxies.GetSearchLogProvider(),
+ te.GetSummarizer(),
+ nil,
), nil
+ // Individual engines: not used by agents (they call web_search), but exposed here
+ // so a developer can test one provider's real API in isolation. Each searcher is
+ // wrapped in searcherTool to bridge the searchers.Searcher → tools.Tool interface.
+ case tools.GoogleToolName:
+ return &searcherTool{searcher: searchers.NewGoogle(te.cfg)}, nil
+
case tools.DuckDuckGoToolName:
- return tools.NewDuckDuckGoTool(
- te.cfg,
- te.flowID,
- te.taskID,
- te.subtaskID,
- te.proxies.GetSearchLogProvider(),
- ), nil
+ return &searcherTool{searcher: searchers.NewDuckDuckGo(te.cfg)}, nil
case tools.TavilyToolName:
- return tools.NewTavilyTool(
- te.cfg,
- te.flowID,
- te.taskID,
- te.subtaskID,
- te.proxies.GetSearchLogProvider(),
- te.GetSummarizer(),
- ), nil
+ return &searcherTool{searcher: searchers.NewTavily(te.cfg, searchers.SummarizeHandler(te.GetSummarizer()))}, nil
case tools.FirecrawlToolName:
- return tools.NewFirecrawlTool(
- te.cfg,
- te.flowID,
- te.taskID,
- te.subtaskID,
- te.proxies.GetSearchLogProvider(),
- te.GetSummarizer(),
- ), nil
+ return &searcherTool{searcher: searchers.NewFirecrawl(te.cfg, searchers.SummarizeHandler(te.GetSummarizer()))}, nil
case tools.TraversaalToolName:
- return tools.NewTraversaalTool(
- te.cfg,
- te.flowID,
- te.taskID,
- te.subtaskID,
- te.proxies.GetSearchLogProvider(),
- ), nil
+ return &searcherTool{searcher: searchers.NewTraversaal(te.cfg)}, nil
case tools.PerplexityToolName:
- return tools.NewPerplexityTool(
- te.cfg,
- te.flowID,
- te.taskID,
- te.subtaskID,
- te.proxies.GetSearchLogProvider(),
- te.GetSummarizer(),
- ), nil
+ return &searcherTool{searcher: searchers.NewPerplexity(te.cfg, searchers.SummarizeHandler(te.GetSummarizer()))}, nil
case tools.SearxngToolName:
- return tools.NewSearxngTool(
- te.cfg,
- te.flowID,
- te.taskID,
- te.subtaskID,
- te.proxies.GetSearchLogProvider(),
- te.GetSummarizer(),
- ), nil
+ return &searcherTool{searcher: searchers.NewSearxng(te.cfg, searchers.SummarizeHandler(te.GetSummarizer()))}, nil
case tools.SploitusToolName:
- return tools.NewSploitusTool(
- te.cfg,
- te.flowID,
- te.taskID,
- te.subtaskID,
- te.proxies.GetSearchLogProvider(),
- ), nil
+ return &searcherTool{searcher: searchers.NewSploitus(te.cfg)}, nil
+
+ case "internal":
+ // The internal browser-analytics engine — the opt-in alternative to Tavily.
+ // Not an agent-facing tool (agents call web_search); exposed here so it can be
+ // exercised in isolation. Requires WEB_SEARCH_INTERNAL_ENABLED=true, a configured
+ // scraper (SCRAPER_PUBLIC_URL / SCRAPER_PRIVATE_URL), and at least one available
+ // link engine (e.g. google/duckduckgo) — otherwise IsAvailable() is false.
+ fetcher := tools.NewBrowserPageFetcher(te.flowID, te.taskID, te.subtaskID, te.cfg, te.proxies.GetScreenshotProvider())
+ return &searcherTool{searcher: tools.NewInternalEngine(te.cfg, te.GetSummarizer(), fetcher)}, nil
case tools.SearchInMemoryToolName:
return tools.NewMemoryTool(
diff --git a/backend/cmd/installer/wizard/controller/controller.go b/backend/cmd/installer/wizard/controller/controller.go
index 95e22812..f9d04b6c 100644
--- a/backend/cmd/installer/wizard/controller/controller.go
+++ b/backend/cmd/installer/wizard/controller/controller.go
@@ -1620,6 +1620,11 @@ type SearchEnginesConfig struct {
SearxngTimeRange loader.EnvVar // SEARXNG_TIME_RANGE
SearxngTimeout loader.EnvVar // SEARXNG_TIMEOUT
+ // internal analytics engine settings (opt-in browser-based fallback for web_search)
+ WebSearchInternalEnabled loader.EnvVar // WEB_SEARCH_INTERNAL_ENABLED
+ WebSearchInternalMaxSites loader.EnvVar // WEB_SEARCH_INTERNAL_MAX_SITES
+ WebSearchInternalMaxSiteBytes loader.EnvVar // WEB_SEARCH_INTERNAL_MAX_SITE_BYTES
+
// computed fields (not directly mapped to env vars)
ConfiguredCount int // number of configured engines
}
@@ -1648,29 +1653,35 @@ func (c *controller) GetSearchEnginesConfig() *SearchEnginesConfig {
searxngSafeSearch, _ := c.GetVar("SEARXNG_SAFESEARCH")
searxngTimeRange, _ := c.GetVar("SEARXNG_TIME_RANGE")
searxngTimeout, _ := c.GetVar("SEARXNG_TIMEOUT")
+ webSearchInternalEnabled, _ := c.GetVar("WEB_SEARCH_INTERNAL_ENABLED")
+ webSearchInternalMaxSites, _ := c.GetVar("WEB_SEARCH_INTERNAL_MAX_SITES")
+ webSearchInternalMaxSiteBytes, _ := c.GetVar("WEB_SEARCH_INTERNAL_MAX_SITE_BYTES")
config := &SearchEnginesConfig{
- DuckDuckGoEnabled: duckduckgoEnabled,
- DuckDuckGoRegion: duckduckgoRegion,
- DuckDuckGoSafeSearch: duckduckgoSafeSearch,
- DuckDuckGoTimeRange: duckduckgoTimeRange,
- SploitusEnabled: sploitusEnabled,
- PerplexityAPIKey: perplexityAPIKey,
- PerplexityModel: perplexityModel,
- PerplexityContextSize: perplexityContextSize,
- TavilyAPIKey: tavilyAPIKey,
- FirecrawlAPIKey: firecrawlAPIKey,
- FirecrawlAPIURL: firecrawlAPIURL,
- TraversaalAPIKey: traversaalAPIKey,
- GoogleAPIKey: googleAPIKey,
- GoogleCXKey: googleCXKey,
- GoogleLRKey: googleLRKey,
- SearxngURL: searxngURL,
- SearxngCategories: searxngCategories,
- SearxngLanguage: searxngLanguage,
- SearxngSafeSearch: searxngSafeSearch,
- SearxngTimeRange: searxngTimeRange,
- SearxngTimeout: searxngTimeout,
+ DuckDuckGoEnabled: duckduckgoEnabled,
+ DuckDuckGoRegion: duckduckgoRegion,
+ DuckDuckGoSafeSearch: duckduckgoSafeSearch,
+ DuckDuckGoTimeRange: duckduckgoTimeRange,
+ SploitusEnabled: sploitusEnabled,
+ PerplexityAPIKey: perplexityAPIKey,
+ PerplexityModel: perplexityModel,
+ PerplexityContextSize: perplexityContextSize,
+ TavilyAPIKey: tavilyAPIKey,
+ FirecrawlAPIKey: firecrawlAPIKey,
+ FirecrawlAPIURL: firecrawlAPIURL,
+ TraversaalAPIKey: traversaalAPIKey,
+ GoogleAPIKey: googleAPIKey,
+ GoogleCXKey: googleCXKey,
+ GoogleLRKey: googleLRKey,
+ SearxngURL: searxngURL,
+ SearxngCategories: searxngCategories,
+ SearxngLanguage: searxngLanguage,
+ SearxngSafeSearch: searxngSafeSearch,
+ SearxngTimeRange: searxngTimeRange,
+ SearxngTimeout: searxngTimeout,
+ WebSearchInternalEnabled: webSearchInternalEnabled,
+ WebSearchInternalMaxSites: webSearchInternalMaxSites,
+ WebSearchInternalMaxSiteBytes: webSearchInternalMaxSiteBytes,
}
// compute configured count
@@ -1703,6 +1714,11 @@ func (c *controller) GetSearchEnginesConfig() *SearchEnginesConfig {
if searxngURL.Value != "" {
configuredCount++
}
+ if webSearchInternalEnabled.Value == "true" {
+ configuredCount++
+ } else if webSearchInternalEnabled.Value == "" && webSearchInternalEnabled.Default == "true" {
+ configuredCount++
+ }
config.ConfiguredCount = configuredCount
return config
@@ -1778,6 +1794,15 @@ func (c *controller) UpdateSearchEnginesConfig(config *SearchEnginesConfig) erro
if err := c.SetVar("SEARXNG_TIMEOUT", config.SearxngTimeout.Value); err != nil {
return fmt.Errorf("failed to set SEARXNG_TIMEOUT: %w", err)
}
+ if err := c.SetVar("WEB_SEARCH_INTERNAL_ENABLED", config.WebSearchInternalEnabled.Value); err != nil {
+ return fmt.Errorf("failed to set WEB_SEARCH_INTERNAL_ENABLED: %w", err)
+ }
+ if err := c.SetVar("WEB_SEARCH_INTERNAL_MAX_SITES", config.WebSearchInternalMaxSites.Value); err != nil {
+ return fmt.Errorf("failed to set WEB_SEARCH_INTERNAL_MAX_SITES: %w", err)
+ }
+ if err := c.SetVar("WEB_SEARCH_INTERNAL_MAX_SITE_BYTES", config.WebSearchInternalMaxSiteBytes.Value); err != nil {
+ return fmt.Errorf("failed to set WEB_SEARCH_INTERNAL_MAX_SITE_BYTES: %w", err)
+ }
return nil
}
@@ -1807,6 +1832,9 @@ func (c *controller) ResetSearchEnginesConfig() *SearchEnginesConfig {
"SEARXNG_SAFESEARCH",
"SEARXNG_TIME_RANGE",
"SEARXNG_TIMEOUT",
+ "WEB_SEARCH_INTERNAL_ENABLED",
+ "WEB_SEARCH_INTERNAL_MAX_SITES",
+ "WEB_SEARCH_INTERNAL_MAX_SITE_BYTES",
}
if err := c.ResetVars(vars); err != nil {
diff --git a/backend/cmd/installer/wizard/locale/locale.go b/backend/cmd/installer/wizard/locale/locale.go
index fbe521c8..75c87757 100644
--- a/backend/cmd/installer/wizard/locale/locale.go
+++ b/backend/cmd/installer/wizard/locale/locale.go
@@ -1422,6 +1422,7 @@ const (
• Traversaal - Web scraping and search
• Google Search - Requires API key and Custom Search Engine ID
• Searxng - Internet metasearch engine
+• Internal Analytics Engine - Optional browser-based fallback (scrape + summarize, off by default, no API key required)
Get API keys from:
• Perplexity: https://www.perplexity.ai/
@@ -1468,6 +1469,12 @@ Get API keys from:
ToolsSearchEnginesSearxngTimeRangeDesc = "Searxng search engine time range (day, month, year)"
ToolsSearchEnginesSearxngTimeout = "Searxng Timeout"
ToolsSearchEnginesSearxngTimeoutDesc = "Searxng request timeout in seconds"
+ ToolsSearchEnginesInternalEnabled = "Internal Analytics Engine"
+ ToolsSearchEnginesInternalEnabledDesc = "Enable the built-in browser-analytics fallback for answer/research queries (no API key required; scrapes and summarizes pages, so it requires a configured scraper and at least one available link engine, e.g. DuckDuckGo or Google)"
+ ToolsSearchEnginesInternalMaxSites = "Internal Engine Max Sites"
+ ToolsSearchEnginesInternalMaxSitesDesc = "Maximum number of pages to fetch and summarize per query"
+ ToolsSearchEnginesInternalMaxSiteBytes = "Internal Engine Max Site Bytes"
+ ToolsSearchEnginesInternalMaxSiteBytesDesc = "Maximum markdown bytes read from each page before truncation"
)
// Scraper screen strings
diff --git a/backend/cmd/installer/wizard/models/search_engines_form.go b/backend/cmd/installer/wizard/models/search_engines_form.go
index 6b8e7504..153e67af 100644
--- a/backend/cmd/installer/wizard/models/search_engines_form.go
+++ b/backend/cmd/installer/wizard/models/search_engines_form.go
@@ -2,6 +2,7 @@ package models
import (
"fmt"
+ "strconv"
"strings"
"pentagi/cmd/installer/loader"
@@ -207,10 +208,44 @@ func (m *SearchEnginesFormModel) BuildForm() tea.Cmd {
false,
))
+ // Internal Analytics Engine (boolean, opt-in browser-based fallback)
+ fields = append(fields, m.createBooleanField("internal_enabled",
+ locale.ToolsSearchEnginesInternalEnabled,
+ locale.ToolsSearchEnginesInternalEnabledDesc,
+ config.WebSearchInternalEnabled,
+ ))
+
+ // Internal Engine Max Sites
+ fields = append(fields, m.createIntegerField("internal_max_sites",
+ locale.ToolsSearchEnginesInternalMaxSites,
+ locale.ToolsSearchEnginesInternalMaxSitesDesc,
+ config.WebSearchInternalMaxSites,
+ internalMaxSitesMin,
+ internalMaxSitesMax,
+ ))
+
+ // Internal Engine Max Site Bytes
+ fields = append(fields, m.createIntegerField("internal_max_site_bytes",
+ locale.ToolsSearchEnginesInternalMaxSiteBytes,
+ locale.ToolsSearchEnginesInternalMaxSiteBytesDesc,
+ config.WebSearchInternalMaxSiteBytes,
+ internalMaxSiteBytesMin,
+ internalMaxSiteBytesMax,
+ ))
+
m.SetFormFields(fields)
return nil
}
+// Bounds for the internal analytics engine's numeric settings, enforced both on the
+// input placeholder (as a hint) and in HandleSave (as validation).
+const (
+ internalMaxSitesMin = 1
+ internalMaxSitesMax = 20
+ internalMaxSiteBytesMin = 1024 // 1 KB
+ internalMaxSiteBytesMax = 102400 // 100 KB
+)
+
func (m *SearchEnginesFormModel) createBooleanField(key, title, description string, envVar loader.EnvVar) FormField {
input := NewBooleanInput(m.GetStyles(), m.GetWindow(), envVar)
@@ -261,6 +296,43 @@ func (m *SearchEnginesFormModel) createSelectTextField(key, title, description s
}
}
+func (m *SearchEnginesFormModel) createIntegerField(key, title, description string, envVar loader.EnvVar, min, max int) FormField {
+ input := NewTextInput(m.GetStyles(), m.GetWindow(), envVar)
+
+ if envVar.Default != "" {
+ input.Placeholder = fmt.Sprintf("%s (%d-%d)", envVar.Default, min, max)
+ } else {
+ input.Placeholder = fmt.Sprintf("(%d-%d)", min, max)
+ }
+
+ return FormField{
+ Key: key,
+ Title: title,
+ Description: description,
+ Required: false,
+ Masked: false,
+ Input: input,
+ Value: input.Value(),
+ }
+}
+
+func (m *SearchEnginesFormModel) validateIntegerField(value, fieldName string, min, max int) error {
+ if value == "" {
+ return nil
+ }
+
+ intVal, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("invalid integer value for %s: %s", fieldName, value)
+ }
+
+ if intVal < min || intVal > max {
+ return fmt.Errorf("%s must be between %d and %d", fieldName, min, max)
+ }
+
+ return nil
+}
+
func (m *SearchEnginesFormModel) GetFormTitle() string {
return locale.ToolsSearchEnginesFormTitle
}
@@ -376,6 +448,19 @@ func (m *SearchEnginesFormModel) GetCurrentConfiguration() string {
m.GetStyles().Warning.Render(locale.StatusNotConfigured)))
}
+ // Internal Analytics Engine
+ internalEnabled := config.WebSearchInternalEnabled.Value
+ if internalEnabled == "" {
+ internalEnabled = config.WebSearchInternalEnabled.Default
+ }
+ if internalEnabled == "true" {
+ sections = append(sections, fmt.Sprintf("• Internal Analytics Engine: %s",
+ m.GetStyles().Success.Render(locale.StatusEnabled)))
+ } else {
+ sections = append(sections, fmt.Sprintf("• Internal Analytics Engine: %s",
+ m.GetStyles().Warning.Render(locale.StatusDisabled)))
+ }
+
sections = append(sections, "")
if config.ConfiguredCount > 0 {
sections = append(sections, m.GetStyles().Success.Render(
@@ -408,27 +493,30 @@ func (m *SearchEnginesFormModel) HandleSave() error {
// create a working copy of the current config to modify
newConfig := &controller.SearchEnginesConfig{
// copy current EnvVar fields - they preserve metadata like Line, IsPresent, etc.
- DuckDuckGoEnabled: config.DuckDuckGoEnabled,
- DuckDuckGoRegion: config.DuckDuckGoRegion,
- DuckDuckGoSafeSearch: config.DuckDuckGoSafeSearch,
- DuckDuckGoTimeRange: config.DuckDuckGoTimeRange,
- SploitusEnabled: config.SploitusEnabled,
- PerplexityAPIKey: config.PerplexityAPIKey,
- PerplexityModel: config.PerplexityModel,
- PerplexityContextSize: config.PerplexityContextSize,
- TavilyAPIKey: config.TavilyAPIKey,
- FirecrawlAPIKey: config.FirecrawlAPIKey,
- FirecrawlAPIURL: config.FirecrawlAPIURL,
- TraversaalAPIKey: config.TraversaalAPIKey,
- GoogleAPIKey: config.GoogleAPIKey,
- GoogleCXKey: config.GoogleCXKey,
- GoogleLRKey: config.GoogleLRKey,
- SearxngURL: config.SearxngURL,
- SearxngCategories: config.SearxngCategories,
- SearxngLanguage: config.SearxngLanguage,
- SearxngSafeSearch: config.SearxngSafeSearch,
- SearxngTimeRange: config.SearxngTimeRange,
- SearxngTimeout: config.SearxngTimeout,
+ DuckDuckGoEnabled: config.DuckDuckGoEnabled,
+ DuckDuckGoRegion: config.DuckDuckGoRegion,
+ DuckDuckGoSafeSearch: config.DuckDuckGoSafeSearch,
+ DuckDuckGoTimeRange: config.DuckDuckGoTimeRange,
+ SploitusEnabled: config.SploitusEnabled,
+ PerplexityAPIKey: config.PerplexityAPIKey,
+ PerplexityModel: config.PerplexityModel,
+ PerplexityContextSize: config.PerplexityContextSize,
+ TavilyAPIKey: config.TavilyAPIKey,
+ FirecrawlAPIKey: config.FirecrawlAPIKey,
+ FirecrawlAPIURL: config.FirecrawlAPIURL,
+ TraversaalAPIKey: config.TraversaalAPIKey,
+ GoogleAPIKey: config.GoogleAPIKey,
+ GoogleCXKey: config.GoogleCXKey,
+ GoogleLRKey: config.GoogleLRKey,
+ SearxngURL: config.SearxngURL,
+ SearxngCategories: config.SearxngCategories,
+ SearxngLanguage: config.SearxngLanguage,
+ SearxngSafeSearch: config.SearxngSafeSearch,
+ SearxngTimeRange: config.SearxngTimeRange,
+ SearxngTimeout: config.SearxngTimeout,
+ WebSearchInternalEnabled: config.WebSearchInternalEnabled,
+ WebSearchInternalMaxSites: config.WebSearchInternalMaxSites,
+ WebSearchInternalMaxSiteBytes: config.WebSearchInternalMaxSiteBytes,
}
// update field values based on form input
@@ -486,6 +574,25 @@ func (m *SearchEnginesFormModel) HandleSave() error {
newConfig.SearxngTimeRange.Value = value
case "searxng_timeout":
newConfig.SearxngTimeout.Value = value
+ case "internal_enabled":
+ // validate boolean input
+ if value != "" && value != "true" && value != "false" {
+ return fmt.Errorf("invalid boolean value for %s: %s (must be 'true' or 'false')",
+ locale.ToolsSearchEnginesInternalEnabled, value)
+ }
+ newConfig.WebSearchInternalEnabled.Value = value
+ case "internal_max_sites":
+ if err := m.validateIntegerField(value, locale.ToolsSearchEnginesInternalMaxSites,
+ internalMaxSitesMin, internalMaxSitesMax); err != nil {
+ return err
+ }
+ newConfig.WebSearchInternalMaxSites.Value = value
+ case "internal_max_site_bytes":
+ if err := m.validateIntegerField(value, locale.ToolsSearchEnginesInternalMaxSiteBytes,
+ internalMaxSiteBytesMin, internalMaxSiteBytesMax); err != nil {
+ return err
+ }
+ newConfig.WebSearchInternalMaxSiteBytes.Value = value
}
}
diff --git a/backend/docs/config.md b/backend/docs/config.md
index 5670affd..a8200f45 100644
--- a/backend/docs/config.md
+++ b/backend/docs/config.md
@@ -62,6 +62,7 @@ This document serves as a comprehensive guide to the configuration system in Pen
- [Firecrawl Search](#firecrawl-search)
- [Perplexity Search](#perplexity-search)
- [Searxng Search](#searxng-search)
+ - [Internal Analytics Engine](#internal-analytics-engine)
- [Usage Details](#usage-details-10)
- [Network and Proxy Settings](#network-and-proxy-settings)
- [Usage Details](#usage-details-11)
@@ -1474,7 +1475,7 @@ These settings control the integration with various search engines used for web
| Option | Environment Variable | Default Value | Description |
| --------------------- | ------------------------- | ------------- | ------------------------------------------------------------ |
| PerplexityAPIKey | `PERPLEXITY_API_KEY` | *(none)* | API key for Perplexity search engine |
-| PerplexityModel | `PERPLEXITY_MODEL` | `sonar` | Model to use for Perplexity search |
+| PerplexityModel | `PERPLEXITY_MODEL` | `sonar-pro` | Model to use for Perplexity search |
| PerplexityContextSize | `PERPLEXITY_CONTEXT_SIZE` | `low` | Context size for Perplexity search (`low`, `medium`, `high`) |
### Searxng Search
@@ -1488,6 +1489,16 @@ These settings control the integration with various search engines used for web
| SearxngTimeRange | `SEARXNG_TIME_RANGE` | *(none)* | Time range filter (e.g., `day`, `month`, `year`) |
| SearxngTimeout | `SEARXNG_TIMEOUT` | *(none)* | Request timeout in seconds for Searxng API calls |
+### Internal Analytics Engine
+
+An optional, opt-in fallback engine for the `web_search` tool's analytic modes (`answer`/`research`). When enabled, it discovers links via the first available link engine, fetches each page's main-content markdown through the browser scraper, and asks the summarizer to synthesize a query-focused answer — without a paid analytic API. Off by default because per-page scraping and summarization can cost more than a purpose-built third-party analytic call. Requires a configured scraper and at least one available link engine (e.g. DuckDuckGo, Google).
+
+| Option | Environment Variable | Default Value | Description |
+| ----------------------------- | ------------------------------------- | -------------- | -------------------------------------------------------------- |
+| WebSearchInternalEnabled | `WEB_SEARCH_INTERNAL_ENABLED` | `false` | Enable or disable the internal browser-analytics engine |
+| WebSearchInternalMaxSites | `WEB_SEARCH_INTERNAL_MAX_SITES` | `5` | Maximum number of pages to fetch and summarize per query |
+| WebSearchInternalMaxSiteBytes | `WEB_SEARCH_INTERNAL_MAX_SITE_BYTES` | `10240` | Maximum markdown bytes read from each page before truncation |
+
### Usage Details
The search engine settings are used in `pkg/tools/tools.go` to configure various search providers that AI agents can use:
diff --git a/backend/docs/flow_execution.md b/backend/docs/flow_execution.md
index 00eefbba..ac407b0b 100644
--- a/backend/docs/flow_execution.md
+++ b/backend/docs/flow_execution.md
@@ -43,15 +43,16 @@ This document describes the internal architecture and execution workflow of Flow
- User-provided flow files are available under `/work/uploads` and `/work/resources`
- **Search Network Tools** - External information sources
- - `browser` - Web scraping with screenshot capture
- - `google` - Google Custom Search API integration
- - `duckduckgo` - Anonymous search engine
- - `tavily` - Advanced research with citations
- - `firecrawl` - Web search with full-page content scraping
- - `traversaal` - Structured Q&A search
- - `perplexity` - AI-powered comprehensive research
- - `sploitus` - Search for security exploits and pentest tools
- - `searxng` - Privacy-focused meta search engine
+ - `browser` - Web scraping with screenshot capture
+ - `web_search` - Unified web search. The agent supplies a `query` and an intent `mode`
+ (`links`, `answer`, `research`, `exploit`); the orchestrator selects the underlying
+ engine, retries transient failures, and falls back across providers automatically.
+ Engines orchestrated under the hood (when configured): Google, DuckDuckGo, Searxng,
+ Tavily, Traversaal, Perplexity, Firecrawl, Sploitus, and the optional internal
+ browser-analytics engine (`WEB_SEARCH_INTERNAL_ENABLED`, off by default). The
+ per-mode fallback order is a single data table at the top of
+ `backend/pkg/tools/web_search.go`; the engine primitives live in
+ `backend/pkg/tools/searchers/`.
- **Vector Database Tools** - Semantic search in long-term memory
- `search_in_memory` - General execution memory search
@@ -225,22 +226,14 @@ graph TD
Searcher --> MemoryFirst[Priority 1: Memory Tools]
MemoryFirst --> AnswerSearch[Search Answers]
MemoryFirst --> VectorDB
-
- Searcher --> ReconTools[Priority 3-4: Reconnaissance]
- ReconTools --> Google[Google Search]
- ReconTools --> DuckDuckGo[DuckDuckGo Search]
- ReconTools --> Browser
-
- Searcher --> DeepAnalysis[Priority 5: Deep Analysis]
- DeepAnalysis --> Tavily[Tavily Search]
- DeepAnalysis --> Perplexity[Perplexity Search]
- DeepAnalysis --> Traversaal[Traversaal Search]
-
- Searcher --> SecurityTools[Security Research]
- SecurityTools --> Sploitus[Sploitus - Exploit Database]
-
- Searcher --> MetaSearch[Meta Search Engine]
- MetaSearch --> Searxng[Searxng - Privacy Meta Search]
+
+ Searcher --> WebSearch[web_search Orchestrator<br/>picks engine + falls back]
+ WebSearch --> ModeLinks[mode: links<br/>Google → DuckDuckGo → Searxng → Firecrawl]
+ WebSearch --> ModeAnswer[mode: answer<br/>Tavily → Traversaal → Perplexity → Internal]
+ WebSearch --> ModeResearch[mode: research<br/>Perplexity → Tavily → Traversaal → Internal]
+ WebSearch --> ModeExploit[mode: exploit<br/>Sploitus → Tavily → Traversaal → Perplexity]
+
+ Searcher --> Browser[browser: read a specific URL]
end
subgraph "Adviser Workflows"
@@ -307,7 +300,7 @@ sequenceDiagram
else UseAgents = false
Note over AA,DirectTools: Direct tools only mode
AA->>DirectTools: terminal, file, browser
- AA->>DirectTools: google, duckduckgo, sploitus, tavily, traversaal, perplexity
+ AA->>DirectTools: web_search (modes: links/answer/research/exploit)
AA->>DirectTools: search_in_memory, search_guide, search_answer, search_code
DirectTools-->>AA: Tool responses (no agent delegation)
end
@@ -345,9 +338,9 @@ graph LR
StoreOps[store_guide<br/>store_answer<br/>store_code<br/>auto-store from 18 tools]
end
- subgraph "Auto-Storage Tools (18 total)"
+ subgraph "Auto-Storage Tools"
EnvTools[terminal, file]
- SearchEngines[google, duckduckgo, tavily,<br/>traversaal, perplexity, sploitus, searxng]
+ SearchEngines[web_search]
AgentTools[search, maintenance, coder,<br/>pentester, advice]
end
@@ -753,28 +746,34 @@ The Searcher Agent follows a strict hierarchy for information retrieval:
1. **Priority 1-2: Memory Tools** - Always check internal knowledge first
- `search_answer` - Primary tool for accessing existing knowledge
- `memorist` - Retrieves task/subtask execution history
-
-2. **Priority 3-4: Reconnaissance Tools** - Fast source discovery
- - `google` and `duckduckgo` - Rapid link collection and basic searches
- - `browser` - Targeted content extraction from specific URLs
-
-3. **Priority 5: Deep Analysis Tools** - Complex research synthesis
- - `traversaal` - Structured answers for common questions
- - `tavily` - Research-grade exploration of technical topics
- - `firecrawl` - Deep research with main-content markdown scraped from discovered sites
- - `perplexity` - Comprehensive analysis with advanced reasoning
-
-**Available Search Engines**: Google, DuckDuckGo, Tavily, Firecrawl, Traversaal, Perplexity, Sploitus, Searxng
-
-**Search Engine Configurations**:
-- **Google** - Custom Search API with CX key and language restrictions
-- **DuckDuckGo** - Anonymous search with VQD token authentication
-- **Tavily** - Advanced research with raw content and citations
+
+2. **Priority 3: `web_search`** - All external web search, via one unified tool
+ - The agent supplies a `query` and an intent `mode`; it does NOT choose a provider.
+ - **Modes**: `links` (fast link discovery), `answer` (synthesized answer, default),
+ `research` (deep multi-source synthesis), `exploit` (exploits/PoCs/offensive tools).
+
+3. **Priority 4: `browser`** - Targeted content extraction from a specific, known URL
+
+**web_search orchestration**: For the chosen mode, the orchestrator walks a per-mode
+fallback chain, skipping engines that are not configured, retrying only *retryable*
+failures (HTTP 429/5xx/transport) on the same engine, and moving on immediately for
+*fatal* ones (HTTP 4xx/decode). It returns an error to the agent only after every
+available engine is exhausted, and it records one search-log entry attributed to the
+engine that actually served the result. The fallback table is the single source of
+truth at the top of `backend/pkg/tools/web_search.go`.
+
+**Engines orchestrated** (used only when configured):
+- **Google** - Custom Search API with CX key and language restrictions (links)
+- **DuckDuckGo** - Anonymous search (links)
+- **Searxng** - Privacy meta search aggregating multiple engines (links)
- **Firecrawl** - Web search with main-content markdown scraped from each result
-- **Perplexity** - AI-powered synthesis with configurable context size
-- **Traversaal** - Structured Q&A responses with web links
-- **Sploitus** - Search for security exploits and pentest tools
-- **Searxng** - Meta search aggregating multiple engines with privacy focus
+- **Tavily** - Research-grade exploration with raw content and citations (answer/research)
+- **Traversaal** - Structured Q&A responses with web links (answer/research)
+- **Perplexity** - AI-powered synthesis with configurable context size (answer/research)
+- **Sploitus** - Security exploits and pentest tools (exploit)
+- **Internal Analytics Engine** - optional, off by default (`WEB_SEARCH_INTERNAL_ENABLED`);
+ answers analytic queries by scraping and summarizing pages via the browser, bounded to
+ a configurable byte budget per site
**Action Economy Rules**: Maximum 3-5 search actions per query, stop immediately when sufficient information is found
diff --git a/backend/pkg/config/config.go b/backend/pkg/config/config.go
index 0c87e986..1c50af77 100644
--- a/backend/pkg/config/config.go
+++ b/backend/pkg/config/config.go
@@ -179,7 +179,7 @@ type Config struct {
// === Search Engine: Perplexity AI ===
PerplexityAPIKey string `env:"PERPLEXITY_API_KEY"`
- PerplexityModel string `env:"PERPLEXITY_MODEL" envDefault:"sonar"`
+ PerplexityModel string `env:"PERPLEXITY_MODEL" envDefault:"sonar-pro"`
PerplexityContextSize string `env:"PERPLEXITY_CONTEXT_SIZE" envDefault:"low"`
// === Search Engine: SearXNG (Self-Hosted) ===
@@ -190,6 +190,16 @@ type Config struct {
SearxngTimeRange string `env:"SEARXNG_TIME_RANGE"`
SearxngTimeout int `env:"SEARXNG_TIMEOUT"`
+ // === Web Search Orchestrator: Internal Analytics Engine ===
+ // The internal analytics engine is an OPTIONAL, opt-in fallback for the
+ // analytic web_search modes (answer/research). It produces a synthesized answer
+ // without a paid analytic API by combining link discovery + the browser scraper
+ // + the summarizer. It is OFF by default because per-page scraping and
+ // summarization can cost more than a purpose-built third-party analytic call.
+ WebSearchInternalEnabled bool `env:"WEB_SEARCH_INTERNAL_ENABLED" envDefault:"false"`
+ WebSearchInternalMaxSites int `env:"WEB_SEARCH_INTERNAL_MAX_SITES" envDefault:"5"`
+ WebSearchInternalMaxSiteBytes int `env:"WEB_SEARCH_INTERNAL_MAX_SITE_BYTES" envDefault:"10240"`
+
// === AI Assistant Mode Configuration ===
AssistantUseAgents bool `env:"ASSISTANT_USE_AGENTS" envDefault:"false"`
AssistantSummarizerPreserveLast bool `env:"ASSISTANT_SUMMARIZER_PRESERVE_LAST" envDefault:"true"`
diff --git a/backend/pkg/config/config_test.go b/backend/pkg/config/config_test.go
index f9513b6f..0fa7930b 100644
--- a/backend/pkg/config/config_test.go
+++ b/backend/pkg/config/config_test.go
@@ -424,11 +424,16 @@ func TestNewConfig_SearchEngineDefaults(t *testing.T) {
config, err := NewConfig()
require.NoError(t, err)
- assert.Equal(t, "sonar", config.PerplexityModel)
+ assert.Equal(t, "sonar-pro", config.PerplexityModel)
assert.Equal(t, "low", config.PerplexityContextSize)
assert.Equal(t, "general", config.SearxngCategories)
assert.Equal(t, "0", config.SearxngSafeSearch)
assert.Equal(t, "lang_en", config.GoogleLRKey)
+
+ // web_search internal analytics engine: off by default, with bounded scraping.
+ assert.False(t, config.WebSearchInternalEnabled)
+ assert.Equal(t, 5, config.WebSearchInternalMaxSites)
+ assert.Equal(t, 10240, config.WebSearchInternalMaxSiteBytes)
}
func TestEnsureInstallationID_GeneratesNewUUID(t *testing.T) {
diff --git a/backend/pkg/providers/assistant.go b/backend/pkg/providers/assistant.go
index 64fa3f1b..c77040c9 100644
--- a/backend/pkg/providers/assistant.go
+++ b/backend/pkg/providers/assistant.go
@@ -336,11 +336,7 @@ func (ap *assistantProvider) getAssistantSystemPrompt(ctx context.Context) (stri
"MaintenanceToolName": tools.MaintenanceToolName,
"TerminalToolName": tools.TerminalToolName,
"FileToolName": tools.FileToolName,
- "GoogleToolName": tools.GoogleToolName,
- "DuckDuckGoToolName": tools.DuckDuckGoToolName,
- "TavilyToolName": tools.TavilyToolName,
- "TraversaalToolName": tools.TraversaalToolName,
- "PerplexityToolName": tools.PerplexityToolName,
+ "WebSearchToolName": tools.WebSearchToolName,
"BrowserToolName": tools.BrowserToolName,
"SearchInMemoryToolName": tools.SearchInMemoryToolName,
"SearchGuideToolName": tools.SearchGuideToolName,
diff --git a/backend/pkg/providers/handlers.go b/backend/pkg/providers/handlers.go
index 063cad16..47112911 100644
--- a/backend/pkg/providers/handlers.go
+++ b/backend/pkg/providers/handlers.go
@@ -601,6 +601,7 @@ func (fp *flowProvider) GetPentesterHandler(ctx context.Context, taskID, subtask
},
"system": {
"HackResultToolName": tools.HackResultToolName,
+ "WebSearchToolName": tools.WebSearchToolName,
"SearchGuideToolName": tools.SearchGuideToolName,
"StoreGuideToolName": tools.StoreGuideToolName,
"GraphitiEnabled": fp.graphitiClient != nil && fp.graphitiClient.IsEnabled(),
diff --git a/backend/pkg/templates/prompts/assistant.tmpl b/backend/pkg/templates/prompts/assistant.tmpl
index 9737679a..415a76c7 100644
--- a/backend/pkg/templates/prompts/assistant.tmpl
+++ b/backend/pkg/templates/prompts/assistant.tmpl
@@ -23,9 +23,9 @@ You are the user-facing voice of the engagement — the only agent in this syste
{{- if .UseAgents}}
- delegation `question` you send to `{{.SearchToolName}}`, `{{.PentesterToolName}}`, `{{.CoderToolName}}`, `{{.MaintenanceToolName}}`, `{{.MemoristToolName}}`, and the `question`/`code`/`output` you send with `{{.AdviceToolName}}` to the mentor
{{- else}}
- - external search-engine queries you send to whichever providers are available in this engagement (`{{.GoogleToolName}}`, `{{.DuckDuckGoToolName}}`, `{{.TavilyToolName}}`, `{{.TraversaalToolName}}`, `{{.PerplexityToolName}}`)
- vector-store search queries: `{{.SearchInMemoryToolName}}`, `{{.SearchGuideToolName}}`, `{{.SearchAnswerToolName}}`, `{{.SearchCodeToolName}}` (the `questions` arrays)
{{- end}}
+ - the `query` you send to `{{.WebSearchToolName}}` (the unified web search tool that selects the underlying engine for you)
- runtime payloads inside the Docker container: `{{.TerminalToolName}}` `input`/`cwd`, `{{.FileToolName}}` `path`/`content`, `{{.BrowserToolName}}` `url`
External search engines and the vector store are indexed in English and shared across all engagements regardless of their working language: any non-English query retrieves nothing. Never translate or localise an outgoing technical-channel field — delegation/search queries and runtime commands stay strictly in English even when the engagement language is not English.
@@ -162,7 +162,7 @@ External search engines and the vector store are indexed in English and shared a
{{- if .UseAgents}}
- Web research and memory: delegated to specialists (see TEAM COLLABORATION & DELEGATION above) — you do NOT invoke search engines or vector-store searches directly in this mode
{{- else}}
-- Web search engines: `{{.GoogleToolName}}`, `{{.DuckDuckGoToolName}}`, `{{.TavilyToolName}}`, `{{.TraversaalToolName}}`, `{{.PerplexityToolName}}` (and Firecrawl/Searxng/Sploitus when configured) — pick the engine matching the query complexity
+- Web search: `{{.WebSearchToolName}}` — one unified tool. Provide a `query` and a `mode` (`links`, `answer`, `research`, or `exploit`); it selects the best available engine, retries transient failures, and falls back automatically, so you never name a specific engine
- Memory search (read-only): `{{.SearchInMemoryToolName}}`, `{{.SearchGuideToolName}}`, `{{.SearchAnswerToolName}}`, `{{.SearchCodeToolName}}` for retrieving stored knowledge from past engagements
{{- end}}
</available_tools>
diff --git a/backend/pkg/templates/prompts/pentester.tmpl b/backend/pkg/templates/prompts/pentester.tmpl
index cafaab11..685c3248 100644
--- a/backend/pkg/templates/prompts/pentester.tmpl
+++ b/backend/pkg/templates/prompts/pentester.tmpl
@@ -22,7 +22,7 @@ You operate on two parallel channels. The channel of each tool argument is fixed
2. **Technical channel — English.** The wire between you, your team, search engines, the vector store, and the runtime container. Outgoing entries are:
- delegation `question` fields you send to `{{.CoderToolName}}`, `{{.MaintenanceToolName}}`, `{{.MemoristToolName}}`, `{{.SearchToolName}}`, and the `question`/`code`/`output` you send with `{{.AdviceToolName}}` to the mentor
- - external search queries: Sploitus query{{if .GraphitiEnabled}}, `{{.GraphitiSearchToolName}}.query`{{end}}, `{{.SearchGuideToolName}}.questions`
+ - external search queries: `{{.WebSearchToolName}}.query` (use `mode=exploit` to find exploits/PoCs){{if .GraphitiEnabled}}, `{{.GraphitiSearchToolName}}.query`{{end}}, `{{.SearchGuideToolName}}.questions`
- vector-store payloads you write with `{{.StoreGuideToolName}}` (`guide`, `question`)
- runtime payloads inside the Docker container: `{{.TerminalToolName}}` `input`/`cwd`, `{{.FileToolName}}` `path`/`content`, browser `url`
- the `result` field of your closing `{{.HackResultToolName}}` call — the full pentest write-up consumed by the calling agent for further reasoning
diff --git a/backend/pkg/templates/prompts/searcher.tmpl b/backend/pkg/templates/prompts/searcher.tmpl
index 81c29637..46578722 100644
--- a/backend/pkg/templates/prompts/searcher.tmpl
+++ b/backend/pkg/templates/prompts/searcher.tmpl
@@ -20,7 +20,7 @@ You operate on two parallel channels. The channel of each tool argument is fixed
1. **Engagement log — engagement language `{{.Lang}}`.** Your running commentary on this engagement. Entries are every `message` field of every tool call you make (external search engines, browser navigation, the answer vector-store search and store, the memorist delegation, the closing call) and the `message` of your closing `{{.SearchResultToolName}}` call. The engagement coordination team reads the log in `{{.Lang}}`. Keep `message` log entries to 1-2 short sentences narrating what you are about to do or what you just produced.
2. **Technical channel — English.** The wire between you, your team, search engines, the vector store, and the web. Outgoing entries are:
- - search-engine queries you send to whichever providers are available in this engagement (Google, DuckDuckGo, Tavily, Firecrawl, Traversaal, Perplexity, Searxng, Sploitus, etc.) — use exact technical terms, identifiers, and error codes
+ - the `query` you send to the unified `web_search` tool (it selects the underlying provider — Google, DuckDuckGo, Tavily, Firecrawl, Traversaal, Perplexity, Searxng, Sploitus — for you) — use exact technical terms, identifiers, and error codes
- browser `url` for direct retrieval from known sources
- answer vector-store search queries: `{{.SearchAnswerToolName}}.questions`
- answer vector-store write payloads with `{{.StoreAnswerToolName}}` (`answer`, `question`)
@@ -49,10 +49,10 @@ External search engines and the answer vector store are indexed in English and s
- Skip redundant sources if one provides complete information
3. **Source Prioritization**
- - Internal memory → Specialized tools → General search engines
- - Use "browser" for reading technical documentation directly
- - Reserve "tavily"/"perplexity" for complex questions requiring synthesis
- - Match search tools to query complexity
+ - Internal memory → `web_search` → targeted `browser` reads
+ - Use "browser" for reading technical documentation directly from a known URL
+ - Use `web_search` with `mode=research` (or `mode=answer`) for complex questions requiring synthesis; `mode=links` for quick link discovery; `mode=exploit` for exploits/PoCs
+ - Match the `web_search` mode to query complexity
## SUMMARIZATION AWARENESS PROTOCOL
@@ -98,18 +98,18 @@ External search engines and the answer vector store are indexed in English and s
<tool name="memorist" priority="2">For retrieving task/subtask execution history and context</tool>
</memory_tools>
-<reconnaissance_tools>
-<tool name="google" priority="3">For rapid source discovery and initial link collection</tool>
-<tool name="duckduckgo" priority="3">For privacy-sensitive searches and alternative source index</tool>
-<tool name="browser" priority="4">For targeted content extraction from identified sources</tool>
-</reconnaissance_tools>
-
-<deep_analysis_tools>
-<tool name="tavily" priority="5">For research-grade exploration of complex technical topics</tool>
-<tool name="firecrawl" priority="5">For deep research with main-content markdown extracted directly from the discovered web sites</tool>
-<tool name="perplexity" priority="5">For comprehensive analysis with advanced reasoning</tool>
-<tool name="traversaal" priority="4">For discovering structured answers to common questions</tool>
-</deep_analysis_tools>
+<web_search priority="3">
+The single `web_search` tool covers ALL external web search. You do NOT choose a
+provider (Google, DuckDuckGo, Tavily, Firecrawl, Traversaal, Perplexity, Searxng,
+Sploitus) — you choose an intent `mode`, and web_search selects the best available
+engine for that mode, retries transient failures, and falls back automatically:
+<mode name="links">Rapid link discovery with titles/snippets — the cheapest option for collecting public sources.</mode>
+<mode name="answer">A synthesized answer over live sources — the default for a concrete question.</mode>
+<mode name="research">Deep, multi-source analysis with reasoning — for complex technical topics needing synthesis.</mode>
+<mode name="exploit">Exploit code, PoCs, and offensive tooling — for CVEs, software, or vulnerability classes.</mode>
+</web_search>
+
+<tool name="browser" priority="4">For targeted content extraction from a specific, already-identified URL</tool>
</search_tools>
## EXECUTION CONTEXT
diff --git a/backend/pkg/templates/templates.go b/backend/pkg/templates/templates.go
index 66a49339..09e1da33 100644
--- a/backend/pkg/templates/templates.go
+++ b/backend/pkg/templates/templates.go
@@ -99,11 +99,7 @@ var PromptVariables = map[PromptType][]string{
"MaintenanceToolName",
"TerminalToolName",
"FileToolName",
- "GoogleToolName",
- "DuckDuckGoToolName",
- "TavilyToolName",
- "TraversaalToolName",
- "PerplexityToolName",
+ "WebSearchToolName",
"BrowserToolName",
"SearchInMemoryToolName",
"SearchGuideToolName",
@@ -128,6 +124,7 @@ var PromptVariables = map[PromptType][]string{
},
PromptTypePentester: {
"HackResultToolName",
+ "WebSearchToolName",
"SearchGuideToolName",
"StoreGuideToolName",
"GraphitiEnabled",
diff --git a/backend/pkg/templates/validator/testdata.go b/backend/pkg/templates/validator/testdata.go
index 0d623391..6dc85e54 100644
--- a/backend/pkg/templates/validator/testdata.go
+++ b/backend/pkg/templates/validator/testdata.go
@@ -37,12 +37,8 @@ func CreateDummyTemplateData() map[string]any {
"TerminalToolName": tools.TerminalToolName,
"FileToolName": tools.FileToolName,
"BrowserToolName": tools.BrowserToolName,
- "GoogleToolName": tools.GoogleToolName,
- "DuckDuckGoToolName": tools.DuckDuckGoToolName,
+ "WebSearchToolName": tools.WebSearchToolName,
"SploitusToolName": tools.SploitusToolName,
- "TavilyToolName": tools.TavilyToolName,
- "TraversaalToolName": tools.TraversaalToolName,
- "PerplexityToolName": tools.PerplexityToolName,
"SearchInMemoryToolName": tools.SearchInMemoryToolName,
"SearchGuideToolName": tools.SearchGuideToolName,
"SearchAnswerToolName": tools.SearchAnswerToolName,
diff --git a/backend/pkg/tools/args.go b/backend/pkg/tools/args.go
index 4f080b56..ed018716 100644
--- a/backend/pkg/tools/args.go
+++ b/backend/pkg/tools/args.go
@@ -146,6 +146,18 @@ type SploitusAction struct {
Message string `json:"message" jsonschema:"required,title=Search query message" jsonschema_description:"Engagement-log entry — a 1-2 short sentence running commentary explaining the expected result and how it advances the goal. Written in the engagement language declared by your system prompt."`
}
+// WebSearchAction is the LLM-facing schema for the unified web_search tool. The agent
+// supplies a query and an intent `mode`; web_search selects the concrete engine,
+// retries transient failures, and falls back across providers automatically.
+type WebSearchAction struct {
+ Query string `json:"query" jsonschema:"required" jsonschema_description:"Technical-channel payload — the search query. ALWAYS written in English regardless of the engagement language: internet sources and the underlying engines are indexed in English and non-English queries return poor or empty results. Keep it short and keyword-focused."`
+ Mode String `json:"mode,omitempty" jsonschema:"type=string,enum=links,enum=answer,enum=research,enum=exploit" jsonschema_description:"What you need back (default 'answer'). 'links' — a list of source links with snippets (fastest/cheapest). 'answer' — a synthesized answer over live sources. 'research' — deep multi-source analysis with reasoning (most thorough). 'exploit' — exploit code, PoCs, and offensive tools. web_search picks the concrete engine for you and falls back automatically; you do NOT name an engine."`
+ MaxResults Int64 `json:"max_results,omitempty" jsonschema:"type=integer" jsonschema_description:"Maximum number of results to return (1–25; default 5). Ignored by answer/research engines that return a single synthesized answer."`
+ ExploitType String `json:"exploit_type,omitempty" jsonschema:"type=string,enum=exploits,enum=tools" jsonschema_description:"exploit mode only: 'exploits' (default) for exploit code and PoCs, 'tools' for offensive-security tools."`
+ Sort String `json:"sort,omitempty" jsonschema:"type=string,enum=default,enum=date,enum=score" jsonschema_description:"exploit mode only: result ordering — 'default' (relevance), 'date' (newest first), 'score' (highest CVSS first)."`
+ Message string `json:"message" jsonschema:"required,title=Search query message" jsonschema_description:"Engagement-log entry — a 1-2 short sentence running commentary explaining the expected result and how it advances the goal. Written in the engagement language declared by your system prompt."`
+}
+
type GraphitiSearchAction struct {
SearchType String `json:"search_type" jsonschema:"required,type=string,enum=temporal_window,enum=entity_relationships,enum=diverse_results,enum=episode_context,enum=successful_tools,enum=recent_context,enum=entity_by_label" jsonschema_description:"Type of search to perform: temporal_window (time-bounded search), entity_relationships (graph traversal from an entity), diverse_results (anti-redundancy search), episode_context (full agent reasoning and tool outputs), successful_tools (proven techniques), recent_context (latest findings), entity_by_label (type-specific entity search)"`
Query string `json:"query" jsonschema:"required" jsonschema_description:"Technical-channel payload — natural language query against the team's temporal knowledge graph. ALWAYS written in English regardless of the engagement language: the graph is indexed in English and shared across all engagements; non-English queries will fail to retrieve stored episodic memory."`
diff --git a/backend/pkg/tools/google.go b/backend/pkg/tools/google.go
deleted file mode 100644
index 36fb0a1b..00000000
--- a/backend/pkg/tools/google.go
+++ /dev/null
@@ -1,179 +0,0 @@
-package tools
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "strings"
-
- "pentagi/pkg/config"
- "pentagi/pkg/database"
- obs "pentagi/pkg/observability"
- "pentagi/pkg/observability/langfuse"
- "pentagi/pkg/system"
-
- "github.com/sirupsen/logrus"
- customsearch "google.golang.org/api/customsearch/v1"
- "google.golang.org/api/option"
-)
-
-const googleMaxResults = 10
-
-type google struct {
- cfg *config.Config
- flowID int64
- taskID *int64
- subtaskID *int64
- slp SearchLogProvider
-}
-
-func NewGoogleTool(
- cfg *config.Config,
- flowID int64,
- taskID, subtaskID *int64,
- slp SearchLogProvider,
-) Tool {
- return &google{
- cfg: cfg,
- flowID: flowID,
- taskID: taskID,
- subtaskID: subtaskID,
- slp: slp,
- }
-}
-
-func (g *google) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
- if !g.IsAvailable() {
- return "", fmt.Errorf("google is not available")
- }
-
- var action SearchAction
- ctx, observation := obs.Observer.NewObservation(ctx)
- logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(g.flowID, g.taskID, g.subtaskID, logrus.Fields{
- "tool": name,
- "args": string(args),
- }))
-
- if err := json.Unmarshal(args, &action); err != nil {
- logger.WithError(err).Error("failed to unmarshal google search action")
- return "", fmt.Errorf("failed to unmarshal %s search action arguments: %w", name, err)
- }
-
- numResults := int64(action.MaxResults)
- if numResults < 1 || numResults > googleMaxResults {
- numResults = googleMaxResults
- }
-
- logger = logger.WithFields(logrus.Fields{
- "query": action.Query[:min(len(action.Query), 1000)],
- "num_results": numResults,
- })
-
- svc, err := g.newSearchService(ctx)
- if err != nil {
- logger.WithError(err).Error("failed to create google search service")
- return "", err
- }
-
- result, err := g.search(ctx, svc, action.Query, numResults)
- if err != nil {
- observation.Event(
- langfuse.WithEventName("search engine error swallowed"),
- langfuse.WithEventInput(action.Query),
- langfuse.WithEventStatus(err.Error()),
- langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
- langfuse.WithEventMetadata(langfuse.Metadata{
- "tool_name": GoogleToolName,
- "engine": "google",
- "query": action.Query,
- "max_results": numResults,
- "error": err.Error(),
- }),
- )
-
- logger.WithError(err).Error("failed to search in google")
- result = fmt.Sprintf("failed to search in google: %v", err)
- }
-
- if agentCtx, ok := GetAgentContext(ctx); ok {
- _, _ = g.slp.PutLog(
- ctx,
- agentCtx.ParentAgentType,
- agentCtx.CurrentAgentType,
- database.SearchengineTypeGoogle,
- action.Query,
- result,
- g.taskID,
- g.subtaskID,
- )
- }
-
- return result, nil
-}
-
-func (g *google) search(ctx context.Context, svc *customsearch.Service, query string, numResults int64) (string, error) {
- resp, err := svc.Cse.List().Context(ctx).Cx(g.cxKey()).Q(query).Lr(g.lrKey()).Num(numResults).Do()
- if err != nil {
- return "", fmt.Errorf("failed to do request: %w", err)
- }
-
- return g.formatResults(resp), nil
-}
-
-func (g *google) formatResults(res *customsearch.Search) string {
- var writer strings.Builder
- for i, item := range res.Items {
- writer.WriteString(fmt.Sprintf("# %d. %s\n\n", i+1, item.Title))
- writer.WriteString(fmt.Sprintf("## URL\n%s\n\n", item.Link))
- writer.WriteString(fmt.Sprintf("## Snippet\n\n%s\n\n", item.Snippet))
- }
-
- return writer.String()
-}
-
-func (g *google) newSearchService(ctx context.Context) (*customsearch.Service, error) {
- client, err := system.GetHTTPClient(g.cfg)
- if err != nil {
- return nil, fmt.Errorf("failed to create http client: %w", err)
- }
-
- opts := []option.ClientOption{
- option.WithAPIKey(g.apiKey()),
- option.WithHTTPClient(client),
- }
-
- svc, err := customsearch.NewService(ctx, opts...)
- if err != nil {
- return nil, fmt.Errorf("failed to create google search service: %v", err)
- }
-
- return svc, nil
-}
-
-func (g *google) IsAvailable() bool {
- return g.apiKey() != "" && g.cxKey() != ""
-}
-
-func (g *google) apiKey() string {
- if g.cfg == nil {
- return ""
- }
-
- return g.cfg.GoogleAPIKey
-}
-
-func (g *google) cxKey() string {
- if g.cfg == nil {
- return ""
- }
-
- return g.cfg.GoogleCXKey
-}
-
-func (g *google) lrKey() string {
- if g.cfg == nil {
- return ""
- }
-
- return g.cfg.GoogleLRKey
-}
diff --git a/backend/pkg/tools/registry.go b/backend/pkg/tools/registry.go
index dfeba43c..600294f5 100644
--- a/backend/pkg/tools/registry.go
+++ b/backend/pkg/tools/registry.go
@@ -29,6 +29,7 @@ const (
PerplexityToolName = "perplexity"
SearxngToolName = "searxng"
SploitusToolName = "sploitus"
+ WebSearchToolName = "web_search"
SearchToolName = "search"
SearchResultToolName = "search_result"
EnricherResultToolName = "enricher_result"
@@ -115,6 +116,7 @@ var toolsTypeMapping = map[string]ToolType{
PerplexityToolName: SearchNetworkToolType,
SearxngToolName: SearchNetworkToolType,
SploitusToolName: SearchNetworkToolType,
+ WebSearchToolName: SearchNetworkToolType,
SearchToolName: AgentToolType,
SearchResultToolName: StoreAgentResultToolType,
EnricherResultToolName: StoreAgentResultToolType,
@@ -160,6 +162,7 @@ var allowedStoringInMemoryTools = []string{
PerplexityToolName,
SearxngToolName,
SploitusToolName,
+ WebSearchToolName,
MaintenanceToolName,
CoderToolName,
PentesterToolName,
@@ -269,6 +272,16 @@ var registryDefinitions = map[string]llms.FunctionDefinition{
"'CVE-2021-44228'). Returns exploit URLs, CVSS scores, CVE references, and publication dates.",
Parameters: reflector.Reflect(&SploitusAction{}),
},
+ WebSearchToolName: {
+ Name: WebSearchToolName,
+ Description: "Search the web through a unified engine. Provide a `query` and a `mode`: " +
+ "`links` for a quick list of source links with snippets, `answer` for a synthesized answer over " +
+ "live sources (default), `research` for deep multi-source analysis with reasoning, or `exploit` for " +
+ "exploit code, PoCs, and offensive tooling. The tool selects the best available search provider for " +
+ "that mode, retries transient failures, and automatically falls back to alternative providers, so you " +
+ "do NOT choose or name a specific engine. Queries must be short, keyword-focused, and in English.",
+ Parameters: reflector.Reflect(&WebSearchAction{}),
+ },
EnricherResultToolName: {
Name: EnricherResultToolName,
Description: "Send the enriched user's question with additional information to the user",
@@ -451,7 +464,7 @@ func getMessageType(name string) database.MsglogType {
case BrowserToolName:
return database.MsglogTypeBrowser
case MemoristToolName, SearchToolName, GoogleToolName, DuckDuckGoToolName, TavilyToolName, FirecrawlToolName,
- TraversaalToolName, PerplexityToolName, SearxngToolName, SploitusToolName,
+ TraversaalToolName, PerplexityToolName, SearxngToolName, SploitusToolName, WebSearchToolName,
SearchGuideToolName, SearchAnswerToolName, SearchCodeToolName, SearchInMemoryToolName, GraphitiSearchToolName:
return database.MsglogTypeSearch
case AdviceToolName:
diff --git a/backend/pkg/tools/searchers/README.md b/backend/pkg/tools/searchers/README.md
new file mode 100644
index 00000000..15f2815c
--- /dev/null
+++ b/backend/pkg/tools/searchers/README.md
@@ -0,0 +1,44 @@
+# `searchers` — web search primitives
+
+This package holds the individual web-search engines that the `web_search` orchestrator (`pkg/tools/web_search.go`) drives. Each engine wraps a single provider and nothing more: it does one HTTP call (or, for the internal engine, a browser + summarize pass), formats the result as markdown, and returns.
+
+## Contract
+
+Every engine implements `Searcher`:
+
+```go
+type Searcher interface {
+ Engine() database.SearchengineType // stable id, also used for search-log attribution
+ IsAvailable() bool // configured & usable?
+ Handle(ctx context.Context, req Request) (string, error)
+}
+```
+
+Two rules make the orchestrator possible:
+
+1. **Original, unmasked errors.** A searcher NEVER swallows a failure into a `"failed to search…"` string. It returns the real error, classified as one of:
+ - `*RetryableError` — HTTP 429, HTTP 5xx, or transport/network failures. The orchestrator may retry the **same** engine.
+ - `*FatalError` — HTTP 4xx (auth/bad-request/etc.), response-decode errors, unknown status. The orchestrator moves to the **next** engine immediately.
+ - `ErrNotConfigured` — `Handle` was called while `IsAvailable()` is false.
+
+ Use `ClassifyHTTPStatus(status, msg)` for status-based classification, or `Retryable(err, retryAfter)` / `Fatal(err)` directly. `IsRetryable(err)` / `IsFatal(err)` inspect the class.
+
+2. **No side effects beyond Langfuse.** Searchers keep their Langfuse observation (the "wrapper") but do **not** write the DB search-log — the orchestrator writes exactly one search-log row per `web_search` call, attributing it to the engine that won.
+
+`Request` is the already-parsed, engine-agnostic input (`Query`, `MaxResults`, and the exploit-only `ExploitType`/`Sort`). The lenient LLM JSON arg types stay in the parent `tools` package; searchers see plain Go types.
+
+## Import boundary
+
+`searchers` must **not** import `pentagi/pkg/tools` (the orchestrator imports this package). It depends only on neutral packages: `config`, `database` (for the `SearchengineType` attribution enum), `system` (HTTP client), and `observability`.
+
+## Adding a new engine
+
+1. Create `<name>.go` implementing `Searcher` with a `New<Name>(cfg, …)` constructor, `IsAvailable()`, `Engine()`, and a `Handle` that returns typed errors.
+2. Add the engine's config field(s) to `pkg/config/config.go` (+ `.env.example`, `docker-compose.yml`, `config_test.go`).
+3. Construct it in `buildSearchEngines` (`pkg/tools/web_search.go`) and place its id in the relevant `fallbackStrategy` chains — that table is the only place engine priority lives.
+4. If the engine needs a **new** attribution value (not one of the existing `SearchengineType`s), add a goose migration under `backend/migrations/sql/`, a `SearchengineType<Name>` constant in `pkg/database/models.go`, and reconcile `pkg/server/models/searchlogs.go`. Reusing an existing value (as the internal engine reuses `browser`) needs no migration.
+5. Add `<name>_test.go`. The shared MITM proxy harness (`newTestProxy`) lives in `proxy_test.go`.
+
+## Current engines
+
+`google`, `duckduckgo`, `tavily`, `perplexity`, `traversaal`, `sploitus`, `searxng`, `firecrawl`, and `internal` (the opt-in browser-analytics engine, off by default via `WEB_SEARCH_INTERNAL_ENABLED`).
diff --git a/backend/pkg/tools/duckduckgo.go b/backend/pkg/tools/searchers/duckduckgo.go
similarity index 88%
rename from backend/pkg/tools/duckduckgo.go
rename to backend/pkg/tools/searchers/duckduckgo.go
index d0cb66d2..6147da2e 100644
--- a/backend/pkg/tools/duckduckgo.go
+++ b/backend/pkg/tools/searchers/duckduckgo.go
@@ -1,8 +1,7 @@
-package tools
+package searchers
import (
"context"
- "encoding/json"
"fmt"
"io"
"net/http"
@@ -69,54 +68,34 @@ type searchResponse struct {
}
type duckduckgo struct {
- cfg *config.Config
- flowID int64
- taskID *int64
- subtaskID *int64
- slp SearchLogProvider
+ cfg *config.Config
}
-func NewDuckDuckGoTool(
- cfg *config.Config,
- flowID int64,
- taskID, subtaskID *int64,
- slp SearchLogProvider,
-) Tool {
- return &duckduckgo{
- cfg: cfg,
- flowID: flowID,
- taskID: taskID,
- subtaskID: subtaskID,
- slp: slp,
- }
+func NewDuckDuckGo(cfg *config.Config) Searcher {
+ return &duckduckgo{cfg: cfg}
+}
+
+func (d *duckduckgo) Engine() database.SearchengineType {
+ return database.SearchengineTypeDuckduckgo
}
-// Handle processes the search request from an AI agent
-func (d *duckduckgo) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+// Handle processes the search request from the orchestrator
+func (d *duckduckgo) Handle(ctx context.Context, req Request) (string, error) {
if !d.IsAvailable() {
- return "", fmt.Errorf("duckduckgo is not available")
+ return "", ErrNotConfigured
}
- var action SearchAction
ctx, observation := obs.Observer.NewObservation(ctx)
- logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(d.flowID, d.taskID, d.subtaskID, logrus.Fields{
- "tool": name,
- "args": string(args),
- }))
-
- if err := json.Unmarshal(args, &action); err != nil {
- logger.WithError(err).Error("failed to unmarshal duckduckgo search action")
- return "", fmt.Errorf("failed to unmarshal %s search action arguments: %w", name, err)
- }
// Set default number of results if invalid
- numResults := int(action.MaxResults)
+ numResults := int(req.MaxResults)
if numResults < 1 || numResults > duckduckgoMaxResults {
numResults = duckduckgoMaxResults
}
- logger = logger.WithFields(logrus.Fields{
- "query": action.Query[:min(len(action.Query), 1000)],
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "duckduckgo",
+ "query": req.Query[:min(len(req.Query), 1000)],
"num_results": numResults,
"region": d.region(),
"safe_search": d.safeSearch(),
@@ -124,17 +103,16 @@ func (d *duckduckgo) Handle(ctx context.Context, name string, args json.RawMessa
})
// Perform search
- result, err := d.search(ctx, action.Query, numResults)
+ result, err := d.search(ctx, req.Query, numResults)
if err != nil {
observation.Event(
- langfuse.WithEventName("search engine error swallowed"),
- langfuse.WithEventInput(action.Query),
+ langfuse.WithEventName("search engine error"),
+ langfuse.WithEventInput(req.Query),
langfuse.WithEventStatus(err.Error()),
langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
langfuse.WithEventMetadata(langfuse.Metadata{
- "tool_name": DuckDuckGoToolName,
"engine": "duckduckgo",
- "query": action.Query,
+ "query": req.Query,
"max_results": numResults,
"region": d.region(),
"error": err.Error(),
@@ -142,21 +120,10 @@ func (d *duckduckgo) Handle(ctx context.Context, name string, args json.RawMessa
)
logger.WithError(err).Error("failed to search in DuckDuckGo")
- return fmt.Sprintf("failed to search in DuckDuckGo: %v", err), nil
- }
-
- // Log search results if configured
- if agentCtx, ok := GetAgentContext(ctx); ok {
- _, _ = d.slp.PutLog(
- ctx,
- agentCtx.ParentAgentType,
- agentCtx.CurrentAgentType,
- database.SearchengineTypeDuckduckgo,
- action.Query,
- result,
- d.taskID,
- d.subtaskID,
- )
+ // DuckDuckGo already retries transient failures internally (see search);
+ // by the time an error surfaces here, moving to the next engine is the
+ // right call rather than burning another round-trip on the same one.
+ return "", Fatal(fmt.Errorf("duckduckgo search failed: %w", err))
}
return result, nil
diff --git a/backend/pkg/tools/duckduckgo_test.go b/backend/pkg/tools/searchers/duckduckgo_test.go
similarity index 85%
rename from backend/pkg/tools/duckduckgo_test.go
rename to backend/pkg/tools/searchers/duckduckgo_test.go
index 903de62f..881e1a86 100644
--- a/backend/pkg/tools/duckduckgo_test.go
+++ b/backend/pkg/tools/searchers/duckduckgo_test.go
@@ -1,7 +1,6 @@
-package tools
+package searchers
import (
- "fmt"
"io"
"net/http"
"os"
@@ -66,11 +65,6 @@ func TestDuckDuckGoHandle(t *testing.T) {
}
defer proxy.Close()
- flowID := int64(1)
- taskID := int64(10)
- subtaskID := int64(20)
- slp := &searchLogProviderMock{}
-
cfg := &config.Config{
DuckDuckGoEnabled: true,
DuckDuckGoRegion: RegionUS,
@@ -79,17 +73,18 @@ func TestDuckDuckGoHandle(t *testing.T) {
ExternalSSLCAPath: proxy.CACertPath(),
}
- ddg := NewDuckDuckGoTool(cfg, flowID, &taskID, &subtaskID, slp)
+ ddg := NewDuckDuckGo(cfg)
- ctx := PutAgentContext(t.Context(), database.MsgchainTypeSearcher)
got, err := ddg.Handle(
- ctx,
- DuckDuckGoToolName,
- []byte(`{"query":"test query","max_results":5,"message":"m"}`),
+ t.Context(),
+ Request{Query: "test query", MaxResults: 5},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
}
+ if ddg.Engine() != database.SearchengineTypeDuckduckgo {
+ t.Errorf("Engine() = %q, want %q", ddg.Engine(), database.SearchengineTypeDuckduckgo)
+ }
// Verify mock handler was called
if !seenRequest {
@@ -127,28 +122,6 @@ func TestDuckDuckGoHandle(t *testing.T) {
t.Errorf("result missing expected description: %q", got)
}
- // Verify search log was written with agent context
- if slp.calls != 1 {
- t.Errorf("PutLog() calls = %d, want 1", slp.calls)
- }
- if slp.engine != database.SearchengineTypeDuckduckgo {
- t.Errorf("engine = %q, want %q", slp.engine, database.SearchengineTypeDuckduckgo)
- }
- if slp.query != "test query" {
- t.Errorf("logged query = %q, want %q", slp.query, "test query")
- }
- if slp.parentType != database.MsgchainTypeSearcher {
- t.Errorf("parent agent type = %q, want %q", slp.parentType, database.MsgchainTypeSearcher)
- }
- if slp.currType != database.MsgchainTypeSearcher {
- t.Errorf("current agent type = %q, want %q", slp.currType, database.MsgchainTypeSearcher)
- }
- if slp.taskID == nil || *slp.taskID != taskID {
- t.Errorf("task ID = %v, want %d", slp.taskID, taskID)
- }
- if slp.subtaskID == nil || *slp.subtaskID != subtaskID {
- t.Errorf("subtask ID = %v, want %d", slp.subtaskID, subtaskID)
- }
}
func TestDuckDuckGoIsAvailable(t *testing.T) {
@@ -184,16 +157,8 @@ func TestDuckDuckGoIsAvailable(t *testing.T) {
}
}
-func TestDuckDuckGoHandle_ValidationAndSwallowedError(t *testing.T) {
- t.Run("invalid json", func(t *testing.T) {
- ddg := &duckduckgo{cfg: testDuckDuckGoConfig()}
- _, err := ddg.Handle(t.Context(), DuckDuckGoToolName, []byte("{"))
- if err == nil || !strings.Contains(err.Error(), "failed to unmarshal") {
- t.Fatalf("expected unmarshal error, got: %v", err)
- }
- })
-
- t.Run("search error swallowed", func(t *testing.T) {
+func TestDuckDuckGoHandle_ReturnsTypedError(t *testing.T) {
+ t.Run("search error returned as typed error", func(t *testing.T) {
var seenRequest bool
mockMux := http.NewServeMux()
mockMux.HandleFunc("/html/", func(w http.ResponseWriter, r *http.Request) {
@@ -208,7 +173,6 @@ func TestDuckDuckGoHandle_ValidationAndSwallowedError(t *testing.T) {
defer proxy.Close()
ddg := &duckduckgo{
- flowID: 1,
cfg: &config.Config{
DuckDuckGoEnabled: true,
ProxyURL: proxy.URL(),
@@ -218,21 +182,24 @@ func TestDuckDuckGoHandle_ValidationAndSwallowedError(t *testing.T) {
result, err := ddg.Handle(
t.Context(),
- DuckDuckGoToolName,
- []byte(`{"query":"test","max_results":5,"message":"m"}`),
+ Request{Query: "test", MaxResults: 5},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
// Verify mock handler was called (request was intercepted)
if !seenRequest {
t.Error("request was not intercepted by proxy - mock handler was not called")
}
- // Verify error was swallowed and returned as string
- if !strings.Contains(result, "failed to search in DuckDuckGo") {
- t.Errorf("Handle() = %q, expected swallowed error message", result)
+ // The error is now surfaced (not swallowed). DuckDuckGo retries internally, so
+ // a post-retry failure is classified as fatal (move to the next engine).
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsFatal(err) {
+ t.Errorf("Handle() error = %v, want a FatalError", err)
}
})
}
@@ -261,7 +228,6 @@ func TestDuckDuckGoHandle_StatusCodeErrors(t *testing.T) {
defer proxy.Close()
ddg := &duckduckgo{
- flowID: 1,
cfg: &config.Config{
DuckDuckGoEnabled: true,
ProxyURL: proxy.URL(),
@@ -271,19 +237,21 @@ func TestDuckDuckGoHandle_StatusCodeErrors(t *testing.T) {
result, err := ddg.Handle(
t.Context(),
- DuckDuckGoToolName,
- []byte(`{"query":"test","max_results":5,"message":"m"}`),
+ Request{Query: "test", MaxResults: 5},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
- // Error should be swallowed and returned as string
- if !strings.Contains(result, "failed to search in DuckDuckGo") {
- t.Errorf("Handle() = %q, expected swallowed error", result)
+ // The status-code failure surfaces as a typed (fatal) error.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsFatal(err) {
+ t.Errorf("Handle() error = %v, want a FatalError", err)
}
- if !strings.Contains(result, "unexpected status code") {
- t.Errorf("Handle() = %q, expected status code error", result)
+ if !strings.Contains(err.Error(), "unexpected status code") {
+ t.Errorf("Handle() error = %v, expected status code detail", err)
}
})
}
@@ -574,7 +542,6 @@ func TestDuckDuckGoMaxResultsClamp(t *testing.T) {
defer proxy.Close()
ddg := &duckduckgo{
- flowID: 1,
cfg: &config.Config{
DuckDuckGoEnabled: true,
ProxyURL: proxy.URL(),
@@ -584,8 +551,7 @@ func TestDuckDuckGoMaxResultsClamp(t *testing.T) {
_, err = ddg.Handle(
t.Context(),
- DuckDuckGoToolName,
- []byte(fmt.Sprintf(`{"query":"test","max_results":%d,"message":"m"}`, tt.maxResults)),
+ Request{Query: "test", MaxResults: tt.maxResults},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
diff --git a/backend/pkg/tools/searchers/errors.go b/backend/pkg/tools/searchers/errors.go
new file mode 100644
index 00000000..0ee95a20
--- /dev/null
+++ b/backend/pkg/tools/searchers/errors.go
@@ -0,0 +1,75 @@
+package searchers
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "time"
+)
+
+// ErrNotConfigured is returned when Handle is called on an engine whose
+// IsAvailable() is false. The orchestrator treats it as "skip immediately, do not
+// retry". It is defensive: the orchestrator already checks IsAvailable() first.
+var ErrNotConfigured = errors.New("search engine is not configured")
+
+// RetryableError wraps a transient failure that MAY succeed if the SAME engine is
+// retried: HTTP 429, HTTP 5xx, and network/transport errors (*url.Error, timeouts,
+// context deadline on the outbound request). RetryAfter is a hint (0 if unknown).
+type RetryableError struct {
+ Err error
+ RetryAfter time.Duration
+}
+
+func (e *RetryableError) Error() string { return e.Err.Error() }
+func (e *RetryableError) Unwrap() error { return e.Err }
+
+// FatalError wraps a definitive failure that will NOT succeed on retry of the same
+// engine: HTTP 4xx (auth, bad request, not found, method), response-decode errors,
+// and unknown/unexpected status codes. The orchestrator moves to the next engine
+// immediately, without wasting a retry.
+type FatalError struct {
+ Err error
+}
+
+func (e *FatalError) Error() string { return e.Err.Error() }
+func (e *FatalError) Unwrap() error { return e.Err }
+
+// Retryable wraps err as a RetryableError with an optional RetryAfter hint.
+func Retryable(err error, retryAfter time.Duration) error {
+ return &RetryableError{Err: err, RetryAfter: retryAfter}
+}
+
+// Fatal wraps err as a FatalError.
+func Fatal(err error) error {
+ return &FatalError{Err: err}
+}
+
+// ClassifyHTTPStatus maps a non-2xx HTTP status to the right typed error so every
+// engine classifies identically. The engine supplies a human-readable message; the
+// retry/fatal decision is centralized here.
+//
+// 429 -> RetryableError (rate limited; back off and retry the same engine)
+// 5xx -> RetryableError (upstream problem; may clear on retry)
+// 4xx/other -> FatalError (auth/bad-request/etc.; retrying the same engine is pointless)
+func ClassifyHTTPStatus(status int, msg string) error {
+ switch {
+ case status == http.StatusTooManyRequests:
+ return Retryable(fmt.Errorf("%s (HTTP 429)", msg), 0)
+ case status >= 500:
+ return Retryable(fmt.Errorf("%s (HTTP %d)", msg, status), 0)
+ default:
+ return Fatal(fmt.Errorf("%s (HTTP %d)", msg, status))
+ }
+}
+
+// IsRetryable reports whether err (or anything it wraps) is a RetryableError.
+func IsRetryable(err error) bool {
+ var t *RetryableError
+ return errors.As(err, &t)
+}
+
+// IsFatal reports whether err (or anything it wraps) is a FatalError.
+func IsFatal(err error) bool {
+ var t *FatalError
+ return errors.As(err, &t)
+}
diff --git a/backend/pkg/tools/searchers/errors_test.go b/backend/pkg/tools/searchers/errors_test.go
new file mode 100644
index 00000000..7f0c333b
--- /dev/null
+++ b/backend/pkg/tools/searchers/errors_test.go
@@ -0,0 +1,83 @@
+package searchers
+
+import (
+ "errors"
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+)
+
+func TestClassifyHTTPStatus(t *testing.T) {
+ tests := []struct {
+ name string
+ status int
+ wantRetry bool
+ wantFatal bool
+ }{
+ {name: "429 is retryable", status: http.StatusTooManyRequests, wantRetry: true},
+ {name: "500 is retryable", status: http.StatusInternalServerError, wantRetry: true},
+ {name: "502 is retryable", status: http.StatusBadGateway, wantRetry: true},
+ {name: "503 is retryable", status: http.StatusServiceUnavailable, wantRetry: true},
+ {name: "504 is retryable", status: http.StatusGatewayTimeout, wantRetry: true},
+ {name: "400 is fatal", status: http.StatusBadRequest, wantFatal: true},
+ {name: "401 is fatal", status: http.StatusUnauthorized, wantFatal: true},
+ {name: "403 is fatal", status: http.StatusForbidden, wantFatal: true},
+ {name: "404 is fatal", status: http.StatusNotFound, wantFatal: true},
+ {name: "418 is fatal", status: http.StatusTeapot, wantFatal: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ClassifyHTTPStatus(tt.status, "boom")
+ if err == nil {
+ t.Fatal("ClassifyHTTPStatus returned nil")
+ }
+ if IsRetryable(err) != tt.wantRetry {
+ t.Errorf("IsRetryable(%d) = %v, want %v", tt.status, IsRetryable(err), tt.wantRetry)
+ }
+ if IsFatal(err) != tt.wantFatal {
+ t.Errorf("IsFatal(%d) = %v, want %v", tt.status, IsFatal(err), tt.wantFatal)
+ }
+ })
+ }
+}
+
+func TestRetryableAndFatalWrapping(t *testing.T) {
+ base := errors.New("root cause")
+
+ r := Retryable(fmt.Errorf("wrap: %w", base), 5*time.Second)
+ if !IsRetryable(r) {
+ t.Error("Retryable() value should satisfy IsRetryable")
+ }
+ if IsFatal(r) {
+ t.Error("Retryable() value should not satisfy IsFatal")
+ }
+ if !errors.Is(r, base) {
+ t.Error("Retryable() should preserve the wrapped chain for errors.Is")
+ }
+ var re *RetryableError
+ if !errors.As(r, &re) || re.RetryAfter != 5*time.Second {
+ t.Errorf("RetryAfter not preserved, got %+v", re)
+ }
+
+ f := Fatal(fmt.Errorf("wrap: %w", base))
+ if !IsFatal(f) {
+ t.Error("Fatal() value should satisfy IsFatal")
+ }
+ if IsRetryable(f) {
+ t.Error("Fatal() value should not satisfy IsRetryable")
+ }
+ if !errors.Is(f, base) {
+ t.Error("Fatal() should preserve the wrapped chain for errors.Is")
+ }
+}
+
+func TestNotConfiguredIsNeitherRetryableNorFatal(t *testing.T) {
+ if IsRetryable(ErrNotConfigured) {
+ t.Error("ErrNotConfigured must not be retryable")
+ }
+ if IsFatal(ErrNotConfigured) {
+ t.Error("ErrNotConfigured must not be a FatalError type (it is a distinct sentinel)")
+ }
+}
diff --git a/backend/pkg/tools/firecrawl.go b/backend/pkg/tools/searchers/firecrawl.go
similarity index 75%
rename from backend/pkg/tools/firecrawl.go
rename to backend/pkg/tools/searchers/firecrawl.go
index 10902157..7670bdb0 100644
--- a/backend/pkg/tools/firecrawl.go
+++ b/backend/pkg/tools/searchers/firecrawl.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"bytes"
@@ -83,83 +83,49 @@ func (r firecrawlResult) resolvedTitle() string {
type firecrawl struct {
cfg *config.Config
- flowID int64
- taskID *int64
- subtaskID *int64
- slp SearchLogProvider
summarizer SummarizeHandler
}
-func NewFirecrawlTool(
- cfg *config.Config,
- flowID int64,
- taskID, subtaskID *int64,
- slp SearchLogProvider,
- summarizer SummarizeHandler,
-) Tool {
+func NewFirecrawl(cfg *config.Config, summarizer SummarizeHandler) Searcher {
return &firecrawl{
cfg: cfg,
- flowID: flowID,
- taskID: taskID,
- subtaskID: subtaskID,
- slp: slp,
summarizer: summarizer,
}
}
-func (f *firecrawl) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+func (f *firecrawl) Engine() database.SearchengineType {
+ return database.SearchengineTypeFirecrawl
+}
+
+func (f *firecrawl) Handle(ctx context.Context, req Request) (string, error) {
if !f.IsAvailable() {
- return "", fmt.Errorf("firecrawl is not available")
+ return "", ErrNotConfigured
}
- var action SearchAction
ctx, observation := obs.Observer.NewObservation(ctx)
- logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(f.flowID, f.taskID, f.subtaskID, logrus.Fields{
- "tool": name,
- "args": string(args),
- }))
-
- if err := json.Unmarshal(args, &action); err != nil {
- logger.WithError(err).Error("failed to unmarshal firecrawl search action")
- return "", fmt.Errorf("failed to unmarshal %s search action arguments: %w", name, err)
- }
-
- logger = logger.WithFields(logrus.Fields{
- "query": action.Query[:min(len(action.Query), 1000)],
- "max_results": action.MaxResults,
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "firecrawl",
+ "query": req.Query[:min(len(req.Query), 1000)],
+ "max_results": req.MaxResults,
})
- result, err := f.search(ctx, action.Query, action.MaxResults.Int())
+ result, err := f.search(ctx, req.Query, req.MaxResults)
if err != nil {
observation.Event(
- langfuse.WithEventName("search engine error swallowed"),
- langfuse.WithEventInput(action.Query),
+ langfuse.WithEventName("search engine error"),
+ langfuse.WithEventInput(req.Query),
langfuse.WithEventStatus(err.Error()),
langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
langfuse.WithEventMetadata(langfuse.Metadata{
- "tool_name": FirecrawlToolName,
"engine": "firecrawl",
- "query": action.Query,
- "max_results": action.MaxResults.Int(),
+ "query": req.Query,
+ "max_results": req.MaxResults,
"error": err.Error(),
}),
)
logger.WithError(err).Error("failed to search in firecrawl")
- return fmt.Sprintf("failed to search in firecrawl: %v", err), nil
- }
-
- if agentCtx, ok := GetAgentContext(ctx); ok {
- _, _ = f.slp.PutLog(
- ctx,
- agentCtx.ParentAgentType,
- agentCtx.CurrentAgentType,
- database.SearchengineTypeFirecrawl,
- action.Query,
- result,
- f.taskID,
- f.subtaskID,
- )
+ return "", err
}
return result, nil
@@ -168,7 +134,7 @@ func (f *firecrawl) Handle(ctx context.Context, name string, args json.RawMessag
func (f *firecrawl) search(ctx context.Context, query string, maxResults int) (string, error) {
client, err := system.GetHTTPClient(f.cfg)
if err != nil {
- return "", fmt.Errorf("failed to create http client: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create http client: %w", err))
}
// sources is intentionally omitted: /v2/search defaults to ["web"], which is
@@ -184,12 +150,12 @@ func (f *firecrawl) search(ctx context.Context, query string, maxResults int) (s
}
reqBody, err := json.Marshal(reqPayload)
if err != nil {
- return "", fmt.Errorf("failed to marshal request body: %v", err)
+ return "", Fatal(fmt.Errorf("failed to marshal request body: %v", err))
}
req, err := http.NewRequest(http.MethodPost, f.searchURL(), bytes.NewBuffer(reqBody))
if err != nil {
- return "", fmt.Errorf("failed to build request: %v", err)
+ return "", Fatal(fmt.Errorf("failed to build request: %v", err))
}
req = req.WithContext(ctx)
@@ -198,7 +164,7 @@ func (f *firecrawl) search(ctx context.Context, query string, maxResults int) (s
resp, err := client.Do(req)
if err != nil {
- return "", fmt.Errorf("failed to do request: %v", err)
+ return "", Retryable(fmt.Errorf("failed to do request: %v", err), 0)
}
defer resp.Body.Close()
@@ -210,41 +176,41 @@ func (f *firecrawl) parseHTTPResponse(ctx context.Context, query string, resp *h
case http.StatusOK:
var respBody firecrawlSearchResult
if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil {
- return "", fmt.Errorf("failed to decode response body: %v", err)
+ return "", Fatal(fmt.Errorf("failed to decode response body: %v", err))
}
if !respBody.Success {
if respBody.Error != "" {
- return "", fmt.Errorf("request failed: %s", respBody.Error)
+ return "", Fatal(fmt.Errorf("request failed: %s", respBody.Error))
}
- return "", fmt.Errorf("request failed")
+ return "", Fatal(fmt.Errorf("request failed"))
}
return f.buildFirecrawlResult(ctx, query, &respBody), nil
case http.StatusBadRequest:
- return "", fmt.Errorf("request is invalid")
+ return "", Fatal(fmt.Errorf("request is invalid"))
case http.StatusUnauthorized:
- return "", fmt.Errorf("API key is wrong")
+ return "", Fatal(fmt.Errorf("API key is wrong"))
case http.StatusPaymentRequired:
- return "", fmt.Errorf("insufficient credits to perform this request")
+ return "", Fatal(fmt.Errorf("insufficient credits to perform this request"))
case http.StatusForbidden:
- return "", fmt.Errorf("the endpoint requested is hidden for administrators only")
+ return "", Fatal(fmt.Errorf("the endpoint requested is hidden for administrators only"))
case http.StatusNotFound:
- return "", fmt.Errorf("the specified endpoint could not be found")
+ return "", Fatal(fmt.Errorf("the specified endpoint could not be found"))
case http.StatusMethodNotAllowed:
- return "", fmt.Errorf("there need to try to access an endpoint with an invalid method")
+ return "", Fatal(fmt.Errorf("there need to try to access an endpoint with an invalid method"))
case http.StatusRequestTimeout:
- return "", fmt.Errorf("the request timed out. try again later")
+ return "", Retryable(fmt.Errorf("the request timed out. try again later"), 0)
case http.StatusTooManyRequests:
- return "", fmt.Errorf("there are requesting too many results")
+ return "", Retryable(fmt.Errorf("there are requesting too many results"), 0)
case http.StatusInternalServerError:
- return "", fmt.Errorf("there had a problem with our server. try again later")
+ return "", Retryable(fmt.Errorf("there had a problem with our server. try again later"), 0)
case http.StatusBadGateway:
- return "", fmt.Errorf("there was a problem with the server. Please try again later")
+ return "", Retryable(fmt.Errorf("there was a problem with the server. Please try again later"), 0)
case http.StatusServiceUnavailable:
- return "", fmt.Errorf("there are temporarily offline for maintenance. please try again later")
+ return "", Retryable(fmt.Errorf("there are temporarily offline for maintenance. please try again later"), 0)
case http.StatusGatewayTimeout:
- return "", fmt.Errorf("there are temporarily offline for maintenance. please try again later")
+ return "", Retryable(fmt.Errorf("there are temporarily offline for maintenance. please try again later"), 0)
default:
- return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ return "", Fatal(fmt.Errorf("unexpected status code: %d", resp.StatusCode))
}
}
diff --git a/backend/pkg/tools/firecrawl_test.go b/backend/pkg/tools/searchers/firecrawl_test.go
similarity index 85%
rename from backend/pkg/tools/firecrawl_test.go
rename to backend/pkg/tools/searchers/firecrawl_test.go
index 0d1d02da..a7821e9e 100644
--- a/backend/pkg/tools/firecrawl_test.go
+++ b/backend/pkg/tools/searchers/firecrawl_test.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"context"
@@ -48,11 +48,6 @@ func TestFirecrawlHandle(t *testing.T) {
}
defer proxy.Close()
- flowID := int64(1)
- taskID := int64(10)
- subtaskID := int64(20)
- slp := &searchLogProviderMock{}
-
cfg := &config.Config{
FirecrawlAPIKey: testFirecrawlAPIKey,
ProxyURL: proxy.URL(),
@@ -60,17 +55,18 @@ func TestFirecrawlHandle(t *testing.T) {
ExternalSSLInsecure: false,
}
- fc := NewFirecrawlTool(cfg, flowID, &taskID, &subtaskID, slp, nil)
+ fc := NewFirecrawl(cfg, nil)
- ctx := PutAgentContext(t.Context(), database.MsgchainTypeSearcher)
got, err := fc.Handle(
- ctx,
- FirecrawlToolName,
- []byte(`{"query":"test query","max_results":5,"message":"m"}`),
+ t.Context(),
+ Request{Query: "test query", MaxResults: 5},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
}
+ if fc.Engine() != database.SearchengineTypeFirecrawl {
+ t.Errorf("Engine() = %q, want %q", fc.Engine(), database.SearchengineTypeFirecrawl)
+ }
// Verify mock handler was called
if !seenRequest {
@@ -104,29 +100,6 @@ func TestFirecrawlHandle(t *testing.T) {
if !strings.Contains(got, "https://example.com") {
t.Errorf("result missing expected URL 'https://example.com': %q", got)
}
-
- // Verify search log was written with agent context
- if slp.calls != 1 {
- t.Errorf("PutLog() calls = %d, want 1", slp.calls)
- }
- if slp.engine != database.SearchengineTypeFirecrawl {
- t.Errorf("engine = %q, want %q", slp.engine, database.SearchengineTypeFirecrawl)
- }
- if slp.query != "test query" {
- t.Errorf("logged query = %q, want %q", slp.query, "test query")
- }
- if slp.parentType != database.MsgchainTypeSearcher {
- t.Errorf("parent agent type = %q, want %q", slp.parentType, database.MsgchainTypeSearcher)
- }
- if slp.currType != database.MsgchainTypeSearcher {
- t.Errorf("current agent type = %q, want %q", slp.currType, database.MsgchainTypeSearcher)
- }
- if slp.taskID == nil || *slp.taskID != taskID {
- t.Errorf("task ID = %v, want %d", slp.taskID, taskID)
- }
- if slp.subtaskID == nil || *slp.subtaskID != subtaskID {
- t.Errorf("subtask ID = %v, want %d", slp.subtaskID, subtaskID)
- }
}
func TestFirecrawlIsAvailable(t *testing.T) {
@@ -201,7 +174,7 @@ func TestFirecrawlSearchURL(t *testing.T) {
}
func TestFirecrawlParseHTTPResponse_StatusAndDecodeErrors(t *testing.T) {
- fc := &firecrawl{flowID: 1}
+ fc := &firecrawl{}
tests := []struct {
name string
@@ -471,16 +444,8 @@ func TestFirecrawlBuildResult_WithSummarizer(t *testing.T) {
})
}
-func TestFirecrawlHandle_ValidationAndSwallowedError(t *testing.T) {
- t.Run("invalid json", func(t *testing.T) {
- fc := &firecrawl{cfg: testFirecrawlConfig()}
- _, err := fc.Handle(t.Context(), FirecrawlToolName, []byte("{"))
- if err == nil || !strings.Contains(err.Error(), "failed to unmarshal") {
- t.Fatalf("expected unmarshal error, got: %v", err)
- }
- })
-
- t.Run("search error swallowed", func(t *testing.T) {
+func TestFirecrawlHandle_ReturnsTypedError(t *testing.T) {
+ t.Run("upstream 502 returns a retryable error", func(t *testing.T) {
var seenRequest bool
mockMux := http.NewServeMux()
mockMux.HandleFunc("/v2/search", func(w http.ResponseWriter, r *http.Request) {
@@ -495,7 +460,6 @@ func TestFirecrawlHandle_ValidationAndSwallowedError(t *testing.T) {
defer proxy.Close()
fc := &firecrawl{
- flowID: 1,
cfg: &config.Config{
FirecrawlAPIKey: testFirecrawlAPIKey,
ProxyURL: proxy.URL(),
@@ -506,21 +470,23 @@ func TestFirecrawlHandle_ValidationAndSwallowedError(t *testing.T) {
result, err := fc.Handle(
t.Context(),
- FirecrawlToolName,
- []byte(`{"query":"q","max_results":5,"message":"m"}`),
+ Request{Query: "q", MaxResults: 5},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
// Verify mock handler was called (request was intercepted)
if !seenRequest {
t.Error("request was not intercepted by proxy - mock handler was not called")
}
- // Verify error was swallowed and returned as string
- if !strings.Contains(result, "failed to search in firecrawl") {
- t.Errorf("Handle() = %q, expected swallowed error message", result)
+ // The error is now surfaced (not swallowed) and classified. A 502 is retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
})
}
diff --git a/backend/pkg/tools/searchers/google.go b/backend/pkg/tools/searchers/google.go
new file mode 100644
index 00000000..e1b563f4
--- /dev/null
+++ b/backend/pkg/tools/searchers/google.go
@@ -0,0 +1,186 @@
+package searchers
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+
+ "pentagi/pkg/config"
+ "pentagi/pkg/database"
+ obs "pentagi/pkg/observability"
+ "pentagi/pkg/observability/langfuse"
+ "pentagi/pkg/system"
+
+ "github.com/sirupsen/logrus"
+ customsearch "google.golang.org/api/customsearch/v1"
+ "google.golang.org/api/googleapi"
+ "google.golang.org/api/option"
+)
+
+const googleMaxResults = 10
+
+type google struct {
+ cfg *config.Config
+}
+
+func NewGoogle(cfg *config.Config) Searcher {
+ return &google{cfg: cfg}
+}
+
+func (g *google) Engine() database.SearchengineType {
+ return database.SearchengineTypeGoogle
+}
+
+func (g *google) Handle(ctx context.Context, req Request) (string, error) {
+ if !g.IsAvailable() {
+ return "", ErrNotConfigured
+ }
+
+ ctx, observation := obs.Observer.NewObservation(ctx)
+
+ numResults := int64(req.MaxResults)
+ if numResults < 1 || numResults > googleMaxResults {
+ numResults = googleMaxResults
+ }
+
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "google",
+ "query": req.Query[:min(len(req.Query), 1000)],
+ "num_results": numResults,
+ })
+
+ svc, err := g.newSearchService(ctx)
+ if err != nil {
+ logger.WithError(err).Error("failed to create google search service")
+ return "", Fatal(fmt.Errorf("failed to create google search service: %w", err))
+ }
+
+ result, err := g.search(ctx, svc, req.Query, numResults)
+ if err != nil {
+ observation.Event(
+ langfuse.WithEventName("search engine error"),
+ langfuse.WithEventInput(req.Query),
+ langfuse.WithEventStatus(err.Error()),
+ langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
+ langfuse.WithEventMetadata(langfuse.Metadata{
+ "engine": "google",
+ "query": req.Query,
+ "max_results": numResults,
+ "error": err.Error(),
+ }),
+ )
+
+ logger.WithError(err).Error("failed to search in google")
+ return "", classifyGoogleError(err)
+ }
+
+ return result, nil
+}
+
+// classifyGoogleError maps a Google Custom Search failure to a retryable/fatal error.
+// A *googleapi.Error carries the upstream HTTP status (429/5xx retryable, 4xx fatal);
+// anything else is a transport-level failure, which may clear on retry.
+func classifyGoogleError(err error) error {
+ var gerr *googleapi.Error
+ if errors.As(err, &gerr) {
+ return ClassifyHTTPStatus(gerr.Code, "google search failed")
+ }
+ return Retryable(fmt.Errorf("google search failed: %w", err), 0)
+}
+
+func (g *google) search(ctx context.Context, svc *customsearch.Service, query string, numResults int64) (string, error) {
+ resp, err := svc.Cse.List().Context(ctx).Cx(g.cxKey()).Q(query).Lr(g.lrKey()).Num(numResults).Do()
+ if err != nil {
+ return "", fmt.Errorf("failed to do request: %w", err)
+ }
+
+ return g.formatResults(resp), nil
+}
+
+func (g *google) formatResults(res *customsearch.Search) string {
+ var writer strings.Builder
+ for i, item := range res.Items {
+ writer.WriteString(fmt.Sprintf("# %d. %s\n\n", i+1, item.Title))
+ writer.WriteString(fmt.Sprintf("## URL\n%s\n\n", item.Link))
+ writer.WriteString(fmt.Sprintf("## Snippet\n\n%s\n\n", item.Snippet))
+ }
+
+ return writer.String()
+}
+
+func (g *google) newSearchService(ctx context.Context) (*customsearch.Service, error) {
+ client, err := system.GetHTTPClient(g.cfg)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create http client: %w", err)
+ }
+
+ // google.golang.org/api normally injects the API key through the HTTP transport it
+ // builds itself. But we MUST supply our own proxy/TLS client via WithHTTPClient, and
+ // WithHTTPClient takes precedence — it replaces that transport, so option.WithAPIKey
+ // is silently dropped and requests go out unauthenticated (HTTP 403 "unregistered
+ // caller"). Attach the key ourselves as the `key` query parameter (the documented
+ // Custom Search auth) by wrapping the proxy client's transport.
+ client.Transport = &googleAPIKeyTransport{
+ key: g.apiKey(),
+ base: client.Transport,
+ }
+
+ svc, err := customsearch.NewService(ctx, option.WithHTTPClient(client))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create google search service: %v", err)
+ }
+
+ return svc, nil
+}
+
+// googleAPIKeyTransport attaches the Google API key as the `key` query parameter to
+// every outgoing request, so authentication survives the proxy/TLS client that
+// option.WithHTTPClient forces us to use (see newSearchService).
+type googleAPIKeyTransport struct {
+ key string
+ base http.RoundTripper
+}
+
+func (t *googleAPIKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ // Clone so the caller's request is never mutated.
+ r := req.Clone(req.Context())
+ q := r.URL.Query()
+ q.Set("key", t.key)
+ r.URL.RawQuery = q.Encode()
+
+ base := t.base
+ if base == nil {
+ base = http.DefaultTransport
+ }
+ return base.RoundTrip(r)
+}
+
+func (g *google) IsAvailable() bool {
+ return g.apiKey() != "" && g.cxKey() != ""
+}
+
+func (g *google) apiKey() string {
+ if g.cfg == nil {
+ return ""
+ }
+
+ return g.cfg.GoogleAPIKey
+}
+
+func (g *google) cxKey() string {
+ if g.cfg == nil {
+ return ""
+ }
+
+ return g.cfg.GoogleCXKey
+}
+
+func (g *google) lrKey() string {
+ if g.cfg == nil {
+ return ""
+ }
+
+ return g.cfg.GoogleLRKey
+}
diff --git a/backend/pkg/tools/google_test.go b/backend/pkg/tools/searchers/google_test.go
similarity index 57%
rename from backend/pkg/tools/google_test.go
rename to backend/pkg/tools/searchers/google_test.go
index 09d120f8..0d2b09d3 100644
--- a/backend/pkg/tools/google_test.go
+++ b/backend/pkg/tools/searchers/google_test.go
@@ -1,8 +1,8 @@
-package tools
+package searchers
import (
"context"
- "fmt"
+ "net/http"
"strings"
"testing"
@@ -69,8 +69,15 @@ func TestGoogleIsAvailable(t *testing.T) {
}
}
+func TestGoogleEngine(t *testing.T) {
+ g := NewGoogle(testGoogleConfig())
+ if g.Engine() != database.SearchengineTypeGoogle {
+ t.Errorf("Engine() = %q, want %q", g.Engine(), database.SearchengineTypeGoogle)
+ }
+}
+
func TestGoogleFormatResults(t *testing.T) {
- g := &google{flowID: 1}
+ g := &google{}
t.Run("empty results", func(t *testing.T) {
res := &customsearch.Search{Items: nil}
@@ -178,91 +185,31 @@ func TestGoogleNewSearchService(t *testing.T) {
})
}
-func TestGoogleHandle_ValidationAndSwallowedError(t *testing.T) {
- t.Run("invalid json", func(t *testing.T) {
- g := &google{cfg: testGoogleConfig()}
- _, err := g.Handle(t.Context(), GoogleToolName, []byte("{"))
- if err == nil || !strings.Contains(err.Error(), "failed to unmarshal") {
- t.Fatalf("expected unmarshal error, got: %v", err)
- }
- })
-
- t.Run("search error swallowed", func(t *testing.T) {
- // Use canceled context to make Do() fail immediately
+func TestGoogleHandle_ReturnsTypedError(t *testing.T) {
+ t.Run("search error returned as typed error", func(t *testing.T) {
+ // Use a canceled context to make Do() fail immediately.
ctx, cancel := context.WithCancel(t.Context())
cancel()
g := &google{cfg: testGoogleConfig()}
- got, err := g.Handle(
- ctx,
- GoogleToolName,
- []byte(`{"query":"q","max_results":5,"message":"m"}`),
- )
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
+ result, err := g.Handle(ctx, Request{Query: "q", MaxResults: 5})
+
+ // The error is now surfaced (not swallowed). A canceled request is a
+ // transport-level failure (not a *googleapi.Error), so classifyGoogleError
+ // classifies it as retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
}
- if !strings.Contains(got, "failed to search in google") {
- t.Fatalf("Handle() = %q, expected swallowed error", got)
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
})
}
-func TestGoogleHandle_WithAgentContext(t *testing.T) {
- // Note: This test cannot fully verify search behavior without a real API call.
- // It verifies parameter handling and agent context propagation.
-
- flowID := int64(1)
- taskID := int64(10)
- subtaskID := int64(20)
- slp := &searchLogProviderMock{}
-
- g := NewGoogleTool(testGoogleConfig(), flowID, &taskID, &subtaskID, slp)
-
- // Use canceled context to make search fail quickly
- ctx, cancel := context.WithCancel(t.Context())
- cancel()
- ctx = PutAgentContext(ctx, database.MsgchainTypeSearcher)
-
- // This will fail due to canceled context, but we can verify the structure
- result, err := g.Handle(
- ctx,
- GoogleToolName,
- []byte(`{"query":"test query","max_results":5,"message":"m"}`),
- )
-
- // Error should be swallowed
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
- if !strings.Contains(result, "failed to search in google") {
- t.Errorf("Handle() = %q, expected swallowed error message", result)
- }
-
- // Search log should be written even on error
- if slp.calls != 1 {
- t.Errorf("PutLog() calls = %d, want 1", slp.calls)
- }
- if slp.engine != database.SearchengineTypeGoogle {
- t.Errorf("engine = %q, want %q", slp.engine, database.SearchengineTypeGoogle)
- }
- if slp.query != "test query" {
- t.Errorf("logged query = %q, want %q", slp.query, "test query")
- }
- if slp.parentType != database.MsgchainTypeSearcher {
- t.Errorf("parent agent type = %q, want %q", slp.parentType, database.MsgchainTypeSearcher)
- }
- if slp.currType != database.MsgchainTypeSearcher {
- t.Errorf("current agent type = %q, want %q", slp.currType, database.MsgchainTypeSearcher)
- }
- if slp.taskID == nil || *slp.taskID != taskID {
- t.Errorf("task ID = %v, want %d", slp.taskID, taskID)
- }
- if slp.subtaskID == nil || *slp.subtaskID != subtaskID {
- t.Errorf("subtask ID = %v, want %d", slp.subtaskID, subtaskID)
- }
-}
-
func TestGoogleMaxResultsClamp(t *testing.T) {
tests := []struct {
name string
@@ -280,24 +227,22 @@ func TestGoogleMaxResultsClamp(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
g := &google{cfg: testGoogleConfig()}
- // Use canceled context to fail quickly without real API call
+ // Use a canceled context to fail quickly without a real API call.
ctx, cancel := context.WithCancel(t.Context())
cancel()
- result, err := g.Handle(
- ctx,
- GoogleToolName,
- []byte(`{"query":"test","max_results":`+strings.TrimSpace(fmt.Sprintf("%d", tt.maxResults))+`,"message":"m"}`),
- )
+ result, err := g.Handle(ctx, Request{Query: "test", MaxResults: tt.maxResults})
- // Should not return error (errors are swallowed)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
+ // Errors are now surfaced (not swallowed): a canceled request is a
+ // transport-level failure, classified as retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
}
-
- // Should contain error message since context is canceled
- if !strings.Contains(result, "failed to search in google") {
- t.Errorf("Handle() = %q, expected swallowed error", result)
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
})
}
@@ -330,3 +275,82 @@ func TestGoogleConfigHelpers_NilConfig(t *testing.T) {
t.Errorf("lrKey() with nil config = %q, want empty", g.lrKey())
}
}
+
+// roundTripFunc adapts a function to http.RoundTripper for transport unit tests.
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
+
+// TestGoogleAPIKeyTransport_AddsKeyParam guards the fix for the WithHTTPClient /
+// WithAPIKey drop: the wrapping transport must add `key` to every request, preserve
+// existing params, and not mutate the caller's request.
+func TestGoogleAPIKeyTransport_AddsKeyParam(t *testing.T) {
+ var captured *http.Request
+ base := roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ captured = req
+ return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody, Header: make(http.Header)}, nil
+ })
+
+ rt := &googleAPIKeyTransport{key: "test-key", base: base}
+ req, err := http.NewRequest(http.MethodGet, "https://customsearch.googleapis.com/customsearch/v1?q=hello&cx=cx1", nil)
+ if err != nil {
+ t.Fatalf("failed to build request: %v", err)
+ }
+
+ if _, err := rt.RoundTrip(req); err != nil {
+ t.Fatalf("RoundTrip() unexpected error: %v", err)
+ }
+
+ if got := captured.URL.Query().Get("key"); got != "test-key" {
+ t.Errorf("key param = %q, want test-key", got)
+ }
+ if got := captured.URL.Query().Get("q"); got != "hello" {
+ t.Errorf("q param = %q, want hello (existing params must be preserved)", got)
+ }
+ if req.URL.Query().Get("key") != "" {
+ t.Error("the caller's original request was mutated (key added to it)")
+ }
+}
+
+// TestGoogleHandle_SendsAPIKeyThroughProxy is the end-to-end regression guard: it
+// drives a real Handle through the proxy/TLS client (the exact setup that dropped the
+// key) and asserts the API key and cx reach the wire, producing a parsed result.
+func TestGoogleHandle_SendsAPIKeyThroughProxy(t *testing.T) {
+ var receivedURL string
+ mockMux := http.NewServeMux()
+ mockMux.HandleFunc("/customsearch/v1", func(w http.ResponseWriter, r *http.Request) {
+ receivedURL = r.URL.String()
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"items":[{"title":"Doc","link":"https://example.com","snippet":"snip"}]}`))
+ })
+
+ proxy, err := newTestProxy("customsearch.googleapis.com", mockMux)
+ if err != nil {
+ t.Fatalf("failed to create proxy: %v", err)
+ }
+ defer proxy.Close()
+
+ cfg := &config.Config{
+ GoogleAPIKey: "test-key",
+ GoogleCXKey: "test-cx",
+ ProxyURL: proxy.URL(),
+ ExternalSSLCAPath: proxy.CACertPath(),
+ }
+ g := NewGoogle(cfg)
+
+ got, err := g.Handle(t.Context(), Request{Query: "hello world", MaxResults: 5})
+ if err != nil {
+ t.Fatalf("Handle() unexpected error: %v", err)
+ }
+
+ if !strings.Contains(receivedURL, "key=test-key") {
+ t.Errorf("request URL = %q, expected it to carry key=test-key", receivedURL)
+ }
+ if !strings.Contains(receivedURL, "cx=test-cx") {
+ t.Errorf("request URL = %q, expected it to carry cx=test-cx", receivedURL)
+ }
+ if !strings.Contains(got, "https://example.com") {
+ t.Errorf("result missing expected URL: %q", got)
+ }
+}
diff --git a/backend/pkg/tools/searchers/internal.go b/backend/pkg/tools/searchers/internal.go
new file mode 100644
index 00000000..82608ecf
--- /dev/null
+++ b/backend/pkg/tools/searchers/internal.go
@@ -0,0 +1,261 @@
+package searchers
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "regexp"
+ "strings"
+
+ "pentagi/pkg/config"
+ "pentagi/pkg/database"
+ obs "pentagi/pkg/observability"
+ "pentagi/pkg/observability/langfuse"
+
+ "github.com/sirupsen/logrus"
+)
+
+const (
+ internalDefaultMaxSites = 5
+ internalDefaultMaxSiteBytes = 10 * 1024 // 10 KB of markdown per site
+ internalLinkDiscoveryLimit = 8 // how many candidate links to ask the link engine for
+)
+
+// urlPattern extracts candidate source URLs from a link engine's markdown output.
+// The link engines format URLs in several shapes ("* URL https://…", "## URL\nhttps://…",
+// "[https://…](https://…)"), so a permissive http(s) matcher is the most robust way to
+// recover them without coupling this engine to each engine's formatting.
+var urlPattern = regexp.MustCompile(`https?://[^\s)\]<>"']+`)
+
+// internalEngine is the optional, opt-in browser-analytics engine. Instead of calling
+// a paid analytic API, it discovers links with the first available link searcher,
+// fetches each page's main-content markdown through the browser scraper (bounded per
+// site), and asks the summarizer to synthesize a query-focused answer. It is disabled
+// by default (WEB_SEARCH_INTERNAL_ENABLED) because scraping + summarizing many pages
+// can cost more than a purpose-built third-party analytic call.
+type internalEngine struct {
+ cfg *config.Config
+ fetcher PageFetcher
+ links []Searcher // link-discovery engines, in orchestrator priority order
+ summarizer SummarizeHandler
+}
+
+// NewInternal builds the internal analytics engine. fetcher and summarizer are
+// injected by the orchestrator (the fetcher wraps the browser tool). links are the
+// link-oriented searchers used to discover URLs to read.
+func NewInternal(
+ cfg *config.Config,
+ fetcher PageFetcher,
+ links []Searcher,
+ summarizer SummarizeHandler,
+) Searcher {
+ return &internalEngine{
+ cfg: cfg,
+ fetcher: fetcher,
+ links: links,
+ summarizer: summarizer,
+ }
+}
+
+func (e *internalEngine) Engine() database.SearchengineType {
+ // The internal engine's work is browser-driven, so it attributes its search-log
+ // entry to the existing (otherwise unused) "browser" engine value — no new enum
+ // value or DB migration is required.
+ return database.SearchengineTypeBrowser
+}
+
+func (e *internalEngine) IsAvailable() bool {
+ if e.cfg == nil || !e.cfg.WebSearchInternalEnabled {
+ return false
+ }
+ if e.fetcher == nil || e.summarizer == nil {
+ return false
+ }
+ for _, l := range e.links {
+ if l != nil && l.IsAvailable() {
+ return true
+ }
+ }
+ return false
+}
+
+func (e *internalEngine) Handle(ctx context.Context, req Request) (string, error) {
+ if !e.IsAvailable() {
+ return "", ErrNotConfigured
+ }
+
+ ctx, observation := obs.Observer.NewObservation(ctx)
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "internal",
+ "query": req.Query[:min(len(req.Query), 1000)],
+ })
+
+ result, err := e.analyze(ctx, req)
+ if err != nil {
+ observation.Event(
+ langfuse.WithEventName("search engine error"),
+ langfuse.WithEventInput(req.Query),
+ langfuse.WithEventStatus(err.Error()),
+ langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
+ langfuse.WithEventMetadata(langfuse.Metadata{
+ "engine": "internal",
+ "query": req.Query,
+ "error": err.Error(),
+ }),
+ )
+ logger.WithError(err).Error("internal analytics engine failed")
+ return "", err
+ }
+
+ return result, nil
+}
+
+func (e *internalEngine) analyze(ctx context.Context, req Request) (string, error) {
+ urls, out, err := e.discoverURLs(ctx, req)
+ if err != nil {
+ return "", err
+ }
+ if len(urls) == 0 {
+ return "", Fatal(fmt.Errorf("internal engine: link discovery returned no usable URLs"))
+ }
+
+ maxSites := e.cfg.WebSearchInternalMaxSites
+ if maxSites <= 0 {
+ maxSites = internalDefaultMaxSites
+ }
+ maxBytes := e.cfg.WebSearchInternalMaxSiteBytes
+ if maxBytes <= 0 {
+ maxBytes = internalDefaultMaxSiteBytes
+ }
+
+ var (
+ blocks []string
+ usedURLs []string
+ fetched int
+ lastFetch error
+ )
+ out = strings.TrimSpace(out)
+ if out != "" {
+ blocks = append(blocks, fmt.Sprintf("<search-results>\n%s\n</search-results>", out))
+ }
+ for _, u := range urls {
+ if fetched >= maxSites {
+ break
+ }
+ md, ferr := e.fetcher.FetchMarkdown(ctx, u)
+ if ferr != nil {
+ // Best-effort: one page failing is not fatal; remember the last error in
+ // case every page fails.
+ lastFetch = ferr
+ continue
+ }
+ md = strings.TrimSpace(md)
+ if md == "" {
+ continue
+ }
+ if len(md) > maxBytes {
+ md = md[:maxBytes]
+ }
+ // The source id (1-based, in fetch order) is what the summarizer cites as
+ // [Source N]; usedURLs tracks the matching URL so it can be listed at the end.
+ blocks = append(blocks, fmt.Sprintf("<source id=\"%d\" url=\"%s\">\n%s\n</source>", fetched+1, u, md))
+ usedURLs = append(usedURLs, u)
+ fetched++
+ }
+
+ if fetched == 0 {
+ // Nothing could be read. If the pages errored (vs. returned empty), surface a
+ // retryable error so the orchestrator can fall back to another engine.
+ if lastFetch != nil {
+ return "", Retryable(fmt.Errorf("internal engine: all pages failed to fetch: %w", lastFetch), 0)
+ }
+ return "", Fatal(fmt.Errorf("internal engine: no readable content found"))
+ }
+
+ prompt := e.buildPrompt(req.Query, blocks)
+ answer, serr := e.summarizer(ctx, prompt)
+ if serr != nil {
+ return "", Retryable(fmt.Errorf("internal engine: summarization failed: %w", serr), 0)
+ }
+
+ return appendSources(answer, usedURLs), nil
+}
+
+// appendSources appends the list of source URLs the answer was synthesized from, so the
+// [Source N] citations in the summary can be traced back to the page they came from. The
+// numbering matches the source ids fed to the summarizer (1-based, in fetch order).
+func appendSources(answer string, urls []string) string {
+ if len(urls) == 0 {
+ return answer
+ }
+ var sb strings.Builder
+ sb.WriteString(strings.TrimRight(answer, "\n"))
+ sb.WriteString("\n\n### Sources\n\n")
+ for i, u := range urls {
+ parsedURL, err := url.Parse(u)
+ if err != nil {
+ sb.WriteString(fmt.Sprintf("%d. %s\n", i+1, u))
+ continue
+ }
+ sb.WriteString(fmt.Sprintf("%d. [%s](%s)\n", i+1, parsedURL.Hostname(), u))
+ }
+ return sb.String()
+}
+
+// discoverURLs asks the first available link searcher for candidate URLs and extracts
+// them from its markdown output. A discovery error is propagated as-is (already typed).
+func (e *internalEngine) discoverURLs(ctx context.Context, req Request) ([]string, string, error) {
+ linkReq := Request{Query: req.Query, MaxResults: internalLinkDiscoveryLimit}
+
+ for _, l := range e.links {
+ if l == nil || !l.IsAvailable() {
+ continue
+ }
+ out, err := l.Handle(ctx, linkReq)
+ if err != nil {
+ // Propagate the typed error from the link engine; the orchestrator decides
+ // retry-vs-fallback for the internal engine as a whole.
+ return nil, "", err
+ }
+ return dedupeURLs(urlPattern.FindAllString(out, -1)), out, nil
+ }
+
+ return nil, "", Fatal(fmt.Errorf("internal engine: no link-discovery engine is available"))
+}
+
+func (e *internalEngine) buildPrompt(query string, blocks []string) string {
+ var sb strings.Builder
+ sb.WriteString("<instructions>\n")
+ sb.WriteString("TASK: Answer the user query using ONLY the web sources below.\n\n")
+ sb.WriteString(fmt.Sprintf("USER QUERY: %q\n\n", query))
+ sb.WriteString("REQUIREMENTS:\n")
+ sb.WriteString("1. Give a direct, comprehensive answer to the user query.\n")
+ sb.WriteString("2. Preserve critical facts, numbers, commands, code snippets, and technical details.\n")
+ sb.WriteString("3. Remove any non-essential details that are not relevant to the user query.\n")
+ sb.WriteString("4. Cite sources as [Source #] where # is the source id.\n")
+ sb.WriteString("5. If the sources do not answer the query, say so explicitly.\n")
+ sb.WriteString("6. Use `###` headers to separate paragraphs.\n")
+ sb.WriteString("</instructions>\n\n")
+ for _, b := range blocks {
+ sb.WriteString(b)
+ sb.WriteString("\n\n")
+ }
+ return sb.String()
+}
+
+func dedupeURLs(urls []string) []string {
+ seen := make(map[string]struct{}, len(urls))
+ out := make([]string, 0, len(urls))
+ for _, u := range urls {
+ u = strings.TrimRight(u, ".,;")
+ if u == "" {
+ continue
+ }
+ if _, ok := seen[u]; ok {
+ continue
+ }
+ seen[u] = struct{}{}
+ out = append(out, u)
+ }
+ return out
+}
diff --git a/backend/pkg/tools/searchers/internal_test.go b/backend/pkg/tools/searchers/internal_test.go
new file mode 100644
index 00000000..a8e5b701
--- /dev/null
+++ b/backend/pkg/tools/searchers/internal_test.go
@@ -0,0 +1,216 @@
+package searchers
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+
+ "pentagi/pkg/config"
+ "pentagi/pkg/database"
+)
+
+// fakeFetcher scripts FetchMarkdown responses by URL.
+type fakeFetcher struct {
+ pages map[string]string
+ errs map[string]error
+ calls int
+}
+
+func (f *fakeFetcher) FetchMarkdown(_ context.Context, url string) (string, error) {
+ f.calls++
+ if err, ok := f.errs[url]; ok {
+ return "", err
+ }
+ return f.pages[url], nil
+}
+
+// fakeLinkSearcher returns a fixed markdown blob (with URLs) as a link engine would.
+type fakeLinkSearcher struct {
+ available bool
+ output string
+ err error
+}
+
+func (f *fakeLinkSearcher) Engine() database.SearchengineType { return database.SearchengineTypeGoogle }
+func (f *fakeLinkSearcher) IsAvailable() bool { return f.available }
+func (f *fakeLinkSearcher) Handle(_ context.Context, _ Request) (string, error) {
+ if f.err != nil {
+ return "", f.err
+ }
+ return f.output, nil
+}
+
+func enabledInternalCfg() *config.Config {
+ return &config.Config{
+ WebSearchInternalEnabled: true,
+ WebSearchInternalMaxSites: 3,
+ WebSearchInternalMaxSiteBytes: 20,
+ }
+}
+
+func TestInternalIsAvailable(t *testing.T) {
+ fetcher := &fakeFetcher{}
+ sum := SummarizeHandler(func(_ context.Context, s string) (string, error) { return s, nil })
+ link := &fakeLinkSearcher{available: true}
+
+ t.Run("disabled by config", func(t *testing.T) {
+ e := NewInternal(&config.Config{WebSearchInternalEnabled: false}, fetcher, []Searcher{link}, sum)
+ if e.IsAvailable() {
+ t.Error("internal engine must be unavailable when WEB_SEARCH_INTERNAL_ENABLED=false")
+ }
+ })
+ t.Run("no fetcher", func(t *testing.T) {
+ e := NewInternal(enabledInternalCfg(), nil, []Searcher{link}, sum)
+ if e.IsAvailable() {
+ t.Error("internal engine must be unavailable without a page fetcher")
+ }
+ })
+ t.Run("no available link engine", func(t *testing.T) {
+ e := NewInternal(enabledInternalCfg(), fetcher, []Searcher{&fakeLinkSearcher{available: false}}, sum)
+ if e.IsAvailable() {
+ t.Error("internal engine must be unavailable when no link engine is available")
+ }
+ })
+ t.Run("fully configured", func(t *testing.T) {
+ e := NewInternal(enabledInternalCfg(), fetcher, []Searcher{link}, sum)
+ if !e.IsAvailable() {
+ t.Error("internal engine should be available when enabled + fetcher + link engine present")
+ }
+ if e.Engine() != database.SearchengineTypeBrowser {
+ t.Errorf("Engine() = %q, want browser (attribution)", e.Engine())
+ }
+ })
+}
+
+func TestInternalAnalyzeSummarizesBoundedContent(t *testing.T) {
+ link := &fakeLinkSearcher{available: true, output: "1. https://a.example\n2. https://b.example\n"}
+ fetcher := &fakeFetcher{pages: map[string]string{
+ "https://a.example": strings.Repeat("A", 100), // longer than MaxSiteBytes=20
+ "https://b.example": "short B content",
+ }}
+
+ var captured string
+ sum := SummarizeHandler(func(_ context.Context, prompt string) (string, error) {
+ captured = prompt
+ return "SYNTHESIZED ANSWER", nil
+ })
+
+ e := NewInternal(enabledInternalCfg(), fetcher, []Searcher{link}, sum)
+ got, err := e.Handle(context.Background(), Request{Query: "what is A"})
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.Contains(got, "SYNTHESIZED ANSWER") {
+ t.Errorf("result = %q, want it to contain the summarizer output", got)
+ }
+ // The fetched source URLs must be appended as a numbered Sources section, in fetch
+ // order, matching the [Source N] ids the summarizer was given.
+ if !strings.Contains(got, "### Sources") {
+ t.Errorf("result = %q, want an appended '### Sources' section", got)
+ }
+ if !strings.Contains(got, "1. [a.example](https://a.example)") ||
+ !strings.Contains(got, "2. [b.example](https://b.example)") {
+ t.Errorf("result = %q, want the fetched URLs as numbered markdown links in fetch order", got)
+ }
+ // Per-site markdown must be truncated to MaxSiteBytes (20).
+ if strings.Contains(captured, strings.Repeat("A", 21)) {
+ t.Error("page A markdown was not truncated to the per-site byte limit")
+ }
+ if !strings.Contains(captured, "https://a.example") || !strings.Contains(captured, "https://b.example") {
+ t.Error("summarizer prompt should reference both source URLs")
+ }
+}
+
+func TestAppendSources(t *testing.T) {
+ if got := appendSources("answer", nil); got != "answer" {
+ t.Errorf("appendSources with no URLs = %q, want the answer unchanged", got)
+ }
+
+ // Each source is rendered as a numbered markdown link whose text is the URL host.
+ got := appendSources("answer\n\n", []string{
+ "https://github.com/vxcontrol/pentagi",
+ "https://pentagi.com/get-started",
+ })
+ want := "answer\n\n### Sources\n\n" +
+ "1. [github.com](https://github.com/vxcontrol/pentagi)\n" +
+ "2. [pentagi.com](https://pentagi.com/get-started)\n"
+ if got != want {
+ t.Errorf("appendSources = %q, want %q", got, want)
+ }
+}
+
+func TestInternalRespectsMaxSites(t *testing.T) {
+ cfg := enabledInternalCfg()
+ cfg.WebSearchInternalMaxSites = 1
+ link := &fakeLinkSearcher{available: true, output: "https://a.example https://b.example https://c.example"}
+ fetcher := &fakeFetcher{pages: map[string]string{
+ "https://a.example": "A", "https://b.example": "B", "https://c.example": "C",
+ }}
+ sum := SummarizeHandler(func(_ context.Context, s string) (string, error) { return s, nil })
+
+ e := NewInternal(cfg, fetcher, []Searcher{link}, sum)
+ if _, err := e.Handle(context.Background(), Request{Query: "q"}); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if fetcher.calls != 1 {
+ t.Errorf("fetched %d pages, want 1 (MaxSites cap)", fetcher.calls)
+ }
+}
+
+func TestInternalAllPagesFailIsRetryable(t *testing.T) {
+ link := &fakeLinkSearcher{available: true, output: "https://a.example https://b.example"}
+ fetcher := &fakeFetcher{errs: map[string]error{
+ "https://a.example": errors.New("boom"),
+ "https://b.example": errors.New("boom"),
+ }}
+ sum := SummarizeHandler(func(_ context.Context, s string) (string, error) { return s, nil })
+
+ e := NewInternal(enabledInternalCfg(), fetcher, []Searcher{link}, sum)
+ _, err := e.Handle(context.Background(), Request{Query: "q"})
+ if err == nil {
+ t.Fatal("expected an error when every page fails to fetch")
+ }
+ if !IsRetryable(err) {
+ t.Errorf("error = %v, want retryable when all pages fail", err)
+ }
+}
+
+func TestInternalSummarizerFailureIsRetryable(t *testing.T) {
+ link := &fakeLinkSearcher{available: true, output: "https://a.example"}
+ fetcher := &fakeFetcher{pages: map[string]string{"https://a.example": "content"}}
+ sum := SummarizeHandler(func(_ context.Context, _ string) (string, error) { return "", errors.New("llm down") })
+
+ e := NewInternal(enabledInternalCfg(), fetcher, []Searcher{link}, sum)
+ _, err := e.Handle(context.Background(), Request{Query: "q"})
+ if err == nil || !IsRetryable(err) {
+ t.Fatalf("expected a retryable error on summarizer failure, got %v", err)
+ }
+}
+
+func TestInternalLinkDiscoveryErrorPropagates(t *testing.T) {
+ link := &fakeLinkSearcher{available: true, err: Fatal(errors.New("link engine broke"))}
+ fetcher := &fakeFetcher{}
+ sum := SummarizeHandler(func(_ context.Context, s string) (string, error) { return s, nil })
+
+ e := NewInternal(enabledInternalCfg(), fetcher, []Searcher{link}, sum)
+ _, err := e.Handle(context.Background(), Request{Query: "q"})
+ if err == nil || !IsFatal(err) {
+ t.Fatalf("expected the link engine's fatal error to propagate, got %v", err)
+ }
+}
+
+func TestDedupeURLs(t *testing.T) {
+ in := []string{"https://a.com", "https://a.com", "https://b.com.", "https://a.com,"}
+ got := dedupeURLs(in)
+ // Trailing punctuation stripped, duplicates removed.
+ want := []string{"https://a.com", "https://b.com"}
+ if len(got) != len(want) {
+ t.Fatalf("dedupeURLs = %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Errorf("dedupeURLs[%d] = %q, want %q", i, got[i], want[i])
+ }
+ }
+}
diff --git a/backend/pkg/tools/perplexity.go b/backend/pkg/tools/searchers/perplexity.go
similarity index 82%
rename from backend/pkg/tools/perplexity.go
rename to backend/pkg/tools/searchers/perplexity.go
index f5e58ea0..a06e45bc 100644
--- a/backend/pkg/tools/perplexity.go
+++ b/backend/pkg/tools/searchers/perplexity.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"bytes"
@@ -25,7 +25,7 @@ import (
const (
perplexityURL = "https://api.perplexity.ai/chat/completions"
perplexityTimeout = 60 * time.Second
- perplexityModel = "sonar"
+ perplexityModel = "sonar-pro"
perplexityTemperature = 0.5
perplexityTopP = 0.9
perplexityMaxTokens = 4000
@@ -83,85 +83,50 @@ type Usage struct {
// perplexity - structure for working with Perplexity API
type perplexity struct {
cfg *config.Config
- flowID int64
- taskID *int64
- subtaskID *int64
- slp SearchLogProvider
summarizer SummarizeHandler
}
-func NewPerplexityTool(
- cfg *config.Config,
- flowID int64,
- taskID, subtaskID *int64,
- slp SearchLogProvider,
- summarizer SummarizeHandler,
-) Tool {
+func NewPerplexity(cfg *config.Config, summarizer SummarizeHandler) Searcher {
return &perplexity{
cfg: cfg,
- flowID: flowID,
- taskID: taskID,
- subtaskID: subtaskID,
- slp: slp,
summarizer: summarizer,
}
}
+func (p *perplexity) Engine() database.SearchengineType {
+ return database.SearchengineTypePerplexity
+}
+
// Handle processes a search request through Perplexity API
-func (p *perplexity) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+func (p *perplexity) Handle(ctx context.Context, req Request) (string, error) {
if !p.IsAvailable() {
- return "", fmt.Errorf("perplexity is not available")
+ return "", ErrNotConfigured
}
- var action SearchAction
ctx, observation := obs.Observer.NewObservation(ctx)
- logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(p.flowID, p.taskID, p.subtaskID, logrus.Fields{
- "tool": name,
- "args": string(args),
- }))
-
- if err := json.Unmarshal(args, &action); err != nil {
- logger.WithError(err).Error("failed to unmarshal perplexity search action")
- return "", fmt.Errorf("failed to unmarshal %s search action arguments: %w", name, err)
- }
-
- logger = logger.WithFields(logrus.Fields{
- "query": action.Query[:min(len(action.Query), 1000)],
- "max_results": action.MaxResults,
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "perplexity",
+ "query": req.Query[:min(len(req.Query), 1000)],
+ "model": p.model(),
})
- result, err := p.search(ctx, action.Query)
+ result, err := p.search(ctx, req.Query)
if err != nil {
observation.Event(
- langfuse.WithEventName("search engine error swallowed"),
- langfuse.WithEventInput(action.Query),
+ langfuse.WithEventName("search engine error"),
+ langfuse.WithEventInput(req.Query),
langfuse.WithEventStatus(err.Error()),
langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
langfuse.WithEventMetadata(langfuse.Metadata{
- "tool_name": PerplexityToolName,
- "engine": "perplexity",
- "query": action.Query,
- "model": p.model(),
- "max_results": action.MaxResults.Int(),
- "error": err.Error(),
+ "engine": "perplexity",
+ "query": req.Query,
+ "model": p.model(),
+ "error": err.Error(),
}),
)
logger.WithError(err).Error("failed to search in perplexity")
- return fmt.Sprintf("failed to search in perplexity: %v", err), nil
- }
-
- if agentCtx, ok := GetAgentContext(ctx); ok {
- _, _ = p.slp.PutLog(
- ctx,
- agentCtx.ParentAgentType,
- agentCtx.CurrentAgentType,
- database.SearchengineTypePerplexity,
- action.Query,
- result,
- p.taskID,
- p.subtaskID,
- )
+ return "", err
}
return result, nil
@@ -171,7 +136,7 @@ func (p *perplexity) Handle(ctx context.Context, name string, args json.RawMessa
func (p *perplexity) search(ctx context.Context, query string) (string, error) {
client, err := system.GetHTTPClient(p.cfg)
if err != nil {
- return "", fmt.Errorf("failed to create http client: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create http client: %w", err))
}
client.Timeout = p.timeout()
@@ -200,13 +165,13 @@ func (p *perplexity) search(ctx context.Context, query string) (string, error) {
// Serializing the request
reqBody, err := json.Marshal(reqPayload)
if err != nil {
- return "", fmt.Errorf("failed to marshal request body: %w", err)
+ return "", Fatal(fmt.Errorf("failed to marshal request body: %w", err))
}
// Creating HTTP request
req, err := http.NewRequestWithContext(ctx, http.MethodPost, perplexityURL, bytes.NewBuffer(reqBody))
if err != nil {
- return "", fmt.Errorf("failed to create request: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create request: %w", err))
}
// Setting request headers
@@ -216,25 +181,30 @@ func (p *perplexity) search(ctx context.Context, query string) (string, error) {
// Sending the request
resp, err := client.Do(req)
if err != nil {
- return "", fmt.Errorf("failed to send request: %w", err)
+ return "", Retryable(fmt.Errorf("failed to send request: %w", err), 0)
}
defer resp.Body.Close()
- // Handling the response
+ // Handling the response. handleErrorResponse keeps the per-status message; the
+ // retryable/fatal classification is decided here from the status code.
if resp.StatusCode != http.StatusOK {
- return "", p.handleErrorResponse(resp.StatusCode)
+ baseErr := p.handleErrorResponse(resp.StatusCode)
+ if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
+ return "", Retryable(baseErr, 0)
+ }
+ return "", Fatal(baseErr)
}
// Reading the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
- return "", fmt.Errorf("failed to read response body: %w", err)
+ return "", Retryable(fmt.Errorf("failed to read response body: %w", err), 0)
}
// Deserializing the response
var response CompletionResponse
if err := json.Unmarshal(body, &response); err != nil {
- return "", fmt.Errorf("failed to unmarshal response: %w", err)
+ return "", Fatal(fmt.Errorf("failed to unmarshal response: %w", err))
}
// Forming the result
diff --git a/backend/pkg/tools/perplexity_test.go b/backend/pkg/tools/searchers/perplexity_test.go
similarity index 81%
rename from backend/pkg/tools/perplexity_test.go
rename to backend/pkg/tools/searchers/perplexity_test.go
index 3f683f75..360b2938 100644
--- a/backend/pkg/tools/perplexity_test.go
+++ b/backend/pkg/tools/searchers/perplexity_test.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"io"
@@ -63,11 +63,6 @@ func TestPerplexityHandle(t *testing.T) {
}
defer proxy.Close()
- flowID := int64(1)
- taskID := int64(10)
- subtaskID := int64(20)
- slp := &searchLogProviderMock{}
-
cfg := &config.Config{
PerplexityAPIKey: testPerplexityAPIKey,
PerplexityModel: "sonar",
@@ -76,17 +71,18 @@ func TestPerplexityHandle(t *testing.T) {
ExternalSSLCAPath: proxy.CACertPath(),
}
- px := NewPerplexityTool(cfg, flowID, &taskID, &subtaskID, slp, nil)
+ px := NewPerplexity(cfg, nil)
- ctx := PutAgentContext(t.Context(), database.MsgchainTypeSearcher)
got, err := px.Handle(
- ctx,
- PerplexityToolName,
- []byte(`{"query":"test query","max_results":5,"message":"m"}`),
+ t.Context(),
+ Request{Query: "test query"},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
}
+ if px.Engine() != database.SearchengineTypePerplexity {
+ t.Errorf("Engine() = %q, want %q", px.Engine(), database.SearchengineTypePerplexity)
+ }
// Verify mock handler was called
if !seenRequest {
@@ -126,29 +122,6 @@ func TestPerplexityHandle(t *testing.T) {
if !strings.Contains(got, "https://example.com") {
t.Errorf("result missing expected citation 'https://example.com': %q", got)
}
-
- // Verify search log was written with agent context
- if slp.calls != 1 {
- t.Errorf("PutLog() calls = %d, want 1", slp.calls)
- }
- if slp.engine != database.SearchengineTypePerplexity {
- t.Errorf("engine = %q, want %q", slp.engine, database.SearchengineTypePerplexity)
- }
- if slp.query != "test query" {
- t.Errorf("logged query = %q, want %q", slp.query, "test query")
- }
- if slp.parentType != database.MsgchainTypeSearcher {
- t.Errorf("parent agent type = %q, want %q", slp.parentType, database.MsgchainTypeSearcher)
- }
- if slp.currType != database.MsgchainTypeSearcher {
- t.Errorf("current agent type = %q, want %q", slp.currType, database.MsgchainTypeSearcher)
- }
- if slp.taskID == nil || *slp.taskID != taskID {
- t.Errorf("task ID = %v, want %d", slp.taskID, taskID)
- }
- if slp.subtaskID == nil || *slp.subtaskID != subtaskID {
- t.Errorf("subtask ID = %v, want %d", slp.subtaskID, subtaskID)
- }
}
func TestPerplexityIsAvailable(t *testing.T) {
@@ -185,7 +158,7 @@ func TestPerplexityIsAvailable(t *testing.T) {
}
func TestPerplexityHandleErrorResponse(t *testing.T) {
- px := &perplexity{flowID: 1}
+ px := &perplexity{}
tests := []struct {
name string
@@ -263,7 +236,7 @@ func TestPerplexityHandleErrorResponse(t *testing.T) {
}
func TestPerplexityFormatResponse(t *testing.T) {
- px := &perplexity{flowID: 1}
+ px := &perplexity{}
t.Run("empty choices returns fallback message", func(t *testing.T) {
resp := &CompletionResponse{Choices: []Choice{}}
@@ -373,16 +346,8 @@ func TestPerplexityGetSummarizePrompt(t *testing.T) {
})
}
-func TestPerplexityHandle_ValidationAndSwallowedError(t *testing.T) {
- t.Run("invalid json", func(t *testing.T) {
- px := &perplexity{cfg: testPerplexityConfig()}
- _, err := px.Handle(t.Context(), PerplexityToolName, []byte("{"))
- if err == nil || !strings.Contains(err.Error(), "failed to unmarshal") {
- t.Fatalf("expected unmarshal error, got: %v", err)
- }
- })
-
- t.Run("search error swallowed", func(t *testing.T) {
+func TestPerplexityHandle_ReturnsTypedError(t *testing.T) {
+ t.Run("upstream 502 returns a retryable error", func(t *testing.T) {
var seenRequest bool
mockMux := http.NewServeMux()
mockMux.HandleFunc("/chat/completions", func(w http.ResponseWriter, r *http.Request) {
@@ -397,7 +362,6 @@ func TestPerplexityHandle_ValidationAndSwallowedError(t *testing.T) {
defer proxy.Close()
px := &perplexity{
- flowID: 1,
cfg: &config.Config{
PerplexityAPIKey: testPerplexityAPIKey,
ProxyURL: proxy.URL(),
@@ -407,21 +371,23 @@ func TestPerplexityHandle_ValidationAndSwallowedError(t *testing.T) {
result, err := px.Handle(
t.Context(),
- PerplexityToolName,
- []byte(`{"query":"q","max_results":5,"message":"m"}`),
+ Request{Query: "q"},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
// Verify mock handler was called (request was intercepted)
if !seenRequest {
t.Error("request was not intercepted by proxy - mock handler was not called")
}
- // Verify error was swallowed and returned as string
- if !strings.Contains(result, "failed to search in perplexity") {
- t.Errorf("Handle() = %q, expected swallowed error message", result)
+ // The error is now surfaced (not swallowed) and classified. A 502 is retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
})
}
@@ -431,9 +397,10 @@ func TestPerplexityHandle_StatusCodeErrors(t *testing.T) {
name string
statusCode int
errContain string
+ retryable bool
}{
- {"unauthorized", http.StatusUnauthorized, "API key"},
- {"server error", http.StatusInternalServerError, "server"},
+ {"unauthorized", http.StatusUnauthorized, "API key", false},
+ {"server error", http.StatusInternalServerError, "server", true},
}
for _, tt := range tests {
@@ -450,7 +417,6 @@ func TestPerplexityHandle_StatusCodeErrors(t *testing.T) {
defer proxy.Close()
px := &perplexity{
- flowID: 1,
cfg: &config.Config{
PerplexityAPIKey: testPerplexityAPIKey,
ProxyURL: proxy.URL(),
@@ -460,19 +426,27 @@ func TestPerplexityHandle_StatusCodeErrors(t *testing.T) {
result, err := px.Handle(
t.Context(),
- PerplexityToolName,
- []byte(`{"query":"test","max_results":5,"message":"m"}`),
+ Request{Query: "test"},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
- // Error should be swallowed and returned as string
- if !strings.Contains(result, "failed to search in perplexity") {
- t.Errorf("Handle() = %q, expected swallowed error", result)
+ // The status-code failure surfaces as a typed error (not swallowed).
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
}
- if !strings.Contains(result, tt.errContain) {
- t.Errorf("Handle() = %q, expected to contain %q", result, tt.errContain)
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if tt.retryable {
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
+ }
+ } else {
+ if !IsFatal(err) {
+ t.Errorf("Handle() error = %v, want a FatalError", err)
+ }
+ }
+ if !strings.Contains(err.Error(), tt.errContain) {
+ t.Errorf("Handle() error = %v, expected to contain %q", err, tt.errContain)
}
})
}
diff --git a/backend/pkg/tools/proxy_test.go b/backend/pkg/tools/searchers/proxy_test.go
similarity index 97%
rename from backend/pkg/tools/proxy_test.go
rename to backend/pkg/tools/searchers/proxy_test.go
index 6b345fbd..a9b253f8 100644
--- a/backend/pkg/tools/proxy_test.go
+++ b/backend/pkg/tools/searchers/proxy_test.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"bufio"
@@ -23,8 +23,6 @@ import (
"sync"
"testing"
"time"
-
- "pentagi/pkg/database"
)
var _ SummarizeHandler = testSummarizerHandler
@@ -34,40 +32,6 @@ func testSummarizerHandler(ctx context.Context, result string) (string, error) {
return "test summarized: " + result, nil
}
-var _ SearchLogProvider = &searchLogProviderMock{}
-
-type searchLogProviderMock struct {
- calls int64
- engine database.SearchengineType
- query string
- result string
- taskID *int64
- subtaskID *int64
- parentType database.MsgchainType
- currType database.MsgchainType
-}
-
-func (m *searchLogProviderMock) PutLog(
- _ context.Context,
- initiator database.MsgchainType,
- executor database.MsgchainType,
- engine database.SearchengineType,
- query string,
- result string,
- taskID *int64,
- subtaskID *int64,
-) (int64, error) {
- m.calls++
- m.parentType = initiator
- m.currType = executor
- m.engine = engine
- m.query = query
- m.result = result
- m.taskID = taskID
- m.subtaskID = subtaskID
- return m.calls, nil
-}
-
// testProxy is a MITM HTTP/HTTPS proxy server for unit testing that intercepts
// requests to a specific domain and redirects them to a mock HTTP server.
type testProxy struct {
diff --git a/backend/pkg/tools/searchers/searchers.go b/backend/pkg/tools/searchers/searchers.go
new file mode 100644
index 00000000..45a56fd4
--- /dev/null
+++ b/backend/pkg/tools/searchers/searchers.go
@@ -0,0 +1,76 @@
+// Package searchers holds the individual web-search primitives (google, duckduckgo,
+// tavily, perplexity, traversaal, sploitus, searxng, firecrawl, and the optional
+// internal browser-analytics engine) that the tools.web_search orchestrator drives.
+//
+// Each searcher wraps a single provider, keeps its own Langfuse observation, and
+// returns the ORIGINAL error — classified as *RetryableError or *FatalError — so the
+// orchestrator can decide whether to retry the same engine or fall back to the next
+// one. Searchers never mask an error as a "failed to search…" string and never write
+// to the database search-log; both concerns belong to the orchestrator.
+//
+// This package must not import pentagi/pkg/tools (the orchestrator imports this
+// package). It depends only on neutral packages: config, database (for the
+// SearchengineType attribution enum), system (HTTP client), and observability.
+package searchers
+
+import (
+ "context"
+
+ "pentagi/pkg/database"
+)
+
+// Request is the engine-agnostic, already-parsed input the orchestrator hands to
+// every searcher. The lenient LLM JSON arg types (tools.Int64, tools.String, …) are
+// unmarshaled ONCE by the orchestrator; searchers only ever see plain Go types.
+type Request struct {
+ // Query is the technical-channel search query, always in English. The
+ // orchestrator guarantees it is non-empty.
+ Query string
+
+ // MaxResults is already clamped by the orchestrator to a sane range.
+ MaxResults int
+
+ // ExploitType and Sort are exploit-search hints. They are empty for every
+ // non-exploit mode and honored only by engines that support them (sploitus).
+ ExploitType string // "exploits" | "tools"
+ Sort string // "default" | "date" | "score"
+}
+
+// SummarizeHandler compresses oversized source content into a query-focused answer.
+// It has the same underlying signature as tools.SummarizeHandler; the orchestrator
+// passes the flow summarizer in via an explicit conversion.
+type SummarizeHandler func(ctx context.Context, result string) (string, error)
+
+// Searcher is a single search primitive. Implementations keep their own Langfuse
+// observation, return the original (typed) error, and never touch the DB search-log.
+type Searcher interface {
+ // Engine is the stable identifier used for search-log attribution and for keying
+ // the orchestrator's fallback table.
+ Engine() database.SearchengineType
+
+ // IsAvailable reports whether the engine is configured and usable. The
+ // orchestrator skips unavailable engines before calling Handle.
+ IsAvailable() bool
+
+ // Handle runs one query. The caller has already parsed and normalized the
+ // request, which is why this signature takes a Request rather than the raw
+ // (name string, args json.RawMessage) pair the tools.Tool interface uses.
+ Handle(ctx context.Context, req Request) (string, error)
+}
+
+// Link is a single discovered source. It is produced by link-oriented engines and
+// consumed by the internal analytics engine when it needs URLs to fetch and
+// summarize.
+type Link struct {
+ Title string
+ URL string
+ Snippet string
+}
+
+// PageFetcher fetches a single URL and returns its main content as markdown. It is
+// implemented in the tools package on top of the existing browser tool / scraper and
+// injected into the internal analytics engine, so this package need not depend on the
+// tools package. Callers bound the returned content themselves.
+type PageFetcher interface {
+ FetchMarkdown(ctx context.Context, url string) (string, error)
+}
diff --git a/backend/pkg/tools/searxng.go b/backend/pkg/tools/searchers/searxng.go
similarity index 71%
rename from backend/pkg/tools/searxng.go
rename to backend/pkg/tools/searchers/searxng.go
index 6a2be3ad..3969ebd0 100644
--- a/backend/pkg/tools/searxng.go
+++ b/backend/pkg/tools/searchers/searxng.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"context"
@@ -25,87 +25,53 @@ const (
type searxng struct {
cfg *config.Config
- flowID int64
- taskID *int64
- subtaskID *int64
- slp SearchLogProvider
summarizer SummarizeHandler
}
-func NewSearxngTool(
- cfg *config.Config,
- flowID int64,
- taskID, subtaskID *int64,
- slp SearchLogProvider,
- summarizer SummarizeHandler,
-) Tool {
+func NewSearxng(cfg *config.Config, summarizer SummarizeHandler) Searcher {
return &searxng{
cfg: cfg,
- flowID: flowID,
- taskID: taskID,
- subtaskID: subtaskID,
- slp: slp,
summarizer: summarizer,
}
}
+func (s *searxng) Engine() database.SearchengineType {
+ return database.SearchengineTypeSearxng
+}
+
func (s *searxng) IsAvailable() bool {
return s.baseURL() != ""
}
-func (s *searxng) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+func (s *searxng) Handle(ctx context.Context, req Request) (string, error) {
if !s.IsAvailable() {
- return "", fmt.Errorf("searxng is not available")
+ return "", ErrNotConfigured
}
- var action SearchAction
ctx, observation := obs.Observer.NewObservation(ctx)
- logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(s.flowID, s.taskID, s.subtaskID, logrus.Fields{
- "tool": name,
- "args": string(args),
- }))
-
- if err := json.Unmarshal(args, &action); err != nil {
- logger.WithError(err).Error("failed to unmarshal searxng search action")
- return "", fmt.Errorf("failed to unmarshal %s search action arguments: %w", name, err)
- }
-
- logger = logger.WithFields(logrus.Fields{
- "query": action.Query[:min(len(action.Query), 1000)],
- "max_results": action.MaxResults,
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "searxng",
+ "query": req.Query[:min(len(req.Query), 1000)],
+ "max_results": req.MaxResults,
})
- result, err := s.search(ctx, action.Query, action.MaxResults.Int())
+ result, err := s.search(ctx, req.Query, req.MaxResults)
if err != nil {
observation.Event(
- langfuse.WithEventName("search engine error swallowed"),
- langfuse.WithEventInput(action.Query),
+ langfuse.WithEventName("search engine error"),
+ langfuse.WithEventInput(req.Query),
langfuse.WithEventStatus(err.Error()),
langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
langfuse.WithEventMetadata(langfuse.Metadata{
- "tool_name": SearxngToolName,
"engine": "searxng",
- "query": action.Query,
- "max_results": action.MaxResults.Int(),
+ "query": req.Query,
+ "max_results": req.MaxResults,
"error": err.Error(),
}),
)
logger.WithError(err).Error("failed to search in searxng")
- return fmt.Sprintf("failed to search in searxng: %v", err), nil
- }
-
- if agentCtx, ok := GetAgentContext(ctx); ok {
- _, _ = s.slp.PutLog(
- ctx,
- agentCtx.ParentAgentType,
- agentCtx.CurrentAgentType,
- database.SearchengineTypeSearxng,
- action.Query,
- result,
- s.taskID,
- s.subtaskID,
- )
+ return "", err
}
return result, nil
@@ -114,7 +80,7 @@ func (s *searxng) Handle(ctx context.Context, name string, args json.RawMessage)
func (s *searxng) search(ctx context.Context, query string, maxResults int) (string, error) {
apiURL, err := url.Parse(s.baseURL())
if err != nil {
- return "", fmt.Errorf("invalid searxng base URL: %w", err)
+ return "", Fatal(fmt.Errorf("invalid searxng base URL: %w", err))
}
if !strings.HasSuffix(apiURL.Path, "/search") {
@@ -142,21 +108,21 @@ func (s *searxng) search(ctx context.Context, query string, maxResults int) (str
client, err := system.GetHTTPClient(s.cfg)
if err != nil {
- return "", fmt.Errorf("failed to create http client: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create http client: %w", err))
}
client.Timeout = s.timeout()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL.String(), nil)
if err != nil {
- return "", fmt.Errorf("failed to create request: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create request: %w", err))
}
req.Header.Set("User-Agent", "PentAGI/1.0")
resp, err := client.Do(req)
if err != nil {
- return "", fmt.Errorf("failed to do request: %w", err)
+ return "", Retryable(fmt.Errorf("failed to do request: %w", err), 0)
}
defer resp.Body.Close()
@@ -165,12 +131,16 @@ func (s *searxng) search(ctx context.Context, query string, maxResults int) (str
func (s *searxng) parseHTTPResponse(resp *http.Response, query string) (string, error) {
if resp.StatusCode != http.StatusOK {
- return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ err := fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
+ return "", Retryable(err, 0)
+ }
+ return "", Fatal(err)
}
var searxngResponse SearxngResponse
if err := json.NewDecoder(resp.Body).Decode(&searxngResponse); err != nil {
- return "", fmt.Errorf("failed to decode response body: %w", err)
+ return "", Fatal(fmt.Errorf("failed to decode response body: %w", err))
}
return s.formatResults(searxngResponse.Results, query), nil
diff --git a/backend/pkg/tools/searxng_test.go b/backend/pkg/tools/searchers/searxng_test.go
similarity index 79%
rename from backend/pkg/tools/searxng_test.go
rename to backend/pkg/tools/searchers/searxng_test.go
index 2c9c1ed8..1603defe 100644
--- a/backend/pkg/tools/searxng_test.go
+++ b/backend/pkg/tools/searchers/searxng_test.go
@@ -1,7 +1,6 @@
-package tools
+package searchers
import (
- "context"
"io"
"net/http"
"strings"
@@ -58,11 +57,6 @@ func TestSearxngHandle(t *testing.T) {
}
defer proxy.Close()
- flowID := int64(1)
- taskID := int64(10)
- subtaskID := int64(20)
- slp := &searchLogProviderMock{}
-
cfg := &config.Config{
SearxngURL: testSearxngURL,
SearxngLanguage: "en",
@@ -73,17 +67,18 @@ func TestSearxngHandle(t *testing.T) {
ExternalSSLCAPath: proxy.CACertPath(),
}
- sx := NewSearxngTool(cfg, flowID, &taskID, &subtaskID, slp, nil)
+ sx := NewSearxng(cfg, nil)
- ctx := PutAgentContext(t.Context(), database.MsgchainTypeSearcher)
got, err := sx.Handle(
- ctx,
- SearxngToolName,
- []byte(`{"query":"test query","max_results":5,"message":"m"}`),
+ t.Context(),
+ Request{Query: "test query", MaxResults: 5},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
}
+ if sx.Engine() != database.SearchengineTypeSearxng {
+ t.Errorf("Engine() = %q, want %q", sx.Engine(), database.SearchengineTypeSearxng)
+ }
// Verify mock handler was called
if !seenRequest {
@@ -126,29 +121,6 @@ func TestSearxngHandle(t *testing.T) {
if !strings.Contains(got, "Test content") {
t.Errorf("result missing expected content 'Test content': %q", got)
}
-
- // Verify search log was written with agent context
- if slp.calls != 1 {
- t.Errorf("PutLog() calls = %d, want 1", slp.calls)
- }
- if slp.engine != database.SearchengineTypeSearxng {
- t.Errorf("engine = %q, want %q", slp.engine, database.SearchengineTypeSearxng)
- }
- if slp.query != "test query" {
- t.Errorf("logged query = %q, want %q", slp.query, "test query")
- }
- if slp.parentType != database.MsgchainTypeSearcher {
- t.Errorf("parent agent type = %q, want %q", slp.parentType, database.MsgchainTypeSearcher)
- }
- if slp.currType != database.MsgchainTypeSearcher {
- t.Errorf("current agent type = %q, want %q", slp.currType, database.MsgchainTypeSearcher)
- }
- if slp.taskID == nil || *slp.taskID != taskID {
- t.Errorf("task ID = %v, want %d", slp.taskID, taskID)
- }
- if slp.subtaskID == nil || *slp.subtaskID != subtaskID {
- t.Errorf("subtask ID = %v, want %d", slp.subtaskID, subtaskID)
- }
}
func TestSearxngIsAvailable(t *testing.T) {
@@ -185,7 +157,7 @@ func TestSearxngIsAvailable(t *testing.T) {
}
func TestSearxngParseHTTPResponse_StatusAndDecodeErrors(t *testing.T) {
- sx := &searxng{flowID: 1}
+ sx := &searxng{}
t.Run("status error", func(t *testing.T) {
resp := &http.Response{
@@ -228,7 +200,7 @@ func TestSearxngParseHTTPResponse_StatusAndDecodeErrors(t *testing.T) {
}
func TestSearxngFormatResults_NoResults(t *testing.T) {
- sx := &searxng{flowID: 1}
+ sx := &searxng{}
result := sx.formatResults([]SearxngResult{}, "test query")
if !strings.Contains(result, "No Results Found") {
@@ -240,7 +212,7 @@ func TestSearxngFormatResults_NoResults(t *testing.T) {
}
func TestSearxngFormatResults_WithResults(t *testing.T) {
- sx := &searxng{flowID: 1}
+ sx := &searxng{}
results := []SearxngResult{
{
@@ -278,16 +250,8 @@ func TestSearxngFormatResults_WithResults(t *testing.T) {
}
}
-func TestSearxngHandle_ValidationAndSwallowedError(t *testing.T) {
- t.Run("invalid json", func(t *testing.T) {
- sx := &searxng{cfg: testSearxngConfig()}
- _, err := sx.Handle(t.Context(), SearxngToolName, []byte("{"))
- if err == nil || !strings.Contains(err.Error(), "failed to unmarshal") {
- t.Fatalf("expected unmarshal error, got: %v", err)
- }
- })
-
- t.Run("search error swallowed", func(t *testing.T) {
+func TestSearxngHandle_ReturnsTypedError(t *testing.T) {
+ t.Run("upstream 502 returns a retryable error", func(t *testing.T) {
var seenRequest bool
mockMux := http.NewServeMux()
mockMux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
@@ -302,7 +266,6 @@ func TestSearxngHandle_ValidationAndSwallowedError(t *testing.T) {
defer proxy.Close()
sx := &searxng{
- flowID: 1,
cfg: &config.Config{
SearxngURL: testSearxngURL,
ProxyURL: proxy.URL(),
@@ -312,22 +275,24 @@ func TestSearxngHandle_ValidationAndSwallowedError(t *testing.T) {
}
result, err := sx.Handle(
- context.Background(),
- SearxngToolName,
- []byte(`{"query":"q","max_results":5,"message":"m"}`),
+ t.Context(),
+ Request{Query: "q", MaxResults: 5},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
// Verify mock handler was called (request was intercepted)
if !seenRequest {
t.Error("request was not intercepted by proxy - mock handler was not called")
}
- // Verify error was swallowed and returned as string
- if !strings.Contains(result, "failed to search in searxng") {
- t.Errorf("Handle() = %q, expected swallowed error message", result)
+ // The error is now surfaced (not swallowed) and classified. A 502 is retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
})
}
@@ -356,12 +321,11 @@ func TestSearxngHandle_DefaultLimit(t *testing.T) {
SearxngTimeout: 30,
}
- sx := NewSearxngTool(cfg, 1, nil, nil, nil, nil)
+ sx := NewSearxng(cfg, nil)
_, err = sx.Handle(
t.Context(),
- SearxngToolName,
- []byte(`{"query":"test","message":"m"}`),
+ Request{Query: "test"},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
@@ -397,12 +361,11 @@ func TestSearxngHandle_TimeRange(t *testing.T) {
SearxngTimeout: 30,
}
- sx := NewSearxngTool(cfg, 1, nil, nil, nil, nil)
+ sx := NewSearxng(cfg, nil)
_, err = sx.Handle(
t.Context(),
- SearxngToolName,
- []byte(`{"query":"test","max_results":5,"message":"m"}`),
+ Request{Query: "test", MaxResults: 5},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
diff --git a/backend/pkg/tools/sploitus.go b/backend/pkg/tools/searchers/sploitus.go
similarity index 79%
rename from backend/pkg/tools/sploitus.go
rename to backend/pkg/tools/searchers/sploitus.go
index 7ab35270..8f71ec2e 100644
--- a/backend/pkg/tools/sploitus.go
+++ b/backend/pkg/tools/searchers/sploitus.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"bytes"
@@ -35,83 +35,62 @@ const (
// sploitus represents the Sploitus exploit search tool
type sploitus struct {
- cfg *config.Config
- flowID int64
- taskID *int64
- subtaskID *int64
- slp SearchLogProvider
+ cfg *config.Config
}
-// NewSploitusTool creates a new Sploitus search tool instance
-func NewSploitusTool(
- cfg *config.Config,
- flowID int64,
- taskID, subtaskID *int64,
- slp SearchLogProvider,
-) Tool {
- return &sploitus{
- cfg: cfg,
- flowID: flowID,
- taskID: taskID,
- subtaskID: subtaskID,
- slp: slp,
- }
+// NewSploitus creates a new Sploitus search primitive.
+func NewSploitus(cfg *config.Config) Searcher {
+ return &sploitus{cfg: cfg}
+}
+
+func (s *sploitus) Engine() database.SearchengineType {
+ return database.SearchengineTypeSploitus
}
-// Handle processes a Sploitus exploit search request from an AI agent
-func (s *sploitus) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+// Handle processes a Sploitus exploit search request from the orchestrator.
+func (s *sploitus) Handle(ctx context.Context, req Request) (string, error) {
if !s.IsAvailable() {
- return "", fmt.Errorf("sploitus is not available")
+ return "", ErrNotConfigured
}
- var action SploitusAction
ctx, observation := obs.Observer.NewObservation(ctx)
- logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(s.flowID, s.taskID, s.subtaskID, logrus.Fields{
- "tool": name,
- "args": string(args),
- }))
-
- if err := json.Unmarshal(args, &action); err != nil {
- logger.WithError(err).Error("failed to unmarshal sploitus search action")
- return "", fmt.Errorf("failed to unmarshal %s search action arguments: %w", name, err)
- }
// Normalise exploit type
- exploitType := strings.ToLower(strings.TrimSpace(action.ExploitType.String()))
+ exploitType := strings.ToLower(strings.TrimSpace(req.ExploitType))
if exploitType == "" {
exploitType = defaultSploitusType
}
// Normalise sort order
- sort := strings.ToLower(strings.TrimSpace(action.Sort.String()))
+ sort := strings.ToLower(strings.TrimSpace(req.Sort))
if sort == "" {
sort = sploitusDefaultSort
}
// Clamp max results
- limit := action.MaxResults.Int()
+ limit := req.MaxResults
if limit < 1 || limit > maxSploitusLimit {
limit = defaultSploitusLimit
}
- logger = logger.WithFields(logrus.Fields{
- "query": action.Query[:min(len(action.Query), 1000)],
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "sploitus",
+ "query": req.Query[:min(len(req.Query), 1000)],
"exploit_type": exploitType,
"sort": sort,
"limit": limit,
})
- result, err := s.search(ctx, action.Query, exploitType, sort, limit)
+ result, err := s.search(ctx, req.Query, exploitType, sort, limit)
if err != nil {
observation.Event(
- langfuse.WithEventName("sploitus search error swallowed"),
- langfuse.WithEventInput(action.Query),
+ langfuse.WithEventName("sploitus search error"),
+ langfuse.WithEventInput(req.Query),
langfuse.WithEventStatus(err.Error()),
langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
langfuse.WithEventMetadata(langfuse.Metadata{
- "tool_name": SploitusToolName,
"engine": "sploitus",
- "query": action.Query,
+ "query": req.Query,
"exploit_type": exploitType,
"sort": sort,
"limit": limit,
@@ -120,20 +99,7 @@ func (s *sploitus) Handle(ctx context.Context, name string, args json.RawMessage
)
logger.WithError(err).Error("failed to search in Sploitus")
- return fmt.Sprintf("failed to search in Sploitus: %v", err), nil
- }
-
- if agentCtx, ok := GetAgentContext(ctx); ok {
- _, _ = s.slp.PutLog(
- ctx,
- agentCtx.ParentAgentType,
- agentCtx.CurrentAgentType,
- database.SearchengineTypeSploitus,
- action.Query,
- result,
- s.taskID,
- s.subtaskID,
- )
+ return "", err
}
return result, nil
@@ -151,19 +117,19 @@ func (s *sploitus) search(ctx context.Context, query, exploitType, sort string,
bodyBytes, err := json.Marshal(reqBody)
if err != nil {
- return "", fmt.Errorf("failed to marshal request body: %w", err)
+ return "", Fatal(fmt.Errorf("failed to marshal request body: %w", err))
}
client, err := system.GetHTTPClient(s.cfg)
if err != nil {
- return "", fmt.Errorf("failed to create http client: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create http client: %w", err))
}
client.Timeout = sploitusRequestTimeout
req, err := http.NewRequestWithContext(ctx, http.MethodPost, sploitusAPIURL, bytes.NewReader(bodyBytes))
if err != nil {
- return "", fmt.Errorf("failed to create request: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create request: %w", err))
}
// Build referer with query to mimic browser behavior
@@ -186,22 +152,27 @@ func (s *sploitus) search(ctx context.Context, query, exploitType, sort string,
resp, err := client.Do(req)
if err != nil {
- return "", fmt.Errorf("request to Sploitus failed: %w", err)
+ return "", Retryable(fmt.Errorf("request to Sploitus failed: %w", err), 0)
}
defer resp.Body.Close()
- // Sploitus API returns 499 when rate limit is temporarily exceeded
+ // Sploitus API returns 499 (and sometimes 422) when its rate limit is temporarily
+ // exceeded — a transient condition that may clear on retry.
if resp.StatusCode == 499 || resp.StatusCode == 422 {
- return "", fmt.Errorf("Sploitus API rate limit exceeded (HTTP %d), please try again later", resp.StatusCode)
+ return "", Retryable(fmt.Errorf("Sploitus API rate limit exceeded (HTTP %d), please try again later", resp.StatusCode), 0)
}
if resp.StatusCode != http.StatusOK {
- return "", fmt.Errorf("Sploitus API returned HTTP %d", resp.StatusCode)
+ err := fmt.Errorf("Sploitus API returned HTTP %d", resp.StatusCode)
+ if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
+ return "", Retryable(err, 0)
+ }
+ return "", Fatal(err)
}
var apiResp sploitusResponse
if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
- return "", fmt.Errorf("failed to decode Sploitus response: %w", err)
+ return "", Fatal(fmt.Errorf("failed to decode Sploitus response: %w", err))
}
return formatSploitusResults(query, exploitType, limit, apiResp), nil
diff --git a/backend/pkg/tools/sploitus_test.go b/backend/pkg/tools/searchers/sploitus_test.go
similarity index 83%
rename from backend/pkg/tools/sploitus_test.go
rename to backend/pkg/tools/searchers/sploitus_test.go
index 7df00229..f9c6c292 100644
--- a/backend/pkg/tools/sploitus_test.go
+++ b/backend/pkg/tools/searchers/sploitus_test.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"fmt"
@@ -66,28 +66,24 @@ func TestSploitusHandle(t *testing.T) {
}
defer proxy.Close()
- flowID := int64(1)
- taskID := int64(10)
- subtaskID := int64(20)
- slp := &searchLogProviderMock{}
-
cfg := &config.Config{
SploitusEnabled: true,
ProxyURL: proxy.URL(),
ExternalSSLCAPath: proxy.CACertPath(),
}
- sp := NewSploitusTool(cfg, flowID, &taskID, &subtaskID, slp)
+ sp := NewSploitus(cfg)
- ctx := PutAgentContext(t.Context(), database.MsgchainTypeSearcher)
got, err := sp.Handle(
- ctx,
- SploitusToolName,
- []byte(`{"query":"nginx","exploit_type":"exploits","sort":"date","max_results":5}`),
+ t.Context(),
+ Request{Query: "nginx", ExploitType: "exploits", Sort: "date", MaxResults: 5},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
}
+ if sp.Engine() != database.SearchengineTypeSploitus {
+ t.Errorf("Engine() = %q, want %q", sp.Engine(), database.SearchengineTypeSploitus)
+ }
// Verify mock handler was called
if !seenRequest {
@@ -136,29 +132,6 @@ func TestSploitusHandle(t *testing.T) {
if !strings.Contains(got, "Test Exploit for nginx") {
t.Errorf("result missing expected title: %q", got)
}
-
- // Verify search log was written with agent context
- if slp.calls != 1 {
- t.Errorf("PutLog() calls = %d, want 1", slp.calls)
- }
- if slp.engine != database.SearchengineTypeSploitus {
- t.Errorf("engine = %q, want %q", slp.engine, database.SearchengineTypeSploitus)
- }
- if slp.query != "nginx" {
- t.Errorf("logged query = %q, want %q", slp.query, "nginx")
- }
- if slp.parentType != database.MsgchainTypeSearcher {
- t.Errorf("parent agent type = %q, want %q", slp.parentType, database.MsgchainTypeSearcher)
- }
- if slp.currType != database.MsgchainTypeSearcher {
- t.Errorf("current agent type = %q, want %q", slp.currType, database.MsgchainTypeSearcher)
- }
- if slp.taskID == nil || *slp.taskID != taskID {
- t.Errorf("task ID = %v, want %d", slp.taskID, taskID)
- }
- if slp.subtaskID == nil || *slp.subtaskID != subtaskID {
- t.Errorf("subtask ID = %v, want %d", slp.subtaskID, subtaskID)
- }
}
func TestSploitusIsAvailable(t *testing.T) {
@@ -194,16 +167,8 @@ func TestSploitusIsAvailable(t *testing.T) {
}
}
-func TestSploitusHandle_ValidationAndSwallowedError(t *testing.T) {
- t.Run("invalid json", func(t *testing.T) {
- sp := &sploitus{cfg: testSploitusConfig()}
- _, err := sp.Handle(t.Context(), SploitusToolName, []byte("{"))
- if err == nil || !strings.Contains(err.Error(), "failed to unmarshal") {
- t.Fatalf("expected unmarshal error, got: %v", err)
- }
- })
-
- t.Run("search error swallowed", func(t *testing.T) {
+func TestSploitusHandle_ReturnsTypedError(t *testing.T) {
+ t.Run("search error returned as typed error", func(t *testing.T) {
var seenRequest bool
mockMux := http.NewServeMux()
mockMux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
@@ -218,7 +183,6 @@ func TestSploitusHandle_ValidationAndSwallowedError(t *testing.T) {
defer proxy.Close()
sp := &sploitus{
- flowID: 1,
cfg: &config.Config{
SploitusEnabled: true,
ProxyURL: proxy.URL(),
@@ -228,21 +192,23 @@ func TestSploitusHandle_ValidationAndSwallowedError(t *testing.T) {
result, err := sp.Handle(
t.Context(),
- SploitusToolName,
- []byte(`{"query":"test","exploit_type":"exploits"}`),
+ Request{Query: "test", ExploitType: "exploits"},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
// Verify mock handler was called (request was intercepted)
if !seenRequest {
t.Error("request was not intercepted by proxy - mock handler was not called")
}
- // Verify error was swallowed and returned as string
- if !strings.Contains(result, "failed to search in Sploitus") {
- t.Errorf("Handle() = %q, expected swallowed error message", result)
+ // The error is now surfaced (not swallowed) and classified. A 502 is retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
})
}
@@ -272,7 +238,6 @@ func TestSploitusHandle_StatusCodeErrors(t *testing.T) {
defer proxy.Close()
sp := &sploitus{
- flowID: 1,
cfg: &config.Config{
SploitusEnabled: true,
ProxyURL: proxy.URL(),
@@ -282,19 +247,21 @@ func TestSploitusHandle_StatusCodeErrors(t *testing.T) {
result, err := sp.Handle(
t.Context(),
- SploitusToolName,
- []byte(`{"query":"test","exploit_type":"exploits"}`),
+ Request{Query: "test", ExploitType: "exploits"},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
- // Error should be swallowed and returned as string
- if !strings.Contains(result, "failed to search in Sploitus") {
- t.Errorf("Handle() = %q, expected swallowed error", result)
+ // Errors are now surfaced (not swallowed). 499/422 and 5xx are all retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
- if !strings.Contains(result, tt.errContain) {
- t.Errorf("Handle() = %q, expected to contain %q", result, tt.errContain)
+ if !strings.Contains(err.Error(), tt.errContain) {
+ t.Errorf("Handle() error = %v, expected to contain %q", err, tt.errContain)
}
})
}
@@ -437,7 +404,6 @@ func TestSploitusDefaultValues(t *testing.T) {
defer proxy.Close()
sp := &sploitus{
- flowID: 1,
cfg: &config.Config{
SploitusEnabled: true,
ProxyURL: proxy.URL(),
@@ -445,11 +411,10 @@ func TestSploitusDefaultValues(t *testing.T) {
},
}
- // Test with minimal action (only query, no type/sort/maxResults)
+ // Test with minimal request (only query, no type/sort/maxResults)
_, err = sp.Handle(
t.Context(),
- SploitusToolName,
- []byte(`{"query":"test"}`),
+ Request{Query: "test"},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
diff --git a/backend/pkg/tools/tavily.go b/backend/pkg/tools/searchers/tavily.go
similarity index 72%
rename from backend/pkg/tools/tavily.go
rename to backend/pkg/tools/searchers/tavily.go
index 6e283ebb..98f09e5b 100644
--- a/backend/pkg/tools/tavily.go
+++ b/backend/pkg/tools/searchers/tavily.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"bytes"
@@ -20,7 +20,7 @@ import (
const tavilyURL = "https://api.tavily.com/search"
-const maxRawContentLength = 3000
+const maxRawContentLength = 8192
type tavilyRequest struct {
ApiKey string `json:"api_key"`
@@ -52,83 +52,49 @@ type tavilyResult struct {
type tavily struct {
cfg *config.Config
- flowID int64
- taskID *int64
- subtaskID *int64
- slp SearchLogProvider
summarizer SummarizeHandler
}
-func NewTavilyTool(
- cfg *config.Config,
- flowID int64,
- taskID, subtaskID *int64,
- slp SearchLogProvider,
- summarizer SummarizeHandler,
-) Tool {
+func NewTavily(cfg *config.Config, summarizer SummarizeHandler) Searcher {
return &tavily{
cfg: cfg,
- flowID: flowID,
- taskID: taskID,
- subtaskID: subtaskID,
- slp: slp,
summarizer: summarizer,
}
}
-func (t *tavily) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+func (t *tavily) Engine() database.SearchengineType {
+ return database.SearchengineTypeTavily
+}
+
+func (t *tavily) Handle(ctx context.Context, req Request) (string, error) {
if !t.IsAvailable() {
- return "", fmt.Errorf("tavily is not available")
+ return "", ErrNotConfigured
}
- var action SearchAction
ctx, observation := obs.Observer.NewObservation(ctx)
- logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(t.flowID, t.taskID, t.subtaskID, logrus.Fields{
- "tool": name,
- "args": string(args),
- }))
-
- if err := json.Unmarshal(args, &action); err != nil {
- logger.WithError(err).Error("failed to unmarshal tavily search action")
- return "", fmt.Errorf("failed to unmarshal %s search action arguments: %w", name, err)
- }
-
- logger = logger.WithFields(logrus.Fields{
- "query": action.Query[:min(len(action.Query), 1000)],
- "max_results": action.MaxResults,
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "tavily",
+ "query": req.Query[:min(len(req.Query), 1000)],
+ "max_results": req.MaxResults,
})
- result, err := t.search(ctx, action.Query, action.MaxResults.Int())
+ result, err := t.search(ctx, req.Query, req.MaxResults)
if err != nil {
observation.Event(
- langfuse.WithEventName("search engine error swallowed"),
- langfuse.WithEventInput(action.Query),
+ langfuse.WithEventName("search engine error"),
+ langfuse.WithEventInput(req.Query),
langfuse.WithEventStatus(err.Error()),
langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
langfuse.WithEventMetadata(langfuse.Metadata{
- "tool_name": TavilyToolName,
"engine": "tavily",
- "query": action.Query,
- "max_results": action.MaxResults.Int(),
+ "query": req.Query,
+ "max_results": req.MaxResults,
"error": err.Error(),
}),
)
logger.WithError(err).Error("failed to search in tavily")
- return fmt.Sprintf("failed to search in tavily: %v", err), nil
- }
-
- if agentCtx, ok := GetAgentContext(ctx); ok {
- _, _ = t.slp.PutLog(
- ctx,
- agentCtx.ParentAgentType,
- agentCtx.CurrentAgentType,
- database.SearchengineTypeTavily,
- action.Query,
- result,
- t.taskID,
- t.subtaskID,
- )
+ return "", err
}
return result, nil
@@ -137,7 +103,7 @@ func (t *tavily) Handle(ctx context.Context, name string, args json.RawMessage)
func (t *tavily) search(ctx context.Context, query string, maxResults int) (string, error) {
client, err := system.GetHTTPClient(t.cfg)
if err != nil {
- return "", fmt.Errorf("failed to create http client: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create http client: %w", err))
}
reqPayload := tavilyRequest{
@@ -152,12 +118,12 @@ func (t *tavily) search(ctx context.Context, query string, maxResults int) (stri
}
reqBody, err := json.Marshal(reqPayload)
if err != nil {
- return "", fmt.Errorf("failed to marshal request body: %v", err)
+ return "", Fatal(fmt.Errorf("failed to marshal request body: %v", err))
}
req, err := http.NewRequest(http.MethodPost, tavilyURL, bytes.NewBuffer(reqBody))
if err != nil {
- return "", fmt.Errorf("failed to build request: %v", err)
+ return "", Fatal(fmt.Errorf("failed to build request: %v", err))
}
req = req.WithContext(ctx)
@@ -165,7 +131,7 @@ func (t *tavily) search(ctx context.Context, query string, maxResults int) (stri
resp, err := client.Do(req)
if err != nil {
- return "", fmt.Errorf("failed to do request: %v", err)
+ return "", Retryable(fmt.Errorf("failed to do request: %v", err), 0)
}
defer resp.Body.Close()
@@ -177,31 +143,31 @@ func (t *tavily) parseHTTPResponse(ctx context.Context, resp *http.Response) (st
case http.StatusOK:
var respBody tavilySearchResult
if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil {
- return "", fmt.Errorf("failed to decode response body: %v", err)
+ return "", Fatal(fmt.Errorf("failed to decode response body: %v", err))
}
return t.buildTavilyResult(ctx, &respBody), nil
case http.StatusBadRequest:
- return "", fmt.Errorf("request is invalid")
+ return "", Fatal(fmt.Errorf("request is invalid"))
case http.StatusUnauthorized:
- return "", fmt.Errorf("API key is wrong")
+ return "", Fatal(fmt.Errorf("API key is wrong"))
case http.StatusForbidden:
- return "", fmt.Errorf("the endpoint requested is hidden for administrators only")
+ return "", Fatal(fmt.Errorf("the endpoint requested is hidden for administrators only"))
case http.StatusNotFound:
- return "", fmt.Errorf("the specified endpoint could not be found")
+ return "", Fatal(fmt.Errorf("the specified endpoint could not be found"))
case http.StatusMethodNotAllowed:
- return "", fmt.Errorf("there need to try to access an endpoint with an invalid method")
+ return "", Fatal(fmt.Errorf("there need to try to access an endpoint with an invalid method"))
case http.StatusTooManyRequests:
- return "", fmt.Errorf("there are requesting too many results")
+ return "", Retryable(fmt.Errorf("there are requesting too many results"), 0)
case http.StatusInternalServerError:
- return "", fmt.Errorf("there had a problem with our server. try again later")
+ return "", Retryable(fmt.Errorf("there had a problem with our server. try again later"), 0)
case http.StatusBadGateway:
- return "", fmt.Errorf("there was a problem with the server. Please try again later")
+ return "", Retryable(fmt.Errorf("there was a problem with the server. Please try again later"), 0)
case http.StatusServiceUnavailable:
- return "", fmt.Errorf("there are temporarily offline for maintenance. please try again later")
+ return "", Retryable(fmt.Errorf("there are temporarily offline for maintenance. please try again later"), 0)
case http.StatusGatewayTimeout:
- return "", fmt.Errorf("there are temporarily offline for maintenance. please try again later")
+ return "", Retryable(fmt.Errorf("there are temporarily offline for maintenance. please try again later"), 0)
default:
- return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ return "", Fatal(fmt.Errorf("unexpected status code: %d", resp.StatusCode))
}
}
diff --git a/backend/pkg/tools/tavily_test.go b/backend/pkg/tools/searchers/tavily_test.go
similarity index 82%
rename from backend/pkg/tools/tavily_test.go
rename to backend/pkg/tools/searchers/tavily_test.go
index 9efbf2df..c03094fc 100644
--- a/backend/pkg/tools/tavily_test.go
+++ b/backend/pkg/tools/searchers/tavily_test.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"context"
@@ -46,11 +46,6 @@ func TestTavilyHandle(t *testing.T) {
}
defer proxy.Close()
- flowID := int64(1)
- taskID := int64(10)
- subtaskID := int64(20)
- slp := &searchLogProviderMock{}
-
cfg := &config.Config{
TavilyAPIKey: testTavilyAPIKey,
ProxyURL: proxy.URL(),
@@ -58,17 +53,18 @@ func TestTavilyHandle(t *testing.T) {
ExternalSSLInsecure: false,
}
- tav := NewTavilyTool(cfg, flowID, &taskID, &subtaskID, slp, nil)
+ tav := NewTavily(cfg, nil)
- ctx := PutAgentContext(t.Context(), database.MsgchainTypeSearcher)
got, err := tav.Handle(
- ctx,
- TavilyToolName,
- []byte(`{"query":"test query","max_results":5,"message":"m"}`),
+ t.Context(),
+ Request{Query: "test query", MaxResults: 5},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
}
+ if tav.Engine() != database.SearchengineTypeTavily {
+ t.Errorf("Engine() = %q, want %q", tav.Engine(), database.SearchengineTypeTavily)
+ }
// Verify mock handler was called
if !seenRequest {
@@ -106,28 +102,6 @@ func TestTavilyHandle(t *testing.T) {
t.Errorf("result missing expected URL 'https://example.com': %q", got)
}
- // Verify search log was written with agent context
- if slp.calls != 1 {
- t.Errorf("PutLog() calls = %d, want 1", slp.calls)
- }
- if slp.engine != database.SearchengineTypeTavily {
- t.Errorf("engine = %q, want %q", slp.engine, database.SearchengineTypeTavily)
- }
- if slp.query != "test query" {
- t.Errorf("logged query = %q, want %q", slp.query, "test query")
- }
- if slp.parentType != database.MsgchainTypeSearcher {
- t.Errorf("parent agent type = %q, want %q", slp.parentType, database.MsgchainTypeSearcher)
- }
- if slp.currType != database.MsgchainTypeSearcher {
- t.Errorf("current agent type = %q, want %q", slp.currType, database.MsgchainTypeSearcher)
- }
- if slp.taskID == nil || *slp.taskID != taskID {
- t.Errorf("task ID = %v, want %d", slp.taskID, taskID)
- }
- if slp.subtaskID == nil || *slp.subtaskID != subtaskID {
- t.Errorf("subtask ID = %v, want %d", slp.subtaskID, subtaskID)
- }
}
func TestTavilyIsAvailable(t *testing.T) {
@@ -164,7 +138,7 @@ func TestTavilyIsAvailable(t *testing.T) {
}
func TestTavilyParseHTTPResponse_StatusAndDecodeErrors(t *testing.T) {
- tav := &tavily{flowID: 1}
+ tav := &tavily{}
tests := []struct {
name string
@@ -381,16 +355,8 @@ func TestTavilyBuildResult_WithSummarizer(t *testing.T) {
})
}
-func TestTavilyHandle_ValidationAndSwallowedError(t *testing.T) {
- t.Run("invalid json", func(t *testing.T) {
- tav := &tavily{cfg: testTavilyConfig()}
- _, err := tav.Handle(t.Context(), TavilyToolName, []byte("{"))
- if err == nil || !strings.Contains(err.Error(), "failed to unmarshal") {
- t.Fatalf("expected unmarshal error, got: %v", err)
- }
- })
-
- t.Run("search error swallowed", func(t *testing.T) {
+func TestTavilyHandle_ReturnsTypedError(t *testing.T) {
+ t.Run("upstream 502 returns a retryable error", func(t *testing.T) {
var seenRequest bool
mockMux := http.NewServeMux()
mockMux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
@@ -405,7 +371,6 @@ func TestTavilyHandle_ValidationAndSwallowedError(t *testing.T) {
defer proxy.Close()
tav := &tavily{
- flowID: 1,
cfg: &config.Config{
TavilyAPIKey: testTavilyAPIKey,
ProxyURL: proxy.URL(),
@@ -416,21 +381,23 @@ func TestTavilyHandle_ValidationAndSwallowedError(t *testing.T) {
result, err := tav.Handle(
t.Context(),
- TavilyToolName,
- []byte(`{"query":"q","max_results":5,"message":"m"}`),
+ Request{Query: "q", MaxResults: 5},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
// Verify mock handler was called (request was intercepted)
if !seenRequest {
t.Error("request was not intercepted by proxy - mock handler was not called")
}
- // Verify error was swallowed and returned as string
- if !strings.Contains(result, "failed to search in tavily") {
- t.Errorf("Handle() = %q, expected swallowed error message", result)
+ // The error is now surfaced (not swallowed) and classified. A 502 is retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
})
}
diff --git a/backend/pkg/tools/testdata/ddg_result_docker_security.html b/backend/pkg/tools/searchers/testdata/ddg_result_docker_security.html
similarity index 100%
rename from backend/pkg/tools/testdata/ddg_result_docker_security.html
rename to backend/pkg/tools/searchers/testdata/ddg_result_docker_security.html
diff --git a/backend/pkg/tools/testdata/ddg_result_golang_http_client.html b/backend/pkg/tools/searchers/testdata/ddg_result_golang_http_client.html
similarity index 100%
rename from backend/pkg/tools/testdata/ddg_result_golang_http_client.html
rename to backend/pkg/tools/searchers/testdata/ddg_result_golang_http_client.html
diff --git a/backend/pkg/tools/testdata/ddg_result_owasp_vulnerabilities.html b/backend/pkg/tools/searchers/testdata/ddg_result_owasp_vulnerabilities.html
similarity index 100%
rename from backend/pkg/tools/testdata/ddg_result_owasp_vulnerabilities.html
rename to backend/pkg/tools/searchers/testdata/ddg_result_owasp_vulnerabilities.html
diff --git a/backend/pkg/tools/testdata/ddg_result_site_github_golang.html b/backend/pkg/tools/searchers/testdata/ddg_result_site_github_golang.html
similarity index 100%
rename from backend/pkg/tools/testdata/ddg_result_site_github_golang.html
rename to backend/pkg/tools/searchers/testdata/ddg_result_site_github_golang.html
diff --git a/backend/pkg/tools/testdata/ddg_result_sql_injection.html b/backend/pkg/tools/searchers/testdata/ddg_result_sql_injection.html
similarity index 100%
rename from backend/pkg/tools/testdata/ddg_result_sql_injection.html
rename to backend/pkg/tools/searchers/testdata/ddg_result_sql_injection.html
diff --git a/backend/pkg/tools/testdata/sploitus_result_cve_2026.json b/backend/pkg/tools/searchers/testdata/sploitus_result_cve_2026.json
similarity index 100%
rename from backend/pkg/tools/testdata/sploitus_result_cve_2026.json
rename to backend/pkg/tools/searchers/testdata/sploitus_result_cve_2026.json
diff --git a/backend/pkg/tools/testdata/sploitus_result_metasploit.json b/backend/pkg/tools/searchers/testdata/sploitus_result_metasploit.json
similarity index 100%
rename from backend/pkg/tools/testdata/sploitus_result_metasploit.json
rename to backend/pkg/tools/searchers/testdata/sploitus_result_metasploit.json
diff --git a/backend/pkg/tools/testdata/sploitus_result_nginx.json b/backend/pkg/tools/searchers/testdata/sploitus_result_nginx.json
similarity index 100%
rename from backend/pkg/tools/testdata/sploitus_result_nginx.json
rename to backend/pkg/tools/searchers/testdata/sploitus_result_nginx.json
diff --git a/backend/pkg/tools/testdata/sploitus_result_nmap.json b/backend/pkg/tools/searchers/testdata/sploitus_result_nmap.json
similarity index 100%
rename from backend/pkg/tools/testdata/sploitus_result_nmap.json
rename to backend/pkg/tools/searchers/testdata/sploitus_result_nmap.json
diff --git a/backend/pkg/tools/traversaal.go b/backend/pkg/tools/searchers/traversaal.go
similarity index 51%
rename from backend/pkg/tools/traversaal.go
rename to backend/pkg/tools/searchers/traversaal.go
index 326611b7..58864f3a 100644
--- a/backend/pkg/tools/traversaal.go
+++ b/backend/pkg/tools/searchers/traversaal.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"bytes"
@@ -25,81 +25,44 @@ type traversaalSearchResult struct {
}
type traversaal struct {
- cfg *config.Config
- flowID int64
- taskID *int64
- subtaskID *int64
- slp SearchLogProvider
+ cfg *config.Config
}
-func NewTraversaalTool(
- cfg *config.Config,
- flowID int64,
- taskID, subtaskID *int64,
- slp SearchLogProvider,
-) Tool {
- return &traversaal{
- cfg: cfg,
- flowID: flowID,
- taskID: taskID,
- subtaskID: subtaskID,
- slp: slp,
- }
+func NewTraversaal(cfg *config.Config) Searcher {
+ return &traversaal{cfg: cfg}
+}
+
+func (t *traversaal) Engine() database.SearchengineType {
+ return database.SearchengineTypeTraversaal
}
-func (t *traversaal) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+func (t *traversaal) Handle(ctx context.Context, req Request) (string, error) {
if !t.IsAvailable() {
- return "", fmt.Errorf("traversaal is not available")
+ return "", ErrNotConfigured
}
- var action SearchAction
ctx, observation := obs.Observer.NewObservation(ctx)
- logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(t.flowID, t.taskID, t.subtaskID, logrus.Fields{
- "tool": name,
- "args": string(args),
- }))
-
- if err := json.Unmarshal(args, &action); err != nil {
- logger.WithError(err).Error("failed to unmarshal traversaal search action")
- return "", fmt.Errorf("failed to unmarshal %s search action arguments: %w", name, err)
- }
-
- logger = logger.WithFields(logrus.Fields{
- "query": action.Query[:min(len(action.Query), 1000)],
- "max_results": action.MaxResults,
+ logger := logrus.WithContext(ctx).WithFields(logrus.Fields{
+ "engine": "traversaal",
+ "query": req.Query[:min(len(req.Query), 1000)],
})
- result, err := t.search(ctx, action.Query)
+ result, err := t.search(ctx, req.Query)
if err != nil {
observation.Event(
- langfuse.WithEventName("search engine error swallowed"),
- langfuse.WithEventInput(action.Query),
+ langfuse.WithEventName("search engine error"),
+ langfuse.WithEventInput(req.Query),
langfuse.WithEventStatus(err.Error()),
langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
langfuse.WithEventMetadata(langfuse.Metadata{
- "tool_name": TraversaalToolName,
- "engine": "traversaal",
- "query": action.Query,
- "max_results": action.MaxResults.Int(),
- "error": err.Error(),
+ "engine": "traversaal",
+ "query": req.Query,
+ "error": err.Error(),
}),
)
logger.WithError(err).Error("failed to search in traversaal")
- return fmt.Sprintf("failed to search in traversaal: %v", err), nil
- }
-
- if agentCtx, ok := GetAgentContext(ctx); ok {
- _, _ = t.slp.PutLog(
- ctx,
- agentCtx.ParentAgentType,
- agentCtx.CurrentAgentType,
- database.SearchengineTypeTraversaal,
- action.Query,
- result,
- t.taskID,
- t.subtaskID,
- )
+ return "", err
}
return result, nil
@@ -108,7 +71,7 @@ func (t *traversaal) Handle(ctx context.Context, name string, args json.RawMessa
func (t *traversaal) search(ctx context.Context, query string) (string, error) {
client, err := system.GetHTTPClient(t.cfg)
if err != nil {
- return "", fmt.Errorf("failed to create http client: %w", err)
+ return "", Fatal(fmt.Errorf("failed to create http client: %w", err))
}
reqBody, err := json.Marshal(struct {
@@ -117,12 +80,12 @@ func (t *traversaal) search(ctx context.Context, query string) (string, error) {
Query: query,
})
if err != nil {
- return "", fmt.Errorf("failed to marshal request body: %v", err)
+ return "", Fatal(fmt.Errorf("failed to marshal request body: %v", err))
}
req, err := http.NewRequest(http.MethodPost, traversaalURL, bytes.NewBuffer(reqBody))
if err != nil {
- return "", fmt.Errorf("failed to build request: %v", err)
+ return "", Fatal(fmt.Errorf("failed to build request: %v", err))
}
req = req.WithContext(ctx)
@@ -131,7 +94,7 @@ func (t *traversaal) search(ctx context.Context, query string) (string, error) {
resp, err := client.Do(req)
if err != nil {
- return "", fmt.Errorf("failed to do request: %v", err)
+ return "", Retryable(fmt.Errorf("failed to do request: %v", err), 0)
}
defer resp.Body.Close()
@@ -140,13 +103,17 @@ func (t *traversaal) search(ctx context.Context, query string) (string, error) {
func (t *traversaal) parseHTTPResponse(resp *http.Response) (string, error) {
if resp.StatusCode != http.StatusOK {
- return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ err := fmt.Errorf("unexpected status code: %d", resp.StatusCode)
+ if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
+ return "", Retryable(err, 0)
+ }
+ return "", Fatal(err)
}
var respBody struct {
Data traversaalSearchResult `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&respBody); err != nil {
- return "", fmt.Errorf("failed to decode response body: %v", err)
+ return "", Fatal(fmt.Errorf("failed to decode response body: %v", err))
}
var writer strings.Builder
diff --git a/backend/pkg/tools/traversaal_test.go b/backend/pkg/tools/searchers/traversaal_test.go
similarity index 70%
rename from backend/pkg/tools/traversaal_test.go
rename to backend/pkg/tools/searchers/traversaal_test.go
index be6c37a5..25a6f857 100644
--- a/backend/pkg/tools/traversaal_test.go
+++ b/backend/pkg/tools/searchers/traversaal_test.go
@@ -1,4 +1,4 @@
-package tools
+package searchers
import (
"io"
@@ -47,11 +47,6 @@ func TestTraversaalHandle(t *testing.T) {
}
defer proxy.Close()
- flowID := int64(1)
- taskID := int64(10)
- subtaskID := int64(20)
- slp := &searchLogProviderMock{}
-
cfg := &config.Config{
TraversaalAPIKey: testTraversaalAPIKey,
ProxyURL: proxy.URL(),
@@ -59,17 +54,18 @@ func TestTraversaalHandle(t *testing.T) {
ExternalSSLInsecure: false,
}
- trav := NewTraversaalTool(cfg, flowID, &taskID, &subtaskID, slp)
+ trav := NewTraversaal(cfg)
- ctx := PutAgentContext(t.Context(), database.MsgchainTypeSearcher)
got, err := trav.Handle(
- ctx,
- TraversaalToolName,
- []byte(`{"query":"test query","max_results":5,"message":"m"}`),
+ t.Context(),
+ Request{Query: "test query"},
)
if err != nil {
t.Fatalf("Handle() unexpected error: %v", err)
}
+ if trav.Engine() != database.SearchengineTypeTraversaal {
+ t.Errorf("Engine() = %q, want %q", trav.Engine(), database.SearchengineTypeTraversaal)
+ }
// Verify mock handler was called
if !seenRequest {
@@ -106,29 +102,6 @@ func TestTraversaalHandle(t *testing.T) {
if !strings.Contains(got, "https://b.com") {
t.Errorf("result missing expected link 'https://b.com': %q", got)
}
-
- // Verify search log was written with agent context
- if slp.calls != 1 {
- t.Errorf("PutLog() calls = %d, want 1", slp.calls)
- }
- if slp.engine != database.SearchengineTypeTraversaal {
- t.Errorf("engine = %q, want %q", slp.engine, database.SearchengineTypeTraversaal)
- }
- if slp.query != "test query" {
- t.Errorf("logged query = %q, want %q", slp.query, "test query")
- }
- if slp.parentType != database.MsgchainTypeSearcher {
- t.Errorf("parent agent type = %q, want %q", slp.parentType, database.MsgchainTypeSearcher)
- }
- if slp.currType != database.MsgchainTypeSearcher {
- t.Errorf("current agent type = %q, want %q", slp.currType, database.MsgchainTypeSearcher)
- }
- if slp.taskID == nil || *slp.taskID != taskID {
- t.Errorf("task ID = %v, want %d", slp.taskID, taskID)
- }
- if slp.subtaskID == nil || *slp.subtaskID != subtaskID {
- t.Errorf("subtask ID = %v, want %d", slp.subtaskID, subtaskID)
- }
}
func TestTraversaalIsAvailable(t *testing.T) {
@@ -165,7 +138,7 @@ func TestTraversaalIsAvailable(t *testing.T) {
}
func TestTraversaalParseHTTPResponse_StatusAndDecodeErrors(t *testing.T) {
- trav := &traversaal{flowID: 1}
+ trav := &traversaal{}
t.Run("status error", func(t *testing.T) {
resp := &http.Response{
@@ -190,16 +163,8 @@ func TestTraversaalParseHTTPResponse_StatusAndDecodeErrors(t *testing.T) {
})
}
-func TestTraversaalHandle_ValidationAndSwallowedError(t *testing.T) {
- t.Run("invalid json", func(t *testing.T) {
- trav := &traversaal{cfg: testTraversaalConfig()}
- _, err := trav.Handle(t.Context(), TraversaalToolName, []byte("{"))
- if err == nil || !strings.Contains(err.Error(), "failed to unmarshal") {
- t.Fatalf("expected unmarshal error, got: %v", err)
- }
- })
-
- t.Run("search error swallowed", func(t *testing.T) {
+func TestTraversaalHandle_ReturnsTypedError(t *testing.T) {
+ t.Run("upstream 502 returns a retryable error", func(t *testing.T) {
var seenRequest bool
mockMux := http.NewServeMux()
mockMux.HandleFunc("/live/predict", func(w http.ResponseWriter, r *http.Request) {
@@ -214,7 +179,6 @@ func TestTraversaalHandle_ValidationAndSwallowedError(t *testing.T) {
defer proxy.Close()
trav := &traversaal{
- flowID: 1,
cfg: &config.Config{
TraversaalAPIKey: testTraversaalAPIKey,
ProxyURL: proxy.URL(),
@@ -225,21 +189,23 @@ func TestTraversaalHandle_ValidationAndSwallowedError(t *testing.T) {
result, err := trav.Handle(
t.Context(),
- TraversaalToolName,
- []byte(`{"query":"q","max_results":5,"message":"m"}`),
+ Request{Query: "q"},
)
- if err != nil {
- t.Fatalf("Handle() unexpected error: %v", err)
- }
// Verify mock handler was called (request was intercepted)
if !seenRequest {
t.Error("request was not intercepted by proxy - mock handler was not called")
}
- // Verify error was swallowed and returned as string
- if !strings.Contains(result, "failed to search in traversaal") {
- t.Errorf("Handle() = %q, expected swallowed error message", result)
+ // The error is now surfaced (not swallowed) and classified. A 502 is retryable.
+ if err == nil {
+ t.Fatal("Handle() expected an error, got nil")
+ }
+ if result != "" {
+ t.Errorf("Handle() result = %q, want empty on error", result)
+ }
+ if !IsRetryable(err) {
+ t.Errorf("Handle() error = %v, want a RetryableError", err)
}
})
}
diff --git a/backend/pkg/tools/tools.go b/backend/pkg/tools/tools.go
index 1afa672e..fa2cd322 100644
--- a/backend/pkg/tools/tools.go
+++ b/backend/pkg/tools/tools.go
@@ -922,90 +922,12 @@ func (fte *flowToolsExecutor) GetAssistantExecutor(cfg AssistantExecutorConfig)
definitions = append(definitions, registryDefinitions[SearchCodeToolName])
handlers[SearchCodeToolName] = code.Handle
}
+ }
- google := NewGoogleTool(
- fte.cfg,
- fte.flowID, nil, nil,
- fte.slp,
- )
- if google.IsAvailable() {
- definitions = append(definitions, registryDefinitions[GoogleToolName])
- handlers[GoogleToolName] = google.Handle
- }
-
- duckduckgo := NewDuckDuckGoTool(
- fte.cfg,
- fte.flowID, nil, nil,
- fte.slp,
- )
- if duckduckgo.IsAvailable() {
- definitions = append(definitions, registryDefinitions[DuckDuckGoToolName])
- handlers[DuckDuckGoToolName] = duckduckgo.Handle
- }
-
- tavily := NewTavilyTool(
- fte.cfg,
- fte.flowID, nil, nil,
- fte.slp,
- cfg.Summarizer,
- )
- if tavily.IsAvailable() {
- definitions = append(definitions, registryDefinitions[TavilyToolName])
- handlers[TavilyToolName] = tavily.Handle
- }
-
- firecrawl := NewFirecrawlTool(
- fte.cfg,
- fte.flowID, nil, nil,
- fte.slp,
- cfg.Summarizer,
- )
- if firecrawl.IsAvailable() {
- definitions = append(definitions, registryDefinitions[FirecrawlToolName])
- handlers[FirecrawlToolName] = firecrawl.Handle
- }
-
- traversaal := NewTraversaalTool(
- fte.cfg,
- fte.flowID, nil, nil,
- fte.slp,
- )
- if traversaal.IsAvailable() {
- definitions = append(definitions, registryDefinitions[TraversaalToolName])
- handlers[TraversaalToolName] = traversaal.Handle
- }
-
- perplexity := NewPerplexityTool(
- fte.cfg,
- fte.flowID, nil, nil,
- fte.slp,
- cfg.Summarizer,
- )
- if perplexity.IsAvailable() {
- definitions = append(definitions, registryDefinitions[PerplexityToolName])
- handlers[PerplexityToolName] = perplexity.Handle
- }
-
- searxng := NewSearxngTool(
- fte.cfg,
- fte.flowID, nil, nil,
- fte.slp,
- cfg.Summarizer,
- )
- if searxng.IsAvailable() {
- definitions = append(definitions, registryDefinitions[SearxngToolName])
- handlers[SearxngToolName] = searxng.Handle
- }
-
- sploitus := NewSploitusTool(
- fte.cfg,
- fte.flowID, nil, nil,
- fte.slp,
- )
- if sploitus.IsAvailable() {
- definitions = append(definitions, registryDefinitions[SploitusToolName])
- handlers[SploitusToolName] = sploitus.Handle
- }
+ webSearch := buildWebSearch(fte, nil, nil, cfg.Summarizer)
+ if webSearch.IsAvailable() {
+ definitions = append(definitions, registryDefinitions[WebSearchToolName])
+ handlers[WebSearchToolName] = webSearch.Handle
}
flowStatus := NewFlowStatusTool(fte.flowID, fte.db, cfg.Summarizer)
@@ -1468,16 +1390,10 @@ func (fte *flowToolsExecutor) GetPentesterExecutor(cfg PentesterExecutorConfig)
ce.handlers[GraphitiSearchToolName] = graphitiSearch.Handle
}
- sploitus := NewSploitusTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- )
- if sploitus.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[SploitusToolName])
- ce.handlers[SploitusToolName] = sploitus.Handle
+ webSearch := buildWebSearch(fte, cfg.TaskID, cfg.SubtaskID, cfg.Summarizer)
+ if webSearch.IsAvailable() {
+ ce.definitions = append(ce.definitions, registryDefinitions[WebSearchToolName])
+ ce.handlers[WebSearchToolName] = webSearch.Handle
}
return ce, nil
@@ -1530,104 +1446,10 @@ func (fte *flowToolsExecutor) GetSearcherExecutor(cfg SearcherExecutorConfig) (C
ce.handlers[BrowserToolName] = browser.Handle
}
- google := NewGoogleTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- )
- if google.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[GoogleToolName])
- ce.handlers[GoogleToolName] = google.Handle
- }
-
- duckduckgo := NewDuckDuckGoTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- )
- if duckduckgo.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[DuckDuckGoToolName])
- ce.handlers[DuckDuckGoToolName] = duckduckgo.Handle
- }
-
- tavily := NewTavilyTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- cfg.Summarizer,
- )
- if tavily.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[TavilyToolName])
- ce.handlers[TavilyToolName] = tavily.Handle
- }
-
- firecrawl := NewFirecrawlTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- cfg.Summarizer,
- )
- if firecrawl.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[FirecrawlToolName])
- ce.handlers[FirecrawlToolName] = firecrawl.Handle
- }
-
- traversaal := NewTraversaalTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- )
- if traversaal.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[TraversaalToolName])
- ce.handlers[TraversaalToolName] = traversaal.Handle
- }
-
- perplexity := NewPerplexityTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- cfg.Summarizer,
- )
- if perplexity.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[PerplexityToolName])
- ce.handlers[PerplexityToolName] = perplexity.Handle
- }
-
- searxng := NewSearxngTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- cfg.Summarizer,
- )
- if searxng.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[SearxngToolName])
- ce.handlers[SearxngToolName] = searxng.Handle
- }
-
- sploitus := NewSploitusTool(
- fte.cfg,
- fte.flowID,
- cfg.TaskID,
- cfg.SubtaskID,
- fte.slp,
- )
- if sploitus.IsAvailable() {
- ce.definitions = append(ce.definitions, registryDefinitions[SploitusToolName])
- ce.handlers[SploitusToolName] = sploitus.Handle
+ webSearch := buildWebSearch(fte, cfg.TaskID, cfg.SubtaskID, cfg.Summarizer)
+ if webSearch.IsAvailable() {
+ ce.definitions = append(ce.definitions, registryDefinitions[WebSearchToolName])
+ ce.handlers[WebSearchToolName] = webSearch.Handle
}
search := NewSearchTool(
diff --git a/backend/pkg/tools/web_search.go b/backend/pkg/tools/web_search.go
new file mode 100644
index 00000000..6ee41f3c
--- /dev/null
+++ b/backend/pkg/tools/web_search.go
@@ -0,0 +1,482 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "pentagi/pkg/config"
+ "pentagi/pkg/database"
+ obs "pentagi/pkg/observability"
+ "pentagi/pkg/observability/langfuse"
+ "pentagi/pkg/tools/searchers"
+
+ "github.com/sirupsen/logrus"
+)
+
+// ============================================================================
+// web_search engine selection & fallback strategy
+//
+// This block is the SINGLE SOURCE OF TRUTH for how web_search chooses an engine.
+// It is meant to be read and edited by hand: to re-prioritize engines, reorder a
+// slice below; to add a newly-implemented engine, construct it in buildSearchEngines
+// and drop its id into the relevant chains here. Nothing else in this file needs to
+// change to change the behavior.
+// ============================================================================
+
+// Engine identifiers. These are aliases for the database.SearchengineType values so
+// the strategy table reads cleanly AND the winning engine can be logged for
+// attribution with no extra mapping. EngineInternal reuses the (otherwise unused)
+// "browser" attribution value, so the internal analytics engine needs no new enum
+// value and no DB migration.
+const (
+ EngineGoogle = database.SearchengineTypeGoogle
+ EngineDuckDuckGo = database.SearchengineTypeDuckduckgo
+ EngineTavily = database.SearchengineTypeTavily
+ EngineFirecrawl = database.SearchengineTypeFirecrawl
+ EngineTraversaal = database.SearchengineTypeTraversaal
+ EnginePerplexity = database.SearchengineTypePerplexity
+ EngineSearxng = database.SearchengineTypeSearxng
+ EngineSploitus = database.SearchengineTypeSploitus
+ EngineInternal = database.SearchengineTypeBrowser
+)
+
+// SearchMode is the INTENT the agent expresses — the shape of answer it needs. The
+// agent chooses the mode; web_search chooses the concrete engine.
+type SearchMode string
+
+const (
+ // ModeLinks — a ranked list of source links with titles/snippets ("what pages
+ // exist"). Cheapest intent; pure index engines lead.
+ ModeLinks SearchMode = "links"
+
+ // ModeAnswer — a synthesized answer over live sources ("answer my question").
+ // Engines that browse and summarize themselves lead; link engines are the floor.
+ ModeAnswer SearchMode = "answer"
+
+ // ModeResearch — deep, multi-source synthesis with reasoning ("research this").
+ // Most expensive intent; the strongest analytic engine leads.
+ ModeResearch SearchMode = "research"
+
+ // ModeExploit — exploit / PoC / offensive-tool discovery. The exploit index
+ // leads; universal analytic engines and then classic engines back it up.
+ ModeExploit SearchMode = "exploit"
+)
+
+// defaultMode is used when the agent omits `mode` (or sends an unknown one). "answer"
+// is the most generally useful intent and degrades to links on its own chain's tail.
+const defaultMode = ModeAnswer
+
+// fallbackStrategy maps each mode to its ordered engine chain. For a given mode the
+// orchestrator walks the slice in order, SKIPS any engine whose IsAvailable() is
+// false (e.g. no API key configured), and returns the first successful result. The
+// chain is only "exhausted" — and an error surfaced to the LLM — after every
+// AVAILABLE engine in the slice has failed.
+//
+// EngineInternal appears in the analytic chains but is disabled by default
+// (IsAvailable() == cfg.WebSearchInternalEnabled), so it is skipped unless the
+// operator opts in via WEB_SEARCH_INTERNAL_ENABLED=true.
+var fallbackStrategy = map[SearchMode][]database.SearchengineType{
+ // 1. Link discovery — cheap index engines first, ordered by breadth/consistency;
+ // analytic engines are a deep last resort so links never dead-ends.
+ ModeLinks: {
+ EngineGoogle, EngineDuckDuckGo, EngineSearxng, EngineFirecrawl,
+ EngineTavily, EnginePerplexity, EngineTraversaal,
+ },
+
+ // 2. Answer with analysis — engines that navigate + summarize lead; the internal
+ // browser-analytics engine is a mid/late fallback; link engines are the floor.
+ ModeAnswer: {
+ EngineTavily, EngineFirecrawl, EnginePerplexity, EngineInternal, EngineTraversaal,
+ EngineGoogle, EngineDuckDuckGo, EngineSearxng,
+ },
+
+ // 3. Deep research — strongest reasoning engine first, then the rest.
+ ModeResearch: {
+ EnginePerplexity, EngineTavily, EngineFirecrawl, EngineInternal, EngineTraversaal,
+ EngineGoogle, EngineDuckDuckGo, EngineSearxng,
+ },
+
+ // 4. Exploit search — dedicated exploit index first, universal analytic engines
+ // next, classic engines last.
+ ModeExploit: {
+ EngineSploitus, EngineTavily, EngineFirecrawl, EnginePerplexity, EngineInternal,
+ EngineTraversaal, EngineGoogle, EngineDuckDuckGo, EngineSearxng,
+ },
+}
+
+// linkEngineOrder is the priority order of link-discovery engines. It is used to feed
+// the internal analytics engine the URLs to read.
+var linkEngineOrder = []database.SearchengineType{
+ EngineGoogle, EngineDuckDuckGo, EngineSearxng, EngineFirecrawl,
+}
+
+const (
+ // maxEngineAttempts is the per-engine try budget: 1 initial call plus retries for
+ // the retryable error classes (429 / 5xx / transport). Fatal errors never retry.
+ maxEngineAttempts = 2
+ // retryBackoffBase is multiplied by the attempt number for a small linear backoff.
+ retryBackoffBase = 300 * time.Millisecond
+
+ // webSearchDefaultResults is used when the agent omits max_results.
+ webSearchDefaultResults = 5
+ // webSearchMaxResults is the upper clamp (sploitus supports up to 25).
+ webSearchMaxResults = 25
+)
+
+// ============================================================================
+// Orchestrator
+// ============================================================================
+
+type webSearch struct {
+ cfg *config.Config
+ flowID int64
+ taskID *int64
+ subtaskID *int64
+ slp SearchLogProvider
+
+ // engines is the availability-agnostic registry keyed by engine id, built once at
+ // construction. Availability is (re)checked per call so config edits are honored.
+ engines map[database.SearchengineType]searchers.Searcher
+}
+
+// NewWebSearchTool builds the web_search orchestrator. summarizer and fetcher are the
+// flow summarizer and a browser-backed page fetcher (may be nil, which only disables
+// the internal analytics engine).
+func NewWebSearchTool(
+ cfg *config.Config,
+ flowID int64,
+ taskID, subtaskID *int64,
+ slp SearchLogProvider,
+ summarizer SummarizeHandler,
+ fetcher searchers.PageFetcher,
+) Tool {
+ return &webSearch{
+ cfg: cfg,
+ flowID: flowID,
+ taskID: taskID,
+ subtaskID: subtaskID,
+ slp: slp,
+ engines: buildSearchEngines(cfg, summarizer, fetcher),
+ }
+}
+
+// buildSearchEngines constructs every searcher from cfg. To add an engine: construct
+// it here and reference it in fallbackStrategy above.
+func buildSearchEngines(
+ cfg *config.Config,
+ summarizer SummarizeHandler,
+ fetcher searchers.PageFetcher,
+) map[database.SearchengineType]searchers.Searcher {
+ // tools.SummarizeHandler and searchers.SummarizeHandler share an underlying type;
+ // the explicit conversion bridges the two packages without an import cycle.
+ sum := searchers.SummarizeHandler(summarizer)
+
+ engines := map[database.SearchengineType]searchers.Searcher{
+ EngineGoogle: searchers.NewGoogle(cfg),
+ EngineDuckDuckGo: searchers.NewDuckDuckGo(cfg),
+ EngineTavily: searchers.NewTavily(cfg, sum),
+ EngineFirecrawl: searchers.NewFirecrawl(cfg, sum),
+ EngineTraversaal: searchers.NewTraversaal(cfg),
+ EnginePerplexity: searchers.NewPerplexity(cfg, sum),
+ EngineSearxng: searchers.NewSearxng(cfg, sum),
+ EngineSploitus: searchers.NewSploitus(cfg),
+ }
+
+ // The internal analytics engine discovers URLs with the link engines (in priority
+ // order), reads them via the browser fetcher, and summarizes the result.
+ engines[EngineInternal] = NewInternalEngine(cfg, summarizer, fetcher)
+
+ return engines
+}
+
+// NewInternalEngine constructs the internal browser-analytics engine with its link
+// searchers wired in the production priority order (linkEngineOrder). fetcher must be a
+// browser-backed page fetcher (see NewBrowserPageFetcher); a nil fetcher (or a disabled
+// WEB_SEARCH_INTERNAL_ENABLED) yields an engine that reports IsAvailable()==false. This
+// is the single place the internal engine is assembled, reused by the orchestrator and
+// exposed for the function tester.
+func NewInternalEngine(cfg *config.Config, summarizer SummarizeHandler, fetcher searchers.PageFetcher) searchers.Searcher {
+ sum := searchers.SummarizeHandler(summarizer)
+ byID := map[database.SearchengineType]searchers.Searcher{
+ EngineGoogle: searchers.NewGoogle(cfg),
+ EngineDuckDuckGo: searchers.NewDuckDuckGo(cfg),
+ EngineSearxng: searchers.NewSearxng(cfg, sum),
+ EngineFirecrawl: searchers.NewFirecrawl(cfg, sum),
+ }
+ links := make([]searchers.Searcher, 0, len(linkEngineOrder))
+ for _, id := range linkEngineOrder {
+ if e, ok := byID[id]; ok {
+ links = append(links, e)
+ }
+ }
+ return searchers.NewInternal(cfg, fetcher, links, sum)
+}
+
+// IsAvailable reports whether at least one underlying engine is configured. If none
+// are, web_search is not registered (matching the old per-engine behavior).
+func (w *webSearch) IsAvailable() bool {
+ for _, e := range w.engines {
+ if e != nil && e.IsAvailable() {
+ return true
+ }
+ }
+ return false
+}
+
+func (w *webSearch) Handle(ctx context.Context, name string, args json.RawMessage) (string, error) {
+ var action WebSearchAction
+ if err := json.Unmarshal(args, &action); err != nil {
+ // Malformed arguments ARE fixable by the tool-call arg-fixer, so this is the
+ // one case web_search hard-fails (non-nil error) — matching every other tool.
+ return "", fmt.Errorf("failed to unmarshal %s arguments: %w", name, err)
+ }
+
+ query := strings.TrimSpace(action.Query)
+ if query == "" {
+ return "", fmt.Errorf("%s: 'query' is required and cannot be empty", name)
+ }
+
+ mode := normalizeMode(action.Mode.String())
+ req := searchers.Request{
+ Query: query,
+ MaxResults: clampResults(action.MaxResults.Int()),
+ ExploitType: strings.TrimSpace(action.ExploitType.String()),
+ Sort: strings.TrimSpace(action.Sort.String()),
+ }
+
+ ctx, observation := obs.Observer.NewObservation(ctx)
+ logger := logrus.WithContext(ctx).WithFields(enrichLogrusFields(w.flowID, w.taskID, w.subtaskID, logrus.Fields{
+ "tool": name,
+ "mode": string(mode),
+ "query": query[:min(len(query), 1000)],
+ }))
+
+ chain := fallbackStrategy[mode]
+ attempted := 0
+ var lastErr error
+ var lastEngine database.SearchengineType
+
+ for _, engineID := range chain {
+ engine, ok := w.engines[engineID]
+ if !ok || engine == nil || !engine.IsAvailable() {
+ continue
+ }
+
+ attempted++
+ result, err := w.runWithRetry(ctx, engine, req)
+ if err == nil {
+ w.logSearch(ctx, engineID, query, result)
+ observation.Event(
+ langfuse.WithEventName("web_search resolved"),
+ langfuse.WithEventInput(query),
+ langfuse.WithEventLevel(langfuse.ObservationLevelDefault),
+ langfuse.WithEventMetadata(langfuse.Metadata{
+ "tool_name": WebSearchToolName,
+ "mode": string(mode),
+ "engine": string(engineID),
+ "attempts": attempted,
+ }),
+ )
+ logger.WithFields(logrus.Fields{"engine": engineID, "attempts": attempted}).
+ Info("web_search resolved")
+ return result, nil
+ }
+
+ lastErr, lastEngine = err, engineID
+ logger.WithError(err).WithField("engine", engineID).
+ Warn("web_search engine failed, falling back")
+ }
+
+ // The chain is exhausted. This is NOT a malformed-arguments problem, so degrade
+ // gracefully (message + nil error) rather than burning agent retries — matching
+ // the terminal/browser/graphiti convention.
+ if attempted == 0 {
+ msg := fmt.Sprintf(
+ "web_search: no search engine is configured for mode '%s'. "+
+ "Ask the operator to configure at least one provider "+
+ "(e.g. TAVILY_API_KEY, GOOGLE_API_KEY + GOOGLE_CX_KEY, or DUCKDUCKGO_ENABLED).",
+ mode,
+ )
+ observation.Event(
+ langfuse.WithEventName("web_search unavailable"),
+ langfuse.WithEventInput(query),
+ langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
+ langfuse.WithEventMetadata(langfuse.Metadata{
+ "tool_name": WebSearchToolName,
+ "mode": string(mode),
+ "reason": "no engine configured for mode",
+ }),
+ )
+ logger.Warn("web_search has no configured engine for this mode")
+ return msg, nil
+ }
+
+ w.logSearch(ctx, lastEngine, query, "web_search failed: "+errString(lastErr))
+ observation.Event(
+ langfuse.WithEventName("web_search exhausted"),
+ langfuse.WithEventInput(query),
+ langfuse.WithEventStatus(errString(lastErr)),
+ langfuse.WithEventLevel(langfuse.ObservationLevelWarning),
+ langfuse.WithEventMetadata(langfuse.Metadata{
+ "tool_name": WebSearchToolName,
+ "mode": string(mode),
+ "attempts": attempted,
+ "last_engine": string(lastEngine),
+ "error": errString(lastErr),
+ }),
+ )
+ logger.WithError(lastErr).Warn("web_search exhausted all configured engines")
+
+ return fmt.Sprintf(
+ "web_search: all %d configured engine(s) failed for mode '%s'. Last error (%s): %s. "+
+ "Rephrase the query or try a different mode.",
+ attempted, mode, lastEngine, errString(lastErr),
+ ), nil
+}
+
+// runWithRetry runs one engine, retrying only retryable error classes on the SAME
+// engine. Fatal errors (and ErrNotConfigured) return immediately so the caller moves
+// to the next engine without wasting a round-trip.
+func (w *webSearch) runWithRetry(ctx context.Context, engine searchers.Searcher, req searchers.Request) (string, error) {
+ var err error
+ for attempt := 1; attempt <= maxEngineAttempts; attempt++ {
+ var result string
+ result, err = engine.Handle(ctx, req)
+ if err == nil {
+ return result, nil
+ }
+ if !searchers.IsRetryable(err) || attempt == maxEngineAttempts {
+ return "", err
+ }
+
+ delay := retryBackoffBase * time.Duration(attempt)
+ if ra := retryAfter(err); ra > 0 {
+ delay = ra
+ }
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ case <-time.After(delay):
+ }
+ }
+ return "", err
+}
+
+func (w *webSearch) logSearch(ctx context.Context, engine database.SearchengineType, query, result string) {
+ agentCtx, ok := GetAgentContext(ctx)
+ if !ok {
+ return
+ }
+ _, _ = w.slp.PutLog(
+ ctx,
+ agentCtx.ParentAgentType,
+ agentCtx.CurrentAgentType,
+ engine,
+ query,
+ result,
+ w.taskID,
+ w.subtaskID,
+ )
+}
+
+func normalizeMode(mode string) SearchMode {
+ switch SearchMode(strings.ToLower(strings.TrimSpace(mode))) {
+ case ModeLinks:
+ return ModeLinks
+ case ModeAnswer:
+ return ModeAnswer
+ case ModeResearch:
+ return ModeResearch
+ case ModeExploit:
+ return ModeExploit
+ default:
+ return defaultMode
+ }
+}
+
+func clampResults(n int) int {
+ if n < 1 {
+ return webSearchDefaultResults
+ }
+ if n > webSearchMaxResults {
+ return webSearchMaxResults
+ }
+ return n
+}
+
+func retryAfter(err error) time.Duration {
+ var re *searchers.RetryableError
+ if errors.As(err, &re) {
+ return re.RetryAfter
+ }
+ return 0
+}
+
+func errString(err error) string {
+ if err == nil {
+ return "unknown error"
+ }
+ return err.Error()
+}
+
+// ============================================================================
+// Browser-backed page fetcher for the internal analytics engine
+// ============================================================================
+
+// browserMDReader is the subset of the browser tool the internal analytics engine
+// needs. The browser tool's concrete type satisfies it.
+type browserMDReader interface {
+ ContentMD(ctx context.Context, url string) (string, string, error)
+ IsAvailable() bool
+}
+
+// browserPageFetcher adapts the browser tool to searchers.PageFetcher.
+type browserPageFetcher struct {
+ browser browserMDReader
+}
+
+func (f *browserPageFetcher) FetchMarkdown(ctx context.Context, url string) (string, error) {
+ md, _, err := f.browser.ContentMD(ctx, url)
+ return md, err
+}
+
+// newBrowserPageFetcher builds a page fetcher backed by the browser tool/scraper.
+// Returns nil when the scraper is not configured, which disables the internal
+// analytics engine (its IsAvailable() then reports false).
+func newBrowserPageFetcher(fte *flowToolsExecutor, taskID, subtaskID *int64) searchers.PageFetcher {
+ return NewBrowserPageFetcher(fte.flowID, taskID, subtaskID, fte.cfg, fte.scp)
+}
+
+// NewBrowserPageFetcher builds a browser/scraper-backed page fetcher for the internal
+// analytics engine. It returns nil when the scraper is not configured (the internal
+// engine then reports IsAvailable()==false). Exposed so out-of-flow callers such as the
+// function tester can construct the internal engine.
+func NewBrowserPageFetcher(
+ flowID int64,
+ taskID, subtaskID *int64,
+ cfg *config.Config,
+ scp ScreenshotProvider,
+) searchers.PageFetcher {
+ b := NewBrowserTool(
+ flowID, taskID, subtaskID,
+ cfg.DataDir, cfg.ScraperPrivateURL, cfg.ScraperPublicURL,
+ scp,
+ )
+ reader, ok := b.(browserMDReader)
+ if !ok || !reader.IsAvailable() {
+ return nil
+ }
+ return &browserPageFetcher{browser: reader}
+}
+
+// buildWebSearch constructs the web_search orchestrator for an executor context,
+// wiring the browser-backed page fetcher. Shared by GetAssistantExecutor and
+// GetSearcherExecutor so the two call sites never drift.
+func buildWebSearch(fte *flowToolsExecutor, taskID, subtaskID *int64, summarizer SummarizeHandler) Tool {
+ fetcher := newBrowserPageFetcher(fte, taskID, subtaskID)
+ return NewWebSearchTool(fte.cfg, fte.flowID, taskID, subtaskID, fte.slp, summarizer, fetcher)
+}
diff --git a/backend/pkg/tools/web_search_test.go b/backend/pkg/tools/web_search_test.go
new file mode 100644
index 00000000..e93eb7c6
--- /dev/null
+++ b/backend/pkg/tools/web_search_test.go
@@ -0,0 +1,327 @@
+package tools
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+
+ "pentagi/pkg/config"
+ "pentagi/pkg/database"
+ "pentagi/pkg/tools/searchers"
+)
+
+// searchLogProviderMock is a test double for SearchLogProvider. It moved here from the
+// engines' proxy_test.go when those engines were extracted into the searchers
+// subpackage: the searchers no longer write to the DB search-log (the web_search
+// orchestrator does), so the mock now lives alongside the orchestrator's tests.
+var _ SearchLogProvider = &searchLogProviderMock{}
+
+type searchLogProviderMock struct {
+ calls int64
+ engine database.SearchengineType
+ query string
+ result string
+ taskID *int64
+ subtaskID *int64
+ parentType database.MsgchainType
+ currType database.MsgchainType
+}
+
+func (m *searchLogProviderMock) PutLog(
+ _ context.Context,
+ initiator database.MsgchainType,
+ executor database.MsgchainType,
+ engine database.SearchengineType,
+ query string,
+ result string,
+ taskID *int64,
+ subtaskID *int64,
+) (int64, error) {
+ m.calls++
+ m.parentType = initiator
+ m.currType = executor
+ m.engine = engine
+ m.query = query
+ m.result = result
+ m.taskID = taskID
+ m.subtaskID = subtaskID
+ return m.calls, nil
+}
+
+// fakeSearcher is a scriptable searchers.Searcher for orchestrator tests. It records
+// the global call order (via order) so tests can assert the fallback sequence.
+type fakeSearcher struct {
+ engine database.SearchengineType
+ available bool
+ handler func(call int) (string, error)
+ calls int
+ order *[]database.SearchengineType
+}
+
+func (f *fakeSearcher) Engine() database.SearchengineType { return f.engine }
+func (f *fakeSearcher) IsAvailable() bool { return f.available }
+
+func (f *fakeSearcher) Handle(_ context.Context, _ searchers.Request) (string, error) {
+ if f.order != nil {
+ *f.order = append(*f.order, f.engine)
+ }
+ c := f.calls
+ f.calls++
+ if f.handler == nil {
+ return "", searchers.Fatal(errors.New("no handler"))
+ }
+ return f.handler(c)
+}
+
+func newTestWebSearch(slp SearchLogProvider, engines map[database.SearchengineType]searchers.Searcher) *webSearch {
+ return &webSearch{
+ cfg: &config.Config{},
+ flowID: 1,
+ slp: slp,
+ engines: engines,
+ }
+}
+
+func webSearchArgs(t *testing.T, mode, query string) []byte {
+ t.Helper()
+ if mode == "" {
+ return []byte(`{"query":"` + query + `","message":"m"}`)
+ }
+ return []byte(`{"query":"` + query + `","mode":"` + mode + `","message":"m"}`)
+}
+
+func ctxWithAgent() context.Context {
+ return PutAgentContext(context.Background(), database.MsgchainTypeSearcher)
+}
+
+// TestWebSearchStrategyOrder verifies the orchestrator walks fallbackStrategy in order
+// and skips unavailable engines.
+func TestWebSearchStrategyOrder(t *testing.T) {
+ for _, mode := range []SearchMode{ModeLinks, ModeAnswer, ModeResearch, ModeExploit} {
+ t.Run(string(mode), func(t *testing.T) {
+ var order []database.SearchengineType
+ engines := map[database.SearchengineType]searchers.Searcher{}
+ for _, id := range fallbackStrategy[mode] {
+ engines[id] = &fakeSearcher{
+ engine: id,
+ available: true,
+ order: &order,
+ handler: func(int) (string, error) { return "", searchers.Fatal(errors.New("boom")) },
+ }
+ }
+
+ ws := newTestWebSearch(&searchLogProviderMock{}, engines)
+ _, err := ws.Handle(ctxWithAgent(), WebSearchToolName, webSearchArgs(t, string(mode), "q"))
+ if err != nil {
+ t.Fatalf("Handle() unexpected hard error: %v", err)
+ }
+
+ want := fallbackStrategy[mode]
+ if !reflect.DeepEqual(order, want) {
+ t.Errorf("call order = %v, want %v", order, want)
+ }
+ })
+ }
+}
+
+func TestWebSearchSkipsUnavailable(t *testing.T) {
+ var order []database.SearchengineType
+ // answer chain: tavily(unavail), traversaal(avail, succeeds)
+ engines := map[database.SearchengineType]searchers.Searcher{
+ EngineTavily: &fakeSearcher{engine: EngineTavily, available: false, order: &order},
+ EngineTraversaal: &fakeSearcher{engine: EngineTraversaal, available: true, order: &order, handler: func(int) (string, error) { return "ok", nil }},
+ }
+ slp := &searchLogProviderMock{}
+ ws := newTestWebSearch(slp, engines)
+
+ got, err := ws.Handle(ctxWithAgent(), WebSearchToolName, webSearchArgs(t, "answer", "q"))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "ok" {
+ t.Errorf("result = %q, want %q", got, "ok")
+ }
+ if len(order) != 1 || order[0] != EngineTraversaal {
+ t.Errorf("call order = %v, want [traversaal] (tavily unavailable must be skipped)", order)
+ }
+ if slp.calls != 1 || slp.engine != EngineTraversaal {
+ t.Errorf("search log: calls=%d engine=%q, want 1 traversaal", slp.calls, slp.engine)
+ }
+}
+
+func TestWebSearchFatalMovesToNextEngineWithoutRetry(t *testing.T) {
+ var order []database.SearchengineType
+ first := &fakeSearcher{engine: EngineTavily, available: true, order: &order,
+ handler: func(int) (string, error) { return "", searchers.Fatal(errors.New("401 auth")) }}
+ second := &fakeSearcher{engine: EngineTraversaal, available: true, order: &order,
+ handler: func(int) (string, error) { return "second-result", nil }}
+ engines := map[database.SearchengineType]searchers.Searcher{
+ EngineTavily: first,
+ EngineTraversaal: second,
+ }
+ slp := &searchLogProviderMock{}
+ ws := newTestWebSearch(slp, engines)
+
+ got, err := ws.Handle(ctxWithAgent(), WebSearchToolName, webSearchArgs(t, "answer", "q"))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "second-result" {
+ t.Errorf("result = %q, want second-result", got)
+ }
+ if first.calls != 1 {
+ t.Errorf("first engine called %d times, want 1 (fatal must not retry)", first.calls)
+ }
+ if slp.engine != EngineTraversaal {
+ t.Errorf("search log engine = %q, want traversaal (the winner)", slp.engine)
+ }
+}
+
+func TestWebSearchRetriesRetryableThenSucceeds(t *testing.T) {
+ engine := &fakeSearcher{engine: EngineTavily, available: true, handler: func(call int) (string, error) {
+ if call == 0 {
+ return "", searchers.Retryable(errors.New("429"), 0)
+ }
+ return "recovered", nil
+ }}
+ engines := map[database.SearchengineType]searchers.Searcher{EngineTavily: engine}
+ ws := newTestWebSearch(&searchLogProviderMock{}, engines)
+
+ got, err := ws.Handle(ctxWithAgent(), WebSearchToolName, webSearchArgs(t, "answer", "q"))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "recovered" {
+ t.Errorf("result = %q, want recovered", got)
+ }
+ if engine.calls != 2 {
+ t.Errorf("engine called %d times, want 2 (one retry)", engine.calls)
+ }
+}
+
+func TestWebSearchRetryableExhaustsThenMovesOn(t *testing.T) {
+ persistent429 := &fakeSearcher{engine: EngineTavily, available: true,
+ handler: func(int) (string, error) { return "", searchers.Retryable(errors.New("429"), 0) }}
+ next := &fakeSearcher{engine: EngineTraversaal, available: true,
+ handler: func(int) (string, error) { return "ok", nil }}
+ engines := map[database.SearchengineType]searchers.Searcher{
+ EngineTavily: persistent429,
+ EngineTraversaal: next,
+ }
+ ws := newTestWebSearch(&searchLogProviderMock{}, engines)
+
+ got, err := ws.Handle(ctxWithAgent(), WebSearchToolName, webSearchArgs(t, "answer", "q"))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "ok" {
+ t.Errorf("result = %q, want ok", got)
+ }
+ if persistent429.calls != maxEngineAttempts {
+ t.Errorf("retryable engine called %d times, want %d", persistent429.calls, maxEngineAttempts)
+ }
+}
+
+func TestWebSearchAllExhaustedReturnsSoftError(t *testing.T) {
+ engines := map[database.SearchengineType]searchers.Searcher{
+ EngineTavily: &fakeSearcher{engine: EngineTavily, available: true, handler: func(int) (string, error) { return "", searchers.Fatal(errors.New("down")) }},
+ EngineTraversaal: &fakeSearcher{engine: EngineTraversaal, available: true, handler: func(int) (string, error) { return "", searchers.Fatal(errors.New("down")) }},
+ }
+ slp := &searchLogProviderMock{}
+ ws := newTestWebSearch(slp, engines)
+
+ got, err := ws.Handle(ctxWithAgent(), WebSearchToolName, webSearchArgs(t, "answer", "q"))
+ // Exhaustion is a soft failure: message + nil error (must NOT burn agent retries).
+ if err != nil {
+ t.Fatalf("expected soft (nil) error on exhaustion, got hard error: %v", err)
+ }
+ if got == "" {
+ t.Fatal("expected a soft message, got empty string")
+ }
+ if !strings.Contains(got, "all") || !strings.Contains(got, "failed") {
+ t.Errorf("soft message = %q, want it to explain the exhaustion", got)
+ }
+ if slp.calls != 1 {
+ t.Errorf("search log calls = %d, want 1 failure row", slp.calls)
+ }
+}
+
+func TestWebSearchNothingConfiguredReturnsSoftError(t *testing.T) {
+ // No engine available for the mode.
+ engines := map[database.SearchengineType]searchers.Searcher{
+ EngineTavily: &fakeSearcher{engine: EngineTavily, available: false},
+ }
+ slp := &searchLogProviderMock{}
+ ws := newTestWebSearch(slp, engines)
+
+ got, err := ws.Handle(ctxWithAgent(), WebSearchToolName, webSearchArgs(t, "answer", "q"))
+ if err != nil {
+ t.Fatalf("expected soft error, got hard error: %v", err)
+ }
+ if !strings.Contains(got, "no search engine is configured") {
+ t.Errorf("message = %q, want the 'not configured' guidance", got)
+ }
+ if slp.calls != 0 {
+ t.Errorf("search log calls = %d, want 0 (nothing was attempted)", slp.calls)
+ }
+}
+
+func TestWebSearchMalformedArgsIsHardError(t *testing.T) {
+ ws := newTestWebSearch(&searchLogProviderMock{}, map[database.SearchengineType]searchers.Searcher{})
+ _, err := ws.Handle(ctxWithAgent(), WebSearchToolName, []byte("{not json"))
+ if err == nil {
+ t.Fatal("expected a hard error for malformed args (fixable by the arg-fixer)")
+ }
+}
+
+func TestWebSearchEmptyQueryIsHardError(t *testing.T) {
+ ws := newTestWebSearch(&searchLogProviderMock{}, map[database.SearchengineType]searchers.Searcher{})
+ _, err := ws.Handle(ctxWithAgent(), WebSearchToolName, []byte(`{"query":" ","message":"m"}`))
+ if err == nil {
+ t.Fatal("expected a hard error for an empty query")
+ }
+}
+
+func TestWebSearchDefaultMode(t *testing.T) {
+ // Omitting mode must resolve to defaultMode (answer): the answer chain leads with
+ // tavily, so a tavily-only registry should be used.
+ var order []database.SearchengineType
+ engines := map[database.SearchengineType]searchers.Searcher{
+ EngineTavily: &fakeSearcher{engine: EngineTavily, available: true, order: &order, handler: func(int) (string, error) { return "ok", nil }},
+ }
+ ws := newTestWebSearch(&searchLogProviderMock{}, engines)
+
+ got, err := ws.Handle(ctxWithAgent(), WebSearchToolName, webSearchArgs(t, "", "q"))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "ok" {
+ t.Errorf("result = %q, want ok", got)
+ }
+ if len(order) == 0 || order[0] != EngineTavily {
+ t.Errorf("default mode did not use the answer chain (order=%v)", order)
+ }
+}
+
+func TestNormalizeMode(t *testing.T) {
+ cases := map[string]SearchMode{
+ "links": ModeLinks, "answer": ModeAnswer, "research": ModeResearch, "exploit": ModeExploit,
+ "": defaultMode, "bogus": defaultMode, "ANSWER": ModeAnswer, " research ": ModeResearch,
+ }
+ for in, want := range cases {
+ if got := normalizeMode(in); got != want {
+ t.Errorf("normalizeMode(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestClampResults(t *testing.T) {
+ cases := map[int]int{0: webSearchDefaultResults, -5: webSearchDefaultResults, 1: 1, 25: 25, 100: webSearchMaxResults}
+ for in, want := range cases {
+ if got := clampResults(in); got != want {
+ t.Errorf("clampResults(%d) = %d, want %d", in, got, want)
+ }
+ }
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index 06b239f0..cb5f26ce 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -160,6 +160,9 @@ services:
- PERPLEXITY_API_KEY=${PERPLEXITY_API_KEY:-}
- PERPLEXITY_MODEL=${PERPLEXITY_MODEL:-sonar}
- PERPLEXITY_CONTEXT_SIZE=${PERPLEXITY_CONTEXT_SIZE:-low}
+ - WEB_SEARCH_INTERNAL_ENABLED=${WEB_SEARCH_INTERNAL_ENABLED:-}
+ - WEB_SEARCH_INTERNAL_MAX_SITES=${WEB_SEARCH_INTERNAL_MAX_SITES:-}
+ - WEB_SEARCH_INTERNAL_MAX_SITE_BYTES=${WEB_SEARCH_INTERNAL_MAX_SITE_BYTES:-}
- LANGFUSE_BASE_URL=${LANGFUSE_BASE_URL:-}
- LANGFUSE_PROJECT_ID=${LANGFUSE_PROJECT_ID:-}
- LANGFUSE_PUBLIC_KEY=${LANGFUSE_PUBLIC_KEY:-}