Skip to content

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

feat(perplexity): add --perplexity-search-type opt-in and bound HTTP error-body reads (#1187)

Matt Van Horn268fb870ffea
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index ea3a1ddc..92e0388f 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -48,6 +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.
- `--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.
@@ -117,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. 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, 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).
@@ -288,6 +289,7 @@ Perplexity-specific env vars:
| `LAST30DAYS_PERPLEXITY_MAX_RESULTS` | `10` | Search API and all Agent `web_search` requests | Clamped to 1..20. |
| `LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE` | provider default | Search API and all Agent `web_search` requests | `low`, `medium`, or `high`; omitted unless set. |
| `LAST30DAYS_PERPLEXITY_DOMAIN_FILTER` | unset | Search API and all Agent `web_search` requests | Comma-separated domains, max 20. |
+| `LAST30DAYS_PERPLEXITY_SEARCH_TYPE` | provider default | Search API and all Agent `web_search` requests | `fast` or `web`. Direct `PERPLEXITY_API_KEY` only; OpenRouter Sonar ignores it. Does not enable the source. `--perplexity-search-type` overrides it. |
| `LAST30DAYS_PERPLEXITY_LANGUAGE_FILTER` | unset | Search API only | Comma-separated ISO 639-1 language codes. Agent API has no equivalent. |
| `LAST30DAYS_PERPLEXITY_COUNTRY` | unset | Search API and all Agent `web_search` requests | Two-letter country code such as `US`. |
| `LAST30DAYS_PERPLEXITY_RECENCY_FILTER` | unset | Search API and all Agent `web_search` requests | `hour`, `day`, `week`, `month`, or `year`; exact date filters take precedence. |
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 1d379cb3..480a8313 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -54,6 +54,7 @@ v3 has durable watchlist with multi-source storage and extended time windows.
## Past Contributors
+- [@sk-holmes](https://github.com/sk-holmes) (Sk) - Perplexity direct API modes and async Deep Research ([#629](https://github.com/mvanhorn/last30days-skill/pull/629)); Perplexity Agent API migration ([#1019](https://github.com/mvanhorn/last30days-skill/pull/1019)); Perplexity Fast Search selector and HTTP error-body deadline fix via original PR [#1184](https://github.com/mvanhorn/last30days-skill/pull/1184), landed on main via successor [#1187](https://github.com/mvanhorn/last30days-skill/pull/1187)
- [@terry-li-hm](https://github.com/terry-li-hm) (Terry Li) - empty/qualifier-only GitHub topics → clean no-results ([#953](https://github.com/mvanhorn/last30days-skill/issues/953)) via original PR [#1041](https://github.com/mvanhorn/last30days-skill/pull/1041), landed on main via successor [#1130](https://github.com/mvanhorn/last30days-skill/pull/1130)
- [@23241a6749](https://github.com/23241a6749) - Windows cp1252 fixes ([#549](https://github.com/mvanhorn/last30days-skill/pull/549)); Windows killpg guard ([#552](https://github.com/mvanhorn/last30days-skill/pull/552)); browser promo clarity ([#387](https://github.com/mvanhorn/last30days-skill/pull/561)); setup wizard fix ([#574](https://github.com/mvanhorn/last30days-skill/pull/578)); check-config xargs fix ([#506](https://github.com/mvanhorn/last30days-skill/issues/506)); check-config clean-exit on missing last-run ([#463](https://github.com/mvanhorn/last30days-skill/issues/463)); Firefox multi-profile cookies ([#498](https://github.com/mvanhorn/last30days-skill/issues/498)); X/Twitter CT0 template ([#396](https://github.com/mvanhorn/last30days-skill/issues/396)); .env permission auto-fix ([#573](https://github.com/mvanhorn/last30days-skill/pull/599)); MCP Go tests in CI ([#621](https://github.com/mvanhorn/last30days-skill/issues/621))
- [@JosephOIbrahim](https://github.com/JosephOIbrahim) - Windows Unicode fix ([#17](https://github.com/mvanhorn/last30days-skill/pull/17))
diff --git a/changelog.d/+http-error-body-deadline.fixed.md b/changelog.d/+http-error-body-deadline.fixed.md
new file mode 100644
index 00000000..0efddfd4
--- /dev/null
+++ b/changelog.d/+http-error-body-deadline.fixed.md
@@ -0,0 +1 @@
+Reading an HTTP error response body now counts against the caller's deadline instead of stalling past it, and debug logs redact request API keys, including keys a provider echoes back in an error body. Thanks to @sk-holmes (#1184).
diff --git a/changelog.d/+perplexity-search-type.added.md b/changelog.d/+perplexity-search-type.added.md
new file mode 100644
index 00000000..fb49682b
--- /dev/null
+++ b/changelog.d/+perplexity-search-type.added.md
@@ -0,0 +1 @@
+New `--perplexity-search-type fast|web` flag and `LAST30DAYS_PERPLEXITY_SEARCH_TYPE` setting choose the search type for direct Perplexity Search API and Agent `web_search` requests. They do not enable the Perplexity source and need a direct `PERPLEXITY_API_KEY`. Thanks to @sk-holmes (#1184).
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 05f9849d..a62c03f5 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 resear
The 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. 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, 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.
**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.
@@ -828,6 +828,8 @@ SKILL_DIR="<absolute path of the directory containing the SKILL.md you just Read
**Local corpus source:** If the user asks to include their own notes/documents, preserve each supplied directory as a repeatable `--corpus <dir>` engine flag. `LAST30DAYS_CORPUS_DIRS` activates persistent registered directories automatically. Do not WebSearch, upload, quote into a hosted request, or otherwise expose those paths or contents. Corpus retrieval is an offline source lane; its candidates also bypass remote reranker/fun-scoring prompts and use deterministic local scoring. The engine renders matches under the 🔒 **From your files** badge. The normal recency window uses file modification time; add `--corpus-all-time` only when the user explicitly asks to include older files. Corpus evidence is excluded from `--publish-html`, `library feed --publish`, and agent JSON by default. `LAST30DAYS_CORPUS_IN_EXPORT=1` is the explicit agent-JSON privacy opt-in; never enable it on the user's behalf. When a corpus is configured alongside `LAST30DAYS_API_KEY`/`LAST30DAYS_API_BASE`, the engine deliberately bypasses the hosted backend and runs locally.
+**Perplexity search type:** pass `--perplexity-search-type fast` (or `web`) only when the user asks for Perplexity Fast Search or a specific Perplexity search type; never add it on your own initiative or because a key is configured. It changes only direct Perplexity Search API and Agent `web_search` requests, does not enable the Perplexity source (add the source only if the user also asked for Perplexity), and needs a direct `PERPLEXITY_API_KEY`; OpenRouter Sonar ignores it.
+
**Perplexity source:** use it only when the user asks for Perplexity, Deep Research, or paid grounded synthesis, or when `perplexity` is already enabled in `INCLUDE_SOURCES` / `--search`. Prefer `PERPLEXITY_API_KEY`: normal runs use the controlled Agent API path, `search` returns raw Search API rows, and `both` combines them. Existing `OPENROUTER_API_KEY` installs stay compatible through one synchronous Sonar call; `search` and `both` fall back to Sonar because those direct APIs need a Perplexity key. Every normal mode is capped at one whole-topic planner subquery per command, including competitor fanout, and is not repeated during thin-source retries. With a direct key, normal Agent mode supplies only `web_search`, forces it for citation-critical grounding, uses a bounded step count, and supplies a local instruction. `sonar` remains a deprecated direct-key alias for `agent`. `LAST30DAYS_PERPLEXITY_AGENT_PRESET` is an explicit direct-key choice only; never set it for the user. `--deep-research` requires a normal positional topic. A direct key starts at most one paid `high`-preset background run with a 600-second default wall timeout; OpenRouter preserves the synchronous `perplexity/sonar-deep-research` fallback. It cannot be combined with discovery, drill, cached-only, competitor, or vs-mode. A local timeout does not stop a direct remote run. Report safe model and response metadata, but never expose request headers or raw tool traces.
**Reddit backend pin:** Reddit defaults to the free keyless backend. When `SCRAPECREATORS_API_KEY` is available, ScrapeCreators Reddit **search** backfills only if that free path returns **no items** (empty-only — a thin but non-empty free scrape does not spend credits). If the user wants paid coverage on thin free runs, tell them to set `LAST30DAYS_REDDIT_SC_MIN_ITEMS=<N>` (backfill when free yield is below N). If they say public Reddit is shallow, bot-gated, or missing nested comments, tell them they can set `LAST30DAYS_REDDIT_BACKEND=scrapecreators` alongside `SCRAPECREATORS_API_KEY` to make ScrapeCreators primary and keep the free path as fallback. Do not set either automatically for normal runs.
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index d13c03f6..50114688 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -813,6 +813,8 @@ def build_parser() -> argparse.ArgumentParser:
choices=["auto", "brave", "exa", "serper", "parallel", "parallel-mcp", "keyless", "none"],
help="Web search backend (default: auto; parallel-mcp explicitly opts into the "
"anonymous hosted MCP; keyless forces the zero-key floor)")
+ parser.add_argument("--perplexity-search-type", choices=["web", "fast"],
+ help="Search backend for direct Perplexity Search API and Agent web_search; overrides LAST30DAYS_PERPLEXITY_SEARCH_TYPE. Does not enable the paid source or select an Agent preset.")
parser.add_argument("--deep-research", action="store_true",
help="Use at most one Perplexity Deep Research run. Direct PERPLEXITY_API_KEY uses the Agent API background path; OPENROUTER_API_KEY keeps the synchronous Sonar fallback; cannot be combined with competitor or vs-mode.")
parser.add_argument("--hiring-signals", action="store_true",
@@ -3200,6 +3202,8 @@ def _main(
return _run_store_key(store_key_name)
config = env.get_config(policy=_config_policy_for_args(args, topic, extra_argv))
+ if args.perplexity_search_type is not None:
+ config["LAST30DAYS_PERPLEXITY_SEARCH_TYPE"] = args.perplexity_search_type
# One memo per command: comparison mode runs pipeline.run per entity in
# parallel, so the reset must not live inside the pipeline.
http.reset_reddit_keyless_memo()
@@ -3526,6 +3530,23 @@ def _main(
sys.stderr.write(
"[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.
+ elif (
+ topic
+ and args.perplexity_search_type is not None
+ and not args.diagnose
+ and not args.mock
+ and not args.record_fixtures
+ and not args.deep_research
+ and env.read_secret_env("LAST30DAYS_API_KEY")
+ and os.environ.get("LAST30DAYS_API_BASE")
+ ):
+ sys.stderr.write(
+ "[last30days] --perplexity-search-type set; bypassing the hosted backend "
+ "because it does not apply the Perplexity search type.\n"
+ )
if (
topic
and not args.diagnose
@@ -3535,7 +3556,12 @@ def _main(
and os.environ.get("LAST30DAYS_API_BASE")
and not resolved_corpus_dirs
and not args.deep_research
+ and args.perplexity_search_type is None
):
+ if config.get("LAST30DAYS_PERPLEXITY_SEARCH_TYPE"):
+ sys.stderr.write(
+ "hosted backend does not apply LAST30DAYS_PERPLEXITY_SEARCH_TYPE; skipping\n"
+ )
if _freshness_enabled(args, config):
if args.verify_freshness is True:
sys.stderr.write(
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 99b0928d..e8ec8908 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -630,6 +630,7 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
('LAST30DAYS_PERPLEXITY_AGENT_TIMEOUT_SECONDS', '120'),
('LAST30DAYS_PERPLEXITY_MAX_RESULTS', None),
('LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE', None),
+ ('LAST30DAYS_PERPLEXITY_SEARCH_TYPE', None),
('LAST30DAYS_PERPLEXITY_SEARCH_MODE', None),
('LAST30DAYS_PERPLEXITY_DOMAIN_FILTER', None),
('LAST30DAYS_PERPLEXITY_LANGUAGE_FILTER', None),
diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.py
index e67957a1..21c0a270 100644
--- a/skills/last30days/scripts/lib/http.py
+++ b/skills/last30days/scripts/lib/http.py
@@ -7,7 +7,6 @@ import os
import random
import re
import socket
-import sys
import threading
import time
import urllib.error
@@ -823,8 +822,11 @@ def request(
req = urllib.request.Request(url, data=data, headers=headers, method=method)
+ def log_request(message: str) -> None:
+ log(_scrub_fixture_value(message, redactions=fixture_redactions))
+
safe_url = re.sub(r'([?&])(key|api_key|token|secret)=[^&]*', r'\1\2=***', url)
- log(f"{method} {safe_url}")
+ log_request(f"{method} {safe_url}")
last_error = None
rate_limit_count = 0
@@ -853,13 +855,25 @@ def request(
time.sleep(delay)
return True
- def open_and_read(request_timeout: float) -> tuple[int, str]:
- with _open_request(req, request_timeout) as response:
- return response.status, response.read().decode('utf-8')
+ def open_and_read(
+ request_timeout: float,
+ ) -> tuple[int, str | None, urllib.error.HTTPError | None]:
+ try:
+ with _open_request(req, request_timeout) as response:
+ return response.status, response.read().decode('utf-8'), None
+ except urllib.error.HTTPError as error:
+ # Error bodies can stall just like successful bodies. Read both
+ # inside the same deadline-protected worker before classification.
+ body = None
+ try:
+ body = error.read().decode('utf-8')
+ except (OSError, UnicodeDecodeError):
+ pass
+ return error.code, body, error
def open_and_read_before_deadline(
request_timeout: float,
- ) -> tuple[int, str]:
+ ) -> tuple[int, str | None, urllib.error.HTTPError | None]:
"""Stop waiting at the wall deadline, even during DNS or body reads."""
if deadline_monotonic is None:
return open_and_read(request_timeout)
@@ -895,13 +909,16 @@ def request(
break
request_timeout = min(timeout, remaining)
try:
- response_status, body = open_and_read_before_deadline(request_timeout)
+ response_status, body, response_error = open_and_read_before_deadline(request_timeout)
if (
deadline_monotonic is not None
and time.monotonic() >= deadline_monotonic
):
raise_recorded(deadline_error())
- log(f"Response: {response_status} ({len(body)} bytes)")
+ if response_error is not None:
+ raise response_error
+ body = body or ""
+ log_request(f"Response: {response_status} ({len(body)} bytes)")
if raw:
_fixture_record(fixture_request, value=body, redactions=fixture_redactions)
return body
@@ -911,15 +928,10 @@ def request(
except DeadlineExceeded as exc:
raise_recorded(exc)
except urllib.error.HTTPError as e:
- body = None
- try:
- body = e.read().decode('utf-8')
- except (OSError, UnicodeDecodeError):
- pass
- log(f"HTTP Error {e.code}: {e.reason}")
+ log_request(f"HTTP Error {e.code}: {e.reason}")
if body:
- snippet = " ".join(body.split())
- log(f"Error body: {snippet[:200]}")
+ snippet = _scrub_fixture_value(" ".join(body.split()), redactions=fixture_redactions)
+ log_request(f"Error body: {snippet[:200]}")
last_error = HTTPError(f"HTTP {e.code}: {e.reason}", e.code, body)
# Don't retry client errors (4xx) except rate limits
@@ -942,7 +954,7 @@ def request(
getattr(e, "headers", None),
RETRY_DELAY * (2 ** attempt) + 1,
)
- log(f"Rate limited (429). Waiting {delay:.1f}s before retry {attempt + 2}/{retries}")
+ log_request(f"Rate limited (429). Waiting {delay:.1f}s before retry {attempt + 2}/{retries}")
else:
delay = RETRY_DELAY * (2 ** attempt)
if not sleep_before_retry(delay):
@@ -953,7 +965,7 @@ def request(
# widening is DNS-only — don't grant extra HTTP attempts.
break
except urllib.error.URLError as e:
- log(f"URL Error: {e.reason}")
+ log_request(f"URL Error: {e.reason}")
reason = getattr(e, "reason", None)
# urllib commonly wraps socket.timeout (an alias of TimeoutError
# since 3.10) in URLError; classify those as timeouts, not
@@ -971,14 +983,14 @@ def request(
# causes don't bypass the regular retry budget.
dns_attempts += 1
if effective_retries < MIN_DNS_RETRIES:
- log(
+ log_request(
f"DNS resolution failed; expanding retry budget from "
f"{effective_retries} to {MIN_DNS_RETRIES}"
)
effective_retries = MIN_DNS_RETRIES
if attempt < effective_retries - 1:
delay = 2 ** (dns_attempts - 1) # 1s, 2s, 4s, 8s, ...
- log(
+ log_request(
f"DNS resolution failure (attempt {dns_attempts}); "
f"retrying in {delay:.1f}s"
)
@@ -995,7 +1007,7 @@ def request(
# to non-DNS error paths.
break
except json.JSONDecodeError as e:
- log(f"JSON decode error: {e}")
+ log_request(f"JSON decode error: {e}")
last_error = HTTPError(
f"Invalid JSON response: {e}",
outcome_state=health.SCHEMA_DRIFT,
@@ -1003,7 +1015,7 @@ def request(
raise_recorded(last_error)
except (OSError, TimeoutError, ConnectionResetError) as e:
# Handle socket-level errors (connection reset, timeout, etc.)
- log(f"Connection error: {type(e).__name__}: {e}")
+ log_request(f"Connection error: {type(e).__name__}: {e}")
state = health.TIMEOUT if isinstance(e, TimeoutError) else health.UNREACHABLE
last_error = HTTPError(
f"Connection error: {type(e).__name__}: {e}",
diff --git a/skills/last30days/scripts/lib/perplexity.py b/skills/last30days/scripts/lib/perplexity.py
index 09383c09..fca2ffda 100644
--- a/skills/last30days/scripts/lib/perplexity.py
+++ b/skills/last30days/scripts/lib/perplexity.py
@@ -231,6 +231,16 @@ def _safe_incomplete_reason(data: dict[str, Any]) -> str | None:
return reason[:100] if isinstance(reason, str) and reason else None
+def _search_type(config: dict[str, Any]) -> str | None:
+ """Keep omission intact; search backends are separate from Agent presets."""
+ value = _config_text(config, "LAST30DAYS_PERPLEXITY_SEARCH_TYPE").lower()
+ if not value:
+ return None
+ if value not in {"web", "fast"}:
+ raise ValueError("LAST30DAYS_PERPLEXITY_SEARCH_TYPE must be web or fast")
+ return value
+
+
def _build_search_payload(
query: str,
date_range: tuple[str, str],
@@ -251,6 +261,9 @@ def _build_search_payload(
config,
"LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE",
).lower()
+ search_type = _search_type(config)
+ if search_type is not None:
+ payload["search_type"] = search_type
if context_size in SEARCH_CONTEXT_SIZES:
payload["search_context_size"] = context_size
@@ -310,6 +323,9 @@ def _build_web_search_tool(
config,
"LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE",
).lower()
+ search_type = _search_type(config)
+ if search_type is not None:
+ tool["search_type"] = search_type
if context_size in SEARCH_CONTEXT_SIZES:
tool["search_context_size"] = context_size
@@ -386,6 +402,7 @@ def _safe_request(payload: dict[str, Any]) -> dict[str, Any]:
"type",
"max_results",
"search_context_size",
+ "search_type",
"user_location",
"filters",
)
@@ -1180,8 +1197,11 @@ def _top_level_failure(
deep: bool,
exc: Exception,
provider: str = "perplexity",
+ requested_search_type: str | None = None,
) -> dict[str, Any]:
artifact = _error_artifact(exc)
+ if provider == "perplexity" and requested_search_type is not None:
+ artifact["requested_search_type"] = requested_search_type
if provider == "openrouter":
endpoint = "openrouter-chat-completions"
elif deep:
@@ -1224,8 +1244,13 @@ def search(
provider, api_key = resolved
mode = _mode(config, deep, provider)
+ search_type = None
try:
+ search_type = _search_type(config)
if provider == "openrouter":
+ if search_type is not None:
+ _log("LAST30DAYS_PERPLEXITY_SEARCH_TYPE requires PERPLEXITY_API_KEY; "
+ "it does not change OpenRouter Sonar search")
result = _openrouter_sonar_search(
query,
date_range,
@@ -1252,6 +1277,8 @@ def search(
except Exception as exc:
_log(f"Search API leg failed in both mode: {exc}")
search_artifact = _error_artifact(exc)
+ if search_type is not None:
+ search_artifact["requested_search_type"] = search_type
try:
agent_items, agent_artifact = _agent_search(
query,
@@ -1263,6 +1290,8 @@ def search(
except Exception as exc:
_log(f"Agent API leg failed in both mode: {exc}")
agent_artifact = _error_artifact(exc)
+ if search_type is not None:
+ agent_artifact["requested_search_type"] = search_type
items = _merge_agent_and_search(agent_items, search_items)
return items, {
"label": "perplexity",
@@ -1290,6 +1319,7 @@ def search(
deep,
exc,
provider=provider,
+ requested_search_type=search_type,
)
if deep:
_log_deep_receipt(artifact)
@@ -1302,6 +1332,7 @@ def search(
deep,
exc,
provider=provider,
+ requested_search_type=search_type,
)
if deep:
_log_deep_receipt(artifact)
@@ -1314,6 +1345,7 @@ def search(
deep,
exc,
provider=provider,
+ requested_search_type=search_type,
)
if deep:
_log_deep_receipt(artifact)
diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.py
index 7ad5433e..e2630b09 100644
--- a/tests/test_cli_v3.py
+++ b/tests/test_cli_v3.py
@@ -383,6 +383,119 @@ class CliV3Tests(unittest.TestCase):
self.assertEqual(["reddit", "perplexity"], requested_sources)
self.assertTrue(run_mock.call_args.kwargs["config"]["_deep_research"])
+ def _run_perplexity_search_type_cli(self, argv_extra, config, *, hosted):
+ report = self.make_report(topic="rust releases")
+ diag = {
+ "available_sources": ["reddit"],
+ "providers": {"google": False, "openai": False, "xai": False},
+ "x_backend": None,
+ "bird_installed": True,
+ "bird_authenticated": False,
+ "bird_username": None,
+ "native_web_backend": None,
+ }
+ environ = {"LAST30DAYS_SKIP_PREFLIGHT": "1"}
+ if hosted:
+ environ["LAST30DAYS_API_BASE"] = "https://hosted.example.test"
+ stderr = io.StringIO()
+ with mock.patch.object(
+ cli.env, "get_config", return_value=dict(config),
+ ), mock.patch.object(
+ cli.env, "read_secret_env",
+ return_value="hosted-test-key" if hosted else None,
+ ), mock.patch.object(
+ cli.pipeline, "diagnose", return_value=diag,
+ ), mock.patch.object(
+ cli.pipeline, "run", return_value=report,
+ ) as run_mock, mock.patch(
+ "lib.hosted.run_hosted", return_value=0,
+ ) as hosted_mock, mock.patch(
+ "lib.resolve.auto_resolve", return_value={},
+ ), mock.patch.object(
+ cli.ui, "ProgressDisplay", return_value=mock.Mock(),
+ ), mock.patch.object(
+ cli, "emit_output", return_value="# rendered",
+ ), mock.patch.dict(
+ os.environ, environ, clear=False,
+ ), mock.patch.object(
+ sys, "argv", ["last30days.py", "rust", "releases", *argv_extra],
+ ):
+ if not hosted:
+ os.environ.pop("LAST30DAYS_API_BASE", None)
+ with redirect_stdout(io.StringIO()), redirect_stderr(stderr):
+ rc = cli.main()
+ return rc, run_mock, hosted_mock, stderr.getvalue()
+
+ 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,
+ )
+
+ self.assertEqual(0, rc)
+ hosted_mock.assert_not_called()
+ run_mock.assert_called_once()
+ config = run_mock.call_args.kwargs["config"]
+ self.assertEqual("fast", config["LAST30DAYS_PERPLEXITY_SEARCH_TYPE"])
+ self.assertEqual(1, err.count("--perplexity-search-type"))
+ self.assertIn("bypassing the hosted backend", err)
+ self.assertNotIn("does not apply LAST30DAYS_PERPLEXITY_SEARCH_TYPE", err)
+
+ 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,
+ )
+
+ self.assertEqual(0, rc)
+ hosted_mock.assert_called_once()
+ run_mock.assert_not_called()
+ self.assertEqual(
+ 1,
+ err.count("hosted backend does not apply LAST30DAYS_PERPLEXITY_SEARCH_TYPE"),
+ )
+ self.assertNotIn("bypassing the hosted backend", err)
+
+ def test_hosted_without_perplexity_search_type_is_unchanged(self):
+ rc, run_mock, hosted_mock, err = self._run_perplexity_search_type_cli(
+ [], {}, hosted=True,
+ )
+
+ self.assertEqual(0, rc)
+ hosted_mock.assert_called_once()
+ run_mock.assert_not_called()
+ self.assertNotIn("search type", err.lower())
+ self.assertNotIn("SEARCH_TYPE", err)
+
+ def test_perplexity_search_type_flag_does_not_enable_perplexity(self):
+ _, baseline_run, _, _ = self._run_perplexity_search_type_cli(
+ [], {"PERPLEXITY_API_KEY": "pplx-test"}, hosted=False,
+ )
+ rc, flagged_run, _, err = self._run_perplexity_search_type_cli(
+ ["--perplexity-search-type", "fast"],
+ {"PERPLEXITY_API_KEY": "pplx-test"},
+ hosted=False,
+ )
+
+ self.assertEqual(0, rc)
+ self.assertEqual(
+ baseline_run.call_args.kwargs["requested_sources"],
+ flagged_run.call_args.kwargs["requested_sources"],
+ )
+ self.assertNotIn("perplexity", flagged_run.call_args.kwargs["requested_sources"] or [])
+ config = flagged_run.call_args.kwargs["config"]
+ self.assertEqual("fast", config["LAST30DAYS_PERPLEXITY_SEARCH_TYPE"])
+ self.assertNotIn("INCLUDE_SOURCES", config)
+ self.assertNotIn("bypassing the hosted backend", err)
+
+ def test_perplexity_search_type_flag_overrides_env_value(self):
+ _, run_mock, _, _ = self._run_perplexity_search_type_cli(
+ ["--perplexity-search-type", "web"],
+ {"LAST30DAYS_PERPLEXITY_SEARCH_TYPE": "fast"},
+ hosted=False,
+ )
+
+ config = run_mock.call_args.kwargs["config"]
+ self.assertEqual("web", config["LAST30DAYS_PERPLEXITY_SEARCH_TYPE"])
+
def test_build_parser_still_accepts_other_web_backend_values(self):
parser = cli.build_parser()
for value in ("auto", "brave", "exa", "serper", "parallel", "parallel-mcp", "none"):
diff --git a/tests/test_env_v3.py b/tests/test_env_v3.py
index 7d4d1882..6d150437 100644
--- a/tests/test_env_v3.py
+++ b/tests/test_env_v3.py
@@ -57,6 +57,7 @@ class EnvV3Tests(unittest.TestCase):
"LAST30DAYS_PERPLEXITY_AGENT_TIMEOUT_SECONDS": "120",
"LAST30DAYS_PERPLEXITY_MAX_RESULTS": "3",
"LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE": "low",
+ "LAST30DAYS_PERPLEXITY_SEARCH_TYPE": "fast",
"LAST30DAYS_PERPLEXITY_SEARCH_MODE": "academic",
"LAST30DAYS_PERPLEXITY_DOMAIN_FILTER": "example.com",
"LAST30DAYS_PERPLEXITY_LANGUAGE_FILTER": "en",
diff --git a/tests/test_http_v3.py b/tests/test_http_v3.py
index 29af27e0..589a8e20 100644
--- a/tests/test_http_v3.py
+++ b/tests/test_http_v3.py
@@ -1,3 +1,5 @@
+import io
+import threading
import urllib.error
import unittest
import time
@@ -41,7 +43,7 @@ class Test429RetryLimit(unittest.TestCase):
@patch("lib.http.urllib.request.urlopen")
@patch("lib.http.time.sleep")
- @patch("lib.http.time.monotonic", side_effect=[0.0, 0.5, 0.5])
+ @patch("lib.http.time.monotonic", return_value=0.5)
def test_shared_deadline_stops_retry_before_backoff_crosses_it(
self,
_mock_monotonic,
@@ -106,6 +108,47 @@ class Test429RetryLimit(unittest.TestCase):
self.assertLess(time.monotonic() - started, 0.12)
+ @patch("lib.http.urllib.request.urlopen")
+ def test_shared_deadline_stops_waiting_during_error_body_read(self, mock_urlopen):
+ release = threading.Event()
+ read_started = threading.Event()
+
+ class SlowBody(io.BytesIO):
+ def read(self, *args, **kwargs):
+ read_started.set()
+ release.wait(1)
+ return super().read(*args, **kwargs)
+
+ mock_urlopen.side_effect = urllib.error.HTTPError(
+ "https://example.com", 500, "Server error", {}, SlowBody(b"error")
+ )
+ started = time.monotonic()
+ try:
+ with self.assertRaises(http.DeadlineExceeded):
+ http.request(
+ "GET", "https://example.com", retries=1,
+ deadline_monotonic=started + 0.05,
+ )
+ self.assertTrue(read_started.is_set())
+ self.assertLess(time.monotonic() - started, 0.5)
+ self.assertEqual(mock_urlopen.call_count, 1)
+ finally:
+ release.set()
+
+ @patch("lib.http.urllib.request.urlopen")
+ def test_error_body_within_deadline_keeps_status_and_body(self, mock_urlopen):
+ mock_urlopen.side_effect = urllib.error.HTTPError(
+ "https://example.com", 401, "Unauthorized", {}, io.BytesIO(b"bad token")
+ )
+ with self.assertRaises(http.HTTPError) as caught:
+ http.request(
+ "GET", "https://example.com", retries=1,
+ deadline_monotonic=time.monotonic() + 1,
+ )
+ self.assertEqual(caught.exception.status_code, 401)
+ self.assertEqual(caught.exception.body, "bad token")
+ self.assertEqual(caught.exception.outcome_state, http.health.AUTH_FAILED)
+
@patch("lib.http.urllib.request.urlopen")
def test_worker_socket_timeout_is_not_wall_deadline_expiration(
self,
@@ -212,6 +255,18 @@ class TestDNSResolutionRetry(unittest.TestCase):
# Caller passed retries=2, but the budget expanded to MIN_DNS_RETRIES=3.
self.assertEqual(mock_urlopen.call_count, http.MIN_DNS_RETRIES)
+ @patch("lib.http.urllib.request.urlopen")
+ @patch("lib.http.time.sleep")
+ def test_dns_failure_widens_single_attempt_budget(self, mock_sleep, mock_urlopen):
+ """DNS failures widen the budget to MIN_DNS_RETRIES, even from retries=1."""
+ import socket
+ mock_urlopen.side_effect = urllib.error.URLError(socket.gaierror(-2, "DNS failure"))
+
+ with self.assertRaises(http.HTTPError):
+ http.request("GET", "https://example.com", retries=1)
+
+ self.assertEqual(mock_urlopen.call_count, http.MIN_DNS_RETRIES)
+
@patch("lib.http.urllib.request.urlopen")
@patch("lib.http.time.sleep")
def test_gaierror_succeeds_after_transient_failure(self, mock_sleep, mock_urlopen):
@@ -300,3 +355,48 @@ class TestDNSResolutionRetry(unittest.TestCase):
http.request("GET", "http://flaky.example", retries=2)
self.assertEqual(mock_urlopen.call_count, 2)
+
+
+class TestDebugLogRedaction(unittest.TestCase):
+ """Debug log lines must not echo credentials the request carried."""
+
+ SECRET = "sk-live-abcdef1234567890"
+
+ def _logged(self, mock_log) -> str:
+ return "\n".join(call.args[0] for call in mock_log.call_args_list)
+
+ @patch("lib.http.log")
+ @patch("lib.http.urllib.request.urlopen")
+ def test_error_body_echoing_bearer_token_is_redacted(self, mock_urlopen, mock_log):
+ mock_urlopen.side_effect = urllib.error.HTTPError(
+ "https://example.com", 401, "Unauthorized", {},
+ io.BytesIO(f"invalid key Bearer {self.SECRET}".encode("utf-8")),
+ )
+
+ with self.assertRaises(http.HTTPError):
+ http.request(
+ "POST", "https://example.com", retries=1,
+ headers={"Authorization": f"Bearer {self.SECRET}"},
+ json_data={"q": "x"},
+ )
+
+ logged = self._logged(mock_log)
+ self.assertIn("Error body:", logged)
+ self.assertIn("<redacted>", logged)
+ self.assertNotIn(self.SECRET, logged)
+
+ @patch("lib.http.log")
+ @patch("lib.http.urllib.request.urlopen")
+ @patch("lib.http.time.sleep")
+ def test_url_error_echoing_api_key_is_redacted(self, _mock_sleep, mock_urlopen, mock_log):
+ mock_urlopen.side_effect = urllib.error.URLError(f"proxy refused key {self.SECRET}")
+
+ with self.assertRaises(http.HTTPError):
+ http.request(
+ "GET", "https://example.com", retries=1,
+ headers={"X-Api-Key": self.SECRET},
+ )
+
+ logged = self._logged(mock_log)
+ self.assertIn("URL Error:", logged)
+ self.assertNotIn(self.SECRET, logged)
diff --git a/tests/test_perplexity_fast_search.py b/tests/test_perplexity_fast_search.py
new file mode 100644
index 00000000..2cc1aa88
--- /dev/null
+++ b/tests/test_perplexity_fast_search.py
@@ -0,0 +1,143 @@
+"""Fast Search transport contract; no provider calls or credentials required."""
+import sys
+from unittest.mock import patch
+
+import pytest
+
+import last30days as cli
+from lib import env, perplexity
+
+DATE_RANGE = ("2026-09-01", "2026-09-27")
+KEY = "LAST30DAYS_PERPLEXITY_SEARCH_TYPE"
+SEARCH_RESPONSE = {
+ "id": "search-fixture",
+ "results": [{"title": "Rust release", "url": "https://example.com/rust",
+ "snippet": "Release source", "date": "2026-09-25"}],
+}
+AGENT_RESPONSE = {"id": "agent-fixture", "status": "completed", "output_text": "Summary", "output": []}
+
+
[email protected]("search_type", [None, "web", "fast"])
[email protected]("mode", ["search", "agent", "both"])
+def test_transport_type_and_safe_receipt_preserve_filters(search_type, mode):
+ config = {"PERPLEXITY_API_KEY": "dummy-test-key",
+ "LAST30DAYS_PERPLEXITY_MODE": mode,
+ "LAST30DAYS_PERPLEXITY_DOMAIN_FILTER": "example.com",
+ "LAST30DAYS_PERPLEXITY_MAX_RESULTS": "25"}
+ if search_type:
+ config[KEY] = search_type
+ responses = {perplexity.PERPLEXITY_SEARCH_URL: SEARCH_RESPONSE,
+ perplexity.PERPLEXITY_AGENT_URL: AGENT_RESPONSE}
+ with patch.object(perplexity.http, "post", side_effect=lambda url, *a, **kw: responses[url]) as post:
+ items, artifact = perplexity.search("Rust releases", DATE_RANGE, config)
+ assert post.call_count == (2 if mode == "both" else 1)
+ for call in post.call_args_list:
+ is_search = call.args[0] == perplexity.PERPLEXITY_SEARCH_URL
+ payload = call.args[1]
+ request = payload if is_search else payload["tools"][0]
+ receipt = artifact["search" if is_search else "agent"] if mode == "both" else artifact
+ recorded = receipt["request"] if is_search else receipt["request"]["tools"][0]
+ if search_type:
+ assert request["search_type"] == recorded["search_type"] == search_type
+ else:
+ assert "search_type" not in request
+ assert "search_type" not in recorded
+ filters = request if is_search else request["filters"]
+ assert filters["search_domain_filter"] == ["example.com"]
+ assert filters["search_after_date_filter"] == "09/01/2026"
+ assert filters["search_before_date_filter"] == "09/27/2026"
+ assert request["max_results"] == 20
+ assert "dummy-test-key" not in str(receipt)
+ if not is_search:
+ assert "preset" not in payload
+ assert payload["tool_choice"] == {"type": "web_search"}
+ if mode == "search":
+ assert items[0]["snippet"] == "Release source"
+ assert items[0]["date"] == "2026-09-25"
+
+
[email protected]("deep,preset", [(False, "fast"), (False, "high"), (True, None)])
+def test_explicit_type_is_independent_of_mutable_agent_preset(deep, preset):
+ config = {KEY: "web", "LAST30DAYS_PERPLEXITY_AGENT_PRESET": preset}
+ payload, receipt = perplexity._build_agent_payload("test prompt", DATE_RANGE, config, deep)
+ assert payload["preset"] == ("high" if deep else preset)
+ assert payload["tools"][0]["search_type"] == "web"
+ assert receipt["request"]["tools"][0]["search_type"] == "web"
+
+
[email protected]("mode", ["search", "agent", "both"])
+def test_invalid_type_makes_no_paid_request(mode):
+ with patch.object(perplexity.http, "post") as post:
+ items, artifact = perplexity.search("topic", DATE_RANGE, {
+ "PERPLEXITY_API_KEY": "dummy-test-key", KEY: "pro",
+ "LAST30DAYS_PERPLEXITY_MODE": mode})
+ post.assert_not_called()
+ assert items == []
+ assert "must be web or fast" in str(artifact)
+
+
+def test_openrouter_keeps_sonar_and_discloses_ignored_search_type():
+ response = {"choices": [{"message": {"content": "Summary"}}]}
+ with patch.object(perplexity.http, "post", return_value=response) as post, patch.object(perplexity, "_log") as log:
+ _, artifact = perplexity.search("topic", DATE_RANGE, {
+ "OPENROUTER_API_KEY": "dummy-test-key", KEY: "fast"})
+ assert post.call_count == 1
+ assert post.call_args.args[0] == perplexity.OPENROUTER_URL
+ assert "search_type" not in str(post.call_args.args[1])
+ assert artifact["provider"] == "openrouter"
+ assert any("does not change OpenRouter" in str(call) for call in log.call_args_list)
+
+
[email protected]("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"]
+ if cli_value:
+ args += ["--perplexity-search-type", cli_value]
+ class ConfigCaptured(Exception):
+ pass
+ with patch.object(sys, "argv", args), patch.object(cli.env, "get_config", return_value={KEY: "fast"}), patch.object(cli, "_propagate_config_to_environ", side_effect=ConfigCaptured) as capture:
+ with pytest.raises(ConfigCaptured):
+ cli.main()
+ config = capture.call_args.args[0]
+ assert config[KEY] == expected
+ assert "INCLUDE_SOURCES" not in config
+ assert "LAST30DAYS_PERPLEXITY_MODE" not in config
+ assert "LAST30DAYS_PERPLEXITY_AGENT_PRESET" not in config
+
+
+def test_cli_rejects_sonar_only_search_type():
+ with pytest.raises(SystemExit) as exc:
+ cli.build_parser().parse_args(["topic", "--perplexity-search-type", "pro"])
+ assert exc.value.code == 2
+
+
+def test_search_type_loads_from_config_file_and_environment(tmp_path, monkeypatch):
+ config_file = tmp_path / ".env"
+ config_file.write_text(f"{KEY}=fast\n")
+ config_file.chmod(0o600)
+ monkeypatch.setattr(env, "CONFIG_FILE", config_file)
+ monkeypatch.delenv(KEY, raising=False)
+ with patch.object(env, "_find_project_env", return_value=None), patch.object(env, "_load_keychain", return_value={}), patch.object(env, "_load_pass", return_value={}):
+ assert env.get_config()[KEY] == "fast"
+ monkeypatch.setenv(KEY, "web")
+ assert env.get_config()[KEY] == "web"
+
+
[email protected]("mode", ["search", "agent", "both"])
[email protected]("failure", [
+ perplexity.http.HTTPError("unavailable", status_code=503),
+ TimeoutError("timed out"),
+])
+def test_failed_legs_keep_requested_type_without_extra_requests(mode, failure):
+ with patch.object(perplexity.http, "post", side_effect=failure) as post:
+ items, artifact = perplexity.search("topic", DATE_RANGE, {
+ "PERPLEXITY_API_KEY": "dummy-test-key", KEY: "fast",
+ "LAST30DAYS_PERPLEXITY_MODE": mode})
+ assert post.call_count == (2 if mode == "both" else 1)
+ assert items == []
+ legs = [artifact["search"], artifact["agent"]] if mode == "both" else [artifact]
+ for leg in legs:
+ assert leg["error"]
+ assert leg["requested_search_type"] == "fast"
+ assert "effective_search_type" not in leg
+ assert "dummy-test-key" not in str(leg)