Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(provider): recover invalidated Codex OAuth sessions (#1014)

Haozhe Wu1c4795f42742
diff --git a/agent/src/providers/openai_codex.py b/agent/src/providers/openai_codex.py
index 2839b254b..97c96a1a5 100644
--- a/agent/src/providers/openai_codex.py
+++ b/agent/src/providers/openai_codex.py
@@ -9,14 +9,30 @@ key path because ChatGPT OAuth tokens are not OpenAI API keys.
from __future__ import annotations
import asyncio
+import base64
import hashlib
import json
import os
+import threading
+import time
+from contextlib import contextmanager
from dataclasses import dataclass, field
-from typing import Any, Callable, Iterable, Optional
+from pathlib import Path
+from typing import Any, Callable, Iterable, Iterator, Optional
from urllib.parse import urlparse
from src.config.accessor import get_env_config
+from src.config.paths import get_runtime_root
+
+try: # pragma: no cover - platform-specific imports are exercised via mocks.
+ import fcntl
+except ImportError: # pragma: no cover - Windows.
+ fcntl = None # type: ignore[assignment]
+
+try: # pragma: no cover - platform-specific imports are exercised via mocks.
+ import msvcrt
+except ImportError: # pragma: no cover - POSIX.
+ msvcrt = None # type: ignore[assignment]
try:
import httpx
@@ -25,6 +41,17 @@ except ImportError:
DEFAULT_CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"
DEFAULT_ORIGINATOR = "vibe-trading"
+_CODEX_REFRESH_MARGIN_SECONDS = 300
+_CODEX_FORCE_REFRESH_TTL_SECONDS = 2_147_483_647
+_CODEX_LOGIN_COMMAND = "vibe-trading provider login openai-codex"
+_CODEX_TOKEN_FILENAME = "openai-codex.json"
+_PERMANENT_REFRESH_ERROR_CODES = {
+ "invalid_grant",
+ "refresh_token_invalidated",
+ "refresh_token_reused",
+ "token_invalidated",
+}
+_TOKEN_REFRESH_THREAD_LOCK = threading.Lock()
class CodexStreamError(RuntimeError):
@@ -45,6 +72,141 @@ class CodexStreamError(RuntimeError):
super().__init__(message)
+class CodexAuthenticationError(CodexStreamError):
+ """Raised when a rejected Codex session requires explicit login."""
+
+ def __init__(self, detail: str) -> None:
+ message = detail.rstrip(". ")
+ if _CODEX_LOGIN_COMMAND not in message:
+ message = f"{message}. Run: {_CODEX_LOGIN_COMMAND}"
+ super().__init__(401, message)
+
+
+class _CodexRefreshError(RuntimeError):
+ """Internal refresh failure with retry and invalidation metadata."""
+
+ def __init__(self, detail: str, *, status_code: int | None, permanent: bool) -> None:
+ super().__init__(detail)
+ self.status_code = status_code
+ self.permanent = permanent
+
+
+def _build_codex_token_storage(path: Path | None = None) -> Any:
+ """Build the Vibe-owned Codex token store.
+
+ The path deliberately does not use oauth-cli-kit's default storage, because
+ that backend imports and copies ``~/.codex/auth.json``. A copied rotating
+ refresh token gives two processes ownership of one OAuth session and causes
+ the ``token_invalidated`` / ``refresh_token_reused`` failure in issue #975.
+ """
+ try:
+ from oauth_cli_kit.storage import FileTokenStorage
+ except ImportError as exc:
+ raise RuntimeError("oauth-cli-kit is not installed. Run: pip install oauth-cli-kit") from exc
+
+ token_path = path or (get_runtime_root() / "auth" / _CODEX_TOKEN_FILENAME)
+
+ class VibeCodexTokenStorage(FileTokenStorage):
+ def get_token_path(self) -> Path:
+ return token_path
+
+ return VibeCodexTokenStorage(
+ token_filename=_CODEX_TOKEN_FILENAME,
+ app_name="vibe-trading",
+ import_codex_cli=False,
+ )
+
+
+def _clear_codex_token(storage: Any) -> None:
+ """Remove only Vibe's invalid credential cache."""
+ try:
+ storage.get_token_path().unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def _lock_token_file(handle: Any) -> None:
+ """Acquire a cross-process lock on an opened token lock file."""
+ if fcntl is not None:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
+ return
+ if msvcrt is not None: # pragma: no cover - exercised with a platform mock.
+ handle.seek(0, os.SEEK_END)
+ if handle.tell() == 0:
+ handle.write(b"\0")
+ handle.flush()
+ os.fsync(handle.fileno())
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
+ return
+ raise RuntimeError("No supported file-lock backend for Codex OAuth refresh")
+
+
+def _unlock_token_file(handle: Any) -> None:
+ """Release the lock acquired by :func:`_lock_token_file`."""
+ if fcntl is not None:
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+ return
+ if msvcrt is not None: # pragma: no cover - exercised with a platform mock.
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+
+
+@contextmanager
+def _codex_refresh_lock(storage: Any) -> Iterator[None]:
+ """Serialize refresh-token rotation across threads and processes."""
+ lock_path = storage.get_token_path().with_name(f"{storage.get_token_path().name}.lock")
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ with _TOKEN_REFRESH_THREAD_LOCK:
+ with lock_path.open("a+b") as handle:
+ try:
+ os.chmod(lock_path, 0o600)
+ except OSError:
+ pass
+ _lock_token_file(handle)
+ try:
+ yield
+ finally:
+ _unlock_token_file(handle)
+
+
+def _decode_jwt_claims(access_token: str) -> dict[str, Any]:
+ """Decode unverified JWT claims used only for expiry/account metadata."""
+ try:
+ payload = access_token.split(".", 2)[1]
+ payload += "=" * (-len(payload) % 4)
+ decoded = base64.urlsafe_b64decode(payload.encode("ascii"))
+ claims = json.loads(decoded.decode("utf-8"))
+ except (IndexError, UnicodeError, ValueError, json.JSONDecodeError):
+ return {}
+ return claims if isinstance(claims, dict) else {}
+
+
+def _token_expiry_ms(token: Any) -> int:
+ """Return the access token's real JWT expiry, with stored expiry fallback."""
+ access = getattr(token, "access", "")
+ claims = _decode_jwt_claims(access) if isinstance(access, str) else {}
+ jwt_expiry = claims.get("exp")
+ if isinstance(jwt_expiry, (int, float)) and not isinstance(jwt_expiry, bool):
+ return int(jwt_expiry * 1000)
+ try:
+ stored_expiry = int(getattr(token, "expires"))
+ except (TypeError, ValueError):
+ return 0
+ return stored_expiry * 1000 if stored_expiry < 100_000_000_000 else stored_expiry
+
+
+def _load_codex_oauth_provider() -> Any:
+ """Load oauth-cli-kit's provider constants without using its token cache."""
+ try:
+ from oauth_cli_kit import OPENAI_CODEX_PROVIDER
+ except ImportError as exc:
+ raise RuntimeError(
+ f"OpenAI Codex OAuth requires oauth-cli-kit. Install dependencies, then run: {_CODEX_LOGIN_COMMAND}"
+ ) from exc
+ return OPENAI_CODEX_PROVIDER
+
+
@dataclass
class CodexToolCall:
"""Internal tool-call representation compatible with ChatLLM parsing."""
@@ -71,9 +233,8 @@ class CodexAIMessage:
"finish_reason",
self.response_metadata.get("finish_reason", "stop"),
)
- reasoning = (
- self.additional_kwargs.get("reasoning_content", "")
- + other.additional_kwargs.get("reasoning_content", "")
+ reasoning = self.additional_kwargs.get("reasoning_content", "") + other.additional_kwargs.get(
+ "reasoning_content", ""
)
return CodexAIMessage(
content=(self.content or "") + (other.content or ""),
@@ -87,30 +248,25 @@ def login_openai_codex(
print_fn: Callable[[str], None] | None = None,
prompt_fn: Callable[[str], str] | None = None,
) -> Any:
- """Run interactive ChatGPT/Codex OAuth login and persist the token."""
+ """Force interactive ChatGPT/Codex OAuth login into Vibe-owned storage."""
try:
- from oauth_cli_kit import get_token, login_oauth_interactive
+ from oauth_cli_kit import login_oauth_interactive
except ImportError as exc:
raise RuntimeError("oauth-cli-kit is not installed. Run: pip install oauth-cli-kit") from exc
- token = None
- try:
- token = get_token()
- except Exception:
- pass
- if token and getattr(token, "access", None):
- return token
- return login_oauth_interactive(print_fn=print_fn or print, prompt_fn=prompt_fn or input)
+ return login_oauth_interactive(
+ print_fn=print_fn or print,
+ prompt_fn=prompt_fn or input,
+ provider=_load_codex_oauth_provider(),
+ originator=DEFAULT_ORIGINATOR,
+ storage=_build_codex_token_storage(),
+ )
def get_openai_codex_login_status() -> Any | None:
- """Return the persisted OAuth token, if available."""
+ """Return a usable Vibe-owned OAuth token, if available."""
try:
- from oauth_cli_kit import get_token
- except ImportError:
- return None
- try:
- token = get_token()
+ token = _get_codex_token()
except Exception:
return None
if token and getattr(token, "access", None):
@@ -118,21 +274,112 @@ def get_openai_codex_login_status() -> Any | None:
return None
-def _get_codex_token() -> Any:
+def _refresh_codex_token(token: Any, storage: Any) -> Any:
+ """Refresh through oauth-cli-kit without accepting its stale fallback.
+
+ Args:
+ token: Current token carrying the rotating refresh credential.
+ storage: Vibe-owned destination store.
+
+ Returns:
+ The refreshed token.
+
+ Raises:
+ _CodexRefreshError: If oauth-cli-kit cannot obtain a replacement token.
+ """
try:
from oauth_cli_kit import get_token
- except ImportError as exc:
- raise RuntimeError(
- "OpenAI Codex OAuth requires oauth-cli-kit. Install dependencies, then run: "
- "vibe-trading provider login openai-codex"
- ) from exc
- try:
- token = get_token()
+
+ # The very large TTL forces oauth-cli-kit to call the token endpoint.
+ # We compare the result with ``token`` below because oauth-cli-kit may
+ # otherwise return the old, locally-unexpired token after refresh fails.
+ refreshed = get_token(
+ provider=_load_codex_oauth_provider(),
+ storage=storage,
+ min_ttl_seconds=_CODEX_FORCE_REFRESH_TTL_SECONDS,
+ )
except Exception as exc:
- raise RuntimeError("OpenAI Codex is not logged in. Run: vibe-trading provider login openai-codex") from exc
- if not (token and getattr(token, "access", None) and getattr(token, "account_id", None)):
- raise RuntimeError("OpenAI Codex is not logged in. Run: vibe-trading provider login openai-codex")
- return token
+ detail = str(exc).lower()
+ raise _CodexRefreshError(
+ f"Codex OAuth token refresh failed: {type(exc).__name__}",
+ status_code=None,
+ permanent=any(code in detail for code in _PERMANENT_REFRESH_ERROR_CODES),
+ ) from exc
+ if not getattr(refreshed, "access", None) or not getattr(refreshed, "account_id", None):
+ raise _CodexRefreshError(
+ "Codex OAuth token refresh returned incomplete credentials",
+ status_code=502,
+ permanent=False,
+ )
+ return refreshed
+
+
+def _missing_codex_login_error() -> CodexAuthenticationError:
+ return CodexAuthenticationError("OpenAI Codex is not logged in")
+
+
+def _get_codex_token(
+ *,
+ force_refresh: bool = False,
+ rejected_access: str | None = None,
+) -> Any:
+ """Return a usable Vibe-owned token, refreshing once when required.
+
+ Args:
+ force_refresh: Refresh even when the local expiry clock is still fresh.
+ rejected_access: Access token rejected by the backend. If another
+ process already replaced it while this process waited for the lock,
+ the newer token is used without a second refresh rotation.
+
+ Returns:
+ A usable OAuth token.
+
+ Raises:
+ RuntimeError: If no Vibe-owned credentials exist.
+ CodexAuthenticationError: If the OAuth session was invalidated and an
+ explicit login is required.
+ CodexStreamError: If an expired token cannot be refreshed because of a
+ transient OAuth endpoint failure.
+ """
+ storage = _build_codex_token_storage()
+ token = storage.load()
+ if not (token and token.access and token.refresh and token.account_id):
+ raise _missing_codex_login_error()
+
+ now_ms = int(time.time() * 1000)
+ if not force_refresh and _token_expiry_ms(token) - now_ms > _CODEX_REFRESH_MARGIN_SECONDS * 1000:
+ return token
+
+ with _codex_refresh_lock(storage):
+ latest = storage.load()
+ if not (latest and latest.access and latest.refresh and latest.account_id):
+ raise _missing_codex_login_error()
+ token = latest
+ now_ms = int(time.time() * 1000)
+
+ if rejected_access and token.access != rejected_access and _token_expiry_ms(token) > now_ms:
+ return token
+ if not force_refresh and _token_expiry_ms(token) - now_ms > _CODEX_REFRESH_MARGIN_SECONDS * 1000:
+ return token
+
+ try:
+ refreshed = _refresh_codex_token(token, storage)
+ except _CodexRefreshError as exc:
+ if exc.permanent:
+ _clear_codex_token(storage)
+ raise CodexAuthenticationError("The Vibe-Trading Codex OAuth session was invalidated") from exc
+ if not force_refresh and _token_expiry_ms(token) > now_ms:
+ return token
+ raise CodexStreamError(
+ exc.status_code or 503,
+ f"Codex OAuth recovery temporarily failed: {exc}",
+ ) from exc
+ if refreshed.access == token.access:
+ if not force_refresh and _token_expiry_ms(token) > now_ms:
+ return token
+ _clear_codex_token(storage)
+ raise CodexAuthenticationError("The Codex backend rejected the access token and refresh did not replace it")
+ return refreshed
def validate_codex_base_url(url: str) -> str:
@@ -144,14 +391,8 @@ def validate_codex_base_url(url: str) -> str:
"""
value = (url or DEFAULT_CODEX_URL).strip().rstrip("/")
parsed = urlparse(value)
- if (
- parsed.scheme != "https"
- or parsed.netloc != "chatgpt.com"
- or parsed.path != "/backend-api/codex/responses"
- ):
- raise ValueError(
- "OpenAI Codex OAuth only supports https://chatgpt.com/backend-api/codex/responses"
- )
+ if parsed.scheme != "https" or parsed.netloc != "chatgpt.com" or parsed.path != "/backend-api/codex/responses":
+ raise ValueError("OpenAI Codex OAuth only supports https://chatgpt.com/backend-api/codex/responses")
return value
@@ -218,23 +459,27 @@ def _convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[st
input_items.append(_convert_user_message(content))
elif role == "assistant":
if isinstance(content, str) and content:
- input_items.append({
- "type": "message",
- "role": "assistant",
- "content": [{"type": "output_text", "text": content}],
- "status": "completed",
- "id": f"msg_{idx}",
- })
+ input_items.append(
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [{"type": "output_text", "text": content}],
+ "status": "completed",
+ "id": f"msg_{idx}",
+ }
+ )
for tool_call in msg.get("tool_calls", []) or []:
fn = tool_call.get("function") or {}
call_id, item_id = _split_tool_call_id(tool_call.get("id"))
- input_items.append({
- "type": "function_call",
- "id": item_id or f"fc_{idx}",
- "call_id": call_id or f"call_{idx}",
- "name": fn.get("name"),
- "arguments": fn.get("arguments") or "{}",
- })
+ input_items.append(
+ {
+ "type": "function_call",
+ "id": item_id or f"fc_{idx}",
+ "call_id": call_id or f"call_{idx}",
+ "name": fn.get("name"),
+ "arguments": fn.get("arguments") or "{}",
+ }
+ )
elif role == "tool":
call_id, _ = _split_tool_call_id(msg.get("tool_call_id"))
output = content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
@@ -250,12 +495,14 @@ def _convert_tools(tools: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
if not name:
continue
params = fn.get("parameters") or {}
- converted.append({
- "type": "function",
- "name": name,
- "description": fn.get("description") or "",
- "parameters": params if isinstance(params, dict) else {},
- })
+ converted.append(
+ {
+ "type": "function",
+ "name": name,
+ "description": fn.get("description") or "",
+ "parameters": params if isinstance(params, dict) else {},
+ }
+ )
return converted
@@ -375,9 +622,7 @@ class OpenAICodexLLM:
self.timeout = timeout
self.tools = tools or []
self.reasoning_effort = reasoning_effort
- self.codex_url = validate_codex_base_url(
- codex_url or get_env_config().llm.openai_codex_base_url
- )
+ self.codex_url = validate_codex_base_url(codex_url or get_env_config().llm.openai_codex_base_url)
def bind_tools(self, tools: list[dict[str, Any]]) -> "OpenAICodexLLM":
return OpenAICodexLLM(
@@ -410,21 +655,50 @@ class OpenAICodexLLM:
body["reasoning"] = {"effort": self.reasoning_effort.lower()}
return body
- def _headers(self) -> dict[str, str]:
- token = _get_codex_token()
+ def _headers(
+ self,
+ *,
+ force_refresh: bool = False,
+ rejected_access: str | None = None,
+ ) -> dict[str, str]:
+ token = _get_codex_token(
+ force_refresh=force_refresh,
+ rejected_access=rejected_access,
+ )
return _build_headers(str(token.account_id), str(token.access))
- def stream(self, messages: list[dict[str, Any]], config: Optional[dict[str, Any]] = None) -> Iterable[CodexAIMessage]:
+ def stream(
+ self, messages: list[dict[str, Any]], config: Optional[dict[str, Any]] = None
+ ) -> Iterable[CodexAIMessage]:
timeout = (config or {}).get("timeout") or self.timeout
+ body = self._body(messages, stream=True)
+ headers = self._headers()
with httpx.Client(timeout=timeout, follow_redirects=True, trust_env=True) as client:
- with client.stream("POST", self.codex_url, headers=self._headers(), json=self._body(messages, stream=True)) as response:
- if response.status_code != 200:
+ for attempt in range(2):
+ with client.stream(
+ "POST",
+ self.codex_url,
+ headers=headers,
+ json=body,
+ ) as response:
+ if response.status_code == 200:
+ yield from _message_chunks_from_events(_events_from_lines(response.iter_lines()))
+ return
raw = response.read().decode("utf-8", "ignore")
- # Raise the typed CodexStreamError (carries ``status_code``)
- # so ``ProviderStreamError.retryable`` can correctly classify
- # deterministic 4xx as non-retryable.
- raise CodexStreamError(response.status_code, raw)
- yield from _message_chunks_from_events(_events_from_lines(response.iter_lines()))
+ status_code = response.status_code
+
+ if status_code == 401 and attempt == 0:
+ authorization = headers.get("Authorization", "")
+ rejected_access = authorization[7:] if authorization.startswith("Bearer ") else None
+ headers = self._headers(
+ force_refresh=True,
+ rejected_access=rejected_access,
+ )
+ continue
+
+ # Preserve the typed status so deterministic 4xx failures are
+ # not retried again by the provider-level retry wrapper.
+ raise CodexStreamError(status_code, raw)
def invoke(self, messages: list[dict[str, Any]], config: Optional[dict[str, Any]] = None) -> CodexAIMessage:
accumulated: CodexAIMessage | None = None
diff --git a/agent/tests/test_openai_codex.py b/agent/tests/test_openai_codex.py
index 94a44eb10..9c6fbbe69 100644
--- a/agent/tests/test_openai_codex.py
+++ b/agent/tests/test_openai_codex.py
@@ -3,7 +3,9 @@
from __future__ import annotations
import json
+import time
from pathlib import Path
+from types import SimpleNamespace
import pytest
@@ -11,11 +13,18 @@ from src.providers import llm as llm_mod
from src.providers.chat import ProviderStreamError
from src.providers.openai_codex import (
DEFAULT_CODEX_URL,
+ CodexAuthenticationError,
CodexStreamError,
OpenAICodexLLM,
+ _CodexRefreshError,
+ _build_codex_token_storage,
+ _codex_refresh_lock,
_events_from_lines,
+ _get_codex_token,
_message_chunks_from_events,
_strip_model_prefix,
+ _token_expiry_ms,
+ login_openai_codex,
validate_codex_base_url,
)
@@ -23,6 +32,17 @@ from src.providers.openai_codex import (
DEFAULT_CODEX_MODEL = "openai-codex/gpt-5.4"
+def _jwt(payload: dict[str, object]) -> str:
+ """Build an unsigned JWT-shaped value for claim parsing tests."""
+ import base64
+
+ def _part(value: dict[str, object]) -> str:
+ raw = json.dumps(value, separators=(",", ":")).encode("utf-8")
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+ return f"{_part({'alg': 'none'})}.{_part(payload)}.signature"
+
+
def test_provider_default_model_matches_live_codex_account_path() -> None:
providers_path = Path(__file__).resolve().parents[1] / "src" / "providers" / "llm_providers.json"
providers = json.loads(providers_path.read_text(encoding="utf-8"))
@@ -53,16 +73,18 @@ def test_build_llm_returns_codex_adapter(monkeypatch: pytest.MonkeyPatch) -> Non
def test_codex_body_strips_provider_prefix_and_converts_tools() -> None:
adapter = OpenAICodexLLM(model=DEFAULT_CODEX_MODEL)
- body = adapter.bind_tools([
- {
- "type": "function",
- "function": {
- "name": "bash",
- "description": "Run a shell command",
- "parameters": {"type": "object", "properties": {"command": {"type": "string"}}},
- },
- }
- ])._body(
+ body = adapter.bind_tools(
+ [
+ {
+ "type": "function",
+ "function": {
+ "name": "bash",
+ "description": "Run a shell command",
+ "parameters": {"type": "object", "properties": {"command": {"type": "string"}}},
+ },
+ }
+ ]
+ )._body(
[
{"role": "system", "content": "You are careful."},
{"role": "user", "content": "Say hi."},
@@ -77,37 +99,250 @@ def test_codex_body_strips_provider_prefix_and_converts_tools() -> None:
assert body["input"][0]["content"][0]["text"] == "Say hi."
-def test_missing_codex_token_raises_login_hint(monkeypatch: pytest.MonkeyPatch) -> None:
- oauth_cli_kit = pytest.importorskip(
- "oauth_cli_kit",
- reason="oauth-cli-kit is declared in requirements.txt but optional at runtime",
+def test_codex_storage_is_vibe_owned_and_never_imports_codex_cli(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ runtime_root = tmp_path / "vibe-home"
+ user_home = tmp_path / "user-home"
+ official_store = user_home / ".codex" / "auth.json"
+ official_store.parent.mkdir(parents=True)
+ official_store.write_text(
+ json.dumps(
+ {
+ "tokens": {
+ "access_token": "official-access-must-not-be-imported",
+ "refresh_token": "official-refresh-must-not-be-imported",
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(runtime_root))
+ monkeypatch.setenv("HOME", str(user_home))
+ monkeypatch.setenv("USERPROFILE", str(user_home))
+ monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(official_store))
+
+ storage = _build_codex_token_storage()
+
+ assert storage.get_token_path() == runtime_root / "auth" / "openai-codex.json"
+ assert storage.load() is None
+
+
+def test_explicit_login_always_runs_interactive_with_vibe_storage(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ oauth_cli_kit = pytest.importorskip("oauth_cli_kit")
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ calls: list[dict[str, object]] = []
+ interactive_token = SimpleNamespace(
+ access="new-access",
+ refresh="new-refresh",
+ expires=int(time.time() * 1000) + 3_600_000,
+ account_id="account-1",
)
- def _missing_token() -> None:
- raise RuntimeError("missing")
+ def _interactive(**kwargs: object) -> object:
+ calls.append(kwargs)
+ return interactive_token
+
+ def _unexpected_cache_probe(*args: object, **kwargs: object) -> object:
+ raise AssertionError("explicit login must not accept a cached token")
+
+ monkeypatch.setattr(oauth_cli_kit, "login_oauth_interactive", _interactive)
+ monkeypatch.setattr(oauth_cli_kit, "get_token", _unexpected_cache_probe)
- monkeypatch.setattr(oauth_cli_kit, "get_token", _missing_token)
+ result = login_openai_codex(print_fn=lambda _: None, prompt_fn=lambda _: "code")
+
+ assert result is interactive_token
+ assert len(calls) == 1
+ storage = calls[0]["storage"]
+ assert storage.get_token_path() == tmp_path / "auth" / "openai-codex.json"
+
+
+def test_missing_codex_token_raises_login_hint(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
adapter = OpenAICodexLLM(model=DEFAULT_CODEX_MODEL)
- with pytest.raises(RuntimeError, match="vibe-trading provider login openai-codex"):
+ with pytest.raises(CodexAuthenticationError, match="vibe-trading provider login openai-codex"):
adapter._headers()
+def test_real_jwt_expiry_overrides_stale_stored_expiry() -> None:
+ jwt_expiry_seconds = int(time.time()) + 90
+ token = SimpleNamespace(
+ access=_jwt({"exp": jwt_expiry_seconds}),
+ expires=int(time.time() * 1000) + 86_400_000,
+ )
+
+ assert _token_expiry_ms(token) == jwt_expiry_seconds * 1000
+
+
+def test_stale_refresh_fallback_invalidates_only_vibe_cache(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ import src.providers.openai_codex as codex_mod
+ import oauth_cli_kit
+
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ storage = _build_codex_token_storage()
+ storage.save(
+ SimpleNamespace(
+ access="server-invalid-access",
+ refresh="server-invalid-refresh",
+ expires=int(time.time() * 1000) + 3_600_000,
+ account_id="account-1",
+ )
+ )
+
+ refresh_calls: list[dict[str, object]] = []
+
+ def _stale_fallback(**kwargs: object) -> object:
+ refresh_calls.append(kwargs)
+ return storage.load()
+
+ monkeypatch.setattr(codex_mod, "_build_codex_token_storage", lambda: storage)
+ monkeypatch.setattr(oauth_cli_kit, "get_token", _stale_fallback)
+
+ with pytest.raises(CodexAuthenticationError, match="provider login openai-codex"):
+ _get_codex_token(force_refresh=True, rejected_access="server-invalid-access")
+
+ assert storage.load() is None
+ assert refresh_calls[0]["storage"] is storage
+ assert refresh_calls[0]["min_ttl_seconds"] > 1_000_000_000
+
+
+def test_force_refresh_ignores_clock_fresh_expiry(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ import src.providers.openai_codex as codex_mod
+
+ storage = _build_codex_token_storage(tmp_path / "openai-codex.json")
+ storage.save(
+ SimpleNamespace(
+ access="server-invalid-access",
+ refresh="old-refresh",
+ expires=int(time.time() * 1000) + 3_600_000,
+ account_id="account-1",
+ )
+ )
+ refreshed = SimpleNamespace(
+ access="recovered-access",
+ refresh="rotated-refresh",
+ expires=int(time.time() * 1000) + 3_600_000,
+ account_id="account-1",
+ )
+ refresh_calls: list[str] = []
+
+ def _refresh(token: object, destination: object) -> object:
+ refresh_calls.append(token.access)
+ destination.save(refreshed)
+ return refreshed
+
+ monkeypatch.setattr(codex_mod, "_build_codex_token_storage", lambda: storage)
+ monkeypatch.setattr(codex_mod, "_refresh_codex_token", _refresh)
+
+ result = _get_codex_token(
+ force_refresh=True,
+ rejected_access="server-invalid-access",
+ )
+
+ assert result is refreshed
+ assert refresh_calls == ["server-invalid-access"]
+ assert storage.load().access == "recovered-access"
+
+
+def test_force_refresh_reuses_token_rotated_by_another_process(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ import src.providers.openai_codex as codex_mod
+
+ storage = _build_codex_token_storage(tmp_path / "openai-codex.json")
+ storage.save(
+ SimpleNamespace(
+ access="already-rotated-access",
+ refresh="already-rotated-refresh",
+ expires=int(time.time() * 1000) + 3_600_000,
+ account_id="account-1",
+ )
+ )
+ monkeypatch.setattr(codex_mod, "_build_codex_token_storage", lambda: storage)
+ monkeypatch.setattr(
+ codex_mod,
+ "_refresh_codex_token",
+ lambda *args, **kwargs: pytest.fail("must not rotate a second time"),
+ )
+
+ result = _get_codex_token(
+ force_refresh=True,
+ rejected_access="older-rejected-access",
+ )
+
+ assert result.access == "already-rotated-access"
+
+
+def test_transient_forced_refresh_failure_preserves_cache_and_is_retryable(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ import src.providers.openai_codex as codex_mod
+
+ storage = _build_codex_token_storage(tmp_path / "openai-codex.json")
+ storage.save(
+ SimpleNamespace(
+ access="server-invalid-access",
+ refresh="recoverable-refresh",
+ expires=int(time.time() * 1000) + 3_600_000,
+ account_id="account-1",
+ )
+ )
+
+ def _unavailable(*args: object, **kwargs: object) -> object:
+ raise _CodexRefreshError(
+ "temporarily unavailable",
+ status_code=503,
+ permanent=False,
+ )
+
+ monkeypatch.setattr(codex_mod, "_build_codex_token_storage", lambda: storage)
+ monkeypatch.setattr(codex_mod, "_refresh_codex_token", _unavailable)
+
+ with pytest.raises(CodexStreamError) as excinfo:
+ _get_codex_token(
+ force_refresh=True,
+ rejected_access="server-invalid-access",
+ )
+
+ assert excinfo.value.status_code == 503
+ assert storage.load().refresh == "recoverable-refresh"
+
+
def test_sse_events_parse_text_and_function_calls() -> None:
- events = list(_events_from_lines([
- 'data: {"type":"response.output_text.delta","delta":"Hi"}',
- "",
- 'data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_1","id":"fc_1","name":"bash","arguments":""}}',
- "",
- 'data: {"type":"response.function_call_arguments.delta","call_id":"call_1","delta":"{\\"command\\":\\"pw"}',
- "",
- 'data: {"type":"response.function_call_arguments.delta","call_id":"call_1","delta":"d\\"}"}',
- "",
- 'data: {"type":"response.output_item.done","item":{"type":"function_call","call_id":"call_1"}}',
- "",
- "data: [DONE]",
- "",
- ]))
+ events = list(
+ _events_from_lines(
+ [
+ 'data: {"type":"response.output_text.delta","delta":"Hi"}',
+ "",
+ 'data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_1","id":"fc_1","name":"bash","arguments":""}}',
+ "",
+ 'data: {"type":"response.function_call_arguments.delta","call_id":"call_1","delta":"{\\"command\\":\\"pw"}',
+ "",
+ 'data: {"type":"response.function_call_arguments.delta","call_id":"call_1","delta":"d\\"}"}',
+ "",
+ 'data: {"type":"response.output_item.done","item":{"type":"function_call","call_id":"call_1"}}',
+ "",
+ "data: [DONE]",
+ "",
+ ]
+ )
+ )
chunks = list(_message_chunks_from_events(events))
@@ -115,9 +350,9 @@ def test_sse_events_parse_text_and_function_calls() -> None:
assert chunks[1].tool_calls == [{"id": "call_1|fc_1", "name": "bash", "args": {"command": "pwd"}}]
-def test_stream_non_200_response_raises_http_error(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_stream_non_401_response_is_not_retried(monkeypatch: pytest.MonkeyPatch) -> None:
class _FakeResponse:
- status_code = 401
+ status_code = 403
def __enter__(self) -> "_FakeResponse":
return self
@@ -126,7 +361,7 @@ def test_stream_non_200_response_raises_http_error(monkeypatch: pytest.MonkeyPat
return None
def read(self) -> bytes:
- return b"unauthorized"
+ return b"forbidden"
class _FakeClient:
def __init__(self, **kwargs: object) -> None:
@@ -145,9 +380,9 @@ def test_stream_non_200_response_raises_http_error(monkeypatch: pytest.MonkeyPat
monkeypatch.setattr(codex_mod.httpx, "Client", _FakeClient)
adapter = OpenAICodexLLM(model=DEFAULT_CODEX_MODEL)
- adapter._headers = lambda: {}
+ adapter._headers = lambda **kwargs: {}
- with pytest.raises(RuntimeError, match="OpenAI Codex HTTP 401"):
+ with pytest.raises(RuntimeError, match="OpenAI Codex HTTP 403"):
list(adapter.stream([{"role": "user", "content": "hello"}]))
@@ -162,6 +397,8 @@ def test_stream_non_200_response_raises_typed_codex_stream_error(
``CodexStreamError(RuntimeError)`` subclass that exposes the upstream
status so retry classification works correctly.
"""
+ request_count = 0
+
class _FakeResponse:
status_code = 401
@@ -185,13 +422,15 @@ def test_stream_non_200_response_raises_typed_codex_stream_error(
return None
def stream(self, *args: object, **kwargs: object) -> _FakeResponse:
+ nonlocal request_count
+ request_count += 1
return _FakeResponse()
import src.providers.openai_codex as codex_mod
monkeypatch.setattr(codex_mod.httpx, "Client", _FakeClient)
adapter = OpenAICodexLLM(model=DEFAULT_CODEX_MODEL)
- adapter._headers = lambda: {}
+ adapter._headers = lambda **kwargs: {"Authorization": "Bearer still-invalid"}
with pytest.raises(CodexStreamError) as excinfo:
list(adapter.stream([{"role": "user", "content": "hello"}]))
@@ -199,6 +438,7 @@ def test_stream_non_200_response_raises_typed_codex_stream_error(
# CodexStreamError carries the status_code so ProviderStreamError
# classifies 401 as non-retryable downstream.
assert excinfo.value.status_code == 401
+ assert request_count == 2
err = ProviderStreamError(
provider="openai-codex",
@@ -209,6 +449,99 @@ def test_stream_non_200_response_raises_typed_codex_stream_error(
assert err.retryable is False
+def test_stream_refreshes_once_after_clock_fresh_token_gets_401(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import src.providers.openai_codex as codex_mod
+
+ responses = [401, 200]
+ sent_authorizations: list[str] = []
+ header_calls: list[tuple[bool, str | None]] = []
+
+ class _FakeResponse:
+ def __init__(self, status_code: int) -> None:
+ self.status_code = status_code
+
+ def __enter__(self) -> "_FakeResponse":
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ return None
+
+ def read(self) -> bytes:
+ return b'{"error":{"code":"token_invalidated"}}'
+
+ def iter_lines(self) -> list[str]:
+ return [
+ 'data: {"type":"response.output_text.delta","delta":"recovered"}',
+ "",
+ "data: [DONE]",
+ "",
+ ]
+
+ class _FakeClient:
+ def __init__(self, **kwargs: object) -> None:
+ pass
+
+ def __enter__(self) -> "_FakeClient":
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ return None
+
+ def stream(self, *args: object, **kwargs: object) -> _FakeResponse:
+ sent_authorizations.append(kwargs["headers"]["Authorization"])
+ return _FakeResponse(responses.pop(0))
+
+ def _headers(*, force_refresh: bool = False, rejected_access: str | None = None) -> dict[str, str]:
+ header_calls.append((force_refresh, rejected_access))
+ access = "fresh-access" if force_refresh else "server-invalid-access"
+ return {"Authorization": f"Bearer {access}"}
+
+ monkeypatch.setattr(codex_mod.httpx, "Client", _FakeClient)
+ adapter = OpenAICodexLLM(model=DEFAULT_CODEX_MODEL)
+ adapter._headers = _headers
+
+ chunks = list(adapter.stream([{"role": "user", "content": "hello"}]))
+
+ assert [chunk.content for chunk in chunks] == ["recovered"]
+ assert sent_authorizations == ["Bearer server-invalid-access", "Bearer fresh-access"]
+ assert header_calls == [
+ (False, None),
+ (True, "server-invalid-access"),
+ ]
+
+
+def test_refresh_lock_uses_windows_byte_range_backend(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ import src.providers.openai_codex as codex_mod
+
+ calls: list[tuple[int, int]] = []
+
+ class _FakeMsvcrt:
+ LK_LOCK = 1
+ LK_UNLCK = 2
+
+ @staticmethod
+ def locking(fd: int, mode: int, count: int) -> None:
+ assert count == 1
+ calls.append((mode, count))
+
+ storage = _build_codex_token_storage(tmp_path / "openai-codex.json")
+ monkeypatch.setattr(codex_mod, "fcntl", None)
+ monkeypatch.setattr(codex_mod, "msvcrt", _FakeMsvcrt)
+
+ with _codex_refresh_lock(storage):
+ assert calls == [(_FakeMsvcrt.LK_LOCK, 1)]
+
+ assert calls == [
+ (_FakeMsvcrt.LK_LOCK, 1),
+ (_FakeMsvcrt.LK_UNLCK, 1),
+ ]
+
+
def test_codex_400_is_non_retryable_via_codex_stream_error() -> None:
"""Deterministic codex 400 is non-retryable through CodexStreamError."""
err = ProviderStreamError(