feat(providers): add ChatGPT/Codex subscription OAuth (PKCE + account-id, hardcoded catalog)

29th platform `openai-codex` (uses_oauth, Responses wire). PKCE-localhost login at
auth.openai.com (client app_EMoamEEZ73f0CkXaXp7hrann, redirect localhost:1455/auth/
callback, form token exchange, fresh-random state) reusing the claude-pro-max flow;
OAuthFlow::PkceLocalhost gained a redirect_path and OAuthConfig an authorize_extra
(empty elsewhere, so claude/xai/copilot authorize URLs stay byte-identical).

Codex-specific: the access token is a JWT carrying chatgpt_account_id, which becomes
the `chatgpt-account-id` inference header. It is derived STATELESSLY from whichever
bearer rides each request (so a rotated token needs no persisted field), and BOTH
login and refresh fail fast when the claim is absent — gated on the explicit
OAuthConfig.requires_chatgpt_account_id fact, never inferred from the token-body
encoding (a plain form endpoint is the OAuth norm and must not inherit this).

Inference rides the existing Responses wire at chatgpt.com/backend-api/codex →
/responses, with codex headers (chatgpt-account-id, originator, OpenAI-Beta
responses=experimental, codex UA) gated on SamplerConfig.openai_codex so API-key
`openai` stays byte-identical; store:false was already the global Responses default.

Catalog is HARDCODED (no live endpoint exists for this backend; read from the
official Codex CLI's model cache): gpt-5.6-sol/terra/luna + gpt-5.5, ctx 272000,
each with its real reasoning levels (low..ultra — ReasoningEffort gained Ultra).
Excluded: gpt-5.3-codex-spark (supported_in_api=false), gpt-5.4/-mini and
codex-auto-review (hidden) — they would list but fail at inference. The fetch
short-circuits before any HTTP; Kigi never shells out to the codex CLI or reads
~/.codex.

Security review fixes: redact any `account-id` header from request logs (it was
reaching debug logs), strict 3-segment JWT check (fail closed), refresh no longer
fails open on a missing claim. Inherits leak-safe pooled routing (scope
oauth/openai-codex) — never the Kimi token. Full gate green (234 suites, 0 warnings).
This commit is contained in:
2026-07-22 08:28:03 -04:00
parent 8179438278
commit 422e241e13
27 changed files with 1294 additions and 106 deletions
@@ -605,6 +605,11 @@ mod tests {
);
assert_eq!(
ids[kimi_pos + 4],
"openai-codex",
"openai-codex is the next interactive OAuth login, after github-copilot"
);
assert_eq!(
ids[kimi_pos + 5],
MOONSHOT_CN_METHOD_ID,
"the api-key rows follow the generic oauth logins"
);
@@ -756,6 +761,7 @@ mod tests {
"xai-grok",
"claude-pro-max",
"github-copilot",
"openai-codex",
MOONSHOT_CN_METHOD_ID,
MOONSHOT_AI_METHOD_ID,
"openai",
@@ -807,6 +813,7 @@ mod tests {
"xai-grok",
"claude-pro-max",
"github-copilot",
"openai-codex",
MOONSHOT_CN_METHOD_ID,
MOONSHOT_AI_METHOD_ID,
"openai",
@@ -851,6 +858,7 @@ mod tests {
"xai-grok",
"claude-pro-max",
"github-copilot",
"openai-codex",
MOONSHOT_CN_METHOD_ID,
MOONSHOT_AI_METHOD_ID,
"openai",
@@ -898,6 +906,7 @@ mod tests {
"xai-grok",
"claude-pro-max",
"github-copilot",
"openai-codex",
MOONSHOT_CN_METHOD_ID,
MOONSHOT_AI_METHOD_ID,
"openai",
@@ -4099,6 +4099,15 @@ pub fn sampling_config_for_model(
.as_deref()
.and_then(kigi_models::parse_managed_model_key)
.is_some_and(|(platform, _)| platform.sends_copilot_editor_headers());
// ChatGPT/Codex Responses identity headers: a managed key whose platform is
// openai-codex drives the codex headers (`chatgpt-account-id` + originator +
// OpenAI-Beta) in the sampler. Gated here so API-key `openai` Responses
// requests stay byte-identical.
let openai_codex = info
.id
.as_deref()
.and_then(kigi_models::parse_managed_model_key)
.is_some_and(|(platform, _)| platform.sends_codex_responses_headers());
SamplerConfig {
api_key: credentials.api_key,
model: model_name,
@@ -4110,6 +4119,7 @@ pub fn sampling_config_for_model(
auth_scheme: credentials.auth_scheme,
anthropic_oauth,
github_copilot,
openai_codex,
chat_compat,
extra_headers,
context_window: info.context_window.get(),
@@ -334,6 +334,19 @@ fn fetch_one_platform_models(
bearer: &str,
enrichment: &kigi_models::enrichment::EnrichmentCatalog,
) -> Result<(Vec<crate::agent::config::ModelEntryConfig>, Option<String>), BackendError> {
// A platform that serves NO live `/models` listing (openai-codex) delivers a
// HARDCODED catalog: short-circuit BEFORE any HTTP, mapping the compiled-in
// `WireModel`s through the SAME `platform_wire_model_to_entry` output a live
// listing produces (context window + per-model reasoning efforts). The
// bearer is unused here (login gates availability; no request is made).
if let Some(wire_models) = platform.hardcoded_catalog() {
let base_url = platform_fetch_base(platform, endpoints);
let models = wire_models
.into_iter()
.map(|wire| platform_wire_model_to_entry(platform, wire, &base_url))
.collect();
return Ok((models, None));
}
let client = crate::http::shared_blocking_client();
let url = match platform.listing() {
kigi_models::ListingDialect::OpenAi => platform_models_url(platform, endpoints),
@@ -1401,6 +1414,104 @@ mod tests {
);
}
/// openai-codex fetch: the catalog is HARDCODED, so the fetch path
/// short-circuits BEFORE any HTTP — there is NO mock `/models` server, yet
/// the fetch returns exactly the 4 compiled-in models keyed
/// `openai-codex/<slug>` on the Responses backend, ctx 272000, each exposing
/// its exact reasoning efforts (incl. the codex-only `xhigh`/`max`/`ultra`).
/// A BOGUS base URL confirms no live `/models` request is attempted (it would
/// otherwise fail against an unroutable host).
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn openai_codex_catalog_is_hardcoded_with_no_http_fetch() {
// Unroutable base: if the fetch path tried a live `/models` request it
// would error here; the hardcoded short-circuit ignores it for fetching.
let _base = kigi_test_support::EnvGuard::set(
kigi_models::CODEX_BASE_URL_ENV,
"http://127.0.0.1:1/codex",
);
let endpoints = crate::agent::config::EndpointsConfig::default();
// The session token merely marks openai-codex "enabled"; it is unused by
// the hardcoded path (no request rides it).
let mut oauth_tokens = OAuthSessionTokens::new();
oauth_tokens.insert(
kigi_models::PlatformId::OpenaiCodex,
"codex-session-tok".to_string(),
);
let keys = crate::agent::models::PlatformApiKeys::default();
let result = tokio::task::spawn_blocking(move || {
fetch_platform_models_blocking(&endpoints, None, &oauth_tokens, &keys)
})
.await
.unwrap()
.expect("openai-codex hardcoded catalog fetch must succeed with no HTTP");
assert_eq!(
result
.models
.iter()
.map(|m| m.id.as_deref().unwrap_or_default())
.collect::<Vec<_>>(),
vec![
"openai-codex/gpt-5.6-sol",
"openai-codex/gpt-5.6-terra",
"openai-codex/gpt-5.6-luna",
"openai-codex/gpt-5.5",
],
"exactly the 4 hardcoded models, keyed openai-codex/<slug>"
);
// Excluded models never appear.
for absent in [
"openai-codex/gpt-5.3-codex-spark",
"openai-codex/gpt-5.4",
"openai-codex/gpt-5.4-mini",
"openai-codex/codex-auto-review",
] {
assert!(
!result
.models
.iter()
.any(|m| m.id.as_deref() == Some(absent)),
"{absent} must be absent from the hardcoded catalog"
);
}
let sol = &result.models[0];
assert_eq!(
sol.api_backend,
crate::sampling::ApiBackend::Responses,
"openai-codex speaks the Responses wire"
);
assert_eq!(sol.context_window.get(), 272_000);
assert_eq!(sol.name.as_deref(), Some("GPT-5.6-Sol"));
assert!(
!sol.supported_in_api,
"subscription (uses_oauth) models require the OAuth session"
);
assert!(sol.supports_reasoning_effort);
assert_eq!(
sol.reasoning_efforts
.iter()
.map(|o| o.id.as_str())
.collect::<Vec<_>>(),
vec!["low", "medium", "high", "xhigh", "max", "ultra"],
"sol exposes the full codex effort menu incl. ultra"
);
// gpt-5.5 tops out at xhigh (no max/ultra).
let five_five = result
.models
.iter()
.find(|m| m.id.as_deref() == Some("openai-codex/gpt-5.5"))
.unwrap();
assert_eq!(
five_five
.reasoning_efforts
.iter()
.map(|o| o.id.as_str())
.collect::<Vec<_>>(),
vec!["low", "medium", "high", "xhigh"]
);
}
/// DeepSeek-cycle e2e: bare OpenAI-shape listing + enrichment efforts
/// (high/max) produce ChatCompletions entries whose sampler config
/// speaks the DeepSeek thinking dialect.
@@ -60,6 +60,7 @@ fn effort_label(effort: ReasoningEffort) -> String {
ReasoningEffort::High => "High",
ReasoningEffort::Xhigh => "X-High",
ReasoningEffort::Max => "Max",
ReasoningEffort::Ultra => "Ultra",
}
.to_string()
}
@@ -893,6 +893,11 @@ async fn read_parent_sampling_config(
// false, so the other ChatCompletions paths stay byte-identical.
let github_copilot = kigi_models::parse_managed_model_key(ctx.model_id.0.as_ref())
.is_some_and(|(platform, _)| platform.sends_copilot_editor_headers());
// ChatGPT/Codex headers inherit from the parent model's platform
// (openai-codex → true); every other platform / BYOK → false, so the
// API-key openai Responses path stays byte-identical.
let openai_codex = kigi_models::parse_managed_model_key(ctx.model_id.0.as_ref())
.is_some_and(|(platform, _)| platform.sends_codex_responses_headers());
let inherited = kigi_sampler::SamplerConfig {
api_key: creds.api_key,
base_url: cfg.base_url,
@@ -904,6 +909,7 @@ async fn read_parent_sampling_config(
auth_scheme,
anthropic_oauth,
github_copilot,
openai_codex,
chat_compat: cfg.chat_compat,
extra_headers,
context_window: cfg.context_window.get(),