AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(perplexity): keep hosted routing without a direct key; never block Sonar on search type (#1188)
Matt Van Horn1fadbe5097c1
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 92e0388f..c42d7648 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -48,7 +48,7 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(- `--json-profile {agent,raw}` - select the research JSON shape used with `--emit=json`. `agent` is the default, versioned workflow contract; `raw` preserves the full internal `Report` dump for debugging and power users. See the [JSON export reference](docs/reference/json-export.md).- `--corpus <dir>` - add a local `.md`/`.txt` directory as a private ranked source; repeat the flag for multiple directories. PDFs are extracted only when `pdftotext` is on PATH and otherwise skip with a note. File modification time supplies recency, so the normal research window applies.- `--corpus-all-time` - include relevant registered files whose modification time is older than the current research window. Without this flag, a 30-day run includes only files modified in those 30 days.-- `--perplexity-search-type {fast,web}` - search type for direct Perplexity Search API and Agent `web_search` requests on this run; overrides `LAST30DAYS_PERPLEXITY_SEARCH_TYPE`. It does not enable the Perplexity source and needs a direct `PERPLEXITY_API_KEY`. When the hosted backend is configured, this flag makes the run execute locally with one stderr notice; a value set only in `LAST30DAYS_PERPLEXITY_SEARCH_TYPE` keeps hosted routing and prints a note that it was not applied.+- `--perplexity-search-type {fast,web}` - search type for direct Perplexity Search API and Agent `web_search` requests on this run; overrides `LAST30DAYS_PERPLEXITY_SEARCH_TYPE`. It does not enable the Perplexity source and needs a direct `PERPLEXITY_API_KEY`. When the hosted backend is configured and a direct `PERPLEXITY_API_KEY` exists, this flag makes the run execute locally with one stderr notice; without a direct key the run stays hosted and prints a note that the flag was not applied; a value set only in `LAST30DAYS_PERPLEXITY_SEARCH_TYPE` keeps hosted routing and prints a note that it was not applied.- `--register {default,exec,dev,creator,eli5}` - shape a standard single-topic Markdown or HTML research brief for its audience. `exec` is decisions-first with five core findings and numbers up top; `dev` gives GitHub, code, and technical signals more room; `creator` leads with hooks, Best Takes, community reactions, and virality metrics; `eli5` keeps the established evidence layout and asks the synthesizing agent for accessible language. Registers do not change retrieval, JSON exports, discovery, drill, library feed/search, or comparison output.- `--discover [domain]` - trending discovery, two-stage: a river-listing sweep NOMINATES candidate topics, then each nomination gets a full research pass (Reddit with comments, X, YouTube, Techmeme, arXiv, HN, Polymarket, web) before ranking. Bare `--discover` (no domain) is **global trending**: every feed's own hot list (r/all rising/top-week, Hacker News front/best, Digg clusters when `digg-pp-cli` is on PATH) with no keyword gate; with a domain, the sweep is category-scoped and keyword-gated, and broad X activity joins when an X backend is authenticated. Every topic must clear a confidence floor (cross-source confirmation or a genuinely strong single-source spike); when nothing clears it the run reports "Nothing solid this window" instead of ranked noise. Run without a positional topic; it is mutually exclusive with `--drill`. `--emit=json` uses the separate versioned discovery contract (now with `outcome`, `weak_signal`, per-topic `top_comment` and `corroboration_count`) documented in the [JSON export reference](docs/reference/json-export.md).- `--discover-shallow` - skip discovery's per-topic research passes and rank on listing evidence only. Faster and thinner; the confidence floor still applies. An explicit `--search` source list bounds both the sweep and the research passes. On a protocol run (below), adding it to the `--nominate-only` leg marks the bundle quick-tier so the resume leg uses the faster shallow research pass.@@ -118,7 +118,7 @@ Override the global location with `LAST30DAYS_CONFIG_DIR=/path` (or `LAST30DAYS_The project-scoped file is useful for **intentional per-client setups**: drop a `.claude/last30days.env` into each client folder (`SCRAPECREATORS_API_KEY`, `INCLUDE_SOURCES`, `LAST30DAYS_MEMORY_DIR`, `BSKY_HANDLE`, etc), then opt in with `LAST30DAYS_TRUST_PROJECT_CONFIG=1` from your shell or `~/.config/last30days/.env`. Folder-mode hosts such as Codex desktop do not trust hidden project config by default, and discovery stops at the git root so unrelated parent folders cannot silently influence runs. An untrusted repo's `.claude/last30days.env` is not read.-**`LAST30DAYS_API_KEY`** + **`LAST30DAYS_API_BASE`** - optional remote-API backend. Set BOTH to route research through a remote API endpoint instead of running the local sources: `LAST30DAYS_API_BASE` is the endpoint (there is no built-in default), and `LAST30DAYS_API_KEY` is the bearer key for it. When both are set (and `--mock` is not passed), the engine submits the topic to that endpoint, polls with progress on stderr, and prints the server's report; none of the per-source keys below are used for that run. A configured local corpus is the privacy exception: the engine bypasses the hosted backend and runs locally rather than forwarding file-derived input. The `--perplexity-search-type` flag also runs locally, because the hosted backend cannot apply it. Non-default `--register` selections are forwarded with the request so server-side synthesis uses the same audience preset. Leave either unset to run local sources exactly as normal. Unlike the other keys here, these two are read only from the **process environment** (export them in your shell or host config) - they are deliberately not loaded from the `.env` files above, so a project-scoped `.env` can never silently redirect research to a remote endpoint. The remote endpoint does not return the local `Report` needed for the versioned agent JSON profile; use `--emit=json --json-profile=raw` for its existing server-response JSON contract.+**`LAST30DAYS_API_KEY`** + **`LAST30DAYS_API_BASE`** - optional remote-API backend. Set BOTH to route research through a remote API endpoint instead of running the local sources: `LAST30DAYS_API_BASE` is the endpoint (there is no built-in default), and `LAST30DAYS_API_KEY` is the bearer key for it. When both are set (and `--mock` is not passed), the engine submits the topic to that endpoint, polls with progress on stderr, and prints the server's report; none of the per-source keys below are used for that run. A configured local corpus is the privacy exception: the engine bypasses the hosted backend and runs locally rather than forwarding file-derived input. The `--perplexity-search-type` flag also runs locally when a direct `PERPLEXITY_API_KEY` exists, because the hosted backend cannot apply it. Non-default `--register` selections are forwarded with the request so server-side synthesis uses the same audience preset. Leave either unset to run local sources exactly as normal. Unlike the other keys here, these two are read only from the **process environment** (export them in your shell or host config) - they are deliberately not loaded from the `.env` files above, so a project-scoped `.env` can never silently redirect research to a remote endpoint. The remote endpoint does not return the local `Report` needed for the versioned agent JSON profile; use `--emit=json --json-profile=raw` for its existing server-response JSON contract.**`BRIGHTDATA_API_KEY`** - optional, for the `amazon` source. The Bright Data CLI normally owns its own auth via `brightdata login`, so this is only needed if you would rather keep an explicit key in `.env` or the keychain. It is resolved through the standard config layering and passed to the CLI through the child process environment, never on the command line (where it would be readable from `/proc/<pid>/cmdline` by other local users on a shared host).diff --git a/changelog.d/1188.fixed.md b/changelog.d/1188.fixed.mdnew file mode 100644index 00000000..ab339925--- /dev/null+++ b/changelog.d/1188.fixed.md@@ -0,0 +1 @@+`--perplexity-search-type` no longer moves hosted-backend runs to local research when no direct `PERPLEXITY_API_KEY` is configured, and an invalid `LAST30DAYS_PERPLEXITY_SEARCH_TYPE` value no longer blocks OpenRouter Sonar searches.diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex a62c03f5..cf0d435f 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -531,7 +531,7 @@ Set `LAST30DAYS_MEMORY_DIR` before invoking the skill to choose where raw researThe engine reads `LAST30DAYS_MEMORY_DIR` from either the process env or `~/.config/last30days/.env`, so direct CLI invocations (`python3 scripts/last30days.py ...`) without `--save-dir` will still save when the env var is set. Mirrors the `LAST30DAYS_STORE` env-or-flag convention. Explicit `--save-dir` always wins.-When both `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` are set, the engine runs the research through that configured remote API instead of local sources (unless `--mock` is passed); `LAST30DAYS_API_BASE` is the endpoint and has no built-in default, so leaving either variable unset runs local sources normally. A configured `--corpus` / `LAST30DAYS_CORPUS_DIRS` is the privacy exception: the engine bypasses the hosted backend and runs locally so no file-derived input is forwarded. An explicit `--perplexity-search-type` flag also runs locally, because the hosted backend cannot apply it; the engine prints one stderr notice. A `LAST30DAYS_PERPLEXITY_SEARCH_TYPE` value set only in the environment keeps hosted routing and prints a note that it was not applied. The invocation is otherwise unchanged: same flags, `--quick`/`--deep` map to search depth, a non-default `--register` is forwarded for server-side synthesis, progress lines still stream on stderr (`[narrate] step=...` plus a compact elapsed/eta line), and the report prints on stdout and saves to the memory dir as usual, so Steps 1-4 proceed normally on the output. The exception is research JSON: the remote endpoint does not return the local `Report` needed for the versioned agent profile, so use `--emit=json --json-profile=raw` for its existing server-response JSON contract. No per-source keys or setup-wizard credentials are needed for the search itself in this mode. Two engine exits need specific handling: exit code 3 means the API asked a clarifying question first - the engine prints the question and options on stderr; present them to the user and re-run with the chosen angle folded into the topic. An insufficient-credits failure (HTTP 402) prints the account's balance, the amount needed, and a billing link - relay those lines to the user verbatim; do not fall back to WebSearch-only synthesis.+When both `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` are set, the engine runs the research through that configured remote API instead of local sources (unless `--mock` is passed); `LAST30DAYS_API_BASE` is the endpoint and has no built-in default, so leaving either variable unset runs local sources normally. A configured `--corpus` / `LAST30DAYS_CORPUS_DIRS` is the privacy exception: the engine bypasses the hosted backend and runs locally so no file-derived input is forwarded. An explicit `--perplexity-search-type` flag also runs locally when a direct `PERPLEXITY_API_KEY` exists, because the hosted backend cannot apply it; the engine prints one stderr notice. Without a direct key the run stays hosted and prints a note that the flag was not applied. A `LAST30DAYS_PERPLEXITY_SEARCH_TYPE` value set only in the environment keeps hosted routing and prints a note that it was not applied. The invocation is otherwise unchanged: same flags, `--quick`/`--deep` map to search depth, a non-default `--register` is forwarded for server-side synthesis, progress lines still stream on stderr (`[narrate] step=...` plus a compact elapsed/eta line), and the report prints on stdout and saves to the memory dir as usual, so Steps 1-4 proceed normally on the output. The exception is research JSON: the remote endpoint does not return the local `Report` needed for the versioned agent profile, so use `--emit=json --json-profile=raw` for its existing server-response JSON contract. No per-source keys or setup-wizard credentials are needed for the search itself in this mode. Two engine exits need specific handling: exit code 3 means the API asked a clarifying question first - the engine prints the question and options on stderr; present them to the user and re-run with the chosen angle folded into the topic. An insufficient-credits failure (HTTP 402) prints the account's balance, the amount needed, and a billing link - relay those lines to the user verbatim; do not fall back to WebSearch-only synthesis.**Developer-only eval capture:** `--record-fixtures <dir>` is a hidden direct-engine flag for maintaining the deterministic research-quality suite. It records scrubbed HTTP and CLI-adapter responses to `<dir>/http.json`; it is never part of the user-facing slash-command invocation. Follow `docs/reference/eval.md` for fixture review, replay, and baseline rules.diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 50114688..2b2f3c10 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -3531,11 +3531,14 @@ def _main("[last30days] Local corpus configured; bypassing the hosted backend so files stay on this machine.\n")# An explicit --perplexity-search-type is per-invocation intent the hosted- # backend cannot honor, so it runs locally. Key on the parsed CLI flag only:- # a value from LAST30DAYS_PERPLEXITY_SEARCH_TYPE must never move routing.+ # backend cannot honor, so it runs locally, but only when a direct+ # PERPLEXITY_API_KEY can apply it; otherwise the switch would trade hosted+ # coverage for nothing. Key on the parsed CLI flag only: a value from+ # LAST30DAYS_PERPLEXITY_SEARCH_TYPE must never move routing.elif (topicand args.perplexity_search_type is not None+ and config.get("PERPLEXITY_API_KEY")and not args.diagnoseand not args.mockand not args.record_fixtures@@ -3556,9 +3559,14 @@ def _main(and os.environ.get("LAST30DAYS_API_BASE")and not resolved_corpus_dirsand not args.deep_research- and args.perplexity_search_type is None+ and (args.perplexity_search_type is None or not config.get("PERPLEXITY_API_KEY"))):- if config.get("LAST30DAYS_PERPLEXITY_SEARCH_TYPE"):+ if args.perplexity_search_type is not None:+ sys.stderr.write(+ "hosted backend does not apply --perplexity-search-type and no direct "+ "PERPLEXITY_API_KEY is configured to run it locally; skipping\n"+ )+ elif config.get("LAST30DAYS_PERPLEXITY_SEARCH_TYPE"):sys.stderr.write("hosted backend does not apply LAST30DAYS_PERPLEXITY_SEARCH_TYPE; skipping\n")diff --git a/skills/last30days/scripts/lib/perplexity.py b/skills/last30days/scripts/lib/perplexity.pyindex fca2ffda..b4efe5f5 100644--- a/skills/last30days/scripts/lib/perplexity.py+++ b/skills/last30days/scripts/lib/perplexity.py@@ -1246,9 +1246,10 @@ def search(mode = _mode(config, deep, provider)search_type = Nonetry:- search_type = _search_type(config)if provider == "openrouter":- if search_type is not None:+ # Sonar ignores the direct-only setting, so never validate it here:+ # an unusable value must not block an otherwise working search.+ if _config_text(config, "LAST30DAYS_PERPLEXITY_SEARCH_TYPE"):_log("LAST30DAYS_PERPLEXITY_SEARCH_TYPE requires PERPLEXITY_API_KEY; ""it does not change OpenRouter Sonar search")result = _openrouter_sonar_search(@@ -1260,6 +1261,7 @@ def search(if deep:_log_deep_receipt(result[1])return result+ search_type = _search_type(config)if mode == PERPLEXITY_MODE_SEARCH:return _search_api(query, date_range, config, api_key)if mode == PERPLEXITY_MODE_BOTH:diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.pyindex e2630b09..4827ddc8 100644--- a/tests/test_cli_v3.py+++ b/tests/test_cli_v3.py@@ -428,7 +428,9 @@ class CliV3Tests(unittest.TestCase):def test_perplexity_search_type_flag_bypasses_hosted_with_one_notice(self):rc, run_mock, hosted_mock, err = self._run_perplexity_search_type_cli(- ["--perplexity-search-type", "fast"], {}, hosted=True,+ ["--perplexity-search-type", "fast"],+ {"PERPLEXITY_API_KEY": "pplx-test"},+ hosted=True,)self.assertEqual(0, rc)@@ -440,6 +442,35 @@ class CliV3Tests(unittest.TestCase):self.assertIn("bypassing the hosted backend", err)self.assertNotIn("does not apply LAST30DAYS_PERPLEXITY_SEARCH_TYPE", err)+ def test_perplexity_search_type_flag_without_direct_key_stays_hosted(self):+ rc, run_mock, hosted_mock, err = self._run_perplexity_search_type_cli(+ ["--perplexity-search-type", "fast"],+ {"OPENROUTER_API_KEY": "or-test"},+ hosted=True,+ )++ self.assertEqual(0, rc)+ hosted_mock.assert_called_once()+ run_mock.assert_not_called()+ self.assertEqual(1, err.count("no direct PERPLEXITY_API_KEY is configured"))+ self.assertNotIn("bypassing the hosted backend", err)++ def test_search_type_flag_without_direct_key_matches_no_flag_routing(self):+ # Without a direct key the flag cannot apply, so hosted routing and its+ # local-only option checks must match a run without the flag.+ for extra in (["--x-posts", "https://x.com/a/status/1"], ["--emit=json", "--json-profile=agent"]):+ plain_rc, plain_run, plain_hosted, _ = self._run_perplexity_search_type_cli(+ extra, {"OPENROUTER_API_KEY": "or-test"}, hosted=True,+ )+ flag_rc, flag_run, flag_hosted, _ = self._run_perplexity_search_type_cli(+ ["--perplexity-search-type", "fast", *extra],+ {"OPENROUTER_API_KEY": "or-test"},+ hosted=True,+ )+ self.assertEqual(plain_rc, flag_rc, extra)+ self.assertEqual(plain_run.call_count, flag_run.call_count, extra)+ self.assertEqual(plain_hosted.call_count, flag_hosted.call_count, extra)+def test_env_only_perplexity_search_type_stays_hosted_with_one_note(self):rc, run_mock, hosted_mock, err = self._run_perplexity_search_type_cli([], {"LAST30DAYS_PERPLEXITY_SEARCH_TYPE": "fast"}, hosted=True,diff --git a/tests/test_perplexity_fast_search.py b/tests/test_perplexity_fast_search.pyindex 2cc1aa88..07e81bcf 100644--- a/tests/test_perplexity_fast_search.py+++ b/tests/test_perplexity_fast_search.py@@ -88,6 +88,18 @@ def test_openrouter_keeps_sonar_and_discloses_ignored_search_type():assert any("does not change OpenRouter" in str(call) for call in log.call_args_list)[email protected]("value", ["pro", "FAST!", "garbage"])+def test_invalid_type_never_blocks_openrouter_sonar(value):+ response = {"choices": [{"message": {"content": "Summary"}}]}+ with patch.object(perplexity.http, "post", return_value=response) as post:+ items, artifact = perplexity.search("topic", DATE_RANGE, {+ "OPENROUTER_API_KEY": "dummy-test-key", KEY: value})+ assert post.call_count == 1+ assert post.call_args.args[0] == perplexity.OPENROUTER_URL+ assert artifact["provider"] == "openrouter"+ assert "must be web or fast" not in str(artifact)++@pytest.mark.parametrize("cli_value,expected", [(None, "fast"), ("web", "web")])def test_cli_override_reaches_config_without_enabling_paid_source(cli_value, expected):args = ["last30days.py", "Rust releases"]