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(setup): surface ScrapeCreators /profile 5xx instead of already-linked (#925)
dev_Hakaze90deb7c2ec56
diff --git a/changelog.d/882.fixed.md b/changelog.d/882.fixed.mdnew file mode 100644index 00000000..5bc09f08--- /dev/null+++ b/changelog.d/882.fixed.md@@ -0,0 +1 @@+ScrapeCreators GitHub device flow: `fetch_api_key` no longer collapses HTTP 5xx from `/v1/github/device/profile` into the already-linked "Authorized but failed to fetch API key" path. Server errors surface as `reason: upstream_error` with a distinct message (after bounded retries and a truncated body in the detail), and SKILL.md routes those failures to web signup/retry instead of "your GitHub is probably already linked."diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex 4f29399a..fa40aeef 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -615,7 +615,8 @@ Options:3. **Run `--github-poll`** (background with a 5-minute timeout, or foreground): `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-poll`. Parse the **LAST** JSON line of its stdout for the final status:- `status == "success"`: the engine persisted the key (`"persisted": true`, MASKED `api_key` - never ask for or echo the raw key); confirm "You're in! 10,000 free calls. TikTok, Instagram, empty-path Reddit search backup, and YouTube transcript fallback are now active."- `status == "success"` but `"persisted": false` (key write failed): do NOT claim sources are active - tell the user signup worked but saving the key failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually.- - `status == "error"` **with `message == "Authorized but failed to fetch API key"`**: GitHub authorized fine - do NOT say auth failed. This usually means your GitHub is **already linked** to a ScrapeCreators account. Tell the user: "GitHub authorized, but I couldn't auto-grab your ScrapeCreators key - your GitHub is probably already linked to an account. Get your key at scrapecreators.com and paste it here, or Skip." Then accept a pasted key (write `SCRAPECREATORS_API_KEY` to `.env`) or offer the web/skip options.+ - `status == "error"` **with `message == "Authorized but failed to fetch API key"`** (exact match; often also `"reason": "no_api_key"`): GitHub authorized fine - do NOT say auth failed. This usually means your GitHub is **already linked** to a ScrapeCreators account. Tell the user: "GitHub authorized, but I couldn't auto-grab your ScrapeCreators key - your GitHub is probably already linked to an account. Get your key at scrapecreators.com and paste it here, or Skip." Then accept a pasted key (write `SCRAPECREATORS_API_KEY` to `.env`) or offer the web/skip options.+ - `status == "error"` **with `message` containing `ScrapeCreators profile failed`** (or `"reason": "upstream_error"`): GitHub authorized fine - do NOT say auth failed, and do **NOT** say the GitHub is already linked. ScrapeCreators returned a server error after auth. Tell the user: "GitHub authorized, but ScrapeCreators had a server error minting your key - this is on their side, not yours. Sign up or log in at scrapecreators.com, grab a key there, and paste it, or Skip / retry later." Accept a pasted key or offer web/skip. Do not imply they already have a working linked account.- `status == "timeout"`, or any other `status == "error"` message: show "GitHub auth didn't complete - no worries, sign up at scrapecreators.com or try again later," then offer the web option below.- **One-shot fallback:** hosts that prefer a single call can still run `setup --github` (foreground), which chains start+poll; tell the user first that a code will appear on their clipboard to paste.- "Open scrapecreators.com (Google sign-in)" - run `open https://scrapecreators.com` via Bash, then ask them to paste the API key. Write `SCRAPECREATORS_API_KEY={key}` to `~/.config/last30days/.env`.@@ -667,7 +668,8 @@ For hosts without interactive modal prompts (OpenClaw, Codex, Cursor, Gemini CLI**5. ScrapeCreators signup offer (every first run, consent BEFORE launching the browser).** Explain it grants 10,000 free calls that add TikTok and Instagram, plus optional backups: Reddit search backfill when the free path returns no items (empty-only by default; thin-run / SC-primary are opt-in env knobs — see Reddit backend pin below), and a YouTube transcript fallback when yt-dlp is rate-limited or bot-gated. GitHub signup grants the full 10,000 free calls (more than the web form), and it opens a GitHub authorization page where you enter a short code. Ask, e.g.: `Want to unlock TikTok, Instagram, and more? I can sign you up for ScrapeCreators with GitHub (10,000 free calls, ~20-30s) - it opens a browser and you enter a short code. (yes / no)` **Wait for the answer.**- On **yes** → two commands. FIRST run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-start` in the FOREGROUND - it returns in ~1-2s with a `Your GitHub code: XXXX-XXXX` line plus a JSON blob, copies the code to the clipboard, and opens the browser. Read the `user_code` from that output and immediately tell the user: the code, that it's on their clipboard so they can just paste it (Cmd+V) on the GitHub page - do not make them hunt for it. (If `status == "already_registered"`, stop here - their existing key is active. If the output said the clipboard copy failed, tell them to type the code.) THEN run `"${LAST30DAYS_PYTHON:-python3}" skills/last30days/scripts/last30days.py setup --github-poll` (background with a 5-min timeout, or foreground) and parse the **LAST** JSON line of its stdout for the final status. On success the engine persists the key automatically and returns `"persisted": true` with a MASKED `api_key` (never ask for or echo the raw key). Confirm the paid sources are active.- On **success but `"persisted": false`** (auth completed yet the key write failed) → do NOT claim sources are active. Tell the user signup worked but saving failed, and have them add `SCRAPECREATORS_API_KEY=<key>` to `~/.config/last30days/.env` manually (the raw key is masked in output, so re-run `setup --github` or retrieve it from scrapecreators.com to get the value).- - On **`status == "error"` with `message == "Authorized but failed to fetch API key"`** → GitHub authorized fine, so do NOT say auth failed. This usually means the GitHub account is already linked to a ScrapeCreators account. Tell the user: "GitHub authorized, but I couldn't auto-grab your ScrapeCreators key - your GitHub is probably already linked to an account. Get your key at scrapecreators.com and paste it, or Skip." Accept a pasted key or offer web/skip.+ - On **`status == "error"` with `message == "Authorized but failed to fetch API key"`** (exact match; often `"reason": "no_api_key"`) → GitHub authorized fine, so do NOT say auth failed. This usually means the GitHub account is already linked to a ScrapeCreators account. Tell the user: "GitHub authorized, but I couldn't auto-grab your ScrapeCreators key - your GitHub is probably already linked to an account. Get your key at scrapecreators.com and paste it, or Skip." Accept a pasted key or offer web/skip.+ - On **`status == "error"` with `message` containing `ScrapeCreators profile failed`** (or `"reason": "upstream_error"`) → GitHub authorized fine; do NOT say auth failed, and do **NOT** say the account is already linked. ScrapeCreators returned a server error after auth. Tell the user: "GitHub authorized, but ScrapeCreators had a server error minting your key - this is on their side, not yours. Sign up or log in at scrapecreators.com, grab a key there, and paste it, or Skip / retry later." Accept a pasted key or offer web/skip.- On **timeout, or any other error** → tell the user it didn't complete and offer to retry or the web signup at scrapecreators.com.- On **no** → note they can run it later by asking to set up ScrapeCreators, then continue.diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex df7d2973..5c889613 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -1046,22 +1046,98 @@ def poll_device_auth(return None-def fetch_api_key(access_token: str) -> Optional[str]:- """Fetch the ScrapeCreators API key using the GitHub access token.+# Bounded retries for transient ScrapeCreators /profile 5xx (see #882).+_PROFILE_FETCH_ATTEMPTS = 3+_PROFILE_FETCH_RETRY_SLEEP_S = 1.0+_PROFILE_ERROR_BODY_LIMIT = 200- GETs the device/profile endpoint with Bearer auth.- Returns:- api_key string on success, None on failure.+def _http_error_detail(exc: HTTPError, *, body_limit: int = _PROFILE_ERROR_BODY_LIMIT) -> str:+ """Build a diagnosable HTTPError string including a truncated body.++ The body is capped and never treated as a secret source of truth; callers+ still must not log bearer tokens. Used so a 5xx is not a black box."""+ base = f"HTTP Error {exc.code}: {getattr(exc, 'reason', '') or ''}".rstrip(": ")try:- req = Request(f"{_DEVICE_BASE}/profile")- req.add_header("Authorization", f"Bearer {access_token}")- with urlopen(req, timeout=15) as resp:- data = json.loads(resp.read())- except (HTTPError, URLError, OSError) as exc:- logger.warning("Failed to fetch API key: %s", exc)- return None+ raw = exc.read() or b""+ except Exception:+ return base+ if not raw:+ return base+ text = raw.decode("utf-8", errors="replace").strip()+ if not text:+ return base+ if len(text) > body_limit:+ text = text[:body_limit] + "…"+ return f"{base} body={text!r}"+++def fetch_api_key(access_token: str) -> Dict[str, Any]:+ """Fetch the ScrapeCreators API key using the GitHub access token.++ GETs the device/profile endpoint with Bearer auth. Distinguishes outcomes+ so callers (and SKILL.md) do not collapse a server 5xx into the+ already-linked guidance (#882).++ Returns a result dict:+ - ``{"ok": True, "api_key": str}`` on success+ - ``{"ok": False, "reason": "no_api_key"}`` when /profile is 2xx but has+ no ``api_key`` field (typical already-linked account)+ - ``{"ok": False, "reason": "upstream_error", "http_status": int,+ "detail": str}`` on 5xx after bounded retries+ - ``{"ok": False, "reason": "http_error", "http_status": int,+ "detail": str}`` on other HTTP errors (e.g. 401)+ - ``{"ok": False, "reason": "request_failed", "detail": str}`` on+ network/OS failures+ """+ data: Optional[Dict[str, Any]] = None+ last_upstream: Optional[Dict[str, Any]] = None++ for attempt in range(_PROFILE_FETCH_ATTEMPTS):+ try:+ req = Request(f"{_DEVICE_BASE}/profile")+ req.add_header("Authorization", f"Bearer {access_token}")+ with urlopen(req, timeout=15) as resp:+ data = json.loads(resp.read())+ break+ except HTTPError as exc:+ detail = _http_error_detail(exc)+ if 500 <= int(exc.code) <= 599:+ logger.warning(+ "Device auth /profile upstream error (attempt %s/%s): %s",+ attempt + 1,+ _PROFILE_FETCH_ATTEMPTS,+ detail,+ )+ last_upstream = {+ "ok": False,+ "reason": "upstream_error",+ "http_status": int(exc.code),+ "detail": detail,+ }+ if attempt + 1 < _PROFILE_FETCH_ATTEMPTS:+ time.sleep(_PROFILE_FETCH_RETRY_SLEEP_S)+ continue+ return last_upstream+ logger.warning("Failed to fetch API key: %s", detail)+ return {+ "ok": False,+ "reason": "http_error",+ "http_status": int(exc.code),+ "detail": detail,+ }+ except (URLError, OSError) as exc:+ logger.warning("Failed to fetch API key: %s", exc)+ return {"ok": False, "reason": "request_failed", "detail": str(exc)}++ if data is None:+ # Defensive: loop exited without success or an explicit return.+ return last_upstream or {+ "ok": False,+ "reason": "request_failed",+ "detail": "No profile response",+ }api_key = data.get("api_key")if not api_key:@@ -1073,8 +1149,8 @@ def fetch_api_key(access_token: str) -> Optional[str]:logger.warning("Device auth /profile returned no api_key (fields: %s)", sorted(data.keys()))- return None- return api_key+ return {"ok": False, "reason": "no_api_key"}+ return {"ok": True, "api_key": api_key}def _device_handle_path() -> Path:@@ -1269,15 +1345,50 @@ def run_github_poll(timeout: int = 300, *, _handle: Optional[Dict[str, Any]] = N_cleanup()return {"status": "timeout", "user_code": user_code}- api_key = fetch_api_key(access_token)+ fetched = fetch_api_key(access_token)_cleanup()- if api_key is None:+ if fetched.get("ok") and fetched.get("api_key"):+ return {+ "status": "success",+ "method": "device",+ "api_key": fetched["api_key"],+ "user_code": user_code,+ }++ # Discriminate failure modes so SKILL.md does not misdiagnose a 5xx as+ # "GitHub already linked" (#882). Keep the historical message only for the+ # 2xx-without-api_key / already-linked case.+ reason = fetched.get("reason") or "request_failed"+ if reason == "no_api_key":return {"status": "error","message": "Authorized but failed to fetch API key",+ "reason": "no_api_key",}-- return {"status": "success", "method": "device", "api_key": api_key, "user_code": user_code}+ if reason == "upstream_error":+ http_status = fetched.get("http_status")+ return {+ "status": "error",+ "message": f"Authorized but ScrapeCreators profile failed (HTTP {http_status})",+ "reason": "upstream_error",+ "http_status": http_status,+ "detail": fetched.get("detail"),+ }+ if reason == "http_error":+ http_status = fetched.get("http_status")+ return {+ "status": "error",+ "message": f"Authorized but failed to fetch API key (HTTP {http_status})",+ "reason": "http_error",+ "http_status": http_status,+ "detail": fetched.get("detail"),+ }+ return {+ "status": "error",+ "message": "Authorized but failed to fetch API key",+ "reason": reason,+ "detail": fetched.get("detail"),+ }def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]:diff --git a/tests/test_github_device_auth.py b/tests/test_github_device_auth.pyindex f6672f47..4014ecb2 100644--- a/tests/test_github_device_auth.py+++ b/tests/test_github_device_auth.py@@ -120,7 +120,7 @@ class TestAlreadyRegistered:handle.write_text(_json.dumps({"device_code": "dc", "interval": 1, "user_code": "819B-F71B"}))mock_handle.return_value = handlemock_poll.return_value = "access-token"- mock_fetch.return_value = "sc_polled_key"+ mock_fetch.return_value = {"ok": True, "api_key": "sc_polled_key"}result = setup_wizard.run_github_poll(timeout=1)@@ -148,7 +148,7 @@ class TestAlreadyRegistered:)mock_handle.return_value = handlemock_poll.return_value = "tok"- mock_fetch.return_value = "sc_k"+ mock_fetch.return_value = {"ok": True, "api_key": "sc_k"}setup_wizard.run_github_poll(timeout=1)@@ -169,7 +169,7 @@ class TestAlreadyRegistered:{"device_code": "dc", "interval": 1, "user_code": "819B-F71B", "clipboard_ok": True},)mock_poll.return_value = "tok"- mock_fetch.return_value = "sc_oneshot_key"+ mock_fetch.return_value = {"ok": True, "api_key": "sc_oneshot_key"}result = setup_wizard.run_full_device_auth(timeout=1)@@ -200,7 +200,7 @@ class TestFetchApiKeyLogging:result = setup_wizard.fetch_api_key("gh_access_token")- assert result is None+ assert result == {"ok": False, "reason": "no_api_key"}# The warning must include the field names but never the secret value.logged = " ".join(str(c) for c in mock_logger.warning.call_args_list)assert "linked" in logged and "token" in loggeddiff --git a/tests/test_onboarding_contract.py b/tests/test_onboarding_contract.pyindex 56705609..a1e54909 100644--- a/tests/test_onboarding_contract.py+++ b/tests/test_onboarding_contract.py@@ -377,6 +377,16 @@ class TestOnboardingContract(unittest.TestCase):self.assertIn("Authorized but failed to fetch API key", slice_text, slice_name)self.assertIn("already linked", slice_text, slice_name)+ def test_upstream_profile_error_branch_distinct_from_already_linked(self):+ """A ScrapeCreators /profile 5xx must not be diagnosed as already-linked (#882)."""+ for slice_name, slice_text in (("modal", self.modal), ("prose", self.prose)):+ self.assertIn("ScrapeCreators profile failed", slice_text, slice_name)+ self.assertIn("upstream_error", slice_text, slice_name)+ self.assertIn("server error", slice_text, slice_name)+ # Guidance forbids the already-linked misdiagnosis on this path.+ self.assertIn("do **NOT** say", slice_text, slice_name)+ self.assertIn("already linked", slice_text, slice_name)+# --- Legacy guarantees retained ---def test_old_silent_wizard_instruction_removed(self):diff --git a/tests/test_setup_openclaw.py b/tests/test_setup_openclaw.pyindex 9a7625c4..f4c079c5 100644--- a/tests/test_setup_openclaw.py+++ b/tests/test_setup_openclaw.py@@ -317,7 +317,7 @@ class TestFetchApiKey:@patch("lib.setup_wizard.urlopen")def test_success(self, mock_urlopen):- """Returns api_key from profile response."""+ """Returns ok+api_key from profile response."""resp_data = {"api_key": "sc-key-abc123", "username": "testuser"}mock_resp = MagicMock()mock_resp.read.return_value = json.dumps(resp_data).encode()@@ -326,11 +326,11 @@ class TestFetchApiKey:mock_urlopen.return_value = mock_respresult = setup_wizard.fetch_api_key("gho_token")- assert result == "sc-key-abc123"+ assert result == {"ok": True, "api_key": "sc-key-abc123"}@patch("lib.setup_wizard.urlopen")def test_no_api_key_in_response(self, mock_urlopen):- """Returns None when api_key is not in the response."""+ """Returns no_api_key when api_key is not in the response."""resp_data = {"username": "testuser"}mock_resp = MagicMock()mock_resp.read.return_value = json.dumps(resp_data).encode()@@ -339,18 +339,46 @@ class TestFetchApiKey:mock_urlopen.return_value = mock_respresult = setup_wizard.fetch_api_key("gho_token")- assert result is None+ assert result == {"ok": False, "reason": "no_api_key"}@patch("lib.setup_wizard.urlopen")- def test_http_error_returns_none(self, mock_urlopen):- """HTTP error returns None."""+ def test_http_error_returns_http_error(self, mock_urlopen):+ """4xx HTTP error is reason=http_error, not no_api_key."""from urllib.error import HTTPErrormock_urlopen.side_effect = HTTPError("https://example.com", 401, "Unauthorized", {}, None)result = setup_wizard.fetch_api_key("bad_token")- assert result is None+ assert result["ok"] is False+ assert result["reason"] == "http_error"+ assert result["http_status"] == 401++ @patch("lib.setup_wizard.time.sleep")+ @patch("lib.setup_wizard.urlopen")+ def test_http_500_is_upstream_error_with_retries(self, mock_urlopen, mock_sleep):+ """5xx is upstream_error after bounded retries; not no_api_key (#882)."""+ from urllib.error import HTTPError+ from io import BytesIO++ def _http_500(_req, timeout=15):+ raise HTTPError(+ "https://api.scrapecreators.com/v1/github/device/profile",+ 500,+ "Internal Server Error",+ {},+ BytesIO(b'{"message":"internal"}'),+ )++ mock_urlopen.side_effect = _http_500++ result = setup_wizard.fetch_api_key("gho_token")+ assert result["ok"] is False+ assert result["reason"] == "upstream_error"+ assert result["http_status"] == 500+ assert "500" in result["detail"]+ assert mock_urlopen.call_count == setup_wizard._PROFILE_FETCH_ATTEMPTS+ assert mock_sleep.call_count == setup_wizard._PROFILE_FETCH_ATTEMPTS - 1class TestRunFullDeviceAuth:@@ -364,7 +392,7 @@ class TestRunFullDeviceAuth:"""Full flow succeeds: start -> poll -> fetch -> return api_key."""mock_start.return_value = ("dev123", "ABCD-1234", "https://example.com/device", 5)mock_poll.return_value = "access_tok"- mock_fetch.return_value = "sc_live_abc123"+ mock_fetch.return_value = {"ok": True, "api_key": "sc_live_abc123"}result = setup_wizard.run_full_device_auth(timeout=10)@@ -401,15 +429,39 @@ class TestRunFullDeviceAuth:@patch("lib.setup_wizard.run_device_auth")@patch("webbrowser.open")def test_fetch_fails_after_auth(self, mock_browser, mock_start, mock_poll, mock_fetch):- """Auth succeeds but profile fetch fails -> error status."""+ """Auth succeeds but profile has no api_key -> already-linked error message."""+ mock_start.return_value = ("dev123", "CODE-1111", "https://example.com/device", 5)+ mock_poll.return_value = "access_tok"+ mock_fetch.return_value = {"ok": False, "reason": "no_api_key"}++ result = setup_wizard.run_full_device_auth(timeout=10)++ assert result["status"] == "error"+ assert result["message"] == "Authorized but failed to fetch API key"+ assert result["reason"] == "no_api_key"++ @patch("lib.setup_wizard.fetch_api_key")+ @patch("lib.setup_wizard.poll_device_auth")+ @patch("lib.setup_wizard.run_device_auth")+ @patch("webbrowser.open")+ def test_fetch_upstream_500_after_auth(self, mock_browser, mock_start, mock_poll, mock_fetch):+ """Auth succeeds but /profile 5xx -> distinct upstream message (#882)."""mock_start.return_value = ("dev123", "CODE-1111", "https://example.com/device", 5)mock_poll.return_value = "access_tok"- mock_fetch.return_value = None+ mock_fetch.return_value = {+ "ok": False,+ "reason": "upstream_error",+ "http_status": 500,+ "detail": "HTTP Error 500: Internal Server Error",+ }result = setup_wizard.run_full_device_auth(timeout=10)assert result["status"] == "error"- assert "failed to fetch" in result["message"].lower()+ assert result["reason"] == "upstream_error"+ assert "ScrapeCreators profile failed" in result["message"]+ assert "500" in result["message"]+ assert result["message"] != "Authorized but failed to fetch API key"@patch("lib.setup_wizard.run_device_auth")@patch("webbrowser.open")