Skip to content

The agent that grows with you

refactor(tools): collapse xai config-resolution chain, inline single-use web/x_search helpers, flatten guard ladders

Teknium61f834bfec5e
diff --git a/tools/web_result_cache.py b/tools/web_result_cache.py
index 3a8fa66f362..eb8f59fa4cd 100644
--- a/tools/web_result_cache.py
+++ b/tools/web_result_cache.py
@@ -68,10 +68,6 @@ def _host_slug(url: str) -> str:
return re.sub(r"[^A-Za-z0-9._-]", "-", host)[:60].strip("-") or "page"
-def _url_host(url: str) -> str:
- return (urlparse(url).hostname or "").strip("[]")
-
-
def _deep_copy(response: dict) -> dict:
"""Defensive copy so callers mutating a hit never corrupt the cached entry."""
return json.loads(json.dumps(response))
@@ -89,7 +85,8 @@ class SearchMemo:
self._store_lock = threading.Lock()
self._key_locks: Dict[tuple, threading.Lock] = {}
- def _key(self, provider: str, query: str, limit: int) -> tuple:
+ @staticmethod
+ def _key(provider: str, query: str, limit: int) -> tuple:
return (provider, normalize_query(query), bucket_limit(limit))
def lookup(self, provider: str, query: str, limit: int) -> Optional[dict]:
@@ -101,9 +98,8 @@ class SearchMemo:
if hit is None or time.monotonic() >= hit[0]:
self._store.pop(key, None)
return None
- response = hit[1]
logger.info("web_search cache hit: %r via %s", query, provider)
- return _deep_copy(response)
+ return _deep_copy(hit[1])
def store(self, provider: str, query: str, limit: int, response: dict) -> None:
"""Cache a SUCCESSFUL response for the bucketed key."""
@@ -169,9 +165,8 @@ def _cache_dir() -> Optional[Path]:
def _load_index() -> dict:
- path = (d / _INDEX_FILENAME) if (d := _cache_dir()) else None
try:
- data = json.loads(path.read_text(encoding="utf-8")) if path else {}
+ data = json.loads((_cache_dir() / _INDEX_FILENAME).read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except Exception: # noqa: BLE001 — missing/corrupt index == empty cache
return {}
@@ -225,7 +220,7 @@ def _is_cache_exempt_host(url: str) -> bool:
(staging, tunnels, previews) that must fetch live."""
try:
patterns = _web_config().get("cache_exempt_hosts") or []
- host = _url_host(url)
+ host = (urlparse(url).hostname or "").strip("[]")
if not isinstance(patterns, (list, tuple)) or not host:
return False
return any(_host_matches_pattern(host, str(p)) for p in patterns)
@@ -238,13 +233,12 @@ def _is_local_dev_url(url: str) -> bool:
Hostname heuristics only, no DNS: this is a freshness decision, not a security boundary (SSRF enforcement
lives in tools/url_safety.py, which blocks these by default anyway)."""
try:
- host = _url_host(url).lower()
- if not host:
- return True # unparseable → don't cache
- if host == "localhost" or host.endswith((".localhost", ".local")):
+ host = (urlparse(url).hostname or "").strip("[]").lower()
+ # Unparseable → don't cache; single-label (no "." / ":") == LAN name, not public DNS.
+ if not host or host == "localhost" or host.endswith((".localhost", ".local")):
return True
if "." not in host and ":" not in host:
- return True # single-label LAN name, not public DNS
+ return True
import ipaddress
try:
ip = ipaddress.ip_address(host)
@@ -289,10 +283,8 @@ def extract_cache_put(
return
try:
from tools.web_tools import MAX_STORED_TEXT_CHARS
- if len(content) > MAX_STORED_TEXT_CHARS:
- return
file_path = _entry_file_path(url, format, provider)
- if file_path is None:
+ if len(content) > MAX_STORED_TEXT_CHARS or file_path is None:
return
from tools.spill_safety import write_text_exclusive
write_text_exclusive(file_path, content, private=False, overwrite=True)
diff --git a/tools/web_tools.py b/tools/web_tools.py
index 0f76c42f44b..bdc74dd4902 100644
--- a/tools/web_tools.py
+++ b/tools/web_tools.py
@@ -12,7 +12,7 @@ Debug: ``WEB_TOOLS_DEBUG=true`` writes ``logs/web_tools_debug_<UUID>.json``.
import json
import logging
import os
-from typing import List, Dict, Any, Optional
+from typing import List, Any, Optional
import httpx # noqa: F401 — kept at module top so tests can patch tools.web_tools.httpx
# Vendor helpers re-exported so external code and test patches of ``tools.web_tools.<name>`` keep working.
@@ -105,6 +105,11 @@ def _registered_web_provider(backend: str):
return _registry_call("get_provider", None, backend) if backend else None
+def _list_registered_web_providers():
+ """All plugin-registered web providers (empty list on failure)."""
+ return _registry_call("list_providers", [])
+
+
def _probe(provider, method: str, context: str = "") -> Optional[bool]:
"""``bool(provider.<method>())``, or ``None`` if it raised (a broken provider is unavailable; *context* is
appended to the debug log line, e.g. " during readiness check")."""
@@ -116,11 +121,6 @@ def _probe(provider, method: str, context: str = "") -> Optional[bool]:
return None
-def _list_registered_web_providers():
- """All plugin-registered web providers (empty list on failure)."""
- return _registry_call("list_providers", [])
-
-
def _get_backend() -> str:
"""Shared web backend name. A stored ``web.backend`` is returned as-is — no availability probe, no
fallback — so a broken selection surfaces the vendor's honest error rather than silently rerouting.
@@ -182,15 +182,6 @@ def _get_extract_backend() -> str:
return _configured_backend("extract_backend") or _get_backend()
-def _xai_available() -> bool:
- # Cheap probe only (env var OR auth.json OAuth): resolve_xai_http_credentials() may hit the network.
- try:
- from tools.xai_http import has_xai_credentials
- return has_xai_credentials()
- except Exception:
- return False
-
-
def _ddgs_package_importable() -> bool:
"""ddgs is the only backend gated on package presence; single symbol so tests can patch it."""
try:
@@ -200,11 +191,19 @@ def _ddgs_package_importable() -> bool:
return False
-# Built-in backends and their cheap availability probes; any other name is a plugin-registered provider
-# resolved via the registry's ``is_available()``. Lambdas so test patches of module-level helpers (e.g.
-# _ddgs_package_importable, check_firecrawl_api_key) are honored at call time. Includes ``xai`` (probed via
-# has_xai_credentials(), not a registered provider) though the registry's _LEGACY_PREFERENCE omits it —
-# drop it here if xai ever registers.
+def _xai_available() -> bool:
+ # Cheap probe only (env var OR auth.json OAuth): resolve_xai_http_credentials() may hit the network.
+ try:
+ from tools.xai_http import has_xai_credentials
+ return has_xai_credentials()
+ except Exception:
+ return False
+
+
+# Built-in backends -> cheap availability probes; any other name is a plugin provider resolved via the
+# registry's ``is_available()``. Lambdas so test patches of module-level helpers (_ddgs_package_importable,
+# check_firecrawl_api_key) are honored at call time. ``xai`` is probed via has_xai_credentials(), not a
+# registered provider, though the registry's _LEGACY_PREFERENCE omits it — drop it if xai ever registers.
_BUILTIN_AVAILABILITY = {
"exa": lambda: _has_env("EXA_API_KEY"),
"parallel": lambda: _has_env("PARALLEL_API_KEY"),
@@ -241,7 +240,6 @@ def _web_requires_env() -> list[str]:
"TOOL_GATEWAY_USER_TOKEN",
]
-
_debug = DebugSession("web_tools", env_var="WEB_TOOLS_DEBUG")
@@ -302,12 +300,8 @@ def web_search_tool(query: str, limit: int = 5) -> str:
provider = get_active_search_provider()
if provider is None:
- response_data = {
- "success": False,
- "error": _no_provider_error(
- "search", "No web search provider configured. Run `hermes tools` to set one up."
- ),
- }
+ fallback = "No web search provider configured. Run `hermes tools` to set one up."
+ response_data = {"success": False, "error": _no_provider_error("search", fallback)}
else:
logger.info("Web search via %s: '%s' (limit: %d)", provider.name, query, limit)
response_data = _memoized_search(provider, query, limit)
@@ -371,8 +365,7 @@ async def web_extract_tool(urls: List[Any], format: str = None, char_limit: Opti
try:
logger.info("Extracting content from %d URL(s)", len(normalized_urls))
# SSRF protection — filter private/internal URLs before any backend.
- safe_urls, safe_indices = [], []
- ssrf_blocked: Dict[int, Dict[str, Any]] = {}
+ safe_urls, safe_indices, ssrf_blocked = [], [], {}
for index, url in zip(normalized_indices, normalized_urls):
if await async_is_safe_url(url):
safe_urls.append(url)
@@ -402,10 +395,10 @@ async def web_extract_tool(urls: List[Any], format: str = None, char_limit: Opti
debug_call_data["processing_applied"].append("truncate_and_store")
_truncate_results(results, _effective_char_limit(char_limit), debug_call_data)
trimmed = _trim_results(results)
- if not trimmed:
- result_json = tool_error("Content was inaccessible or not found")
- else:
- result_json = json.dumps({"results": trimmed}, indent=2, ensure_ascii=False)
+ result_json = (
+ json.dumps({"results": trimmed}, indent=2, ensure_ascii=False) if trimmed
+ else tool_error("Content was inaccessible or not found")
+ )
# Belt-and-suspenders sweep of the serialized JSON: a provider may tuck a base64 blob in metadata.
cleaned_result = convert_base64_images_to_links(result_json)
debug_call_data["final_response_size"] = len(cleaned_result)
@@ -437,11 +430,9 @@ def check_web_api_key() -> bool:
A plugin-registered provider reporting ``is_available()`` must light the tools up even with no
built-in credentials; resolution funnels through :func:`_is_backend_available`.
"""
- configured = _configured_backend()
- if configured and _is_backend_available(configured):
- return True
- # Boolean OR over built-ins — probe order is irrelevant here.
- if any(_is_backend_available(backend) for backend in _LEGACY_WEB_BACKENDS):
+ # Boolean OR over configured + built-ins — probe order is irrelevant here.
+ candidates = [c for c in (_configured_backend(),) if c] + list(_LEGACY_WEB_BACKENDS)
+ if any(_is_backend_available(backend) for backend in candidates):
return True
# Plugin path. Discovery must run first: check_fn fires at tool-registration time, before any dispatch.
try:
@@ -503,27 +494,17 @@ WEB_EXTRACT_SCHEMA = {
}
registry.register(
- name="web_search",
- toolset="web",
- schema=WEB_SEARCH_SCHEMA,
+ name="web_search", toolset="web", schema=WEB_SEARCH_SCHEMA,
handler=lambda args, **kw: web_search_tool(args.get("query", ""), limit=args.get("limit", 5)),
- check_fn=check_web_api_key,
- requires_env=_web_requires_env(),
- emoji="🔍",
+ check_fn=check_web_api_key, requires_env=_web_requires_env(), emoji="🔍",
max_result_size_chars=100_000,
)
registry.register(
- name="web_extract",
- toolset="web",
- schema=WEB_EXTRACT_SCHEMA,
+ name="web_extract", toolset="web", schema=WEB_EXTRACT_SCHEMA,
handler=lambda args, **kw: web_extract_tool(
- args.get("urls", [])[:5] if isinstance(args.get("urls"), list) else [],
- "markdown",
+ args.get("urls", [])[:5] if isinstance(args.get("urls"), list) else [], "markdown",
char_limit=args.get("char_limit"),
),
- check_fn=check_web_api_key,
- requires_env=_web_requires_env(),
- is_async=True,
- emoji="📄",
+ check_fn=check_web_api_key, requires_env=_web_requires_env(), is_async=True, emoji="📄",
max_result_size_chars=100_000,
)
diff --git a/tools/web_tools_extract.py b/tools/web_tools_extract.py
index fa95babe7d1..d9aa7051e75 100644
--- a/tools/web_tools_extract.py
+++ b/tools/web_tools_extract.py
@@ -57,8 +57,7 @@ def _strict_selection_error(capability: str, backend: str) -> str:
"""Error for a stored-but-unregistered backend: name the disabled plugin, else the bad selection.
Strict selection never silently switches to whatever the availability walk finds."""
failure = f"no registered web {capability} provider has that name"
- fallback = selection_error("web", f"'{backend}'", failure)
- return _no_provider_error(capability, fallback)
+ return _no_provider_error(capability, selection_error("web", f"'{backend}'", failure))
def _result_entry(url: str, error: Optional[str]) -> Dict[str, Any]:
@@ -93,9 +92,7 @@ def _validate_extract_urls(urls: List[Any]):
from agent.redact import _PREFIX_RE
from urllib.parse import unquote
- normalized_urls: List[str] = []
- normalized_indices: List[int] = []
- invalid_urls: Dict[int, Dict[str, Any]] = {}
+ normalized_urls, normalized_indices, invalid_urls = [], [], {}
for index, item in enumerate(urls):
_url = _web_extract_url(item)
if _url is None:
@@ -107,8 +104,7 @@ def _validate_extract_urls(urls: List[Any]):
"Blocked: URL contains what appears to be an API key or token. "
"Secrets must not be sent in URLs."
)
- sensitive_query_key = sensitive_query_param_name(normalized_url)
- if sensitive_query_key:
+ if sensitive_query_key := sensitive_query_param_name(normalized_url):
return _refuse_all(
"Blocked: URL contains a credential-like query parameter "
f"({sensitive_query_key}). Web extract backends are third-party "
@@ -169,10 +165,8 @@ async def _dispatch_extract(provider, fetch_urls: List[str], format: Optional[st
# Cache each successful fetch's full clean text (best-effort; oversized skipped).
for url, fetched in zip(fetch_urls, results):
- if fetched.get("error"):
- continue
_content = fetched.get("raw_content", "") or fetched.get("content", "")
- if _content:
+ if _content and not fetched.get("error"):
extract_cache_put(url, _content, fetched.get("title", ""), format=format, provider=provider.name)
return results
@@ -182,14 +176,11 @@ async def _extract_safe_urls(provider, safe_urls: List[str], format: Optional[st
The disk cache (tools/web_result_cache.py) sits AFTER the secret-URL gate, SSRF gate, and provider
resolution, and is gated per-URL on the website policy — a hit skips only the vendor call, never a
- control. Policy-blocked URLs are cache misses so dispatch handles them exactly as without a cache.
- Keys include provider and format, so switching either within the TTL never serves the other's content.
- """
+ control; policy-blocked URLs are cache misses. Keys include provider and format, so switching either
+ within the TTL never serves the other's content."""
from tools.web_result_cache import extract_cache_get
from tools.website_policy import check_website_access as _check_site
- cached_results: Dict[int, Dict[str, Any]] = {}
- fetch_urls: List[str] = []
- fetch_positions: List[int] = []
+ cached_results, fetch_urls, fetch_positions = {}, [], []
for position, url in enumerate(safe_urls):
try:
_policy_block = _check_site(url)
diff --git a/tools/web_tools_truncate.py b/tools/web_tools_truncate.py
index c5e935f9bd8..b12bb459370 100644
--- a/tools/web_tools_truncate.py
+++ b/tools/web_tools_truncate.py
@@ -51,14 +51,13 @@ def convert_base64_images_to_links(text: str) -> str:
out = re.sub(r"!\[(?P<alt>[^\]]*)\]\(\s*data:image/[^;]+;base64,[A-Za-z0-9+/=\s]+\)", _md_repl, text)
out = re.sub(r"\(\s*data:image/[^;]+;base64,[A-Za-z0-9+/=\s]+\)", "[IMAGE]", out)
- out = re.sub(r"data:image/[^;]+;base64,[A-Za-z0-9+/=]+", "[IMAGE]", out)
- return out
+ return re.sub(r"data:image/[^;]+;base64,[A-Za-z0-9+/=]+", "[IMAGE]", out)
def _store_full_text(url: str, content: str) -> Optional[str]:
- """Write the full page to cache/web; absolute path or None. cache/web is mounted read-only into remote
- backends (credential_files _CACHE_DIRS) so read_file can page the complete text on any backend.
- Best-effort: on failure the truncated content is still returned to the model."""
+ """Write the full page to cache/web; absolute path or None (best-effort: the truncated content is still
+ returned). cache/web is mounted read-only into remote backends (credential_files _CACHE_DIRS) so
+ read_file can page the complete text on any backend."""
try:
import hashlib
from hermes_constants import get_hermes_dir
@@ -92,17 +91,14 @@ def _truncate_with_footer(content: str, url: str, char_limit: int) -> tuple[str,
tail_budget = char_limit - head_budget
head, tail = content[:head_budget], content[-tail_budget:]
# Snap both cuts to line boundaries (head back, tail forward) so we never slice mid-line.
- nl = head.rfind("\n")
- if nl > head_budget * 0.5:
+ if (nl := head.rfind("\n")) > head_budget * 0.5:
head = head[:nl]
- nl = tail.find("\n")
- if 0 <= nl < tail_budget * 0.5:
+ if 0 <= (nl := tail.find("\n")) < tail_budget * 0.5:
tail = tail[nl + 1:]
stored_path = _store_full_text(url, content)
footer_lines = [
- "",
- "─" * 8 + " [TRUNCATED] " + "─" * 8,
+ "", "─" * 8 + " [TRUNCATED] " + "─" * 8,
f"Showing {len(head):,} chars (head) + {len(tail):,} chars (tail) "
f"of {len(content):,} total clean characters.",
]
@@ -134,11 +130,9 @@ def _truncate_results(results: List[dict], char_limit: int, debug_call_data: dic
"""In place: replace each successful entry's content with its base64-cleaned, budgeted text;
per-page truncation metrics go into ``debug_call_data``."""
for result in results:
- if result.get("error"):
- continue
url = result.get("url", "")
raw_content = result.get("raw_content", "") or result.get("content", "")
- if not raw_content:
+ if result.get("error") or not raw_content:
continue
clean = convert_base64_images_to_links(raw_content)
model_text, truncated = _truncate_with_footer(clean, url, char_limit)
diff --git a/tools/website_policy.py b/tools/website_policy.py
index 868ef4e1b40..796ef107d68 100644
--- a/tools/website_policy.py
+++ b/tools/website_policy.py
@@ -36,18 +36,12 @@ class WebsitePolicyError(Exception):
def _normalize_rule(rule: Any) -> Optional[str]:
"""Reduce a rule (bare host, URL, or ``host/path``) to a lowercase host; None for blanks/comments."""
- if not isinstance(rule, str):
- return None
- value = rule.strip().lower()
- if not value or value.startswith("#"):
+ if not isinstance(rule, str) or not (value := rule.strip().lower()) or value.startswith("#"):
return None
if "://" in value:
parsed = urlparse(value)
value = parsed.netloc or parsed.path
- value = value.split("/", 1)[0].strip().rstrip(".")
- if value.startswith("www."):
- value = value[4:]
- return value or None
+ return value.split("/", 1)[0].strip().rstrip(".").removeprefix("www.") or None
def _iter_blocklist_file_rules(path: Path) -> List[str]:
@@ -115,7 +109,6 @@ def load_website_blocklist(config_path: Optional[Path] = None) -> Dict[str, Any]
fresh = _cached_policy_path == resolved_path and (now - _cached_policy_time) < _CACHE_TTL_SECONDS
if _cached_policy is not None and fresh:
return _cached_policy
-
config_path = config_path or default_path
policy = _load_policy_config(config_path)
domains = map(_normalize_rule, _require_type(policy, "domains", list, []))
@@ -183,9 +176,8 @@ def check_website_access(url: str, config_path: Optional[Path] = None) -> Option
if not policy.get("enabled"):
return None
for rule in policy.get("rules", []):
- pattern = rule.get("pattern", "")
+ pattern, source = rule.get("pattern", ""), rule.get("source", "config")
if _match_host_against_rule(host, pattern):
- source = rule.get("source", "config")
logger.info("Blocked URL %s — matched rule '%s' from %s", url, pattern, source)
return {
"url": url, "host": host, "rule": pattern, "source": source,
diff --git a/tools/x_search_tool.py b/tools/x_search_tool.py
index 070af490315..2c5aff19962 100644
--- a/tools/x_search_tool.py
+++ b/tools/x_search_tool.py
@@ -34,7 +34,6 @@ MAX_HANDLES = 10
def _load_x_search_config() -> Dict[str, Any]:
try:
from hermes_cli.config import load_config
-
return load_config().get("x_search", {}) or {}
except Exception:
return {}
@@ -42,13 +41,11 @@ def _load_x_search_config() -> Dict[str, Any]:
def _get_x_search_reasoning_effort() -> Optional[str]:
raw_value = _load_x_search_config().get("reasoning_effort")
- if raw_value is None or not str(raw_value).strip():
- return None
- effort = str(raw_value).strip().lower()
- if effort not in X_SEARCH_REASONING_EFFORTS:
+ effort = str(raw_value).strip().lower() if raw_value is not None else ""
+ if effort and effort not in X_SEARCH_REASONING_EFFORTS:
allowed = ", ".join(X_SEARCH_REASONING_EFFORTS)
raise ValueError(f"x_search.reasoning_effort must be one of: {allowed} (got {raw_value!r})")
- return effort
+ return effort or None
def _get_x_search_int(key: str, default: int, floor: int) -> int:
@@ -59,11 +56,8 @@ def _get_x_search_int(key: str, default: int, floor: int) -> int:
def _resolve_xai_bearer() -> Tuple[str, str, str]:
- """Return ``(api_key, base_url, source)``; ``source`` is ``"xai-oauth"`` or ``"xai"``.
-
- Raises ``RuntimeError`` when no credential is usable so a credential that expires between
- registration and invocation yields a clean tool error, not a 401.
- """
+ """Return ``(api_key, base_url, source)``; ``source`` is ``"xai-oauth"`` or ``"xai"``. Raises RuntimeError
+ when no credential is usable (expiry between registration and call -> clean tool error, not a 401)."""
creds = resolve_xai_http_credentials(prefer_api_key=True)
api_key = str(creds.get("api_key") or "").strip()
if not api_key:
@@ -126,25 +120,20 @@ def _extract_response_text(payload: Dict[str, Any]) -> str:
output_text = str(payload.get("output_text") or "").strip()
if output_text:
return output_text
- parts = [
- str(content.get("text") or "").strip()
- for content in _message_contents(payload)
- if content.get("type") in {"output_text", "text"}
- ]
+ contents = (c for c in _message_contents(payload) if c.get("type") in {"output_text", "text"})
+ parts = (str(c.get("text") or "").strip() for c in contents)
return "\n\n".join(p for p in parts if p).strip()
def _extract_inline_citations(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
return [
{
- "url": annotation.get("url", ""),
- "title": annotation.get("title", ""),
- "start_index": annotation.get("start_index"),
- "end_index": annotation.get("end_index"),
+ "url": a.get("url", ""), "title": a.get("title", ""),
+ "start_index": a.get("start_index"), "end_index": a.get("end_index"),
}
for content in _message_contents(payload)
- for annotation in content.get("annotations", []) or []
- if annotation.get("type") == "url_citation"
+ for a in content.get("annotations", []) or []
+ if a.get("type") == "url_citation"
]
@@ -156,14 +145,12 @@ def _http_error_message(exc: requests.HTTPError) -> str:
payload = response.json()
except Exception:
payload = None
- if isinstance(payload, dict):
- code = str(payload.get("code") or "").strip()
- message = str(payload.get("error") or "").strip() or str(payload)
- if code and code not in message:
- message = f"{code}: {message}"
- return message or str(exc)
- text = str(getattr(response, "text", "") or "").strip()
- return text[:500] if text else str(exc)
+ if not isinstance(payload, dict):
+ text = str(getattr(response, "text", "") or "").strip()
+ return text[:500] if text else str(exc)
+ code = str(payload.get("code") or "").strip()
+ message = str(payload.get("error") or "").strip() or str(payload)
+ return (f"{code}: {message}" if code and code not in message else message) or str(exc)
def _error_json(error: str, exc: BaseException) -> str:
@@ -207,12 +194,9 @@ def _build_x_search_tool_def(
tool_def: Dict[str, Any] = {"type": "x_search"}
active_filters: List[str] = []
- for key, value in (
- ("allowed_x_handles", allowed),
- ("excluded_x_handles", excluded),
- ("from_date", from_date.strip()),
- ("to_date", to_date.strip()),
- ):
+ filters = (("allowed_x_handles", allowed), ("excluded_x_handles", excluded),
+ ("from_date", from_date.strip()), ("to_date", to_date.strip()))
+ for key, value in filters:
if value:
tool_def[key] = value
active_filters.append(key)
@@ -238,16 +222,16 @@ def x_search_tool(
api_key, base_url, source = _resolve_xai_bearer()
except RuntimeError as exc:
return tool_error(str(exc))
+ try:
+ tool_def, active_filters = _build_x_search_tool_def(
+ allowed_x_handles, excluded_x_handles, from_date, to_date,
+ enable_image_understanding, enable_video_understanding,
+ )
+ reasoning_effort = _get_x_search_reasoning_effort()
+ except ValueError as exc:
+ return tool_error(str(exc))
try:
- try:
- tool_def, active_filters = _build_x_search_tool_def(
- allowed_x_handles, excluded_x_handles, from_date, to_date,
- enable_image_understanding, enable_video_understanding,
- )
- reasoning_effort = _get_x_search_reasoning_effort()
- except ValueError as exc:
- return tool_error(str(exc))
payload = {
"model": str(_load_x_search_config().get("model") or "").strip() or DEFAULT_X_SEARCH_MODEL,
"input": [{"role": "user", "content": query.strip()}],
@@ -257,8 +241,7 @@ def x_search_tool(
if reasoning_effort:
payload["reasoning"] = {"effort": reasoning_effort}
headers = {
- "Authorization": f"Bearer {api_key}",
- "Content-Type": "application/json",
+ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json",
"User-Agent": hermes_xai_user_agent(),
}
data = _post_with_retries(f"{base_url}/responses", headers, payload).json()
@@ -267,24 +250,15 @@ def x_search_tool(
# xAI returns 200 with a synthesized answer even when no posts match the narrowing
# filters; with both citation channels empty the answer came from training data.
degraded = bool(active_filters) and not citations and not inline_citations
- return json.dumps(
- {
- "success": True,
- "provider": "xai",
- "credential_source": source,
- "tool": "x_search",
- "model": payload["model"],
- "query": query.strip(),
- "answer": _extract_response_text(data),
- "citations": citations,
- "inline_citations": inline_citations,
- "degraded": degraded,
- "degraded_reason": (
- f"no citations returned despite filters: {', '.join(active_filters)}" if degraded else None
- ),
- },
- ensure_ascii=False,
- )
+ result = {
+ "success": True, "provider": "xai", "credential_source": source, "tool": "x_search",
+ "model": payload["model"], "query": query.strip(), "answer": _extract_response_text(data),
+ "citations": citations, "inline_citations": inline_citations, "degraded": degraded,
+ "degraded_reason": (
+ f"no citations returned despite filters: {', '.join(active_filters)}" if degraded else None
+ ),
+ }
+ return json.dumps(result, ensure_ascii=False)
except requests.HTTPError as e:
logger.error("x_search failed: %s", e, exc_info=True)
return _error_json(_http_error_message(e), e)
diff --git a/tools/xai_http.py b/tools/xai_http.py
index dd0fa38d471..d51d94f4ab2 100644
--- a/tools/xai_http.py
+++ b/tools/xai_http.py
@@ -28,17 +28,12 @@ def has_xai_credentials() -> bool:
multi-account grants never write the providers singleton). Returns False on any exception
so a corrupted auth store can't block other availability scans.
"""
- try:
- from agent.secret_scope import get_secret
- except ImportError: # pragma: no cover — secret_scope is in-repo
- if os.environ.get("XAI_API_KEY", "").strip():
- return True
- else:
- if (get_secret("XAI_API_KEY", "") or "").strip():
- return True
+ from agent.secret_scope import get_secret
+
+ if (get_secret("XAI_API_KEY", "") or "").strip():
+ return True
try:
from hermes_constants import get_hermes_home
-
auth_path = get_hermes_home() / "auth.json"
if not auth_path.exists():
return False
@@ -81,17 +76,6 @@ def hermes_xai_default_headers() -> Dict[str, str]:
return {"User-Agent": hermes_xai_user_agent()}
-def _load_config_section(section_name: str) -> Dict[str, Any]:
- """Return a top-level Hermes config section as a dict, or empty."""
- try:
- from hermes_cli.config import load_config
-
- section = _dict_get(load_config(), section_name)
- return section if isinstance(section, dict) else {}
- except Exception:
- return {}
-
-
_TRUE_WORDS = {"1", "true", "yes", "on", "enabled"}
_FALSE_WORDS = {"0", "false", "no", "off", "disabled"}
@@ -99,10 +83,8 @@ _FALSE_WORDS = {"0", "false", "no", "off", "disabled"}
def _coerce_bool(value: Any, default: bool) -> bool:
if isinstance(value, bool):
return value
- if isinstance(value, str):
- normalized = value.strip().lower()
- if normalized in _TRUE_WORDS | _FALSE_WORDS:
- return normalized in _TRUE_WORDS
+ if isinstance(value, str) and (normalized := value.strip().lower()) in _TRUE_WORDS | _FALSE_WORDS:
+ return normalized in _TRUE_WORDS
return default
@@ -126,11 +108,12 @@ def _coerce_expires_after(value: Any) -> Optional[int]:
def read_xai_imagine_storage_config(section_name: str) -> Dict[str, Any]:
"""Read ``<section_name>.xai.storage`` (``image_gen``/``video_gen``) -> {enabled, public_url, expires_after}.
-
- Storage is on by default so xAI returns permanent public URLs instead of short-lived CDN
- URLs; ``expires_after: null`` means permanent.
- """
- storage = _dict_get(_dict_get(_load_config_section(section_name), "xai"), "storage")
+ On by default so xAI returns permanent public URLs, not short-lived CDN ones; null TTL = permanent."""
+ try:
+ from hermes_cli.config import load_config
+ storage = _dict_get(_dict_get(_dict_get(load_config(), section_name), "xai"), "storage")
+ except Exception:
+ storage = None
storage = storage if isinstance(storage, dict) else {}
return {
"enabled": _coerce_bool(storage.get("enabled"), True),
@@ -147,11 +130,8 @@ def build_xai_storage_options(
if not cfg["enabled"]:
return None
ts = datetime.datetime.now(datetime.UTC).strftime("%Y%m%d-%H%M%S")
- short = uuid.uuid4().hex[:8]
- ext = extension.lstrip(".") or "bin"
- payload: Dict[str, Any] = {
- "filename": f"{filename_prefix}-{ts}-{short}.{ext}", "public_url": bool(cfg["public_url"]),
- }
+ filename = f"{filename_prefix}-{ts}-{uuid.uuid4().hex[:8]}.{extension.lstrip('.') or 'bin'}"
+ payload: Dict[str, Any] = {"filename": filename, "public_url": bool(cfg["public_url"])}
if cfg["expires_after"] is not None:
payload["expires_after"] = cfg["expires_after"]
return payload
@@ -181,7 +161,6 @@ def maybe_mark_xai_storage_notice_seen(section_name: str) -> Optional[str]:
return None
try:
from hermes_constants import get_hermes_home
-
marker_dir = get_hermes_home() / "state"
marker_dir.mkdir(parents=True, exist_ok=True)
marker = marker_dir / f"{section_name}_xai_storage_notice_seen"
@@ -199,12 +178,8 @@ def _resolve_explicit_xai_api_key() -> str:
Both the preferred-key and the no-OAuth fallback paths go through here so scope policy
(incl. failing closed in a multiplexed gateway turn) is never re-implemented per caller.
"""
- try:
- from tools.tool_backend_helpers import resolve_provider_secret
-
- return resolve_provider_secret("XAI_API_KEY", "xai", env_getter=get_env_value)
- except ImportError: # pragma: no cover — helpers are in-repo
- return str(get_env_value("XAI_API_KEY") or "").strip()
+ from tools.tool_backend_helpers import resolve_provider_secret
+ return resolve_provider_secret("XAI_API_KEY", "xai", env_getter=get_env_value)
def _xai_base_url_override() -> str:
@@ -212,18 +187,6 @@ def _xai_base_url_override() -> str:
return str(get_env_value("HERMES_XAI_BASE_URL") or get_env_value("XAI_BASE_URL") or "").strip().rstrip("/")
-def _resolve_explicit_xai_base_url(default: str = DEFAULT_XAI_BASE_URL) -> str:
- """Base URL for the explicit-API-key path, origin-pinned via ``_xai_validate_inference_base_url``
- so a tampered env override can't exfiltrate the bearer; rejection falls back to ``default``."""
- override = _xai_base_url_override()
- try:
- import hermes_cli.auth as auth_mod
-
- return auth_mod._xai_validate_inference_base_url(override, fallback=default)
- except Exception: # pragma: no cover — auth is in-repo
- return override or default
-
-
def resolve_xai_http_credentials(
*, force_refresh: bool = False, api_key_hint: Optional[str] = None, prefer_api_key: bool = False,
) -> Dict[str, str]:
@@ -237,33 +200,30 @@ def resolve_xai_http_credentials(
pass the rejected bearer as ``api_key_hint`` so a multi-account pool refreshes the issuing
entry, not whichever its strategy selects first.
"""
- if prefer_api_key:
- explicit_key = str(_resolve_explicit_xai_api_key() or "").strip()
- if explicit_key:
- return {"provider": "xai", "api_key": explicit_key, "base_url": _resolve_explicit_xai_base_url()}
+ import hermes_cli.auth as auth_mod
+ if prefer_api_key and (explicit_key := str(_resolve_explicit_xai_api_key() or "").strip()):
+ # Origin-pinned so a tampered env override can't exfiltrate the bearer; rejection -> default URL.
+ override = _xai_base_url_override()
+ base_url = auth_mod._xai_validate_inference_base_url(override, fallback=DEFAULT_XAI_BASE_URL)
+ return {"provider": "xai", "api_key": explicit_key, "base_url": base_url}
try:
from agent.credential_pool import load_pool
- import hermes_cli.auth as auth_mod
-
pool = load_pool("xai-oauth")
entry = pool.try_refresh_matching(api_key_hint) if force_refresh else pool.select()
if force_refresh and entry is None:
# A rejected refresh may quarantine the issuing entry; continue with
# the next healthy account rather than resurrecting the stale row.
entry = pool.select()
- access_token = str(
- getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", "")
- ).strip()
+ access_token = getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", "")
fallback_base_url = str(
getattr(entry, "runtime_base_url", None)
or getattr(entry, "base_url", "")
or auth_mod.DEFAULT_XAI_OAUTH_BASE_URL
).strip().rstrip("/")
- override = _xai_base_url_override()
- base_url = auth_mod._xai_validate_inference_base_url(override, fallback=fallback_base_url)
- if access_token:
- return {"provider": "xai-oauth", "api_key": access_token, "base_url": base_url}
+ base_url = auth_mod._xai_validate_inference_base_url(_xai_base_url_override(), fallback=fallback_base_url)
+ if str(access_token).strip():
+ return {"provider": "xai-oauth", "api_key": str(access_token).strip(), "base_url": base_url}
except Exception:
pass
diff --git a/tools/xai_video_tools.py b/tools/xai_video_tools.py
index fed82308384..905d419907b 100644
--- a/tools/xai_video_tools.py
+++ b/tools/xai_video_tools.py
@@ -13,10 +13,9 @@ from tools.registry import registry, tool_error
def _configured_for_xai_video() -> bool:
try:
- cfg = load_config()
+ section = load_config().get("video_gen")
except Exception:
return False
- section = cfg.get("video_gen") if isinstance(cfg, dict) else None
return isinstance(section, dict) and section.get("provider") == "xai"
@@ -79,9 +78,7 @@ def _xai_video_schema(name: str, verb: str, noun: str, prompt_verb: str, extra:
}
-XAI_VIDEO_EDIT_SCHEMA: Dict[str, Any] = _xai_video_schema(
- "xai_video_edit", "Edit", "editing", "modify", {},
-)
+XAI_VIDEO_EDIT_SCHEMA: Dict[str, Any] = _xai_video_schema("xai_video_edit", "Edit", "editing", "modify", {})
XAI_VIDEO_EXTEND_SCHEMA: Dict[str, Any] = _xai_video_schema(
"xai_video_extend", "Extend", "extension", "continue", {
@@ -116,7 +113,6 @@ def _run_xai_video_tool(args: Dict[str, Any], op: str, run, **extra: Any) -> str
"error_type": "provider_not_configured",
"provider": "xai",
})
-
model = _clean_string(args.get("model"))
return json.dumps(run(prompt=prompt, video_url=video_url, model=model, **extra))