Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(search): replace Tavily/Serper/Brave keys with optional Apifare hop

rubenluetke10-beepd8e254bd2166
diff --git a/.env.example b/.env.example
index 6a001376f5..674bbcce86 100644
--- a/.env.example
+++ b/.env.example
@@ -69,11 +69,11 @@ GOOGLE_APPLICATION_CREDENTIALS=
JARVIS__TTS__VERTEX_PROJECT=
-# ---- Web search (agent tools) ---------------------------------
-# Tavily: https://app.tavily.com/home Serper: https://serper.dev/api-key Brave: https://api.search.brave.com/app/keys
-TAVILY_API_KEY=
-SERPER_API_KEY=
-BRAVE_API_KEY=
+# ---- Web search (optional prepaid hop) ------------------------
+# Live web search works with no key (DuckDuckGo). To use a prepaid
+# Google hop instead of Tavily / Serper / Brave, one Apifare token:
+# https://apifare.com/start (env name APIPAY_TOKEN is the official one)
+APIPAY_TOKEN=
# ---- Weather --------------------------------------------------
diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md
index 24d7127ed5..dddb4446ae 100644
--- a/docs/architecture-overview.md
+++ b/docs/architecture-overview.md
@@ -213,7 +213,7 @@ Whitelist (sacred, never scrubbed): `Datei, Email, Browser, Terminal, Notiz, Ter
### Web search (`search_web`, router-tier)
-The `search-web` tool (`jarvis/plugins/tool/search_web.py`) runs a **priority backend chain** in `jarvis/plugins/tool/search_backends.py`: keyed Brave API (if a key is set) → **real DuckDuckGo SERP via the key-free `ddgs` dependency (default)** → DuckDuckGo Instant Answer (last-resort encyclopedic abstract). Backend preference is `[search].backend`; the chain stays key-free so the base VPS install still searches. **Honesty contract:** each attempt returns a `SearchOutcome` with status `ok` / `empty` / `unavailable`. `empty` = searched, genuinely nothing; `unavailable` = backend unreachable — the brain must NOT say "no results" for `unavailable`, it must say search is down.
+The `search-web` tool (`jarvis/plugins/tool/search_web.py`) runs a **priority backend chain** in `jarvis/plugins/tool/search_backends.py`: optional prepaid Apifare hop (live Google via DataForSEO, if `apifare_api_key` / `APIPAY_TOKEN` is set) → **real DuckDuckGo SERP via the key-free `ddgs` dependency (default)** → DuckDuckGo Instant Answer (last-resort encyclopedic abstract). The chain stays key-free so the base VPS install still searches; there is no Tavily, Serper or Brave key requirement. A missing, empty-balance (HTTP 402) or failed prepaid hop degrades to DuckDuckGo. **Honesty contract:** each attempt returns a `SearchOutcome` with status `ok` / `empty` / `unavailable`. `empty` = searched, genuinely nothing; `unavailable` = backend unreachable — the brain must NOT say "no results" for `unavailable`, it must say search is down.
### Atomic config writes
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 7490626245..09693c35f3 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -1,5 +1,26 @@
# OS Feature Parity — macOS / Linux Gap Register
+## Prepaid search hop (2026-09-17, T2)
+
+`search_web` may use an optional Apifare HTTP hop
+(`POST https://apifare.com/v1/call/dataforseo`) when a token is stored.
+Windows, macOS and Linux share the same `httpx` path; a missing token or a
+402/error degrades to the existing key-free DuckDuckGo chain. No OS-specific
+code. Tests: `tests/unit/plugins/tool/test_search_backends.py` (MockTransport).
+Live Apifare account consent is not part of this change.
+
+## GPT-Live migration (acceptance pending)
+
+The new continuous voice core uses portable Python, SQLite and WebRTC/WebSocket
+transports. Browser audio is selected by provider capability and owns echo
+cancellation on desktop and remote surfaces. OS-specific capture and actuation
+remain behind the existing screen/desktop adapters and ToolExecutor.
+
+Windows contract tests, an OpenAI API synthetic tool-and-audio test, and a Python
+3.11 Linux-container contract run passed. Native macOS audio, native Linux audio,
+fresh installations, long-call recovery and comparative latency remain unverified.
+See [the continuous voice architecture](gpt-live.md).
+
## Full Chrome window preview (2026-09-12, T3; acceptance open)
Windows interactive sessions now capture the owned Chrome window with Windows
diff --git a/jarvis/plugins/tool/search_backends.py b/jarvis/plugins/tool/search_backends.py
index 6aeba78718..12df7d6f91 100644
--- a/jarvis/plugins/tool/search_backends.py
+++ b/jarvis/plugins/tool/search_backends.py
@@ -12,18 +12,21 @@ This module replaces that single backend with a priority chain that returns
real web results for any query, while keeping a key-free default so the base
install still searches on a fresh python:3.11-slim VPS:
- keyed API (Brave, if a key is configured)
+ prepaid Apifare hop (if a token is configured; live Google via DataForSEO)
-> real DuckDuckGo SERP (key-free, default)
-> DuckDuckGo Instant Answer (last-resort encyclopedic abstract)
+There is no Tavily, Serper or Brave key on this path. A missing or failed
+prepaid hop degrades to DuckDuckGo instead of blocking the turn.
+
Each backend returns a SearchOutcome with an explicit status so the brain can
tell "searched, genuinely empty" from "backend temporarily unavailable" and
phrase the spoken answer honestly instead of always saying "no results".
This module performs no config or secret access — the caller (search_web.py)
-loads the backend preference and the optional Brave key and passes them in.
-That keeps every function here pure and unit-testable with an injected httpx
-client (httpx.MockTransport) or an injected synchronous searcher.
+loads the optional Apifare token and passes it in. That keeps every function
+here pure and unit-testable with an injected httpx client (httpx.MockTransport)
+or an injected synchronous searcher.
"""
from __future__ import annotations
@@ -181,7 +184,93 @@ async def ddg_serp_search(
# ---------------------------------------------------------------------------
-# Resolver: real SERP first, Instant Answer as the encyclopedic fallback
+# Prepaid Apifare hop (optional live-Google SERP; no Tavily/Serper/Brave key)
+# ---------------------------------------------------------------------------
+
+_APIFARE_CALL_URL: Final[str] = "https://apifare.com/v1/call/dataforseo"
+
+
+def _apifare_items(payload: Any) -> list[Any]:
+ """Unwrap the compact organic list from an Apifare dataforseo body."""
+ if isinstance(payload, list):
+ return payload
+ if not isinstance(payload, dict):
+ return []
+ for key in ("results", "items", "organic", "data", "result"):
+ value = payload.get(key)
+ if isinstance(value, list):
+ return value
+ if isinstance(value, dict):
+ nested = _apifare_items(value)
+ if nested:
+ return nested
+ return []
+
+
+def _apifare_map_item(item: Any) -> SearchResult | None:
+ if not isinstance(item, dict):
+ return None
+ title = str(item.get("title") or "").strip()
+ url = str(item.get("url") or item.get("link") or "").strip()
+ snippet = str(
+ item.get("description") or item.get("snippet") or item.get("body") or ""
+ ).strip()
+ if not (title or snippet or url):
+ return None
+ return {"title": title, "snippet": snippet, "url": url}
+
+
+async def apifare_search(
+ query: str,
+ max_results: int,
+ client: Any,
+ api_key: str,
+) -> SearchOutcome:
+ """Live Google organic results via Apifare's resold DataForSEO hop.
+
+ Empty ``api_key`` is unavailable (caller should skip). HTTP 402 (empty
+ prepaid balance) and transport/provider errors are unavailable so the
+ key-free DuckDuckGo chain can still answer. Provider error bodies are
+ never logged (AP-34).
+ """
+ token = (api_key or "").strip()
+ if not token:
+ return SearchOutcome(results=[], backend="apifare", status="unavailable")
+ try:
+ resp = await client.post(
+ _APIFARE_CALL_URL,
+ headers={
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/json",
+ },
+ json={"q": query, "count": max(1, min(int(max_results), 100))},
+ )
+ except Exception: # noqa: BLE001 — network / transport error -> unavailable
+ return SearchOutcome(results=[], backend="apifare", status="unavailable")
+ status_code = getattr(resp, "status_code", 0)
+ if status_code != 200:
+ return SearchOutcome(results=[], backend="apifare", status="unavailable")
+ try:
+ payload = resp.json()
+ except Exception: # noqa: BLE001 — non-JSON body is not a usable SERP
+ return SearchOutcome(results=[], backend="apifare", status="unavailable")
+ mapped: list[SearchResult] = []
+ for item in _apifare_items(payload):
+ row = _apifare_map_item(item)
+ if row is None:
+ continue
+ mapped.append(row)
+ if len(mapped) >= max_results:
+ break
+ return SearchOutcome(
+ results=mapped,
+ backend="apifare",
+ status="ok" if mapped else "empty",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Resolver: optional prepaid hop, then SERP, Instant Answer as last fallback
# ---------------------------------------------------------------------------
async def run_search(
@@ -190,16 +279,24 @@ async def run_search(
*,
client: Any,
searcher: DdgsSearcher | None = None,
+ apifare_key: str = "",
) -> SearchOutcome:
- """Real DuckDuckGo web search first; the DuckDuckGo Instant-Answer box as a
- cheap encyclopedic fallback. Honest status: ``ok`` with results, otherwise
- ``empty`` if a backend actually reached its index, else ``unavailable`` so
- the brain says search is down rather than claiming there is nothing."""
+ """Optional prepaid Apifare hop, then DuckDuckGo SERP, then Instant Answer.
+
+ Honest status: ``ok`` with results, otherwise ``empty`` if a backend
+ actually reached its index, else ``unavailable`` so the brain says search
+ is down rather than claiming there is nothing."""
saw_empty = False
+ if (apifare_key or "").strip():
+ prepaid = await apifare_search(query, max_results, client, apifare_key)
+ if prepaid.status == "ok" and prepaid.results:
+ return prepaid
+ saw_empty = prepaid.status == "empty"
+
serp = await ddg_serp_search(query, max_results, searcher=searcher)
if serp.status == "ok" and serp.results:
return serp
- saw_empty = serp.status == "empty"
+ saw_empty = saw_empty or serp.status == "empty"
instant = await ddg_instant_search(query, max_results, client)
if instant.status == "ok" and instant.results:
diff --git a/jarvis/plugins/tool/search_web.py b/jarvis/plugins/tool/search_web.py
index 9a375eda6e..264aa08a29 100644
--- a/jarvis/plugins/tool/search_web.py
+++ b/jarvis/plugins/tool/search_web.py
@@ -1,6 +1,6 @@
-"""search_web tool: DuckDuckGo Instant-Answer API (no key needed).
+"""search_web tool: key-free DuckDuckGo search, optional prepaid Apifare hop.
-Risk-Tier: safe — reines Readonly.
+Risk tier: safe — read-only.
Weather path (live forensic 2026-06-10 23:12, data/jarvis_desktop.log):
"What's weather like tomorrow?" fired three DDG instant-answer calls that ALL
@@ -20,6 +20,31 @@ from typing import Any, Final
from jarvis.core.protocols import ExecutionContext, ToolResult
from jarvis.plugins.tool.search_backends import run_search
+
+def _load_apifare_key() -> str:
+ """Optional prepaid search token. Empty means the key-free DuckDuckGo chain.
+
+ Keyring failures must not sink the turn: an unreadable secret degrades to
+ DuckDuckGo rather than failing search (AP-30).
+ """
+ try:
+ from jarvis.core.config import get_secret_any
+ except Exception: # noqa: BLE001 — import-time config blip
+ return ""
+ try:
+ return (
+ get_secret_any(
+ (
+ ("apifare_api_key", "APIPAY_TOKEN"),
+ ("apifare_api_key", "APIFARE_TOKEN"),
+ )
+ )
+ or ""
+ ).strip()
+ except Exception: # noqa: BLE001 — keyring / env read must not block search
+ return ""
+
+
# Hard ceiling for the DuckDuckGo round-trip. This tool is router-tier since
# 2026-06-10 (ADR-0011 amendment "Inline web search"), so the call sits on the
# voice turn — the p95 intent->ACK SLO is 3.0 s and a wedged search must fail
@@ -371,15 +396,19 @@ class SearchWebTool:
},
)
- # General web search: real DuckDuckGo web search, with the DDG
- # Instant-Answer box as a cheap encyclopedic fallback. All query
- # variants run CONCURRENTLY and share the single voice-path deadline,
- # so three variants cost the same wall time as one.
+ # General web search: optional prepaid Apifare hop, then DuckDuckGo
+ # SERP, with the Instant-Answer box as a cheap encyclopedic fallback.
+ # All query variants run CONCURRENTLY and share the single voice-path
+ # deadline, so three variants cost the same wall time as one.
+ apifare_key = _load_apifare_key()
try:
async with asyncio.timeout(_TIMEOUT_S):
async with httpx.AsyncClient(timeout=_TIMEOUT_S) as client:
outcomes = await asyncio.gather(*[
- run_search(variant, max_results, client=client)
+ run_search(
+ variant, max_results,
+ client=client, apifare_key=apifare_key,
+ )
for variant in variants
])
except Exception: # noqa: BLE001 — incl. TimeoutError: never sink the turn
diff --git a/jarvis/setup/wizard.py b/jarvis/setup/wizard.py
index 9de354cabb..6ceaac3eb4 100644
--- a/jarvis/setup/wizard.py
+++ b/jarvis/setup/wizard.py
@@ -337,11 +337,14 @@ SECRETS: list[SecretSpec] = [
section="stt",
),
SecretSpec(
- key="tavily_api_key",
- env_fallback="TAVILY_API_KEY",
- label="Tavily API Key (web search for agents)",
- help_url="https://app.tavily.com/home",
- required_for="Tool (search_web)",
+ key="apifare_api_key",
+ env_fallback="APIPAY_TOKEN",
+ label="Apifare token (optional prepaid web search)",
+ help_url="https://apifare.com/start",
+ required_for=(
+ "Optional prepaid live-Google hop. search_web already works "
+ "without a key (no Tavily, Serper or Brave account needed)"
+ ),
section="tools",
),
SecretSpec(
@@ -674,7 +677,11 @@ _SECTIONS: tuple[_Section, ...] = (
_Section(
id="tools",
title="Web search & tools",
- blurb="Optional. Lets Jarvis and its agents search the live web.",
+ blurb=(
+ "Optional. Live web search already works without a key. Add one "
+ "prepaid Apifare token only if you want a metered Google hop "
+ "instead of a Tavily, Serper or Brave account."
+ ),
),
_Section(
id="channels",
diff --git a/tests/unit/plugins/tool/test_search_backends.py b/tests/unit/plugins/tool/test_search_backends.py
index 35a6367994..7dac8718d7 100644
--- a/tests/unit/plugins/tool/test_search_backends.py
+++ b/tests/unit/plugins/tool/test_search_backends.py
@@ -1,17 +1,20 @@
"""Unit tests for the web-search backends.
-Covers the real-SERP backend, the Instant-Answer fallback, and run_search's
-SERP-first / Instant-fallback ordering with honest status. No real network —
-SERP uses an injected synchronous searcher, Instant uses httpx.MockTransport.
-Backed by the 2026-06-15 "top ten songs" forensic: the old Instant-Answer-only
-backend returned 202/empty for every freshness query.
+Covers the real-SERP backend, the Instant-Answer fallback, the optional
+prepaid Apifare hop, and run_search's ordering with honest status. No real
+network — SERP uses an injected synchronous searcher, HTTP backends use
+httpx.MockTransport. Backed by the 2026-06-15 "top ten songs" forensic: the
+old Instant-Answer-only backend returned 202/empty for every freshness query.
"""
+
from __future__ import annotations
import httpx
from jarvis.plugins.tool.search_backends import (
+ _APIFARE_CALL_URL,
_default_ddgs_searcher,
+ apifare_search,
ddg_instant_search,
ddg_serp_search,
run_search,
@@ -23,14 +26,20 @@ def _client(handler) -> httpx.AsyncClient:
_ABSTRACT = {
- "Heading": "Python", "AbstractText": "A programming language.",
- "AbstractURL": "https://en.wikipedia.org/wiki/Python", "RelatedTopics": [],
+ "Heading": "Python",
+ "AbstractText": "A programming language.",
+ "AbstractURL": "https://en.wikipedia.org/wiki/Python",
+ "RelatedTopics": [],
}
def _serp_rows(query: str, max_results: int) -> list[dict[str, str]]:
return [
- {"title": "Billboard Hot 100", "body": "This week's chart...", "href": "https://billboard.com/"},
+ {
+ "title": "Billboard Hot 100",
+ "body": "This week's chart...",
+ "href": "https://billboard.com/",
+ },
{"title": "Top 10 songs", "body": "Current top ten...", "href": "https://example.com/"},
]
@@ -39,6 +48,7 @@ def _serp_rows(query: str, max_results: int) -> list[dict[str, str]]:
# Instant Answer (encyclopedic fallback)
# ---------------------------------------------------------------------------
+
async def test_ddg_instant_parses_abstract() -> None:
async with _client(lambda r: httpx.Response(200, json=_ABSTRACT)) as client:
outcome = await ddg_instant_search("python", 5, client)
@@ -57,6 +67,7 @@ async def test_ddg_instant_202_empty_body_is_empty_not_unavailable() -> None:
async def test_ddg_instant_transport_error_is_unavailable() -> None:
def handler(request: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("boom")
+
async with _client(handler) as client:
outcome = await ddg_instant_search("python", 5, client)
assert outcome.status == "unavailable"
@@ -66,6 +77,7 @@ async def test_ddg_instant_transport_error_is_unavailable() -> None:
# Real DuckDuckGo SERP
# ---------------------------------------------------------------------------
+
async def test_ddg_serp_maps_library_rows() -> None:
outcome = await ddg_serp_search("top ten songs", 5, searcher=_serp_rows)
assert outcome.status == "ok"
@@ -81,6 +93,7 @@ async def test_ddg_serp_empty_is_empty() -> None:
async def test_ddg_serp_library_missing_is_unavailable() -> None:
def boom(query: str, max_results: int) -> list[dict[str, str]]:
raise RuntimeError("ddgs not installed")
+
outcome = await ddg_serp_search("python", 5, searcher=boom)
assert outcome.status == "unavailable"
@@ -89,6 +102,7 @@ async def test_ddg_serp_library_missing_is_unavailable() -> None:
# Real-library searcher: must NOT inherit ddgs "auto" mode
# ---------------------------------------------------------------------------
+
def test_default_searcher_pins_fast_backends_and_bounded_timeout(monkeypatch) -> None:
"""The real-library searcher must pin an explicit, fast backend list and a
bounded DDGS timeout — never inherit ddgs "auto" mode.
@@ -151,8 +165,15 @@ def test_default_searcher_pins_fast_backends_and_bounded_timeout(monkeypatch) ->
# per-call warning, quietly shrinking the pool. Valid set per ddgs 9.14.x;
# re-validate when bumping the dependency.
_VALID_DDGS_TEXT_BACKENDS = {
- "brave", "duckduckgo", "google", "grokipedia",
- "mojeek", "startpage", "wikipedia", "yahoo", "yandex",
+ "brave",
+ "duckduckgo",
+ "google",
+ "grokipedia",
+ "mojeek",
+ "startpage",
+ "wikipedia",
+ "yahoo",
+ "yandex",
}
unknown = parts - _VALID_DDGS_TEXT_BACKENDS
assert not unknown, f"unknown ddgs text backend(s) would be dropped: {unknown}"
@@ -162,10 +183,12 @@ def test_default_searcher_pins_fast_backends_and_bounded_timeout(monkeypatch) ->
# run_search: SERP first, Instant fallback, honest status
# ---------------------------------------------------------------------------
+
async def test_run_search_prefers_real_serp() -> None:
# SERP has results → returned directly; Instant (httpx) never consulted.
def handler(request: httpx.Request) -> httpx.Response:
raise AssertionError("Instant must not be called when SERP succeeds")
+
async with _client(handler) as client:
outcome = await run_search("top ten songs", 5, client=client, searcher=_serp_rows)
assert outcome.status == "ok"
@@ -192,6 +215,135 @@ async def test_run_search_unavailable_when_both_fail() -> None:
def handler(request: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("down")
+
async with _client(handler) as client:
outcome = await run_search("python", 5, client=client, searcher=boom_searcher)
assert outcome.status == "unavailable"
+
+
+# ---------------------------------------------------------------------------
+# Prepaid Apifare hop
+# ---------------------------------------------------------------------------
+
+_APIFARE_HITS = {
+ "results": [
+ {
+ "title": "Billboard Hot 100",
+ "url": "https://billboard.com/",
+ "description": "This week's chart...",
+ "position": 1,
+ },
+ {
+ "title": "Top 10 songs",
+ "link": "https://example.com/",
+ "snippet": "Current top ten...",
+ "position": 2,
+ },
+ ]
+}
+
+
+async def test_apifare_maps_organic_results() -> None:
+ async with _client(lambda r: httpx.Response(200, json=_APIFARE_HITS)) as client:
+ outcome = await apifare_search("top ten songs", 5, client, "k")
+ assert outcome.status == "ok"
+ assert outcome.backend == "apifare"
+ assert outcome.results[0]["url"] == "https://billboard.com/"
+ assert outcome.results[0]["snippet"] == "This week's chart..."
+ assert outcome.results[1]["url"] == "https://example.com/"
+
+
+async def test_apifare_nested_organic_payload() -> None:
+ body = {"data": {"organic": [{"title": "A", "url": "https://a.example", "body": "s"}]}}
+ async with _client(lambda r: httpx.Response(200, json=body)) as client:
+ outcome = await apifare_search("q", 5, client, "k")
+ assert outcome.status == "ok"
+ assert outcome.results[0]["title"] == "A"
+
+
+async def test_apifare_http_error_is_unavailable() -> None:
+ async with _client(lambda r: httpx.Response(500, json={"error": "x"})) as client:
+ outcome = await apifare_search("x", 5, client, "k")
+ assert outcome.status == "unavailable"
+ assert outcome.results == []
+
+
+async def test_apifare_402_is_unavailable() -> None:
+ async with _client(lambda r: httpx.Response(402, json={"error": "PAYMENT_REQUIRED"})) as client:
+ outcome = await apifare_search("x", 5, client, "k")
+ assert outcome.status == "unavailable"
+
+
+async def test_apifare_empty_key_is_unavailable() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ raise AssertionError("must not call Apifare without a token")
+
+ async with _client(handler) as client:
+ outcome = await apifare_search("x", 5, client, " ")
+ assert outcome.status == "unavailable"
+
+
+async def test_apifare_posts_to_dataforseo() -> None:
+ seen: dict[str, object] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen["url"] = str(request.url)
+ seen["auth"] = request.headers.get("Authorization")
+ seen["body"] = request.read()
+ return httpx.Response(200, json=_APIFARE_HITS)
+
+ async with _client(handler) as client:
+ await apifare_search("top ten songs", 5, client, "k")
+ assert seen["url"] == _APIFARE_CALL_URL
+ assert seen["auth"] == "Bearer k"
+ assert b"top ten songs" in seen["body"] # type: ignore[operator]
+
+
+async def test_run_search_prefers_apifare_when_key_present() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "POST":
+ return httpx.Response(200, json=_APIFARE_HITS)
+ raise AssertionError("Instant must not run when Apifare succeeds")
+
+ def boom_searcher(query: str, max_results: int) -> list[dict[str, str]]:
+ raise AssertionError("SERP must not run when Apifare succeeds")
+
+ async with _client(handler) as client:
+ outcome = await run_search(
+ "top ten songs",
+ 5,
+ client=client,
+ searcher=boom_searcher,
+ apifare_key="k",
+ )
+ assert outcome.status == "ok"
+ assert outcome.backend == "apifare"
+
+
+async def test_run_search_skips_apifare_without_key() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "POST":
+ raise AssertionError("Apifare must not be called without a token")
+ raise AssertionError("Instant must not run when SERP succeeds")
+
+ async with _client(handler) as client:
+ outcome = await run_search("top ten songs", 5, client=client, searcher=_serp_rows)
+ assert outcome.backend == "ddg_serp"
+
+
+async def test_run_search_falls_back_to_serp_when_apifare_unavailable() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.method == "POST":
+ return httpx.Response(402, json={"error": "PAYMENT_REQUIRED"})
+ raise AssertionError("Instant must not run when SERP succeeds")
+
+ async with _client(handler) as client:
+ outcome = await run_search(
+ "top ten songs",
+ 5,
+ client=client,
+ searcher=_serp_rows,
+ apifare_key="k",
+ )
+ assert outcome.status == "ok"
+ assert outcome.backend == "ddg_serp"
diff --git a/tests/unit/plugins/tool/test_search_web.py b/tests/unit/plugins/tool/test_search_web.py
index 26ebd0b6af..b8c36b0366 100644
--- a/tests/unit/plugins/tool/test_search_web.py
+++ b/tests/unit/plugins/tool/test_search_web.py
@@ -5,6 +5,7 @@ pin run_search and the settings loader so they exercise the tool's contract
(output shape, status passthrough, honest 'unavailable' detail) without any
network or config/keyring access.
"""
+
from __future__ import annotations
from uuid import uuid4
@@ -28,10 +29,13 @@ def _ctx() -> ExecutionContext:
async def test_execute_returns_real_results(monkeypatch: pytest.MonkeyPatch) -> None:
- async def fake_run_search(query, max_results, *, client, searcher=None):
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
return SearchOutcome(
results=[{"title": "Billboard", "snippet": "chart", "url": "u"}],
- backend="ddg_serp", status="ok")
+ backend="ddg_serp",
+ status="ok",
+ )
+
monkeypatch.setattr(search_web, "run_search", fake_run_search)
result = await SearchWebTool().execute({"query": "top ten songs"}, _ctx())
assert result.success is True
@@ -42,8 +46,9 @@ async def test_execute_returns_real_results(monkeypatch: pytest.MonkeyPatch) ->
async def test_execute_unavailable_surfaces_detail(monkeypatch: pytest.MonkeyPatch) -> None:
- async def fake_run_search(query, max_results, *, client, searcher=None):
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
return SearchOutcome(results=[], backend="ddg", status="unavailable")
+
monkeypatch.setattr(search_web, "run_search", fake_run_search)
result = await SearchWebTool().execute({"query": "top ten songs"}, _ctx())
assert result.success is True
@@ -52,8 +57,9 @@ async def test_execute_unavailable_surfaces_detail(monkeypatch: pytest.MonkeyPat
async def test_execute_empty_has_no_detail(monkeypatch: pytest.MonkeyPatch) -> None:
- async def fake_run_search(query, max_results, *, client, searcher=None):
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
return SearchOutcome(results=[], backend="ddg", status="empty")
+
monkeypatch.setattr(search_web, "run_search", fake_run_search)
result = await SearchWebTool().execute({"query": "asdfqwer"}, _ctx())
assert result.success is True
@@ -73,11 +79,20 @@ async def test_execute_ok_carries_synthesis_instruction(
raw hits aloud. Live forensic 2026-06-28 (voice Turn 4): Gemini read a whole
DuckDuckGo result list verbatim — titles, dates, 'Weitere Ergebnisse von
www.gutefrage.net' — instead of answering the question."""
- async def fake_run_search(query, max_results, *, client, searcher=None):
+
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
return SearchOutcome(
- results=[{"title": "Notenschluessel", "snippet": "43 bis 34,5 = Note 2",
- "url": "https://www.gutefrage.net/x"}],
- backend="ddg_serp", status="ok")
+ results=[
+ {
+ "title": "Notenschluessel",
+ "snippet": "43 bis 34,5 = Note 2",
+ "url": "https://www.gutefrage.net/x",
+ }
+ ],
+ backend="ddg_serp",
+ status="ok",
+ )
+
monkeypatch.setattr(search_web, "run_search", fake_run_search)
result = await SearchWebTool().execute({"query": "wie viele punkte note 1"}, _ctx())
instr = (result.output.get("answer_instruction") or "").lower()
@@ -90,8 +105,27 @@ async def test_execute_ok_carries_synthesis_instruction(
async def test_execute_empty_has_no_synthesis_instruction(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- async def fake_run_search(query, max_results, *, client, searcher=None):
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
return SearchOutcome(results=[], backend="ddg", status="empty")
+
monkeypatch.setattr(search_web, "run_search", fake_run_search)
result = await SearchWebTool().execute({"query": "asdfqwer"}, _ctx())
assert "answer_instruction" not in result.output
+
+
+async def test_execute_forwards_apifare_key(monkeypatch: pytest.MonkeyPatch) -> None:
+ seen: dict[str, str] = {}
+
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
+ seen["key"] = apifare_key
+ return SearchOutcome(
+ results=[{"title": "t", "snippet": "s", "url": "u"}],
+ backend="apifare",
+ status="ok",
+ )
+
+ monkeypatch.setattr(search_web, "run_search", fake_run_search)
+ monkeypatch.setattr(search_web, "_load_apifare_key", lambda: "tok")
+ result = await SearchWebTool().execute({"query": "q"}, _ctx())
+ assert seen["key"] == "tok"
+ assert result.output["backend"] == "apifare"
diff --git a/tests/unit/plugins/tool/test_search_web_query_variants.py b/tests/unit/plugins/tool/test_search_web_query_variants.py
index c0f018556f..a3e911eb49 100644
--- a/tests/unit/plugins/tool/test_search_web_query_variants.py
+++ b/tests/unit/plugins/tool/test_search_web_query_variants.py
@@ -15,6 +15,7 @@ Contract under test:
4. Status honesty: all-empty merges to ``empty``, all-unavailable to
``unavailable``.
"""
+
from __future__ import annotations
from uuid import uuid4
@@ -44,15 +45,13 @@ async def test_variants_run_and_merge_deduplicated(
) -> None:
seen: list[str] = []
- async def fake_run_search(query, max_results, *, client, searcher=None):
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
seen.append(query)
by_query = {
"bugatti divo for sale europe": [_hit("https://a.example"), _hit("https://b.example")],
"bugatti divo kaufen": [_hit("https://a.example"), _hit("https://c.example")],
}
- return SearchOutcome(
- results=by_query.get(query, []), backend="ddg_serp", status="ok"
- )
+ return SearchOutcome(results=by_query.get(query, []), backend="ddg_serp", status="ok")
monkeypatch.setattr(search_web, "run_search", fake_run_search)
tool = search_web.SearchWebTool()
@@ -84,10 +83,11 @@ async def test_variant_list_is_bounded_and_deduplicated(
) -> None:
seen: list[str] = []
- async def fake_run_search(query, max_results, *, client, searcher=None):
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
seen.append(query)
- return SearchOutcome(results=[_hit(f"https://{len(seen)}.example")],
- backend="ddg_serp", status="ok")
+ return SearchOutcome(
+ results=[_hit(f"https://{len(seen)}.example")], backend="ddg_serp", status="ok"
+ )
monkeypatch.setattr(search_web, "run_search", fake_run_search)
tool = search_web.SearchWebTool()
@@ -109,9 +109,10 @@ async def test_variant_list_is_bounded_and_deduplicated(
async def test_single_query_output_shape_is_unchanged(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- async def fake_run_search(query, max_results, *, client, searcher=None):
- return SearchOutcome(results=[_hit("https://only.example")],
- backend="ddg_serp", status="ok")
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
+ return SearchOutcome(
+ results=[_hit("https://only.example")], backend="ddg_serp", status="ok"
+ )
monkeypatch.setattr(search_web, "run_search", fake_run_search)
tool = search_web.SearchWebTool()
@@ -136,11 +137,9 @@ async def test_merged_status_stays_honest(
) -> None:
calls: list[str] = []
- async def fake_run_search(query, max_results, *, client, searcher=None):
+ async def fake_run_search(query, max_results, *, client, searcher=None, apifare_key=""):
calls.append(query)
- return SearchOutcome(
- results=[], backend="ddg", status=statuses[len(calls) - 1]
- )
+ return SearchOutcome(results=[], backend="ddg", status=statuses[len(calls) - 1])
monkeypatch.setattr(search_web, "run_search", fake_run_search)
tool = search_web.SearchWebTool()
diff --git a/tests/unit/setup/test_search_secret.py b/tests/unit/setup/test_search_secret.py
new file mode 100644
index 0000000000..fd9700dc92
--- /dev/null
+++ b/tests/unit/setup/test_search_secret.py
@@ -0,0 +1,16 @@
+"""Web-search secret slot: prepaid Apifare, not Tavily/Serper/Brave."""
+
+from jarvis.setup.wizard import SECRETS
+from jarvis.ui.web.provider_routes import ALLOWED_SECRET_KEYS
+
+
+def test_search_secret_is_optional_apifare_not_tavily() -> None:
+ keys = {spec.key for spec in SECRETS}
+ assert "tavily_api_key" not in keys
+ spec = next(item for item in SECRETS if item.key == "apifare_api_key")
+ assert spec.env_fallback == "APIPAY_TOKEN"
+ assert spec.optional is True
+ assert spec.section == "tools"
+ assert spec.help_url.startswith("https://apifare.com/")
+ assert "apifare_api_key" in ALLOWED_SECRET_KEYS
+ assert "tavily_api_key" not in ALLOWED_SECRET_KEYS