Files
nanobot/nanobot/providers/openai_codex_provider.py
T
chengyongru a4d2430140 refactor: remove redundant comments and docstrings (#6527)
* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
2026-10-30 13:07:03 +08:00

935 lines
37 KiB
Python

# pyright: reportMissingTypeStubs=false, reportPrivateUsage=false
from __future__ import annotations
import asyncio
import hashlib
import importlib.util
import json
import os
import re
import ssl
from collections.abc import Awaitable, Callable
from typing import Any, cast
from uuid import uuid4
import httpx
from loguru import logger
from oauth_cli_kit import get_token as get_codex_token
from oauth_cli_kit.providers import OPENAI_CODEX_PROVIDER
from oauth_cli_kit.storage import FileTokenStorage
from nanobot import __version__
from nanobot.events import NO_EVENTS, ContextCompactionEvent
from nanobot.providers.base import (
CONTEXT_SAFETY_BUFFER,
LLMProvider,
LLMResponse,
LLMUsage,
ProviderCallContext,
ProviderConversationState,
)
from nanobot.providers.images import prepare_inline_images
from nanobot.providers.oauth_catalog_cache import (
OAuthCatalogAuthRequiredError,
OAuthModelCatalog,
OAuthModelCatalogSnapshot,
oauth_catalog_auth_rejected,
)
from nanobot.providers.openai_responses import (
ResponsesBackend,
ResponsesWebSocketOptions,
responses_state_matches,
)
from nanobot.providers.openai_responses.state import (
responses_compaction_items,
without_response_item_ids,
)
from nanobot.providers.openai_responses.websocket import ResponsesWebSocketError
from nanobot.providers.registry import ProviderModelSpec, find_by_name
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import estimate_prompt_tokens
DEFAULT_CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"
DEFAULT_OPENAI_CODEX_MODELS_URL = "https://chatgpt.com/backend-api/codex/models"
# Avoid restricting model discovery to a pinned Codex client release.
OPENAI_CODEX_CATALOG_CLIENT_VERSION = "99.99.99"
DEFAULT_ORIGINATOR = "nanobot"
_LANGFUSE_TRACE_WARNING = "Langfuse tracing failed for Codex request: {}"
def _usage_details(usage: LLMUsage | None) -> dict[str, int] | None:
"""Split inclusive input usage into Langfuse's exclusive token buckets."""
if usage is None:
return None
cached_tokens = (usage.cache_read_tokens or 0) + (usage.cache_write_tokens or 0)
details = {
"input": usage.input_tokens - cached_tokens,
"output": usage.output_tokens,
"total": usage.total_tokens,
}
if usage.cache_read_tokens is not None:
details["input_cached_tokens"] = usage.cache_read_tokens
if usage.cache_write_tokens is not None:
details["input_cache_creation"] = usage.cache_write_tokens
return details
class _CodexGenerationTracer:
"""Best-effort Langfuse updates; the request owns generation closure."""
def __init__(self, generation: Any | None) -> None:
self._generation = generation
def record_success(self, result: LLMResponse) -> None:
output: Any = result.content
if result.tool_calls:
output = {
"content": result.content,
"tool_calls": [
{"name": call.name, "arguments": call.arguments} for call in result.tool_calls
],
}
self._update(output=output, usage_details=_usage_details(result.usage))
def record_error(self, response: LLMResponse) -> None:
self._update(
output=response.content,
level="ERROR",
status_message=response.content,
)
def _update(self, **kwargs: Any) -> None:
generation = self._generation
filtered = {k: v for k, v in kwargs.items() if v is not None}
if generation is None or not filtered:
return
try:
generation.update(**filtered)
except Exception as exc:
logger.warning(_LANGFUSE_TRACE_WARNING, exc)
def close(self) -> None:
generation = self._generation
if generation is None:
return
try:
generation.end()
except Exception as exc:
logger.warning(_LANGFUSE_TRACE_WARNING, exc)
def _start_codex_langfuse_generation(
*,
name: str,
model: str,
body: dict[str, Any],
) -> _CodexGenerationTracer:
"""Start a Langfuse generation for a Codex request, or a no-op tracer.
Detection and the SDK call share one try/except so a broken
``find_spec`` can't fail the Codex request itself.
"""
try:
if os.environ.get("LANGFUSE_SECRET_KEY") and importlib.util.find_spec("langfuse"):
from langfuse import get_client
langfuse = get_client()
generation = langfuse.start_observation(
name=name,
as_type="generation",
model=model,
input={
"instructions": body.get("instructions"),
"input": body.get("input"),
"tools": body.get("tools"),
},
model_parameters={
key: body[key]
for key in ("reasoning", "tool_choice", "text", "parallel_tool_calls")
if key in body
},
)
return _CodexGenerationTracer(generation)
if os.environ.get("LANGFUSE_SECRET_KEY"):
logger.warning(
"LANGFUSE_SECRET_KEY is set but langfuse is not installed; "
"run `nanobot plugins enable langfuse` to enable tracing"
)
return _CodexGenerationTracer(None)
except Exception as exc:
logger.warning(_LANGFUSE_TRACE_WARNING, exc)
return _CodexGenerationTracer(None)
class OpenAICodexProvider(LLMProvider):
"""Use Codex OAuth to call the Responses API."""
def __init__(
self,
default_model: str = "openai-codex/gpt-5.6-sol",
proxy: str | None = None,
extra_body: dict[str, Any] | None = None,
*,
provider_name: str = "openai_codex",
):
super().__init__(api_key=None, api_base=None, provider_name=provider_name)
self.default_model = default_model
self.proxy = proxy or None
self._extra_body = dict(extra_body or {})
self._responses = ResponsesBackend(websocket_options=ResponsesWebSocketOptions(
beta_header="responses_websockets=2026-02-06",
))
self._ssl_contexts: dict[bool, ssl.SSLContext] = {}
async def aclose(self) -> None:
await self._responses.aclose()
def _ssl_context(self, *, verify: bool) -> ssl.SSLContext:
context = self._ssl_contexts.get(verify)
if context is None:
context = httpx.create_ssl_context(
verify=verify,
trust_env=self.proxy is None,
)
self._ssl_contexts[verify] = context
return context
async def _call_codex(
self,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None,
model: str | None,
max_tokens: int,
reasoning_effort: str | None,
tool_choice: str | dict[str, Any] | None,
on_content_delta: Callable[[str], Awaitable[None]] | None = None,
on_thinking_delta: Callable[[str], Awaitable[None]] | None = None,
on_tool_call_delta: Callable[[dict[str, Any]], Awaitable[None]] | None = None,
provider_context: ProviderCallContext | None = None,
) -> LLMResponse:
model = model or self.default_model
sanitized_messages = self._sanitize_empty_content(messages)
sanitized_state = (
provider_context.conversation_state if provider_context is not None else None
)
if sanitized_state is not None:
sanitized_state = sanitized_state.with_pending_messages(
self._sanitize_empty_content(sanitized_state.pending_messages)
)
prepared = self._responses.prepare(
sanitized_messages, state=sanitized_state,
provider=self._responses_state_provider(), model=_strip_model_prefix(model),
tools=tools, tool_choice=tool_choice,
)
body = prepared.body
replayed = prepared.replayed
session_id = provider_context.session_id if provider_context is not None else None
session_routing_key = _prompt_cache_key(session_id) if session_id else None
body.update({
"stream": True,
"instructions": body["instructions"] or "",
"text": {"verbosity": "medium"},
"tool_choice": tool_choice or "auto",
"parallel_tool_calls": True,
})
if session_routing_key:
body["prompt_cache_key"] = session_routing_key
body["include"] = ["reasoning.encrypted_content"]
reasoning_options = _build_reasoning_options(reasoning_effort)
if replayed and "gpt-5.6" in _strip_model_prefix(model).lower():
reasoning_options = dict(reasoning_options or {})
reasoning_options["context"] = "all_turns"
if reasoning_options:
body["reasoning"] = reasoning_options
if self._extra_body:
# Apply explicit provider overrides last, matching other provider backends.
body.update(self._extra_body)
effective_cache_key = body.get("prompt_cache_key")
request_model = _diagnostic_token(body.get("model"))
effective_reasoning = body.get("reasoning")
request_effort = _diagnostic_token(
cast(dict[object, object], effective_reasoning).get("effort")
if isinstance(effective_reasoning, dict) else None
)
stage = "oauth_token"
native_compaction_state: ProviderConversationState | None = None
native_compaction_event_id: str | None = None
events = provider_context.events if provider_context is not None else NO_EVENTS
def finish_compaction(result: LLMResponse) -> LLMResponse:
if native_compaction_state is not None and not result.provider_compaction_applied:
result.provider_compaction_applied = True
result.provider_compaction_state = native_compaction_state
result.provider_compaction_scope = "prior_context"
result.provider_compaction_event_id = native_compaction_event_id
return result
input_budget = (
provider_context.compaction_input_budget if provider_context is not None else None
)
if input_budget is not None:
if not replayed or not self.supports_pre_request_compaction(model):
return LLMResponse(
content="Required Codex pre-request compaction is unavailable; request not sent.",
finish_reason="error", error_kind="context_window_exceeded",
error_should_retry=False,
preserve_provider_state_on_error=True,
)
if provider_context is not None and provider_context.context_window_tokens is not None:
input_budget = min(
input_budget,
provider_context.context_window_tokens - max_tokens - CONTEXT_SAFETY_BUFFER,
)
try:
token = await asyncio.to_thread(get_codex_token, proxy=self.proxy)
headers = _build_headers(
cast(str, token.account_id),
token.access,
session_routing_key=(
effective_cache_key if isinstance(effective_cache_key, str) else None
),
)
async def _send(
request_body: dict[str, Any],
*,
emit_deltas: bool,
trace_name: str,
validate: Callable[[LLMResponse], object] | None = None,
) -> LLMResponse:
wire_body = await prepare_inline_images(without_response_item_ids(request_body))
tracer = _start_codex_langfuse_generation(
name=trace_name,
model=_strip_model_prefix(str(wire_body.get("model") or model)),
body=wire_body,
)
try:
result = None
if session_id:
result = await self._responses.websocket_request(
session_id, DEFAULT_CODEX_URL, headers, wire_body,
provider=self._responses_state_provider(),
verify=self._ssl_context(verify=True), proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
if result is None:
try:
result = await _request_codex(
DEFAULT_CODEX_URL,
headers,
wire_body,
verify=self._ssl_context(verify=True),
proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
except Exception as exc:
if "CERTIFICATE_VERIFY_FAILED" not in str(exc):
raise
logger.warning(
"SSL verification failed for Codex API; retrying with verify=False"
)
result = await _request_codex(
DEFAULT_CODEX_URL,
headers,
wire_body,
verify=self._ssl_context(verify=False),
proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
if validate is not None:
validate(result)
except Exception as exc:
tracer.record_error(_codex_error_response(exc))
raise
else:
tracer.record_success(result)
return result
finally:
tracer.close()
if self.supports_native_compaction(model) and replayed and sanitized_state is not None:
stage = "codex_compaction"
async def send_compaction(request: dict[str, Any]) -> LLMResponse:
nonlocal native_compaction_event_id
compaction_id = uuid4().hex
try:
await events.emit(ContextCompactionEvent(compaction_id, "started", reason="provider_native"))
compacted = await _send(
request,
emit_deltas=False,
trace_name="codex_compaction",
validate=responses_compaction_items,
)
except (Exception, asyncio.CancelledError) as exc:
await shield_and_drain(events.emit(ContextCompactionEvent(
compaction_id,
"cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",
reason="provider_native",
)))
raise
native_compaction_event_id = compaction_id
await shield_and_drain(events.emit(ContextCompactionEvent(compaction_id, "succeeded", reason="provider_native")))
return compacted
native_compaction_state = await self._responses.compact_before_request(
body, state=sanitized_state,
provider=self._responses_state_provider(), model=_strip_model_prefix(model),
context_window_tokens=(
provider_context.context_window_tokens if provider_context else None
),
max_output_tokens=max_tokens, input_budget=input_budget,
send=send_compaction,
)
if input_budget is not None:
estimated = estimate_prompt_tokens([{
"role": "user", "content": json.dumps(body, ensure_ascii=False),
}])
if input_budget <= 0 or estimated > input_budget:
return finish_compaction(LLMResponse(
content=(
"Codex input still exceeds the local budget after native compaction "
f"({estimated}/{input_budget} estimated tokens); request not sent."
),
finish_reason="error", error_kind="context_window_exceeded",
error_should_retry=False,
preserve_provider_state_on_error=True,
))
stage = "codex_request"
result = await _send(body, emit_deltas=True, trace_name="codex_request")
return finish_compaction(result)
except Exception as e:
response = _codex_error_response(e)
if input_budget is not None and stage != "codex_request":
response.preserve_provider_state_on_error = True
exc_type = "CodexHTTPError" if isinstance(e, _CodexHTTPError) else type(e).__name__
logger.warning(
"Codex API request failed: stage={} type={} kind={} retryable={} status={} "
"error_type={} error_code={} retry_after={} summary={} "
"model={} reasoning_effort={} replayed={} compaction_applied={} "
"error_param={} error_message={} request_id={}",
stage,
exc_type,
response.error_kind,
response.error_should_retry,
response.error_status_code,
response.error_type,
response.error_code,
response.retry_after,
_codex_log_summary(exc_type, response),
request_model,
request_effort,
replayed,
native_compaction_state is not None,
getattr(e, "error_param", None),
getattr(e, "error_message", None),
getattr(e, "request_id", None),
)
return finish_compaction(response)
async def chat(
self,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None = None,
model: str | None = None,
max_tokens: int = 4096,
temperature: float = 0.7,
reasoning_effort: str | None = None,
tool_choice: str | dict[str, Any] | None = None,
provider_context: ProviderCallContext | None = None,
) -> LLMResponse:
return await self._call_codex(
messages,
tools,
model,
max_tokens,
reasoning_effort,
tool_choice,
provider_context=provider_context,
)
async def chat_with_context(
self,
*,
provider_context: ProviderCallContext,
**kwargs: Any,
) -> LLMResponse:
return await self.chat(
**kwargs,
provider_context=provider_context,
)
async def chat_stream(
self,
messages: list[dict[str, Any]],
tools: list[dict[str, Any]] | None = None,
model: str | None = None,
max_tokens: int = 4096,
temperature: float = 0.7,
reasoning_effort: str | None = None,
tool_choice: str | dict[str, Any] | None = None,
on_content_delta: Callable[[str], Awaitable[None]] | None = None,
on_thinking_delta: Callable[[str], Awaitable[None]] | None = None,
on_tool_call_delta: Callable[[dict[str, Any]], Awaitable[None]] | None = None,
provider_context: ProviderCallContext | None = None,
) -> LLMResponse:
return await self._call_codex(
messages=messages,
tools=tools,
model=model,
max_tokens=max_tokens,
reasoning_effort=reasoning_effort,
tool_choice=tool_choice,
on_content_delta=on_content_delta,
on_thinking_delta=on_thinking_delta,
on_tool_call_delta=on_tool_call_delta,
provider_context=provider_context,
)
async def chat_stream_with_context(
self,
*,
provider_context: ProviderCallContext,
**kwargs: Any,
) -> LLMResponse:
return await self.chat_stream(
**kwargs,
provider_context=provider_context,
)
def get_default_model(self) -> str:
return self.default_model
@staticmethod
def _responses_state_provider() -> str:
return f"openai_codex:{DEFAULT_CODEX_URL.rstrip('/')}"
def can_resume_conversation_state(
self,
state: ProviderConversationState,
model: str | None = None,
) -> bool:
return responses_state_matches(
state,
provider=self._responses_state_provider(),
model=_strip_model_prefix(model or self.default_model),
)
def supports_native_compaction(self, model: str | None = None) -> bool:
"""Use the Codex backend's inline compaction trigger when needed."""
_ = model
return self._responses.native_compaction_available
def supports_pre_request_compaction(self, model: str | None = None) -> bool:
return self.supports_native_compaction(model)
def _strip_model_prefix(model: str) -> str:
if model.startswith("openai-codex/") or model.startswith("openai_codex/"):
return model.split("/", 1)[1]
return model
def _build_reasoning_options(reasoning_effort: str | None) -> dict[str, str] | None:
if reasoning_effort and reasoning_effort.lower() == "none":
return {"effort": "none"}
options = {"summary": "auto"}
if reasoning_effort:
options["effort"] = reasoning_effort
return options
def _build_headers(
account_id: str,
token: str,
*,
session_routing_key: str | None = None,
) -> dict[str, str]:
headers = {
"Authorization": f"Bearer {token}",
"chatgpt-account-id": account_id,
"OpenAI-Beta": "responses=experimental",
"originator": DEFAULT_ORIGINATOR,
"User-Agent": "nanobot (python)",
"accept": "text/event-stream",
"content-type": "application/json",
}
if session_routing_key:
headers["session-id"] = session_routing_key
return headers
class _CodexHTTPError(RuntimeError):
def __init__(
self,
message: str,
*,
status_code: int | None = None,
retry_after: float | None = None,
error_type: str | None = None,
error_code: str | None = None,
should_retry: bool | None = None,
compaction_unsupported: bool = False,
error_param: str | None = None,
error_message: str | None = None,
request_id: str | None = None,
):
super().__init__(message)
self.status_code = status_code
self.retry_after = retry_after
self.error_type = error_type
self.error_code = error_code
self.should_retry = should_retry
self.compaction_unsupported = compaction_unsupported
self.error_param = error_param
self.error_message = error_message
self.request_id = request_id
async def _request_codex(
url: str,
headers: dict[str, str],
body: dict[str, Any],
verify: ssl.SSLContext | bool,
proxy: str | None = None,
on_content_delta: Callable[[str], Awaitable[None]] | None = None,
on_thinking_delta: Callable[[str], Awaitable[None]] | None = None,
on_tool_call_delta: Callable[[dict[str, Any]], Awaitable[None]] | None = None,
) -> LLMResponse:
return await ResponsesBackend.sse_request(
url, headers, body, provider=f"openai_codex:{url.rstrip('/')}",
verify=verify, proxy=proxy, error_factory=_build_codex_http_error,
on_content_delta=on_content_delta, on_thinking_delta=on_thinking_delta,
on_tool_call_delta=on_tool_call_delta,
)
def _build_codex_http_error(status_code: int, headers: httpx.Headers, raw: str) -> _CodexHTTPError:
retry_after = LLMProvider._extract_retry_after_from_headers(headers)
error_type, error_code = LLMProvider._extract_error_type_code(raw)
error_param, error_message = _codex_error_details(raw)
compaction_unsupported = status_code in {400, 404, 422} and any(
marker in raw.lower()
for marker in ("context_management", "compact_threshold", "compaction_trigger")
)
return _CodexHTTPError(
_friendly_error(status_code), status_code=status_code,
retry_after=retry_after, error_type=error_type, error_code=error_code,
should_retry=_should_retry_status(status_code, error_type, error_code, raw),
compaction_unsupported=compaction_unsupported,
error_param=error_param, error_message=error_message,
request_id=_diagnostic_token(headers.get("x-request-id")),
)
def _prompt_cache_key(session_id: str) -> str:
return hashlib.sha256(session_id.encode("utf-8")).hexdigest()
def _friendly_error(status_code: int) -> str:
if status_code == 429:
return "ChatGPT usage quota exceeded or rate limit triggered. Please try again later."
return f"HTTP {status_code}: Codex API request failed"
def _diagnostic_token(value: object) -> str | None:
if isinstance(value, str) and re.fullmatch(r"[a-zA-Z0-9_.:/\[\]-]{1,160}", value):
return value
return None
def _codex_error_details(raw: str) -> tuple[str | None, str | None]:
try:
payload = json.loads(raw)
except ValueError:
return None, None
error = cast(dict[str, object], payload).get("error") if isinstance(payload, dict) else None
if not isinstance(error, dict):
return None, None
fields = cast(dict[str, object], error)
param = _diagnostic_token(fields.get("param"))
message = fields.get("message")
# Arbitrary upstream messages may contain credentials or user input. Only
# retain this bounded rejection template with known reasoning/verbosity values.
enum = r"'(?:none|minimal|low|medium|high|xhigh|max|ultra|auto|concise|detailed)'"
if (
param in {"reasoning.effort", "text.verbosity"}
and isinstance(message, str)
and len(message) <= 512
and re.fullmatch(
rf"Unsupported value: {enum} is not supported with the 'gpt-[a-zA-Z0-9.-]{{1,80}}' "
rf"model\. Supported values are: {enum}(?:(?:, |, and | and ){enum})*\.",
message,
)
):
return param, message
return param, None
def _codex_error_response(exc: Exception) -> LLMResponse:
if isinstance(exc, RuntimeError) and _codex_login_required(exc):
return LLMResponse(
content="OpenAI Codex authorization expired. Please sign in again.",
finish_reason="error",
error_kind="oauth_auth_required",
error_should_retry=False,
)
exc_type = "CodexHTTPError" if isinstance(exc, _CodexHTTPError) else type(exc).__name__
detail = str(exc).strip()
status_code = getattr(exc, "status_code", None)
error_kind: str | None = None
default_detail: str | None = None
should_retry: bool | None = getattr(exc, "should_retry", None)
if isinstance(exc, (httpx.TimeoutException, asyncio.TimeoutError)):
error_kind = "timeout"
default_detail = "timed out waiting for response"
should_retry = True if should_retry is None else should_retry
elif isinstance(exc, httpx.RemoteProtocolError):
error_kind = "connection"
default_detail = "network protocol error while reading response"
should_retry = True if should_retry is None else should_retry
elif isinstance(exc, (ConnectionError, httpx.NetworkError, httpx.TransportError)):
error_kind = "connection"
default_detail = "network connection failed"
should_retry = True if should_retry is None else should_retry
elif isinstance(exc, (_CodexHTTPError, ResponsesWebSocketError)):
error_kind = "http"
default_detail = "HTTP request failed"
if status_code is not None and should_retry is None:
retry_content = (
None if int(status_code) == 429 and isinstance(exc, _CodexHTTPError) else detail
)
should_retry = _should_retry_status(
int(status_code),
getattr(exc, "error_type", None),
getattr(exc, "error_code", None),
retry_content,
)
detail = detail or default_detail or "unexpected error"
message = f"Error calling Codex ({exc_type}): {detail}"
retry_after = getattr(exc, "retry_after", None) or LLMProvider._extract_retry_after(message)
return LLMResponse(
content=message,
finish_reason="error",
retry_after=retry_after,
error_status_code=int(status_code) if status_code is not None else None,
error_kind=error_kind,
error_type=getattr(exc, "error_type", None),
error_code=getattr(exc, "error_code", None),
error_retry_after_s=retry_after,
error_should_retry=should_retry,
)
def _codex_log_summary(exc_type: str, response: LLMResponse) -> str:
if response.error_status_code is not None:
parts = [f"HTTP {response.error_status_code}"]
if response.error_type:
parts.append(f"type={response.error_type}")
if response.error_code:
parts.append(f"code={response.error_code}")
return " ".join(parts)
kind = (response.error_kind or "").strip()
if kind:
return f"{exc_type} {kind}"
return exc_type
def _should_retry_status(
status_code: int,
error_type: str | None,
error_code: str | None,
content: str | None,
) -> bool:
if status_code == 429:
return LLMProvider._is_retryable_429_response(
LLMResponse(
content=content or "",
finish_reason="error",
error_status_code=status_code,
error_type=error_type,
error_code=error_code,
)
)
return status_code in LLMProvider._RETRYABLE_STATUS_CODES or status_code >= 500
def get_openai_codex_model_catalog(
proxy: str | None = None,
*,
refresh: bool = False,
) -> OAuthModelCatalogSnapshot:
storage = FileTokenStorage(token_filename=OPENAI_CODEX_PROVIDER.token_filename)
token = storage.load()
account_id = getattr(token, "account_id", None)
account_key = _catalog_account_key(account_id)
cache_key = f"{storage.get_token_path()}\0{account_key}\0{proxy or ''}"
return _OPENAI_CODEX_MODEL_CATALOG.get(cache_key=cache_key, proxy=proxy, refresh=refresh)
def invalidate_openai_codex_model_catalog() -> None:
_OPENAI_CODEX_MODEL_CATALOG.invalidate()
def _codex_login_required(exc: RuntimeError) -> bool:
# oauth-cli-kit exposes refresh failures as strings, not typed HTTP errors.
# Interpret only its exact envelope; never propagate the raw token response.
detail = str(exc)
if detail == "OAuth credentials not found. Please run the login command.":
return True
prefix = "Token refresh failed: "
if detail.startswith(prefix):
status, _, body = detail[len(prefix):].partition(" ")
payload: object = None
if len(body) <= 16_384:
try:
payload = json.loads(body)
except ValueError:
pass
return status.isdecimal() and oauth_catalog_auth_rejected(int(status), payload)
return False
def _fetch_openai_codex_models(proxy: str | None) -> tuple[ProviderModelSpec, ...]:
try:
token = get_codex_token(proxy=proxy)
except RuntimeError as exc:
if _codex_login_required(exc):
raise OAuthCatalogAuthRequiredError() from None
raise
account_id = getattr(token, "account_id", None)
if not isinstance(account_id, str) or not account_id:
raise RuntimeError("OpenAI Codex OAuth token has no account ID")
client_kwargs: dict[str, Any] = {"timeout": 10.0, "follow_redirects": False}
if proxy:
client_kwargs.update(proxy=proxy, trust_env=False)
with httpx.Client(**client_kwargs) as client:
response = client.get(
DEFAULT_OPENAI_CODEX_MODELS_URL,
params={"client_version": OPENAI_CODEX_CATALOG_CLIENT_VERSION},
headers={
"Authorization": f"Bearer {token.access}",
"chatgpt-account-id": account_id,
"originator": DEFAULT_ORIGINATOR,
"User-Agent": f"nanobot/{__version__} (python)",
"accept": "application/json",
},
)
response.raise_for_status()
return _parse_openai_codex_models(response.json())
def _parse_openai_codex_models(payload: Any) -> tuple[ProviderModelSpec, ...]:
rows = cast(dict[str, Any], payload).get("models") if isinstance(payload, dict) else None
if not isinstance(rows, list):
return ()
fallback_models = _oauth_fallback_models("openai_codex")
fallback_by_id = {model.id.split("/", 1)[-1]: model for model in fallback_models}
parsed: list[tuple[int, ProviderModelSpec]] = []
seen: set[str] = set()
for value in cast(list[object], rows):
if not isinstance(value, dict):
continue
row = cast(dict[str, Any], value)
wire_id = _catalog_first_text(row, "slug", "id")
if not wire_id or wire_id in seen or row.get("visibility") in {"hide", "none"}:
continue
seen.add(wire_id)
fallback = fallback_by_id.get(wire_id)
priority = row.get("priority")
parsed.append(
(
priority if isinstance(priority, int) and not isinstance(priority, bool) else 2**31,
ProviderModelSpec(
id=f"openai-codex/{wire_id}",
label=(
_catalog_first_text(row, "display_name", "name")
or (fallback.label if fallback is not None else wire_id)
),
description=(
_catalog_first_text(row, "description")
or (fallback.description if fallback is not None else "")
),
owned_by="OpenAI Codex",
context_window=(
_catalog_positive_int(row, "context_window")
or (fallback.context_window if fallback is not None else None)
),
reasoning_efforts=(
_catalog_reasoning_efforts(row.get("supported_reasoning_levels"))
or (fallback.reasoning_efforts if fallback is not None else ())
),
),
)
)
parsed.sort(key=lambda item: item[0])
return tuple(model for _, model in parsed)
def _oauth_fallback_models(provider_name: str) -> tuple[ProviderModelSpec, ...]:
spec = find_by_name(provider_name)
assert spec is not None
return spec.builtin_models
def _catalog_account_key(account_id: object) -> str:
value = account_id if isinstance(account_id, str) else ""
return hashlib.sha256(value.encode()).hexdigest()[:16] if value else "anonymous"
def _catalog_first_text(row: dict[str, Any], *keys: str) -> str:
for key in keys:
value = row.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return ""
def _catalog_positive_int(row: dict[str, Any], *keys: str) -> int | None:
for key in keys:
value = row.get(key)
if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
return int(value)
return None
def _catalog_reasoning_efforts(value: Any) -> tuple[str, ...]:
if not isinstance(value, list):
return ()
efforts: list[str] = []
for item in cast(list[object], value):
if isinstance(item, str):
effort = item.strip()
elif isinstance(item, dict):
effort = _catalog_first_text(cast(dict[str, Any], item), "effort", "value", "id")
else:
effort = ""
if effort and effort not in efforts:
efforts.append(effort)
return tuple(efforts)
_OPENAI_CODEX_MODEL_CATALOG = OAuthModelCatalog(
fallback_models=_oauth_fallback_models("openai_codex"),
fetch=_fetch_openai_codex_models,
)