Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(credentials): default _probe + restore broadcasts for 4 missing providers
trohitgea774307f7a9
diff --git a/server/nodes/search/brave_search.py b/server/nodes/search/brave_search.pyindex 5a33a7d9..d01ac396 100644--- a/server/nodes/search/brave_search.py+++ b/server/nodes/search/brave_search.py@@ -36,6 +36,10 @@ class BraveSearchCredential(ApiKeyCredential):key_name = "X-Subscription-Token"key_location = "header"docs_url = "https://api.search.brave.com/app/keys"+ # Lightweight probe — minimal query, count=1 just to confirm the+ # token authenticates against the web-search endpoint.+ probe_url = "https://api.search.brave.com/res/v1/web/search"+ probe_params = {"q": "ping", "count": 1}class BraveSearchResult(BaseModel):diff --git a/server/nodes/search/perplexity_search.py b/server/nodes/search/perplexity_search.pyindex def5a930..ea22eda2 100644--- a/server/nodes/search/perplexity_search.py+++ b/server/nodes/search/perplexity_search.py@@ -30,6 +30,15 @@ class PerplexityCredential(ApiKeyCredential):key_name = "Authorization"key_location = "bearer"docs_url = "https://docs.perplexity.ai/guides/getting-started"+ # Cheapest valid request: minimal completion, max_tokens=1.+ # Sonar is the always-available default model -- no entitlement gate.+ probe_url = "https://api.perplexity.ai/chat/completions"+ probe_method = "POST"+ probe_json = {+ "model": "sonar",+ "messages": [{"role": "user", "content": "ping"}],+ "max_tokens": 1,+ }class PerplexityResult(BaseModel):diff --git a/server/nodes/search/serper_search.py b/server/nodes/search/serper_search.pyindex b48cfd40..3457539d 100644--- a/server/nodes/search/serper_search.py+++ b/server/nodes/search/serper_search.py@@ -23,6 +23,9 @@ class SerperCredential(ApiKeyCredential):key_name = "X-API-KEY"key_location = "header"docs_url = "https://serper.dev/api-key"+ probe_url = "https://google.serper.dev/search"+ probe_method = "POST"+ probe_json = {"q": "ping", "num": 1}class SerperSearchResult(BaseModel):diff --git a/server/nodes/telegram/_credentials.py b/server/nodes/telegram/_credentials.pyindex f5c77782..16f04416 100644--- a/server/nodes/telegram/_credentials.py+++ b/server/nodes/telegram/_credentials.py@@ -5,7 +5,17 @@ Used by the two telegram plugins in this folder (telegram_send, telegram_receivefrom __future__ import annotations-from services.plugin.credential import ApiKeyCredential+import httpx++from services.plugin.credential import ApiKeyCredential, ProbeResult+++# Telegram embeds the bot token in the URL path (``/bot<token>/getMe``)+# rather than in a header / query / Authorization slot, so the+# declarative ``probe_url`` shape doesn't fit. We override ``_probe``+# directly but reuse :meth:`_handle_probe_response` from the base for+# the 200-with-failure-envelope case.+_TELEGRAM_API = "https://api.telegram.org"class TelegramCredential(ApiKeyCredential):@@ -17,3 +27,44 @@ class TelegramCredential(ApiKeyCredential):key_location = "header"extra_fields = ("telegram_owner_chat_id",)docs_url = "https://core.telegram.org/bots"++ @classmethod+ async def _probe(cls, api_key: str) -> ProbeResult:+ """Validate via ``GET /bot<token>/getMe``.++ Telegram returns 401 for revoked tokens and 404 for malformed+ tokens; both surface as :class:`httpx.HTTPStatusError` and the+ base :meth:`Credential.validate` translates them via+ :func:`classify_credential_error`. A 200 with ``{ok: false}`` is+ rare but possible (legacy token shapes) and is caught in+ :meth:`_handle_probe_response`.+ """+ url = f"{_TELEGRAM_API}/bot{api_key}/getMe"+ async with httpx.AsyncClient(timeout=cls.probe_timeout_seconds) as client:+ response = await client.get(url)+ response.raise_for_status()+ return cls._handle_probe_response(response)++ @classmethod+ def _handle_probe_response(cls, response: httpx.Response) -> ProbeResult:+ payload = response.json()+ if not payload.get("ok"):+ return ProbeResult(+ valid=False,+ message=payload.get("description", "Telegram rejected the bot token"),+ )+ bot = payload.get("result") or {}+ username = bot.get("username")+ return ProbeResult(+ valid=True,+ message=(+ f"Telegram bot token is valid (@{username})"+ if username+ else "Telegram bot token is valid"+ ),+ extra={+ "bot_id": bot.get("id"),+ "bot_username": username,+ "bot_name": bot.get("first_name"),+ },+ )diff --git a/server/services/plugin/credential.py b/server/services/plugin/credential.pyindex 8a49e5a5..4a85a561 100644--- a/server/services/plugin/credential.py+++ b/server/services/plugin/credential.py@@ -347,6 +347,15 @@ class ApiKeyCredential(Credential):category = "Search"key_name = "X-Subscription-Token"key_location = "header"+ probe_url = "https://api.search.brave.com/res/v1/web/search"+ probe_params = {"q": "ping", "count": 1}++ Subclasses get a default :meth:`_probe` for free as long as they+ declare a ``probe_url``. Auth attaches via :meth:`inject` (header /+ query / bearer). Subclasses with bespoke validation (URL with+ embedded token, SDK-based probe, custom 200-with-error envelope)+ override :meth:`_probe` directly — see ``TelegramCredential``,+ ``GoogleMapsCredential``, ``ApifyCredential``."""auth: ClassVar[Literal["api_key"]] = "api_key"@@ -356,6 +365,20 @@ class ApiKeyCredential(Credential):# Extra fields stored alongside (e.g. "apify_account_id" for Apify)extra_fields: ClassVar[Sequence[str]] = ()+ # ---- Declarative HTTP probe ------------------------------------+ #+ # The default :meth:`_probe` builds a request from these attributes,+ # runs it through :meth:`inject` to attach the key, sends via httpx,+ # and calls :meth:`_handle_probe_response` on a 2xx response.+ # ``httpx.HTTPStatusError`` / ``TimeoutException`` / ``ConnectError``+ # propagate to :meth:`Credential.validate`, where+ # :func:`classify_credential_error` produces the user-facing message.+ probe_url: ClassVar[str] = "" # set to enable the default probe+ probe_method: ClassVar[str] = "GET"+ probe_params: ClassVar[Dict[str, Any]] = {}+ probe_json: ClassVar[Optional[Dict[str, Any]]] = None+ probe_timeout_seconds: ClassVar[float] = 10.0+@classmethodasync def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:from core.container import container@@ -390,3 +413,50 @@ class ApiKeyCredential(Credential):qs[name] = api_keyrequest = {**request, "params": qs}return request++ @classmethod+ async def _probe(cls, api_key: str) -> ProbeResult:+ """Default declarative HTTP probe.++ Subclasses set ``probe_url`` (and optionally ``probe_method``,+ ``probe_params``, ``probe_json``); auth attaches via+ :meth:`inject`. Override :meth:`_handle_probe_response` to+ extract provider-specific metadata or detect API-level failures+ embedded in a 2xx response (e.g. Telegram's ``{ok: false}``+ envelope, Maps' ``status: REQUEST_DENIED``).+ """+ if not cls.probe_url:+ raise NotImplementedError(+ f"Credential subclass {cls.__name__} must override _probe() "+ f"or set the `probe_url` class attribute"+ )++ request = cls.inject(+ {"api_key": api_key},+ {"headers": {}, "params": dict(cls.probe_params)},+ )++ async with httpx.AsyncClient(timeout=cls.probe_timeout_seconds) as client:+ response = await client.request(+ cls.probe_method,+ cls.probe_url,+ headers=request.get("headers") or None,+ params=request.get("params") or None,+ json=cls.probe_json,+ )+ response.raise_for_status()+ return cls._handle_probe_response(response)++ @classmethod+ def _handle_probe_response(cls, response: httpx.Response) -> ProbeResult:+ """Translate a 2xx probe response to a :class:`ProbeResult`.++ Default: success message only. Override to inspect the body —+ for example to surface bot identity (Telegram ``getMe``) or to+ catch wrapped failures that arrive as 200s (Telegram+ ``{ok: false}``).+ """+ return ProbeResult(+ valid=True,+ message=f"{cls.display_name or cls.id} API key is valid",+ )