Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix: honor endpoint overrides for X search and Sonar (#1181)

Michel Tomas8e47fc9c6ee2
diff --git a/changelog.d/+base-url-x-search-sonar.fixed.md b/changelog.d/+base-url-x-search-sonar.fixed.md
new file mode 100644
index 00000000..e1e06e51
--- /dev/null
+++ b/changelog.d/+base-url-x-search-sonar.fixed.md
@@ -0,0 +1 @@
+`XAI_BASE_URL` and `OPENROUTER_BASE_URL` now also redirect the X search (`x_search`) and the OpenRouter Sonar fallback, not only the planner and rerank client, so a gateway or proxy sees every request that carries those keys. `--preflight` now lists `OPENROUTER_BASE_URL` among the active endpoint overrides.
diff --git a/skills/last30days/scripts/lib/permission_preflight.py b/skills/last30days/scripts/lib/permission_preflight.py
index 81c1b12c..e9a9c1be 100644
--- a/skills/last30days/scripts/lib/permission_preflight.py
+++ b/skills/last30days/scripts/lib/permission_preflight.py
@@ -12,6 +12,7 @@ ENDPOINT_OVERRIDE_KEYS = {
"LAST30DAYS_SEARXNG_URL",
"LAST30DAYS_YOUTUBE_SSH_HOST",
"OPENAI_BASE_URL",
+ "OPENROUTER_BASE_URL",
"XAI_BASE_URL",
"XIAOHONGSHU_API_BASE",
}
diff --git a/skills/last30days/scripts/lib/perplexity.py b/skills/last30days/scripts/lib/perplexity.py
index b4efe5f5..5e5cac8f 100644
--- a/skills/last30days/scripts/lib/perplexity.py
+++ b/skills/last30days/scripts/lib/perplexity.py
@@ -13,7 +13,7 @@ from datetime import datetime
from typing import Any
from urllib.parse import urlparse
-from . import health, http, log
+from . import health, http, log, providers
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
@@ -1077,8 +1077,9 @@ def _openrouter_sonar_search(
"Content-Type": "application/json",
}
_log(f"Querying OpenRouter {model} for '{query}' ({from_date} to {to_date})")
+ # Honor OPENROUTER_BASE_URL like the planner/rerank client does (providers.py).
data = http.post(
- OPENROUTER_URL,
+ providers.resolve_endpoint("OPENROUTER_BASE_URL", OPENROUTER_URL),
payload,
headers=headers,
timeout=120 if deep else 30,
diff --git a/skills/last30days/scripts/lib/xai_x.py b/skills/last30days/scripts/lib/xai_x.py
index 88622b17..bac0cd17 100644
--- a/skills/last30days/scripts/lib/xai_x.py
+++ b/skills/last30days/scripts/lib/xai_x.py
@@ -5,7 +5,7 @@ import re
import sys
from typing import Any, Dict, List, Optional
-from . import http, log
+from . import http, log, providers
def _safe_text(val) -> str:
@@ -132,13 +132,16 @@ def search_x(
],
}
+ # Honor XAI_BASE_URL like the planner/rerank client does (providers.py), so
+ # an override redirects every request that carries the xAI key, not only some.
+ url = providers.resolve_endpoint("XAI_BASE_URL", XAI_RESPONSES_URL)
# A single non-DNS attempt: the per-call timeout already spans the model's
# full live-search latency, and the inherited http default (retries=5)
# would turn one 90-180s call into a 10-15 minute stall. The shared chain
# deadline bounds the wait wall-clock; failover to the next X backend
# covers the miss.
return http.post(
- XAI_RESPONSES_URL, payload, headers=headers, timeout=timeout,
+ url, payload, headers=headers, timeout=timeout,
retries=1, deadline_monotonic=deadline_monotonic,
cancel=cancel,
)
diff --git a/tests/test_permission_preflight.py b/tests/test_permission_preflight.py
index c298c610..320c96bf 100644
--- a/tests/test_permission_preflight.py
+++ b/tests/test_permission_preflight.py
@@ -9,7 +9,7 @@ from contextlib import redirect_stderr, redirect_stdout
from unittest import mock
import last30days as cli
-from lib import env, permission_preflight, pipeline
+from lib import env, permission_preflight, pipeline, providers
DEFAULT_SAVE_DIR = "~" + "/Documents/Last30Days"
@@ -164,6 +164,53 @@ def test_preflight_reports_ignored_project_config_without_secret_values(tmp_path
assert "sk-global" not in rendered
+def test_preflight_lists_active_provider_base_url_overrides():
+ config = {
+ "OPENAI_BASE_URL": "https://gateway.test/v1",
+ "OPENROUTER_BASE_URL": "https://gateway.test/v1",
+ "XAI_BASE_URL": "https://gateway.test/v1",
+ }
+ preflight = permission_preflight.build(config, _diag())
+
+ assert preflight["network"]["endpoint_overrides"] == [
+ "OPENAI_BASE_URL",
+ "OPENROUTER_BASE_URL",
+ "XAI_BASE_URL",
+ ]
+ rendered = permission_preflight.render_text(preflight)
+ assert "OPENROUTER_BASE_URL" in rendered
+ assert "gateway.test" not in rendered
+
+
+def test_cli_preflight_propagates_file_endpoint_overrides(tmp_path, monkeypatch, capsys):
+ config_file = tmp_path / ".env"
+ config_file.write_text(
+ "XAI_BASE_URL=https://x-gateway.test/v1\n"
+ "OPENROUTER_BASE_URL=https://router-gateway.test/v1\n",
+ encoding="utf-8",
+ )
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(env, "CONFIG_FILE", config_file)
+ for key in ("OPENAI_BASE_URL", "XAI_BASE_URL", "OPENROUTER_BASE_URL"):
+ monkeypatch.setenv(key, "")
+ monkeypatch.setattr(sys, "argv", ["last30days.py", "--preflight", "--emit=json"])
+
+ with mock.patch.object(env, "_load_keychain", return_value={}), \
+ mock.patch.object(env, "_load_pass", return_value={}):
+ assert cli.main() == 0
+
+ preflight = json.loads(capsys.readouterr().out)
+ assert preflight["network"]["endpoint_overrides"] == [
+ "OPENROUTER_BASE_URL", "XAI_BASE_URL",
+ ]
+ assert providers.resolve_endpoint("XAI_BASE_URL", providers.XAI_RESPONSES_URL) == (
+ "https://x-gateway.test/v1/responses"
+ )
+ assert providers.resolve_endpoint("OPENROUTER_BASE_URL", providers.OPENROUTER_URL) == (
+ "https://router-gateway.test/v1/chat/completions"
+ )
+
+
def test_diagnose_uses_preflight_endpoint_override_key_set():
ignored_keys = sorted(permission_preflight.ENDPOINT_OVERRIDE_KEYS) + ["UNRELATED_KEY"]
diag = pipeline.diagnose(
diff --git a/tests/test_perplexity.py b/tests/test_perplexity.py
index 7e983a21..9b1763da 100644
--- a/tests/test_perplexity.py
+++ b/tests/test_perplexity.py
@@ -1,3 +1,4 @@
+import os
import unittest
from unittest.mock import patch
@@ -44,6 +45,13 @@ def _agent_response(
class PerplexityAgentTests(unittest.TestCase):
+ def setUp(self):
+ # The default-URL assertions must not depend on an ambient override.
+ env_patch = patch.dict("os.environ")
+ env_patch.start()
+ self.addCleanup(env_patch.stop)
+ os.environ.pop("OPENROUTER_BASE_URL", None)
+
def test_controlled_agent_uses_direct_key_and_explicit_web_search(self):
citations = [
{
@@ -321,6 +329,36 @@ class PerplexityAgentTests(unittest.TestCase):
self.assertEqual("OpenRouter fallback synthesis", items[0]["snippet"])
self.assertEqual("OpenRouter citation", items[1]["title"])
+ def test_openrouter_sonar_fallback_honors_base_url_override(self):
+ response = {"id": "openrouter-2", "model": "perplexity/sonar-pro",
+ "choices": [{"message": {"content": "ok"}}]}
+ endpoint = "https://gateway.test/v1/chat/completions"
+ for override in ("https://gateway.test/v1", endpoint):
+ for deep, model, timeout in (
+ (False, "perplexity/sonar-pro", 30),
+ (True, "perplexity/sonar-deep-research", 120),
+ ):
+ with self.subTest(override=override, deep=deep), patch.dict(
+ "os.environ", {"OPENROUTER_BASE_URL": override}
+ ), patch("lib.perplexity.http.post", return_value=response) as post:
+ items, artifact = perplexity.search(
+ "test topic",
+ ("2026-05-01", "2026-06-01"),
+ {"OPENROUTER_API_KEY": "or-test"},
+ deep=deep,
+ )
+
+ post.assert_called_once()
+ url, payload = post.call_args.args
+ self.assertEqual(endpoint, url)
+ self.assertEqual(model, payload["model"])
+ self.assertIn("test topic", payload["messages"][0]["content"])
+ self.assertEqual("Bearer or-test", post.call_args.kwargs["headers"]["Authorization"])
+ self.assertEqual(timeout, post.call_args.kwargs["timeout"])
+ self.assertEqual(1, post.call_args.kwargs["retries"])
+ self.assertEqual("openrouter", artifact["provider"])
+ self.assertEqual("ok", items[0]["snippet"])
+
def test_openrouter_search_mode_degrades_to_sonar_fallback(self):
response = {
"id": "openrouter-2",
diff --git a/tests/test_xai_x.py b/tests/test_xai_x.py
index e16d22c6..c581a045 100644
--- a/tests/test_xai_x.py
+++ b/tests/test_xai_x.py
@@ -1,6 +1,9 @@
import json
+import os
import unittest
+from unittest import mock
+from lib import xai_x
from lib.xai_x import parse_x_response
@@ -59,5 +62,52 @@ class TestXaiXEngagementZero(unittest.TestCase):
self.assertEqual(1, eng["replies"])
self.assertEqual(0, eng["quotes"])
+
+class TestXaiXBaseUrlOverride(unittest.TestCase):
+ """XAI_BASE_URL redirects the x_search request like the reasoning client."""
+
+ def _posted_url(self, env):
+ with mock.patch.dict(os.environ, env, clear=True), mock.patch(
+ "lib.xai_x.http.post", return_value={"output": []}
+ ) as post:
+ xai_x.search_x("xai-test", "grok-test", "topic", "2026-05-01", "2026-06-01")
+ return post.call_args.args[0]
+
+ def test_default_endpoint_without_override(self):
+ self.assertEqual(xai_x.XAI_RESPONSES_URL, self._posted_url({}))
+
+ def test_api_root_override_is_honored(self):
+ self.assertEqual(
+ "https://gateway.test/v1/responses",
+ self._posted_url({"XAI_BASE_URL": "https://gateway.test/v1"}),
+ )
+
+ def test_override_preserves_request_and_deadline(self):
+ endpoint = "https://gateway.test/v1/responses"
+ cancel = object()
+ with mock.patch.dict(os.environ, {"XAI_BASE_URL": endpoint}), mock.patch(
+ "lib.xai_x.http.post", return_value={"output": []}
+ ) as post:
+ xai_x.search_x(
+ "xai-test", "grok-test", "routing topic", "2026-05-01", "2026-06-01",
+ depth="quick", deadline_monotonic=1234.5, cancel=cancel,
+ )
+
+ post.assert_called_once()
+ url, payload = post.call_args.args
+ self.assertEqual(endpoint, url)
+ self.assertEqual("grok-test", payload["model"])
+ self.assertIn("routing topic", payload["input"][0]["content"])
+ self.assertEqual(
+ [{"type": "x_search", "from_date": "2026-05-01", "to_date": "2026-06-01"}],
+ payload["tools"],
+ )
+ self.assertEqual("Bearer xai-test", post.call_args.kwargs["headers"]["Authorization"])
+ self.assertEqual(90, post.call_args.kwargs["timeout"])
+ self.assertEqual(1, post.call_args.kwargs["retries"])
+ self.assertEqual(1234.5, post.call_args.kwargs["deadline_monotonic"])
+ self.assertIs(cancel, post.call_args.kwargs["cancel"])
+
+
if __name__ == "__main__":
unittest.main()