This commit is contained in:
fangliquanflq 2026-08-14 13:43:42 +00:00 committed by GitHub
commit 816847e97c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 200 additions and 41 deletions

View File

@ -1,8 +1,8 @@
"""DuckDuckGo search plugin — bundled, auto-loaded.
Backed by the community ``ddgs`` Python package which scrapes DDG's HTML
results page. No API key required, but the package itself must be installed
(it's an optional dep — gated via :meth:`is_available`).
Backed by the community ``ddgs`` package on desktop platforms and a core-httpx
HTML fallback on Termux, where ddgs's native transport cannot run. No API key
is required.
"""
from __future__ import annotations

View File

@ -1,6 +1,6 @@
name: web-ddgs
version: 1.0.0
description: "DuckDuckGo web search via the ddgs Python package — no API key required. Install with `pip install ddgs`."
description: "DuckDuckGo web search without an API key; includes a Termux-compatible HTTP fallback."
author: NousResearch
kind: backend
provides_web_providers:

View File

@ -18,16 +18,18 @@ therefore runs in a disposable child process the parent can terminate/kill.
from __future__ import annotations
import concurrent.futures as cf
import json
import logging
import os
import subprocess
import sys
import time
from html.parser import HTMLParser
from typing import Any, Dict, Optional
from urllib.parse import parse_qs, urljoin, urlparse
from agent.web_search_provider import WebSearchProvider
from hermes_constants import is_termux
logger = logging.getLogger(__name__)
@ -49,6 +51,88 @@ class _SearchInterrupted(Exception):
"""Raised when tools.interrupt.is_interrupted() trips during a search wait."""
_DDG_HTML_ENDPOINT = "https://html.duckduckgo.com/html/"
def _decode_ddg_url(href: str) -> str:
"""Return the destination hidden inside DDG's redirect wrapper."""
absolute = urljoin(_DDG_HTML_ENDPOINT, href)
parsed = urlparse(absolute)
if parsed.hostname in {"duckduckgo.com", "www.duckduckgo.com"}:
destination = parse_qs(parsed.query).get("uddg")
if destination:
return destination[0]
return absolute
class _DDGHTMLParser(HTMLParser):
"""Extract the result fields emitted by DuckDuckGo's HTML endpoint."""
def __init__(self, limit: int) -> None:
super().__init__(convert_charrefs=True)
self.limit = limit
self.results: list[dict[str, Any]] = []
self._field: Optional[str] = None
self._depth = 0
self._current: Optional[dict[str, Any]] = None
def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None:
attributes = dict(attrs)
classes = set((attributes.get("class") or "").split())
if tag == "a" and "result__a" in classes:
if len(self.results) >= self.limit:
# A skipped result must also sever the previous result's
# snippet target; otherwise its snippet is appended there.
self._current = None
self._field = None
self._depth = 0
return
href = attributes.get("href") or ""
self._current = {
"title": "",
"url": _decode_ddg_url(href),
"description": "",
"position": len(self.results) + 1,
}
self.results.append(self._current)
self._field = "title"
self._depth = 1
elif "result__snippet" in classes and self._current is not None:
self._field = "description"
self._depth = 1
elif self._field:
self._depth += 1
def handle_endtag(self, tag: str) -> None:
if not self._field:
return
self._depth -= 1
if self._depth == 0:
self._field = None
def handle_data(self, data: str) -> None:
if self._field and self._current is not None:
current = str(self._current[self._field])
self._current[self._field] = " ".join(f"{current} {data}".split())
def _run_ddg_html_search(query: str, safe_limit: int) -> list[dict[str, Any]]:
"""Search DDG without the Android-incompatible ``primp`` transport."""
import httpx
response = httpx.post(
_DDG_HTML_ENDPOINT,
data={"q": query},
headers={"User-Agent": "Mozilla/5.0 (compatible; Hermes-Agent/1.0)"},
follow_redirects=True,
timeout=10,
)
response.raise_for_status()
parser = _DDGHTMLParser(safe_limit)
parser.feed(response.text)
return parser.results
def _run_ddgs_search(query: str, safe_limit: int) -> list[dict[str, Any]]:
"""Run the blocking ddgs query and return normalized hits.
@ -57,6 +141,9 @@ def _run_ddgs_search(query: str, safe_limit: int) -> list[dict[str, Any]]:
each individual HTTP request; the overall wall-clock cap is enforced by
the parent via process timeout (#68096).
"""
if is_termux():
return _run_ddg_html_search(query, safe_limit)
from ddgs import DDGS # type: ignore
results: list[dict[str, Any]] = []
@ -199,13 +286,10 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any]
)
_last_worker_proc = proc
# ``communicate`` runs in a side thread so the parent can poll interrupt /
# deadline without blocking. Killing the child unblocks communicate.
pool = cf.ThreadPoolExecutor(max_workers=1)
fut = pool.submit(proc.communicate, json.dumps(request))
timed_out = False
interrupted = False
raw = ""
input_payload: Optional[str] = json.dumps(request)
try:
deadline = time.monotonic() + _SEARCH_TIMEOUT_SECS
while True:
@ -217,22 +301,26 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any]
timed_out = True
break
try:
out, _err = fut.result(timeout=min(_POLL_INTERVAL_SECS, remaining))
out, _err = proc.communicate(
input_payload,
timeout=min(_POLL_INTERVAL_SECS, remaining),
)
input_payload = None
raw = out or ""
break
except cf.TimeoutError:
except subprocess.TimeoutExpired:
# communicate() retains its input after a timeout; subsequent
# calls must pass None and continue draining the same pipes.
input_payload = None
continue
finally:
_terminate_and_reap(proc)
# After kill, communicate should return promptly; don't block forever.
if not fut.done():
if not raw:
try:
out, _err = fut.result(timeout=_TERMINATE_GRACE_SECS)
if not raw:
raw = out or ""
except Exception: # noqa: BLE001
out, _err = proc.communicate(timeout=_TERMINATE_GRACE_SECS)
raw = out or ""
except (subprocess.TimeoutExpired, ValueError):
pass
pool.shutdown(wait=False, cancel_futures=True)
if interrupted:
raise _SearchInterrupted("DuckDuckGo search interrupted")
@ -240,7 +328,6 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any]
raise TimeoutError(
f"DuckDuckGo search timed out after {_SEARCH_TIMEOUT_SECS}s"
)
raw = raw.strip()
if not raw:
raise RuntimeError(
@ -281,12 +368,14 @@ class DDGSWebSearchProvider(WebSearchProvider):
return "DuckDuckGo (ddgs)"
def is_available(self) -> bool:
"""Return True when the ``ddgs`` package is importable.
"""Return True when the active platform's transport is available.
Probes the import once; cheap because Python caches the import. Must
NOT perform network I/O — runs at tool-registration time and on every
``hermes tools`` paint.
Termux uses core ``httpx``; other platforms probe ``ddgs`` once. Must
not perform network I/O because this runs during tool registration and
on every ``hermes tools`` paint.
"""
if is_termux():
return True
try:
import ddgs # noqa: F401
@ -307,13 +396,14 @@ class DDGSWebSearchProvider(WebSearchProvider):
a hard wall-clock timeout (``_SEARCH_TIMEOUT_SECS``) so a hung native
``primp`` call cannot freeze the Hermes process (#36776, #68096).
"""
try:
import ddgs # type: ignore # noqa: F401 — availability probe
except ImportError:
return {
"success": False,
"error": "ddgs package is not installed — run `pip install ddgs`",
}
if not is_termux():
try:
import ddgs # type: ignore # noqa: F401 — availability probe
except ImportError:
return {
"success": False,
"error": "ddgs package is not installed — run `pip install ddgs`",
}
# DDGS().text yields at most `max_results` items; we cap defensively
# in case the package ignores the hint.
@ -351,12 +441,13 @@ class DDGSWebSearchProvider(WebSearchProvider):
return {"success": True, "data": {"web": web_results}}
def get_setup_schema(self) -> Dict[str, Any]:
return {
schema = {
"name": "DuckDuckGo (ddgs)",
"badge": "free · no key · search only",
"tag": "Search via the ddgs Python package — no API key (pair with any extract provider)",
"tag": "Search DuckDuckGo without an API key (pair with any extract provider)",
"env_vars": [],
# Trigger `_run_post_setup("ddgs")` after the user picks this row
# so the ddgs Python package gets pip-installed on first selection.
"post_setup": "ddgs",
}
if not is_termux():
# The Android fallback uses core httpx; primp aborts under Termux.
schema["post_setup"] = "ddgs"
return schema

View File

@ -88,8 +88,66 @@ class TestDDGSProviderIsConfigured:
from plugins.web.ddgs.provider import DDGSWebSearchProvider
assert issubclass(DDGSWebSearchProvider, WebSearchProvider)
def test_termux_is_available_without_ddgs_and_skips_installer(self, monkeypatch):
import plugins.web.ddgs.provider as prov
monkeypatch.setattr(prov, "is_termux", lambda: True)
provider = prov.DDGSWebSearchProvider()
assert provider.is_available() is True
assert "post_setup" not in provider.get_setup_schema()
class TestDDGSProviderSearch:
def test_termux_uses_html_transport_without_importing_ddgs(self, monkeypatch):
import plugins.web.ddgs.provider as prov
monkeypatch.setattr(prov, "is_termux", lambda: True)
monkeypatch.setitem(sys.modules, "ddgs", None)
monkeypatch.setattr(
prov,
"_run_ddgs_search_bounded",
lambda query, safe_limit: [{"title": query, "position": safe_limit}],
)
result = prov.DDGSWebSearchProvider().search("termux query", limit=3)
assert result == {
"success": True,
"data": {"web": [{"title": "termux query", "position": 3}]},
}
def test_html_parser_decodes_redirects_and_normalizes_text(self):
from plugins.web.ddgs.provider import _DDGHTMLParser
parser = _DDGHTMLParser(limit=1)
parser.feed(
'<div class="result"><a class="result__a" '
'href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fa%3Fx%3D1">'
'<b>Example</b> &amp; result</a>'
'<a class="result__snippet">A <b>useful</b> description.</a></div>'
'<a class="result__a" href="https://ignored.example">Ignored</a>'
'<a class="result__snippet">Discarded description.</a>'
)
assert parser.results == [{
"title": "Example & result",
"url": "https://example.com/a?x=1",
"description": "A useful description.",
"position": 1,
}]
def test_termux_worker_dispatches_to_html_transport(self, monkeypatch):
import plugins.web.ddgs.provider as prov
expected = [{"title": "hit"}]
monkeypatch.setattr(prov, "is_termux", lambda: True)
monkeypatch.setattr(
prov, "_run_ddg_html_search", lambda query, limit: expected
)
assert prov._run_ddgs_search("q", 2) is expected
def test_happy_path_normalizes_results(self, monkeypatch):
_install_fake_ddgs(monkeypatch, text_results=[
{"title": "A", "href": "https://a.example.com", "body": "desc A"},
@ -233,6 +291,15 @@ class TestDDGSProcessIsolation:
class TestDDGSBackendWiring:
def test_termux_backend_available_without_ddgs(self, monkeypatch):
from tools import web_tools
monkeypatch.setitem(sys.modules, "ddgs", None)
monkeypatch.setattr("hermes_constants.is_termux", lambda: True)
assert web_tools._ddgs_package_importable() is True
assert web_tools._is_backend_available("ddgs") is True
def test_is_backend_available_true_when_package_importable(self, monkeypatch):
from tools import web_tools
monkeypatch.setattr(web_tools, "_ddgs_package_importable", lambda: True)

View File

@ -35,4 +35,3 @@ def test_slash_worker_accepts_profile_home():
assert "env" in call_kwargs
assert call_kwargs["env"]["HERMES_HOME"] == "/home/luke/.hermes/profiles/work"

View File

@ -353,13 +353,15 @@ def _is_backend_available(backend: str) -> bool:
def _ddgs_package_importable() -> bool:
"""Return True when the ``ddgs`` Python package can be imported.
"""Return True when the platform's bundled DDG transport is available.
ddgs is the only backend whose availability is driven by a package
presence rather than an env var / config entry. Wrapped in a helper
so auto-detect and ``_is_backend_available`` share the same check
(and tests can monkeypatch a single symbol).
Termux uses the provider's core-httpx fallback because ``ddgs`` aborts in
native ``primp`` code there. Other platforms require the optional package.
"""
from hermes_constants import is_termux
if is_termux():
return True
try:
import ddgs # noqa: F401
return True