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: prune unsupported Codex auth provider path
Trevin Chow34365e68fede
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex 7f208e2f..7fa3be98 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -2,12 +2,9 @@from __future__ import annotations-import base64-import binasciiimport jsonimport osimport sys-import timefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Literal@@ -27,8 +24,6 @@ else:CONFIG_DIR = Path.home() / ".config" / "last30days"CONFIG_FILE = CONFIG_DIR / ".env"-CODEX_AUTH_FILE = Path(os.environ.get("CODEX_AUTH_FILE", str(Path.home() / ".codex" / "auth.json")))-# macOS Keychain integration: items stored with this service prefix are picked# up automatically on Darwin as the lowest-priority credential source.# Example: `security add-generic-password -a "$USER" -s last30days-XAI_API_KEY -w "xai-..."`.@@ -62,17 +57,14 @@ KEYCHAIN_KEYS = (# separator. Honors PASSWORD_STORE_DIR.DEFAULT_PASS_PATH_PREFIX = "last30days/"-AuthSource = Literal["api_key", "codex", "none"]-AuthStatus = Literal["ok", "missing", "expired", "missing_account_id"]+AuthSource = Literal["api_key", "none"]+AuthStatus = Literal["ok", "missing"]AUTH_SOURCE_API_KEY: AuthSource = "api_key"-AUTH_SOURCE_CODEX: AuthSource = "codex"AUTH_SOURCE_NONE: AuthSource = "none"AUTH_STATUS_OK: AuthStatus = "ok"AUTH_STATUS_MISSING: AuthStatus = "missing"-AUTH_STATUS_EXPIRED: AuthStatus = "expired"-AUTH_STATUS_MISSING_ACCOUNT_ID: AuthStatus = "missing_account_id"@dataclass(frozen=True)@@ -80,8 +72,6 @@ class OpenAIAuth:token: str | Nonesource: AuthSourcestatus: AuthStatus- account_id: str | None- codex_auth_file: strBrowserCookieMode = Literal["off", "read", "plan_only"]@@ -314,102 +304,20 @@ def _load_pass(keys: list[str], prefix: str) -> dict[str, str]:return env-def _decode_jwt_payload(token: str) -> dict[str, Any] | None:- """Decode JWT payload without verification."""- try:- parts = token.split(".")- if len(parts) < 2:- return None- payload_b64 = parts[1]- pad = "=" * (-len(payload_b64) % 4)- decoded = base64.urlsafe_b64decode(payload_b64 + pad)- return json.loads(decoded.decode("utf-8"))- except (json.JSONDecodeError, UnicodeDecodeError, binascii.Error, IndexError) as exc:- sys.stderr.write(f"[last30days] WARNING: malformed JWT token: {exc}\n")- sys.stderr.flush()- return None---def _token_expired(token: str, leeway_seconds: int = 60) -> bool:- """Check if JWT token is expired."""- payload = _decode_jwt_payload(token)- if not payload:- return False- exp = payload.get("exp")- if not exp:- return False- return exp <= (time.time() + leeway_seconds)---def extract_chatgpt_account_id(access_token: str) -> str | None:- """Extract chatgpt_account_id from JWT token."""- payload = _decode_jwt_payload(access_token)- if not payload:- return None- auth_claim = payload.get("https://api.openai.com/auth", {})- if isinstance(auth_claim, dict):- return auth_claim.get("chatgpt_account_id")- return None---def load_codex_auth(path: Path = CODEX_AUTH_FILE) -> dict[str, Any]:- """Load Codex auth JSON."""- if not path.exists():- return {}- try:- with open(path, "r") as f:- return json.load(f)- except json.JSONDecodeError:- sys.stderr.write(- f"[last30days] WARNING: {path} exists but contains invalid JSON -- ignoring\n"- )- sys.stderr.flush()- return {}---def get_codex_access_token() -> tuple[str | None, str]:- """Get Codex access token from auth.json.-- Returns:- (token, status) where status is 'ok', 'missing', or 'expired'- """- auth = load_codex_auth()- token = None- if isinstance(auth, dict):- tokens = auth.get("tokens") or {}- if isinstance(tokens, dict):- token = tokens.get("access_token")- if not token:- token = auth.get("access_token")- if not token:- return None, AUTH_STATUS_MISSING- if _token_expired(token):- return None, AUTH_STATUS_EXPIRED- return token, AUTH_STATUS_OK--def get_openai_auth(file_env: dict[str, str]) -> OpenAIAuth:- """Resolve OpenAI auth from API key or Codex login."""+ """Resolve OpenAI API auth from explicit user-provided API keys."""api_key = os.environ.get('OPENAI_API_KEY') or file_env.get('OPENAI_API_KEY')if api_key:return OpenAIAuth(token=api_key,source=AUTH_SOURCE_API_KEY,status=AUTH_STATUS_OK,- account_id=None,- codex_auth_file=str(CODEX_AUTH_FILE),)- # Codex auth (chatgpt.com backend) intentionally skipped.- # The endpoint is unstable and causes crashes when the token expires.- # Users who want OpenAI should set OPENAI_API_KEY explicitly.-return OpenAIAuth(token=None,source=AUTH_SOURCE_NONE,status=AUTH_STATUS_MISSING,- account_id=None,- codex_auth_file=str(CODEX_AUTH_FILE),)@@ -491,8 +399,6 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:'OPENAI_API_KEY': openai_auth.token,'OPENAI_AUTH_SOURCE': openai_auth.source,'OPENAI_AUTH_STATUS': openai_auth.status,- 'OPENAI_CHATGPT_ACCOUNT_ID': openai_auth.account_id,- 'CODEX_AUTH_FILE': openai_auth.codex_auth_file,}keys = [diff --git a/skills/last30days/scripts/lib/providers.py b/skills/last30days/scripts/lib/providers.pyindex 9927111c..536bd353 100644--- a/skills/last30days/scripts/lib/providers.py+++ b/skills/last30days/scripts/lib/providers.py@@ -17,7 +17,6 @@ XAI_DEFAULT = "grok-4-1-fast"GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses"-CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses"XAI_RESPONSES_URL = "https://api.x.ai/v1/responses"OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"# OpenRouter routes the Gemini Flash Lite tier as the -preview slug; that is the@@ -101,10 +100,8 @@ class GeminiClient(ReasoningClient):class OpenAIClient(ReasoningClient):name = "openai"- def __init__(self, token: str, auth_source: str, account_id: str | None):+ def __init__(self, token: str):self.token = token- self.auth_source = auth_source- self.account_id = account_iddef generate_text(self,@@ -115,29 +112,6 @@ class OpenAIClient(ReasoningClient):response_mime_type: str | None = None,) -> str:del tools, response_mime_type- if self.auth_source == env.AUTH_SOURCE_CODEX:- payload = {- "model": model,- "stream": True,- "store": False,- "input": [- {- "type": "message",- "role": "user",- "content": [{"type": "input_text", "text": prompt}],- }- ],- }- headers = {- "Authorization": f"Bearer {self.token}",- "chatgpt-account-id": self.account_id or "",- "OpenAI-Beta": "responses=experimental",- "originator": "pi",- "Content-Type": "application/json",- }- raw = http.post_raw(CODEX_RESPONSES_URL, payload, headers=headers, timeout=90)- return extract_openai_text(_parse_codex_stream(raw))-payload = {"model": model,"store": False,@@ -310,9 +284,7 @@ def resolve_runtime(config: dict[str, Any], depth: str) -> tuple[schema.Providerx_search_backend=_resolve_x_backend(config),)return runtime, OpenAIClient(- openai_token,- config.get("OPENAI_AUTH_SOURCE") or env.AUTH_SOURCE_API_KEY,- config.get("OPENAI_CHATGPT_ACCOUNT_ID"),+ openai_token)if provider_name == "xai":@@ -406,64 +378,3 @@ def extract_openai_text(payload: dict[str, Any]) -> str:if payload:print(f"[Providers] extract_openai_text: no text in payload keys: {list(payload.keys())}", file=sys.stderr)return ""---def _parse_sse_chunk(chunk: str) -> dict[str, Any] | None:- data_lines = [- line[5:].strip()- for line in chunk.split("\n")- if line.startswith("data:")- ]- if not data_lines:- return None- data = "\n".join(data_lines).strip()- if not data or data == "[DONE]":- return None- try:- return json.loads(data)- except json.JSONDecodeError:- print(f"[Providers] _parse_sse_chunk: invalid JSON: {data[:100]}", file=sys.stderr)- return None---def _parse_codex_stream(raw: str) -> dict[str, Any]:- events: list[dict[str, Any]] = []- buffer = ""- for chunk in raw.splitlines(keepends=True):- buffer += chunk- while "\n\n" in buffer:- event_chunk, buffer = buffer.split("\n\n", 1)- event = _parse_sse_chunk(event_chunk)- if event is not None:- events.append(event)- if buffer.strip():- event = _parse_sse_chunk(buffer)- if event is not None:- events.append(event)-- for event in reversed(events):- if event.get("type") == "response.completed" and isinstance(event.get("response"), dict):- return event["response"]- if isinstance(event.get("response"), dict):- return event["response"]-- output_text = ""- for event in events:- delta = event.get("delta")- if isinstance(delta, str):- output_text += delta- text = event.get("text")- if isinstance(text, str):- output_text += text- if output_text:- return {- "output": [- {- "type": "message",- "content": [{"type": "output_text", "text": output_text}],- }- ]- }- if raw.strip():- print(f"[Providers] _parse_codex_stream: received {len(raw)} bytes but could not extract text", file=sys.stderr)- return {}diff --git a/tests/test_env_cookies.py b/tests/test_env_cookies.pyindex d667a09c..365c4fb0 100644--- a/tests/test_env_cookies.py+++ b/tests/test_env_cookies.py@@ -114,7 +114,6 @@ class TestGetConfigCookieIntegration:from lib.env import get_config, OpenAIAuthmock_openai.return_value = OpenAIAuth(token=None, source="none", status="missing",- account_id=None, codex_auth_file="/fake",)mock_extract.return_value = {"auth_token": "browser_tok", "ct0": "browser_ct0"}env_patch = {@@ -139,7 +138,6 @@ class TestGetConfigCookieIntegration:from lib.env import get_config, OpenAIAuthmock_openai.return_value = OpenAIAuth(token=None, source="none", status="missing",- account_id=None, codex_auth_file="/fake",)mock_extract.return_value = {"auth_token": "browser_tok", "ct0": "browser_ct0"}env_patch = {diff --git a/tests/test_providers_v3.py b/tests/test_providers_v3.pyindex af9e681c..ff84dddd 100644--- a/tests/test_providers_v3.py+++ b/tests/test_providers_v3.py@@ -1,6 +1,8 @@import jsonimport unittest+from typing import get_args+from lib import envfrom lib import providers@@ -63,6 +65,15 @@ class ProvidersV3Tests(unittest.TestCase):depth="default",)+ def test_codex_auth_is_not_supported_as_openai_provider_auth(self):+ self.assertNotIn("codex", get_args(env.AuthSource))+ self.assertFalse(hasattr(env, "AUTH_SOURCE_CODEX"))++ def test_openai_provider_has_no_chatgpt_backend_route(self):+ self.assertFalse(hasattr(providers, "CODEX_RESPONSES_URL"))+ with self.assertRaises(TypeError):+ providers.OpenAIClient("token", "codex", "acct")+class TestExtractJson(unittest.TestCase):def test_direct_json(self):@@ -124,39 +135,5 @@ class TestExtractGeminiText(unittest.TestCase):self.assertEqual("", providers.extract_gemini_text({}))-class TestParseSSEChunk(unittest.TestCase):- def test_valid_chunk(self):- chunk = 'data: {"type": "delta", "text": "hi"}'- result = providers._parse_sse_chunk(chunk)- self.assertEqual(result, {"type": "delta", "text": "hi"})-- def test_done_sentinel(self):- self.assertIsNone(providers._parse_sse_chunk("data: [DONE]"))-- def test_no_data_lines(self):- self.assertIsNone(providers._parse_sse_chunk("event: ping"))-- def test_invalid_json(self):- self.assertIsNone(providers._parse_sse_chunk("data: {bad json"))---class TestParseCodexStream(unittest.TestCase):- def test_response_completed_event(self):- stream = 'data: {"type": "response.completed", "response": {"output_text": "done"}}\n\n'- result = providers._parse_codex_stream(stream)- self.assertEqual(result["output_text"], "done")-- def test_delta_text_accumulation(self):- stream = 'data: {"delta": "hel"}\n\ndata: {"delta": "lo"}\n\n'- result = providers._parse_codex_stream(stream)- text = providers.extract_openai_text(result)- self.assertEqual(text, "hello")-- def test_empty_stream(self):- self.assertEqual({}, providers._parse_codex_stream(""))-- def test_done_only_stream(self):- self.assertEqual({}, providers._parse_codex_stream("data: [DONE]\n\n"))-if __name__ == "__main__":unittest.main()