Skip to content

Personal AI, On Personal Devices

Python

feat: add You.com web search engine with a keyless default (#926)

Brian Sparker83329b1505e2
diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md
index 5d6f0d7d..13a9dfd8 100644
--- a/docs/getting-started/configuration.md
+++ b/docs/getting-started/configuration.md
@@ -1088,7 +1088,9 @@ OpenJarvis respects the following environment variables:
| `ANTHROPIC_API_KEY` | API key for Anthropic cloud inference. Required for the `cloud` engine with Claude models. |
| `GOOGLE_API_KEY` | API key for Google Gemini inference. Required for the `google` engine. |
| `MINIMAX_API_KEY` | API key for MiniMax cloud inference. Required for the `cloud` engine with MiniMax models (MiniMax-M3, MiniMax-M2.7, MiniMax-M2.7-highspeed, MiniMax-M2.5, MiniMax-M2.5-highspeed). |
-| `TAVILY_API_KEY` | API key for the Tavily web search tool. Required for the `web_search` tool. |
+| `TAVILY_API_KEY` | API key for the Tavily web search engine. Optional — when set, `auto` engine selection prefers Tavily. |
+| `YOUDOTCOM_API_KEY` | API key for the You.com web search engine. Optional — raises the keyless free-tier limits and enables You.com Contents extraction for URL queries. |
+| `OPENJARVIS_WEB_SEARCH_ENGINE` | Web search engine for the `web_search` tool: `auto` (default), `youcom`, `tavily`, or `duckduckgo`. |
## Next Steps
diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md
index 1942629e..f7c3597e 100644
--- a/docs/getting-started/quickstart.md
+++ b/docs/getting-started/quickstart.md
@@ -135,15 +135,23 @@ cd OpenJarvis
This launches the backend API server and a React frontend at [http://localhost:5173](http://localhost:5173).
You get a ChatGPT-like interface with streaming responses, tool use, energy monitoring, and a telemetry dashboard — all running locally on your hardware.
-Web search is available through the built-in DuckDuckGo fallback. To use
-Tavily, add `TAVILY_API_KEY` under **Settings → Tools → Web Search** after the
-app starts, or export it before starting quickstart:
+Web search works with no configuration: queries go to the You.com keyless
+free tier, which is rate limited per IP and needs no signup. To raise those
+limits, or to use Tavily instead, add `YOUDOTCOM_API_KEY` or `TAVILY_API_KEY`
+under **Settings → Tools → Web Search** after the app starts, or export one
+before starting quickstart:
```bash
-export TAVILY_API_KEY="tvly-..."
+export YOUDOTCOM_API_KEY="..." # free key: https://you.com/platform
./scripts/quickstart.sh
```
+Set `OPENJARVIS_WEB_SEARCH_ENGINE` to pick an engine explicitly — `youcom`,
+`tavily`, or `duckduckgo`. The default, `auto`, uses Tavily when
+`TAVILY_API_KEY` is set and You.com otherwise. DuckDuckGo remains the fallback
+for every engine; dropping to it is logged at `WARNING`, since its scraped
+results are unranked.
+
The script does not automatically source `.env` files. Run `source .env`
first if that is where you keep the key. Stop any existing OpenJarvis server
before restarting so it inherits the updated environment.
@@ -272,7 +280,7 @@ Agents add multi-turn reasoning and tool-calling capabilities. The `orchestrator
| `retrieval` | Search the memory store for relevant context. |
| `llm` | Make sub-queries to another model. |
| `file_read` | Read files with path validation. |
-| `web_search` | Web search via the Tavily API (requires `tools-search` extra). |
+| `web_search` | Web search via You.com (keyless by default) or Tavily, with a DuckDuckGo fallback. |
### CLI Example
diff --git a/docs/user-guide/deep-research.md b/docs/user-guide/deep-research.md
index 5d8724c3..98c1ccbb 100644
--- a/docs/user-guide/deep-research.md
+++ b/docs/user-guide/deep-research.md
@@ -160,6 +160,6 @@ Smaller chunk sizes work better for code, where each function or class is a natu
**Slow responses** -- The agent makes multiple search passes. Each turn involves a model call. Reduce `max_turns` or use a smaller model (`qwen3.5:4b`) for faster but less thorough results.
-**Web search not working** -- The `web_search` tool requires the Tavily API. Install with `uv sync --extra tools-search` and set `TAVILY_API_KEY`.
+**Web search not working** -- The `web_search` tool needs no API key by default; it uses the You.com keyless free tier, which is rate limited per IP. Set `YOUDOTCOM_API_KEY` (free key at [you.com/platform](https://you.com/platform?utm_source=open-jarvis-openjarvis&utm_medium=oss_integration&utm_campaign=2026-09-oss-integrations&utm_content=docs)) for higher limits, or install Tavily with `uv sync --extra tools-search` and set `TAVILY_API_KEY`. A `WARNING` naming the failed engine is logged whenever search drops to the DuckDuckGo fallback.
**Wrong chunks retrieved** -- Try re-indexing with different chunk sizes. For technical documents, smaller chunks (`256`) often retrieve more precisely. For narrative text, larger chunks (`1024`) preserve more context.
diff --git a/src/openjarvis/core/credentials.py b/src/openjarvis/core/credentials.py
index 4858901f..7535a4be 100644
--- a/src/openjarvis/core/credentials.py
+++ b/src/openjarvis/core/credentials.py
@@ -33,7 +33,7 @@ def _default_path() -> Path:
TOOL_CREDENTIALS: dict[str, list[str]] = {
- "web_search": ["TAVILY_API_KEY"],
+ "web_search": ["TAVILY_API_KEY", "YOUDOTCOM_API_KEY"],
"image_generate": ["OPENAI_API_KEY"],
"slack": ["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"],
"telegram": ["TELEGRAM_BOT_TOKEN"],
@@ -65,6 +65,28 @@ TOOL_CREDENTIALS: dict[str, list[str]] = {
}
+# Keys that unlock or upgrade a tool but are not prerequisites for it. Every
+# key in TOOL_CREDENTIALS is otherwise treated as required — by the Settings UI,
+# by ``jarvis doctor``, and by anything else reading credential status — which
+# leaves no way to describe a tool that also works without one. ``web_search``
+# is the first such tool: the You.com keyless tier serves it with no key at all,
+# and both listed keys only raise limits or result quality.
+OPTIONAL_TOOL_CREDENTIALS: dict[str, frozenset[str]] = {
+ "web_search": frozenset({"TAVILY_API_KEY", "YOUDOTCOM_API_KEY"}),
+}
+
+
+def is_credential_optional(tool_name: str, key: str) -> bool:
+ """Return whether ``key`` is an upgrade for ``tool_name`` rather than required."""
+ return key in OPTIONAL_TOOL_CREDENTIALS.get(tool_name, frozenset())
+
+
+def get_required_credentials(tool_name: str) -> list[str]:
+ """Return only the keys ``tool_name`` cannot run without."""
+ optional = OPTIONAL_TOOL_CREDENTIALS.get(tool_name, frozenset())
+ return [k for k in TOOL_CREDENTIALS.get(tool_name, []) if k not in optional]
+
+
def load_credentials(path: Path | None = None) -> dict[str, dict[str, str]]:
"""Load credentials, preserving malformed input as a recoverable backup."""
p = Path(path) if path else _default_path()
@@ -154,7 +176,11 @@ def delete_credential(
def get_credential_status(tool_name: str) -> dict[str, bool]:
- """Return {KEY: bool} for each required key indicating if set in env."""
+ """Return {KEY: bool} for each declared key indicating if set in env.
+
+ Includes optional keys; use :func:`is_credential_optional` to tell whether a
+ missing key actually blocks the tool.
+ """
keys = TOOL_CREDENTIALS.get(tool_name, [])
return {k: bool(os.environ.get(k)) for k in keys}
diff --git a/src/openjarvis/security/data_boundary_audit.py b/src/openjarvis/security/data_boundary_audit.py
index d104d4f9..a071d1ff 100644
--- a/src/openjarvis/security/data_boundary_audit.py
+++ b/src/openjarvis/security/data_boundary_audit.py
@@ -64,6 +64,7 @@ API_KEY_ENV_VARS = {
"OPENAI_API_KEY": ("OpenAI cloud inference", {"openai", "gpt"}),
"OPENROUTER_API_KEY": ("OpenRouter cloud inference", {"openrouter"}),
"TAVILY_API_KEY": ("Tavily web search", {"tavily", "web_search"}),
+ "YOUDOTCOM_API_KEY": ("You.com web search", {"youcom", "web_search"}),
}
CHANNEL_SECRET_FIELDS: tuple[tuple[str, str, str], ...] = (
@@ -944,12 +945,15 @@ def _audit_tool_surfaces(config: Any, builder: _FindingBuilder) -> None:
tools = _configured_tools(config)
if tools & WEB_SEARCH_TOOLS:
+ destination = _web_search_destination()
builder.add(
finding_id="web-search-tool-configured",
status="warn",
title="Web search tool is configured",
- potential_data_path="user or agent search query -> external search service",
- evidence=f"configured tool(s) = {_format_tools(tools & WEB_SEARCH_TOOLS)}",
+ potential_data_path=(f"user or agent search query -> {destination}"),
+ evidence=(
+ f"configured tool(s) = {_format_tools(tools & WEB_SEARCH_TOOLS)}"
+ ),
recommendation=(
"Review search queries before using web search with sensitive prompts."
),
@@ -1051,6 +1055,28 @@ def _audit_tool_surfaces(config: Any, builder: _FindingBuilder) -> None:
)
+def _web_search_destination() -> str:
+ """Name the service ``web_search`` sends queries to, from env keys alone.
+
+ The default engine is keyless, so no credential is involved and the
+ credential-driven findings above cannot see this egress — hence a separate
+ resolution here. It mirrors ``WebSearchTool._resolve_engine``, which is the
+ source of truth; ``test_data_boundary_audit`` asserts the two agree.
+ """
+ engine = (os.environ.get("OPENJARVIS_WEB_SEARCH_ENGINE") or "auto").strip().lower()
+ if engine not in {"auto", "youcom", "tavily", "duckduckgo"}:
+ engine = "auto"
+ if engine == "auto":
+ engine = "tavily" if os.environ.get("TAVILY_API_KEY") else "youcom"
+
+ if engine == "tavily":
+ return "Tavily web search API"
+ if engine == "duckduckgo":
+ return "DuckDuckGo (HTML scrape)"
+ tier = "keyed" if os.environ.get("YOUDOTCOM_API_KEY") else "keyless free tier"
+ return f"You.com web search API ({tier})"
+
+
def _iter_local_store_targets(
root: Path,
config: Any | None,
diff --git a/src/openjarvis/tools/web_search.py b/src/openjarvis/tools/web_search.py
index 3d71f5de..61b29fd2 100644
--- a/src/openjarvis/tools/web_search.py
+++ b/src/openjarvis/tools/web_search.py
@@ -1,4 +1,19 @@
-"""Web search tool — Tavily API with DuckDuckGo fallback."""
+"""Web search tool — You.com or Tavily, with a DuckDuckGo fallback.
+
+Engine selection is explicit (``engine=`` or ``OPENJARVIS_WEB_SEARCH_ENGINE``)
+rather than a chain of ``try``/``except`` layers. The default, ``"auto"``,
+resolves to whichever engine the environment can actually serve, preferring an
+API-backed engine over the DuckDuckGo HTML scrape:
+
+* ``TAVILY_API_KEY`` set → Tavily (unchanged for existing installs)
+* ``YOUDOTCOM_API_KEY`` set → You.com, keyed
+* neither → You.com, keyless free tier (no signup, rate limited per IP)
+
+The keyless tier is what makes a fresh install API-backed with zero config.
+DuckDuckGo remains the last resort for every engine, and dropping to it is now
+logged at WARNING with the reason, so a typo'd key no longer looks identical to
+a working install with quieter results.
+"""
from __future__ import annotations
@@ -6,6 +21,7 @@ import logging
import os
from typing import Any
+from openjarvis import __version__
from openjarvis.core.registry import ToolRegistry
from openjarvis.core.types import ToolResult
from openjarvis.security.ssrf import check_ssrf
@@ -14,19 +30,91 @@ from openjarvis.tools._stubs import BaseTool, ToolSpec
logger = logging.getLogger(__name__)
+YOUCOM_KEYED_SEARCH_URL = "https://api.you.com/v1/search"
+YOUCOM_KEYLESS_SEARCH_URL = "https://api.you.com/v1/agents/search"
+YOUCOM_CONTENTS_URL = "https://api.you.com/v1/contents"
+YOUCOM_API_KEY_ENV = "YOUDOTCOM_API_KEY"
+
+ENGINE_ENV = "OPENJARVIS_WEB_SEARCH_ENGINE"
+ENGINES = ("auto", "youcom", "tavily", "duckduckgo")
+
+# Identifies OpenJarvis to You.com. The keyless tier carries no API key, so the
+# User-Agent is the only attribution signal; sent to You.com hosts only.
+YOUCOM_USER_AGENT = (
+ f"openjarvis/{__version__} youdotcom-integration/open-jarvis-openjarvis"
+)
+
+# Keyless tier exhaustion (402) and per-IP throttling (429) both mean "get a
+# key", which is a different remedy from a generic HTTP failure.
+_KEYLESS_LIMIT_STATUSES = (402, 429)
+YOUCOM_PLATFORM_URL = (
+ "https://you.com/platform"
+ "?utm_source=open-jarvis-openjarvis&utm_medium=oss_integration"
+ "&utm_campaign=2026-09-oss-integrations&utm_content=error-message"
+)
+_KEY_UPGRADE_HINT = (
+ f"You.com keyless free-tier limit reached. Set {YOUCOM_API_KEY_ENV} for "
+ f"higher limits — a free key is available at {YOUCOM_PLATFORM_URL}"
+)
+
+
+class _WebSearchEngineError(RuntimeError):
+ """An engine failed in a way that should be reported, not swallowed."""
+
+
@ToolRegistry.register("web_search")
class WebSearchTool(BaseTool):
- """Search the web via Tavily API."""
+ """Search the web via You.com or Tavily, falling back to DuckDuckGo."""
tool_id = "web_search"
is_local = False
- def __init__(self, api_key: str | None = None, max_results: int = 5):
+ def __init__(
+ self,
+ api_key: str | None = None,
+ max_results: int = 5,
+ *,
+ engine: str | None = None,
+ youcom_api_key: str | None = None,
+ ):
+ """Configure the search engine.
+
+ ``api_key`` remains the Tavily key, positionally, for backwards
+ compatibility. ``engine`` is one of :data:`ENGINES`; when omitted it
+ comes from ``OPENJARVIS_WEB_SEARCH_ENGINE`` and defaults to ``"auto"``.
+ An unknown engine name falls back to ``"auto"`` with a warning rather
+ than raising, so a typo in the environment cannot break tool loading.
+ """
self._api_key = api_key or os.environ.get("TAVILY_API_KEY")
+ self._youcom_api_key = youcom_api_key or os.environ.get(YOUCOM_API_KEY_ENV)
self._max_results = max_results
+ requested = (engine or os.environ.get(ENGINE_ENV) or "auto").strip().lower()
+ if requested not in ENGINES:
+ logger.warning(
+ "Unknown web search engine %r (expected one of %s); using 'auto'",
+ requested,
+ ", ".join(ENGINES),
+ )
+ requested = "auto"
+ self._engine = requested
+
+ def _resolve_engine(self) -> str:
+ """Resolve ``auto`` to a concrete engine from what the env can serve.
+
+ Tavily wins when its key is set so existing installs are unchanged.
+ Otherwise You.com handles the query — keyed if a key is present,
+ keyless if not, which is the zero-config API-backed path.
+ """
+ if self._engine != "auto":
+ return self._engine
+ if self._api_key:
+ return "tavily"
+ return "youcom"
+
@property
def spec(self) -> ToolSpec:
+ engine = self._resolve_engine()
return ToolSpec(
name="web_search",
description=(
@@ -45,7 +133,17 @@ class WebSearchTool(BaseTool):
"required": ["query"],
},
category="search",
- metadata={"requires_api_key": "TAVILY_API_KEY", "fallback": "duckduckgo"},
+ metadata={
+ # Kept for backwards compatibility: existing readers (Settings
+ # UI, tools endpoint) expect a single Tavily key name here.
+ "requires_api_key": "TAVILY_API_KEY",
+ # web_search needs no key at all on the You.com keyless tier,
+ # so the keys above are upgrades rather than prerequisites.
+ "optional_api_keys": ["TAVILY_API_KEY", YOUCOM_API_KEY_ENV],
+ "engine": engine,
+ "engines": list(ENGINES),
+ "fallback": "duckduckgo",
+ },
)
@staticmethod
@@ -115,6 +213,121 @@ class WebSearchTool(BaseTool):
text = text[:max_chars] + "\n\n[Content truncated]"
return text
+ def _youcom_request(self, path_is_keyed: bool) -> tuple[str, dict[str, str]]:
+ """Pick the You.com endpoint and its headers together.
+
+ The keyless endpoint rejects an API key, and the keyed endpoint
+ requires one, so URL and headers must be chosen in one step — a stale
+ key sent to the keyless path 401s.
+ """
+ headers = {"Accept": "application/json", "User-Agent": YOUCOM_USER_AGENT}
+ if path_is_keyed:
+ headers["X-API-Key"] = self._youcom_api_key or ""
+ return YOUCOM_KEYED_SEARCH_URL, headers
+ return YOUCOM_KEYLESS_SEARCH_URL, headers
+
+ @staticmethod
+ def _format_youcom_results(payload: dict[str, Any]) -> tuple[str, int]:
+ """Render a You.com search payload in the shared result format.
+
+ Web results come before news. Snippets carry the page text the agent
+ should synthesize from; ``description`` is the fallback when a result
+ has none.
+ """
+ results = payload.get("results") or {}
+ parts: list[str] = []
+ count = 0
+ for section in ("web", "news"):
+ for item in results.get(section) or []:
+ title = item.get("title") or "Untitled"
+ url = item.get("url", "")
+ snippets = item.get("snippets") or []
+ content = (
+ "\n".join(snippets) if snippets else item.get("description", "")
+ )
+ parts.append(f"### {title}\nSource: {url}\nSummary: {content}")
+ count += 1
+ return "\n\n---\n\n".join(parts), count
+
+ def _youcom_search(self, query: str, max_results: int) -> ToolResult:
+ """Search via You.com, keyed when a key is set and keyless otherwise."""
+ import httpx
+
+ keyed = bool(self._youcom_api_key)
+ url, headers = self._youcom_request(keyed)
+ try:
+ response = httpx.get(
+ url,
+ params={"query": query, "count": max_results},
+ headers=headers,
+ timeout=30.0,
+ )
+ response.raise_for_status()
+ payload = response.json()
+ except httpx.HTTPStatusError as exc:
+ status = exc.response.status_code
+ if not keyed and status in _KEYLESS_LIMIT_STATUSES:
+ raise _WebSearchEngineError(_KEY_UPGRADE_HINT) from exc
+ raise _WebSearchEngineError(
+ f"You.com search failed with HTTP {status}"
+ ) from exc
+ except (httpx.HTTPError, ValueError) as exc:
+ raise _WebSearchEngineError(f"You.com search failed: {exc}") from exc
+
+ formatted, count = self._format_youcom_results(payload)
+ return ToolResult(
+ tool_name="web_search",
+ content=formatted or "No results found.",
+ success=True,
+ metadata={
+ "num_results": count,
+ "engine": "youcom",
+ "youcom_tier": "keyed" if keyed else "keyless",
+ },
+ )
+
+ def _youcom_extract(self, url: str) -> str | None:
+ """Return You.com-extracted markdown for ``url``, or ``None``.
+
+ The Contents API needs a key, so this is an upgrade over the regex HTML
+ strip in :meth:`_fetch_url` rather than a replacement for it. Any
+ failure returns ``None`` and the caller falls back to the local fetch.
+ """
+ if not self._youcom_api_key:
+ return None
+
+ import httpx
+
+ try:
+ response = httpx.post(
+ YOUCOM_CONTENTS_URL,
+ json={"urls": [url], "formats": ["markdown"]},
+ headers={
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ "User-Agent": YOUCOM_USER_AGENT,
+ "X-API-Key": self._youcom_api_key,
+ },
+ timeout=30.0,
+ )
+ response.raise_for_status()
+ payload = response.json()
+ except (httpx.HTTPError, ValueError) as exc:
+ logger.warning(
+ "You.com Contents extraction failed for %s (%s); falling back to "
+ "local HTML extraction",
+ url,
+ type(exc).__name__,
+ )
+ return None
+
+ items = payload if isinstance(payload, list) else payload.get("results") or []
+ for item in items:
+ markdown = (item or {}).get("markdown")
+ if markdown:
+ return str(markdown)
+ return None
+
def _duckduckgo_search(self, query: str, max_results: int) -> str:
"""Search using DuckDuckGo as fallback."""
from ddgs import DDGS
@@ -143,13 +356,33 @@ class WebSearchTool(BaseTool):
# If the query contains a URL, fetch it directly instead of searching
url = self._extract_url(query) if not self._is_url(query) else query.strip()
if url:
+ if self._resolve_engine() == "youcom":
+ ssrf_error = check_ssrf(self._normalize_url(url))
+ if ssrf_error:
+ return ToolResult(
+ tool_name="web_search",
+ content=f"Failed to fetch URL: {ssrf_error}",
+ success=False,
+ )
+ extracted = self._youcom_extract(url)
+ if extracted:
+ return ToolResult(
+ tool_name="web_search",
+ content=extracted,
+ success=True,
+ metadata={
+ "url": url,
+ "mode": "fetch",
+ "extractor": "youcom_contents",
+ },
+ )
try:
content = self._fetch_url(url)
return ToolResult(
tool_name="web_search",
content=content or "No content found at URL.",
success=True,
- metadata={"url": url, "mode": "fetch"},
+ metadata={"url": url, "mode": "fetch", "extractor": "local"},
)
except Exception as exc:
return ToolResult(
@@ -159,42 +392,78 @@ class WebSearchTool(BaseTool):
)
max_results = params.get("max_results", self._max_results)
+ engine = self._resolve_engine()
+
+ if engine == "duckduckgo":
+ return self._duckduckgo_result(query, max_results)
try:
- from tavily import TavilyClient
-
- client = TavilyClient(api_key=self._api_key)
- response = client.search(
- query,
- max_results=max_results,
- search_depth="advanced",
- include_usage=True,
- )
- results = response.get("results", [])
- formatted_parts = []
- for r in results:
- title = r.get("title", "Untitled")
- url = r.get("url", "")
- content = r.get("content", "") or r.get("snippet", "")
- formatted_parts.append(
- f"### {title}\nSource: {url}\nSummary: {content}"
- )
+ if engine == "youcom":
+ return self._youcom_search(query, max_results)
+ return self._tavily_search(query, max_results)
+ except _WebSearchEngineError as exc:
+ reason = str(exc)
+ except Exception as exc: # engine SDKs raise their own error types
+ reason = f"{type(exc).__name__}: {exc}"
- formatted = "\n\n---\n\n".join(formatted_parts)
- return ToolResult(
- tool_name="web_search",
- content=formatted or "No results found.",
- success=True,
- metadata={
- "num_results": len(results),
- "engine": "tavily",
- "credits": (response.get("usage") or {}).get("credits"),
- },
- )
- except Exception as exc:
- logger.debug(
- "Tavily error (%s), falling back to DuckDuckGo", type(exc).__name__
- )
+ # Falling back is a degradation in result quality, so say so at WARNING
+ # rather than DEBUG — a typo'd key used to look like a quiet install.
+ logger.warning(
+ "%s engine failed (%s); falling back to DuckDuckGo, which returns "
+ "unranked scraped results",
+ engine,
+ reason,
+ )
+ return self._duckduckgo_result(
+ query, max_results, fallback_from=engine, reason=reason
+ )
+
+ def _tavily_search(self, query: str, max_results: int) -> ToolResult:
+ """Search via the Tavily API."""
+ from tavily import TavilyClient
+
+ client = TavilyClient(api_key=self._api_key)
+ response = client.search(
+ query,
+ max_results=max_results,
+ search_depth="advanced",
+ include_usage=True,
+ )
+ results = response.get("results", [])
+ formatted_parts = []
+ for r in results:
+ title = r.get("title", "Untitled")
+ url = r.get("url", "")
+ content = r.get("content", "") or r.get("snippet", "")
+ formatted_parts.append(f"### {title}\nSource: {url}\nSummary: {content}")
+
+ formatted = "\n\n---\n\n".join(formatted_parts)
+ return ToolResult(
+ tool_name="web_search",
+ content=formatted or "No results found.",
+ success=True,
+ metadata={
+ "num_results": len(results),
+ "engine": "tavily",
+ "credits": (response.get("usage") or {}).get("credits"),
+ },
+ )
+
+ def _duckduckgo_result(
+ self,
+ query: str,
+ max_results: int,
+ *,
+ fallback_from: str | None = None,
+ reason: str | None = None,
+ ) -> ToolResult:
+ """Run the DuckDuckGo scrape and record why it was used."""
+ metadata: dict[str, Any] = {"engine": "duckduckgo"}
+ if fallback_from:
+ metadata["fallback_from"] = fallback_from
+ metadata["degraded"] = True
+ if reason:
+ metadata["fallback_reason"] = reason
try:
formatted = self._duckduckgo_search(query, max_results)
@@ -202,22 +471,24 @@ class WebSearchTool(BaseTool):
tool_name="web_search",
content=formatted or "No results found.",
success=True,
- metadata={"engine": "duckduckgo"},
+ metadata=metadata,
)
except ImportError:
return ToolResult(
tool_name="web_search",
content=(
- "tavily-python not installed and ddgs not available."
- " Install with: pip install tavily-python ddgs"
+ "No search engine available: ddgs is not installed."
+ " Install with: pip install ddgs"
),
success=False,
+ metadata=metadata,
)
except Exception as exc:
return ToolResult(
tool_name="web_search",
content=f"Search error: {exc}",
success=False,
+ metadata=metadata,
)
diff --git a/tests/core/test_credentials.py b/tests/core/test_credentials.py
index 2e79ba05..eb33f113 100644
--- a/tests/core/test_credentials.py
+++ b/tests/core/test_credentials.py
@@ -170,3 +170,46 @@ def test_delete_credential_removes_file_value_and_env(cred_path):
def test_delete_rejects_unknown_key(cred_path):
with pytest.raises(ValueError, match="Unknown credential key"):
delete_credential("web_search", "BOGUS_KEY", path=cred_path)
+
+
+class TestOptionalCredentials:
+ """web_search runs keyless, so its keys are upgrades, not prerequisites."""
+
+ def test_web_search_declares_both_search_keys(self):
+ from openjarvis.core.credentials import TOOL_CREDENTIALS
+
+ assert "TAVILY_API_KEY" in TOOL_CREDENTIALS["web_search"]
+ assert "YOUDOTCOM_API_KEY" in TOOL_CREDENTIALS["web_search"]
+
+ def test_search_keys_are_optional(self):
+ from openjarvis.core.credentials import is_credential_optional
+
+ assert is_credential_optional("web_search", "TAVILY_API_KEY") is True
+ assert is_credential_optional("web_search", "YOUDOTCOM_API_KEY") is True
+
+ def test_other_tool_keys_stay_required(self):
+ from openjarvis.core.credentials import is_credential_optional
+
+ assert is_credential_optional("telegram", "TELEGRAM_BOT_TOKEN") is False
+
+ def test_web_search_has_no_required_keys(self):
+ from openjarvis.core.credentials import get_required_credentials
+
+ assert get_required_credentials("web_search") == []
+
+ def test_required_keys_unchanged_for_other_tools(self):
+ from openjarvis.core.credentials import get_required_credentials
+
+ assert get_required_credentials("image_generate") == ["OPENAI_API_KEY"]
+
+ def test_youdotcom_key_can_be_persisted(self, tmp_path, monkeypatch):
+ """Unknown keys are rejected by save_credential, so the Settings UI
+ cannot store a key that is not declared."""
+ from openjarvis.core.credentials import load_credentials, save_credential
+
+ path = tmp_path / "credentials.toml"
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ save_credential("web_search", "YOUDOTCOM_API_KEY", "ydc-key", path=path)
+ assert load_credentials(path=path)["web_search"]["YOUDOTCOM_API_KEY"] == (
+ "ydc-key"
+ )
diff --git a/tests/security/test_data_boundary_audit.py b/tests/security/test_data_boundary_audit.py
index 886345c3..767e8e07 100644
--- a/tests/security/test_data_boundary_audit.py
+++ b/tests/security/test_data_boundary_audit.py
@@ -1303,3 +1303,70 @@ enabled = [
assert "cloud-provider-configured" not in findings
assert "frontend-credential-storage-not-inspected" not in findings
assert report.verdict == "no fail or warn findings detected"
+
+
+class TestWebSearchDestination:
+ """The default search engine is keyless, so no credential finding covers
+ it — the tool-surface finding has to name the destination itself (#923)."""
+
+ def _clear(self, monkeypatch):
+ for key in (
+ "TAVILY_API_KEY",
+ "YOUDOTCOM_API_KEY",
+ "OPENJARVIS_WEB_SEARCH_ENGINE",
+ ):
+ monkeypatch.delenv(key, raising=False)
+
+ def test_keyless_youcom_is_named(self, monkeypatch):
+ from openjarvis.security.data_boundary_audit import _web_search_destination
+
+ self._clear(monkeypatch)
+ assert "You.com" in _web_search_destination()
+ assert "keyless" in _web_search_destination()
+
+ def test_keyed_youcom_is_named(self, monkeypatch):
+ from openjarvis.security.data_boundary_audit import _web_search_destination
+
+ self._clear(monkeypatch)
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "ydc-key")
+ assert "keyed" in _web_search_destination()
+
+ def test_tavily_is_named(self, monkeypatch):
+ from openjarvis.security.data_boundary_audit import _web_search_destination
+
+ self._clear(monkeypatch)
+ monkeypatch.setenv("TAVILY_API_KEY", "tvly-key")
+ assert "Tavily" in _web_search_destination()
+
+ def test_duckduckgo_is_named(self, monkeypatch):
+ from openjarvis.security.data_boundary_audit import _web_search_destination
+
+ self._clear(monkeypatch)
+ monkeypatch.setenv("OPENJARVIS_WEB_SEARCH_ENGINE", "duckduckgo")
+ assert "DuckDuckGo" in _web_search_destination()
+
+ def test_matches_the_tool_resolution(self, monkeypatch):
+ """Guard against the audit's copy of the precedence rule drifting from
+ WebSearchTool._resolve_engine, which is the source of truth."""
+ from openjarvis.security.data_boundary_audit import _web_search_destination
+ from openjarvis.tools.web_search import WebSearchTool
+
+ labels = {
+ "youcom": "You.com",
+ "tavily": "Tavily",
+ "duckduckgo": "DuckDuckGo",
+ }
+ for tavily in (None, "tvly-key"):
+ for youcom in (None, "ydc-key"):
+ for engine in (None, "auto", "youcom", "tavily", "duckduckgo"):
+ self._clear(monkeypatch)
+ if tavily:
+ monkeypatch.setenv("TAVILY_API_KEY", tavily)
+ if youcom:
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", youcom)
+ if engine:
+ monkeypatch.setenv("OPENJARVIS_WEB_SEARCH_ENGINE", engine)
+ resolved = WebSearchTool()._resolve_engine()
+ assert labels[resolved] in _web_search_destination(), (
+ f"tavily={tavily} youcom={youcom} engine={engine}"
+ )
diff --git a/tests/server/test_tools_endpoint.py b/tests/server/test_tools_endpoint.py
index b7db42e2..5cb81bf7 100644
--- a/tests/server/test_tools_endpoint.py
+++ b/tests/server/test_tools_endpoint.py
@@ -62,7 +62,10 @@ def test_web_search_available_without_tavily_key(monkeypatch):
def test_tool_credentials_browser_lifecycle(tmp_path, monkeypatch):
- """The browser API can save, report, and remove a Tavily key."""
+ """The browser API can save, report, and remove a Tavily key.
+
+ ``web_search`` declares a You.com key alongside it, so status reports both.
+ """
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -70,6 +73,7 @@ def test_tool_credentials_browser_lifecycle(tmp_path, monkeypatch):
monkeypatch.setenv("OPENJARVIS_HOME", str(tmp_path / "openjarvis-home"))
monkeypatch.delenv("TAVILY_API_KEY", raising=False)
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
app = FastAPI()
tools_router = create_agent_manager_router(MagicMock())[3]
app.include_router(tools_router)
@@ -82,7 +86,8 @@ def test_tool_credentials_browser_lifecycle(tmp_path, monkeypatch):
assert saved.status_code == 200
assert saved.json() == {"saved": ["TAVILY_API_KEY"]}
assert client.get("/v1/tools/web_search/credentials/status").json() == {
- "TAVILY_API_KEY": True
+ "TAVILY_API_KEY": True,
+ "YOUDOTCOM_API_KEY": False,
}
deleted = client.delete(
@@ -91,5 +96,6 @@ def test_tool_credentials_browser_lifecycle(tmp_path, monkeypatch):
assert deleted.status_code == 200
assert deleted.json() == {"deleted": "TAVILY_API_KEY"}
assert client.get("/v1/tools/web_search/credentials/status").json() == {
- "TAVILY_API_KEY": False
+ "TAVILY_API_KEY": False,
+ "YOUDOTCOM_API_KEY": False,
}
diff --git a/tests/tools/test_web_search.py b/tests/tools/test_web_search.py
index 5ada6770..b8584977 100644
--- a/tests/tools/test_web_search.py
+++ b/tests/tools/test_web_search.py
@@ -37,14 +37,42 @@ class TestWebSearchTool:
assert "No query" in result.content
def test_execute_no_api_key(self, monkeypatch):
- """When no API key, falls back to DuckDuckGo."""
- tool = WebSearchTool(api_key=None)
+ """With no API key at all, queries go to the You.com keyless tier.
+
+ This is the behavior change in #923: the zero-config path used to be
+ the DuckDuckGo HTML scrape, which is unranked and rate limited.
+ """
+ import httpx
+
+ captured = {}
+
+ def _get(url, **kwargs):
+ captured["url"] = url
+ resp = MagicMock()
+ resp.json.return_value = {
+ "results": {
+ "web": [
+ {
+ "url": "https://example.com",
+ "title": "T",
+ "snippets": ["S"],
+ }
+ ]
+ }
+ }
+ resp.raise_for_status = MagicMock()
+ return resp
+
with patch.dict("os.environ", {}, clear=True):
- tool._api_key = None
+ monkeypatch.setattr(httpx, "get", _get)
monkeypatch.delitem(sys.modules, "tavily", raising=False)
+ tool = WebSearchTool(api_key=None)
+ tool._api_key = None
result = tool.execute(query="test query")
+
assert result.success is True
- assert result.metadata["engine"] == "duckduckgo"
+ assert result.metadata["engine"] == "youcom"
+ assert captured["url"] == "https://api.you.com/v1/agents/search"
def test_execute_mocked_tavily(self, monkeypatch):
mock_client = MagicMock()
@@ -503,3 +531,361 @@ class TestExecuteWithUrl:
result = tool.execute(query="https://example.com/broken")
assert result.success is False
assert "Failed to fetch URL" in result.content
+
+
+# ---------------------------------------------------------------------------
+# Engine selection and the You.com engine (#923)
+# ---------------------------------------------------------------------------
+
+
+class TestEngineSelection:
+ def test_auto_prefers_tavily_when_its_key_is_set(self, monkeypatch):
+ """Existing installs are unchanged: a Tavily key still means Tavily."""
+ monkeypatch.setenv("TAVILY_API_KEY", "tvly-x")
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ monkeypatch.delenv("OPENJARVIS_WEB_SEARCH_ENGINE", raising=False)
+ assert WebSearchTool()._resolve_engine() == "tavily"
+
+ def test_auto_uses_youcom_without_any_key(self, monkeypatch):
+ """The zero-config path is API-backed rather than the DDG scrape."""
+ monkeypatch.delenv("TAVILY_API_KEY", raising=False)
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ monkeypatch.delenv("OPENJARVIS_WEB_SEARCH_ENGINE", raising=False)
+ assert WebSearchTool()._resolve_engine() == "youcom"
+
+ def test_explicit_engine_overrides_key_presence(self, monkeypatch):
+ monkeypatch.setenv("TAVILY_API_KEY", "tvly-x")
+ assert WebSearchTool(engine="youcom")._resolve_engine() == "youcom"
+ assert WebSearchTool(engine="duckduckgo")._resolve_engine() == "duckduckgo"
+
+ def test_engine_read_from_environment(self, monkeypatch):
+ monkeypatch.setenv("TAVILY_API_KEY", "tvly-x")
+ monkeypatch.setenv("OPENJARVIS_WEB_SEARCH_ENGINE", "youcom")
+ assert WebSearchTool()._resolve_engine() == "youcom"
+
+ def test_unknown_engine_falls_back_to_auto(self, monkeypatch, caplog):
+ """A typo in the env must not break tool loading."""
+ monkeypatch.delenv("TAVILY_API_KEY", raising=False)
+ monkeypatch.setenv("OPENJARVIS_WEB_SEARCH_ENGINE", "yuo.com")
+ with caplog.at_level("WARNING"):
+ tool = WebSearchTool()
+ assert tool._resolve_engine() == "youcom"
+ assert "Unknown web search engine" in caplog.text
+
+ def test_spec_reports_engine_and_optional_keys(self, monkeypatch):
+ monkeypatch.delenv("TAVILY_API_KEY", raising=False)
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ monkeypatch.delenv("OPENJARVIS_WEB_SEARCH_ENGINE", raising=False)
+ spec = WebSearchTool().spec
+ assert spec.metadata["engine"] == "youcom"
+ assert "YOUDOTCOM_API_KEY" in spec.metadata["optional_api_keys"]
+ # Backwards compatible for readers of the old single-key field.
+ assert spec.metadata["requires_api_key"] == "TAVILY_API_KEY"
+
+
+class TestYouComSearch:
+ """The You.com engine, exercised against mocked HTTP."""
+
+ PAYLOAD = {
+ "results": {
+ "web": [
+ {
+ "url": "https://example.com/a",
+ "title": "Result A",
+ "description": "Desc A",
+ "snippets": ["Snippet A1", "Snippet A2"],
+ },
+ {
+ "url": "https://example.com/b",
+ "title": "Result B",
+ "description": "Desc B only",
+ },
+ ],
+ "news": [
+ {
+ "url": "https://example.com/n",
+ "title": "News N",
+ "snippets": ["Snippet N"],
+ }
+ ],
+ },
+ "metadata": {"query": "test"},
+ }
+
+ def _mock_get(self, monkeypatch, payload=None, status=200):
+ import httpx
+
+ calls = {}
+
+ def _get(url, **kwargs):
+ calls["url"] = url
+ calls["params"] = kwargs.get("params")
+ calls["headers"] = kwargs.get("headers")
+ resp = MagicMock()
+ resp.status_code = status
+ resp.json.return_value = payload if payload is not None else self.PAYLOAD
+ if status >= 400:
+ resp.text = "error body"
+ resp.raise_for_status.side_effect = httpx.HTTPStatusError(
+ f"HTTP {status}", request=MagicMock(), response=resp
+ )
+ else:
+ resp.raise_for_status = MagicMock()
+ return resp
+
+ monkeypatch.setattr(httpx, "get", _get)
+ return calls
+
+ def test_keyless_endpoint_and_no_key_header(self, monkeypatch):
+ """A stale key must never reach the keyless path — it 401s there."""
+ monkeypatch.delenv("TAVILY_API_KEY", raising=False)
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ calls = self._mock_get(monkeypatch)
+
+ result = WebSearchTool(engine="youcom").execute(query="test query")
+
+ assert result.success is True
+ assert calls["url"] == "https://api.you.com/v1/agents/search"
+ assert "X-API-Key" not in calls["headers"]
+ assert result.metadata["youcom_tier"] == "keyless"
+
+ def test_keyed_endpoint_when_key_is_set(self, monkeypatch):
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "ydc-key")
+ calls = self._mock_get(monkeypatch)
+
+ result = WebSearchTool(engine="youcom").execute(query="test query")
+
+ assert calls["url"] == "https://api.you.com/v1/search"
+ assert calls["headers"]["X-API-Key"] == "ydc-key"
+ assert result.metadata["youcom_tier"] == "keyed"
+
+ def test_sends_attribution_user_agent(self, monkeypatch):
+ """Keyless traffic carries no key, so the User-Agent is the only
+ signal identifying OpenJarvis to You.com."""
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ calls = self._mock_get(monkeypatch)
+
+ WebSearchTool(engine="youcom").execute(query="test query")
+
+ assert (
+ "youdotcom-integration/open-jarvis-openjarvis"
+ in (calls["headers"]["User-Agent"])
+ )
+
+ def test_result_format_matches_tavily(self, monkeypatch):
+ """Same labeled Source/Summary shape agents already parse (#390)."""
+ self._mock_get(monkeypatch)
+
+ result = WebSearchTool(engine="youcom").execute(query="test query")
+
+ assert "### Result A" in result.content
+ assert "Source: https://example.com/a" in result.content
+ assert "Summary: Snippet A1\nSnippet A2" in result.content
+ # description is the fallback when a result carries no snippets
+ assert "Summary: Desc B only" in result.content
+ # news results are included after web results
+ assert "### News N" in result.content
+ assert result.metadata["num_results"] == 3
+
+ def test_max_results_passed_as_count(self, monkeypatch):
+ calls = self._mock_get(monkeypatch)
+ WebSearchTool(engine="youcom", max_results=3).execute(query="q", max_results=7)
+ assert calls["params"] == {"query": "q", "count": 7}
+
+ def test_empty_results(self, monkeypatch):
+ self._mock_get(monkeypatch, payload={"results": {}})
+ result = WebSearchTool(engine="youcom").execute(query="q")
+ assert result.success is True
+ assert result.content == "No results found."
+
+ def test_keyless_limit_falls_back_with_upgrade_hint(self, monkeypatch):
+ """402/429 on the keyless tier means 'get a key', and the reason has
+ to reach the caller instead of vanishing into a debug log."""
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ self._mock_get(monkeypatch, status=402)
+
+ mock_ddgs = MagicMock()
+ mock_ddgs.text.return_value = [
+ {"title": "DDG", "href": "https://example.com", "body": "b"}
+ ]
+ mock_module = MagicMock()
+ mock_module.DDGS.return_value = mock_ddgs
+ monkeypatch.setitem(sys.modules, "ddgs", mock_module)
+
+ result = WebSearchTool(engine="youcom").execute(query="q")
+
+ assert result.success is True
+ assert result.metadata["engine"] == "duckduckgo"
+ assert result.metadata["fallback_from"] == "youcom"
+ assert result.metadata["degraded"] is True
+ assert "YOUDOTCOM_API_KEY" in result.metadata["fallback_reason"]
+
+ def test_keyed_http_error_reports_status_not_upgrade_hint(self, monkeypatch):
+ """With a key set, a failure is not a free-tier limit."""
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "ydc-key")
+ self._mock_get(monkeypatch, status=500)
+
+ mock_ddgs = MagicMock()
+ mock_ddgs.text.return_value = []
+ mock_module = MagicMock()
+ mock_module.DDGS.return_value = mock_ddgs
+ monkeypatch.setitem(sys.modules, "ddgs", mock_module)
+
+ result = WebSearchTool(engine="youcom").execute(query="q")
+
+ assert "HTTP 500" in result.metadata["fallback_reason"]
+ assert "YOUDOTCOM_API_KEY" not in result.metadata["fallback_reason"]
+
+
+class TestFallbackVisibility:
+ def test_fallback_is_logged_at_warning(self, monkeypatch, caplog):
+ """Regression for the silent-degradation half of #923: a typo'd key
+ used to look identical to a working install with quieter results."""
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ import httpx
+
+ def _boom(*args, **kwargs):
+ raise httpx.ConnectError("no route to host")
+
+ monkeypatch.setattr(httpx, "get", _boom)
+
+ mock_ddgs = MagicMock()
+ mock_ddgs.text.return_value = []
+ mock_module = MagicMock()
+ mock_module.DDGS.return_value = mock_ddgs
+ monkeypatch.setitem(sys.modules, "ddgs", mock_module)
+
+ with caplog.at_level("WARNING"):
+ result = WebSearchTool(engine="youcom").execute(query="q")
+
+ assert "falling back to DuckDuckGo" in caplog.text
+ assert result.metadata["degraded"] is True
+
+ def test_duckduckgo_engine_is_not_marked_degraded(self, monkeypatch):
+ """Choosing DDG deliberately is not a degradation."""
+ mock_ddgs = MagicMock()
+ mock_ddgs.text.return_value = [
+ {"title": "DDG", "href": "https://example.com", "body": "b"}
+ ]
+ mock_module = MagicMock()
+ mock_module.DDGS.return_value = mock_ddgs
+ monkeypatch.setitem(sys.modules, "ddgs", mock_module)
+
+ result = WebSearchTool(engine="duckduckgo").execute(query="q")
+
+ assert result.metadata["engine"] == "duckduckgo"
+ assert "degraded" not in result.metadata
+
+ def test_missing_ddgs_reports_only_ddgs(self, monkeypatch):
+ """The old message named tavily-python even when Tavily was not in
+ play; the remaining hard requirement is ddgs."""
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ import httpx
+
+ monkeypatch.setattr(
+ httpx, "get", MagicMock(side_effect=httpx.ConnectError("down"))
+ )
+ monkeypatch.delitem(sys.modules, "ddgs", raising=False)
+ import builtins
+
+ original_import = builtins.__import__
+
+ def _mock_import(name, *args, **kwargs):
+ if name == "ddgs":
+ raise ImportError("No module named 'ddgs'")
+ return original_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _mock_import)
+
+ result = WebSearchTool(engine="youcom").execute(query="q")
+
+ assert result.success is False
+ assert "ddgs" in result.content
+
+
+class TestYouComContentsExtraction:
+ def _mock_ssrf(self, monkeypatch):
+ import openjarvis.tools.web_search as _ws
+
+ monkeypatch.setattr(_ws, "check_ssrf", lambda url: None)
+
+ def test_contents_used_for_url_queries_when_keyed(self, monkeypatch):
+ """The URL branch upgrades from the regex HTML strip to extracted
+ markdown when a key is available."""
+ self._mock_ssrf(monkeypatch)
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "ydc-key")
+ import httpx
+
+ resp = MagicMock()
+ resp.json.return_value = [
+ {"url": "https://example.com/a", "markdown": "# Heading\n\nBody text."}
+ ]
+ resp.raise_for_status = MagicMock()
+ post = MagicMock(return_value=resp)
+ monkeypatch.setattr(httpx, "post", post)
+
+ result = WebSearchTool(engine="youcom").execute(query="https://example.com/a")
+
+ assert result.success is True
+ assert result.content == "# Heading\n\nBody text."
+ assert result.metadata["extractor"] == "youcom_contents"
+ assert post.call_args.kwargs["json"]["formats"] == ["markdown"]
+
+ def test_keyless_url_query_uses_local_fetch(self, monkeypatch):
+ """Contents needs a key, so keyless installs keep the local fetch."""
+ self._mock_ssrf(monkeypatch)
+ monkeypatch.delenv("YOUDOTCOM_API_KEY", raising=False)
+ import httpx
+
+ resp = MagicMock()
+ resp.text = "<html><body>Local text</body></html>"
+ resp.headers = {"content-type": "text/html"}
+ resp.raise_for_status = MagicMock()
+ monkeypatch.setattr(httpx, "get", MagicMock(return_value=resp))
+ monkeypatch.setattr(
+ httpx, "post", MagicMock(side_effect=AssertionError("must not be called"))
+ )
+
+ result = WebSearchTool(engine="youcom").execute(query="https://example.com/a")
+
+ assert "Local text" in result.content
+ assert result.metadata["extractor"] == "local"
+
+ def test_contents_failure_falls_back_to_local_fetch(self, monkeypatch):
+ self._mock_ssrf(monkeypatch)
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "ydc-key")
+ import httpx
+
+ monkeypatch.setattr(
+ httpx, "post", MagicMock(side_effect=httpx.ConnectError("down"))
+ )
+ resp = MagicMock()
+ resp.text = "<html><body>Local text</body></html>"
+ resp.headers = {"content-type": "text/html"}
+ resp.raise_for_status = MagicMock()
+ monkeypatch.setattr(httpx, "get", MagicMock(return_value=resp))
+
+ result = WebSearchTool(engine="youcom").execute(query="https://example.com/a")
+
+ assert result.success is True
+ assert "Local text" in result.content
+ assert result.metadata["extractor"] == "local"
+
+ def test_url_branch_ssrf_blocked_before_contents_call(self, monkeypatch):
+ """The Contents upgrade must not become an SSRF bypass."""
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "ydc-key")
+ import openjarvis.tools.web_search as _ws
+
+ monkeypatch.setattr(_ws, "check_ssrf", lambda url: "private IP blocked")
+ import httpx
+
+ monkeypatch.setattr(
+ httpx, "post", MagicMock(side_effect=AssertionError("must not be called"))
+ )
+
+ result = WebSearchTool(engine="youcom").execute(
+ query="http://169.254.169.254/metadata"
+ )
+
+ assert result.success is False
+ assert "private IP blocked" in result.content