Skip to main content

nitpicker_agent/
codex.rs

1//! ChatGPT/Codex subscription auth for OpenAI reviewers.
2//!
3//! Reuses the OAuth token the Codex CLI stores in `~/.codex/auth.json` (read-only; never written
4//! back), refreshing the short-lived access token in-memory via the refresh token. Requests go to
5//! the Codex subscription endpoint, which speaks the OpenAI Responses API with several
6//! backend-specific quirks (see [`CodexClient::send`]).
7//!
8//! Research-only: third-party use of the Codex OAuth client is arguably against OpenAI's ToS,
9//! mirroring the posture of the Antigravity Gemini path.
10
11use std::path::{Path, PathBuf};
12use std::sync::{Arc, Mutex as StdMutex, OnceLock};
13use std::time::{Duration, SystemTime, UNIX_EPOCH};
14
15use base64::Engine;
16use base64::engine::general_purpose::URL_SAFE_NO_PAD;
17use eyre::{Result, WrapErr};
18use rig_core::ProviderError;
19use rig_core::completion::CompletionRequest;
20use rig_core::providers::openai::responses_api::wire::Responses;
21use rig_core::providers::openai::wire::CallerIdentity;
22use rig_core::providers::{chatgpt, openai};
23use serde_json::Value;
24use sha2::{Digest, Sha256};
25use tokio::sync::Mutex;
26
27use crate::llm::{
28    Completion, CompletionResponse, LLMClient, LLMClientDyn, WithRetryExt,
29    compact_provider_error_body, provider_http_status,
30};
31
32/// Codex CLI's public OAuth client id (PKCE, no secret) — shared with the official CLI.
33const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
34const TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
35const ORIGINATOR: &str = "nitpicker";
36/// Refresh this long before the token's stated expiry to avoid racing the deadline.
37const EXPIRY_SKEW: Duration = Duration::from_secs(60);
38/// Bound the token refresh so a stalled auth request can't pin the token mutex (and thus every
39/// concurrent completion sharing the client) indefinitely.
40const REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
41/// Give up establishing a connection after this long (dead host / no route).
42const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
43/// Abort a stalled response: if no bytes arrive for this long, the connection is hung. This is an
44/// idle (per-read) timeout, not a total cap, so a legitimately long streaming turn is not aborted
45/// as long as it keeps making progress — but a hung completion can no longer pin an
46/// `llm_semaphore` permit indefinitely.
47const READ_TIMEOUT: Duration = Duration::from_secs(120);
48
49/// Shared reqwest client for the Codex endpoints, configured so a hung connection can't pin a
50/// shared concurrency permit forever (`reqwest::Client::new()` sets no timeouts).
51fn build_http_client() -> Result<reqwest::Client> {
52    reqwest::Client::builder()
53        .connect_timeout(CONNECT_TIMEOUT)
54        .read_timeout(READ_TIMEOUT)
55        .build()
56        .wrap_err("building Codex HTTP client")
57}
58
59fn user_agent() -> String {
60    format!(
61        "nitpicker/{} ({}; {})",
62        env!("CARGO_PKG_VERSION"),
63        std::env::consts::OS,
64        std::env::consts::ARCH
65    )
66}
67
68// ============================================================================
69// JWT claim parsing (no signature verification — we only read public claims)
70// ============================================================================
71
72fn decode_jwt_claims(token: &str) -> Option<Value> {
73    let payload = token.split('.').nth(1)?;
74    let bytes = URL_SAFE_NO_PAD.decode(payload).ok()?;
75    serde_json::from_slice(&bytes).ok()
76}
77
78/// Mirror the Codex CLI / opencode account-id resolution order.
79fn account_id_from_claims(claims: &Value) -> Option<String> {
80    let direct = claims.get("chatgpt_account_id").and_then(Value::as_str);
81    let nested = claims
82        .get("https://api.openai.com/auth")
83        .and_then(|a| a.get("chatgpt_account_id"))
84        .and_then(Value::as_str);
85    let org = claims
86        .get("organizations")
87        .and_then(Value::as_array)
88        .and_then(|orgs| orgs.first())
89        .and_then(|o| o.get("id"))
90        .and_then(Value::as_str);
91    direct.or(nested).or(org).map(str::to_string)
92}
93
94fn account_id_from_tokens(id_token: Option<&str>, access_token: &str) -> Option<String> {
95    id_token
96        .and_then(decode_jwt_claims)
97        .as_ref()
98        .and_then(account_id_from_claims)
99        .or_else(|| {
100            decode_jwt_claims(access_token)
101                .as_ref()
102                .and_then(account_id_from_claims)
103        })
104}
105
106/// Expiry from the access token's `exp` claim. Missing/unparseable → `UNIX_EPOCH` (already expired),
107/// forcing a refresh on first use; that's not a thrash because the refresh response carries an
108/// authoritative `expires_in`.
109fn expiry_from_access_token(access_token: &str) -> SystemTime {
110    decode_jwt_claims(access_token)
111        .and_then(|c| c.get("exp").and_then(Value::as_u64))
112        // checked_add: a garbage/huge `exp` would otherwise overflow SystemTime and panic; treat
113        // overflow as already-expired (forces a refresh) rather than aborting the process.
114        .and_then(|exp| UNIX_EPOCH.checked_add(Duration::from_secs(exp)))
115        .unwrap_or(UNIX_EPOCH)
116}
117
118// ============================================================================
119// Token store (~/.codex/auth.json)
120// ============================================================================
121
122#[derive(Clone)]
123struct CodexTokens {
124    access_token: String,
125    refresh_token: String,
126    account_id: Option<String>,
127    expires_at: SystemTime,
128}
129
130impl CodexTokens {
131    fn is_expired(&self) -> bool {
132        self.expires_at <= SystemTime::now() + EXPIRY_SKEW
133    }
134}
135
136/// `$CODEX_HOME/auth.json` (when CODEX_HOME is set, non-empty, absolute) else `~/.codex/auth.json`.
137fn auth_path() -> Result<PathBuf> {
138    resolve_auth_path(
139        std::env::var("CODEX_HOME").ok().as_deref(),
140        dirs::home_dir(),
141    )
142}
143
144/// Pure resolution split from env/dirs lookup so it can be unit-tested.
145fn resolve_auth_path(codex_home: Option<&str>, home_dir: Option<PathBuf>) -> Result<PathBuf> {
146    if let Some(home) = codex_home {
147        let trimmed = home.trim();
148        if !trimmed.is_empty() {
149            let path = Path::new(trimmed);
150            if path.is_absolute() {
151                return Ok(path.join("auth.json"));
152            }
153            eyre::bail!("CODEX_HOME must be an absolute path, got \"{home}\"");
154        }
155    }
156    let home =
157        home_dir.ok_or_else(|| eyre::eyre!("cannot resolve home directory (set CODEX_HOME)"))?;
158    Ok(home.join(".codex").join("auth.json"))
159}
160
161fn load_tokens(path: &Path) -> Result<CodexTokens> {
162    let raw = std::fs::read_to_string(path).wrap_err_with(|| {
163        format!(
164            "cannot read {} — run `codex login` with a ChatGPT subscription first",
165            path.display()
166        )
167    })?;
168    parse_tokens(&raw, &path.display().to_string())
169}
170
171/// True when a usable Codex CLI OAuth token file is present (CODEX_HOME or `~/.codex/auth.json`).
172/// Used by `init` detection; reuses the same parse the client does, so API-key-mode files (which
173/// the client rejects) don't surface as a codex provider.
174pub fn auth_available() -> bool {
175    auth_path().and_then(|p| load_tokens(&p)).is_ok()
176}
177
178/// Parse a Codex `auth.json` payload. Split from IO so it is unit-testable without a real file.
179fn parse_tokens(raw: &str, source: &str) -> Result<CodexTokens> {
180    let v: Value =
181        serde_json::from_str(raw).wrap_err_with(|| format!("invalid JSON in {source}"))?;
182    let tokens = v.get("tokens").ok_or_else(|| {
183        eyre::eyre!(
184            "no ChatGPT subscription tokens in {source} — run `codex login` (API-key mode is not supported here)"
185        )
186    })?;
187    let access_token = tokens
188        .get("access_token")
189        .and_then(Value::as_str)
190        .filter(|s| !s.is_empty())
191        .ok_or_else(|| eyre::eyre!("no access_token in {source}"))?
192        .to_string();
193    let refresh_token = tokens
194        .get("refresh_token")
195        .and_then(Value::as_str)
196        .filter(|s| !s.is_empty())
197        .ok_or_else(|| eyre::eyre!("no refresh_token in {source}"))?
198        .to_string();
199    let account_id = tokens
200        .get("account_id")
201        .and_then(Value::as_str)
202        .filter(|s| !s.is_empty())
203        .map(str::to_string)
204        .or_else(|| {
205            account_id_from_tokens(
206                tokens.get("id_token").and_then(Value::as_str),
207                &access_token,
208            )
209        });
210    let expires_at = expiry_from_access_token(&access_token);
211    Ok(CodexTokens {
212        access_token,
213        refresh_token,
214        account_id,
215        expires_at,
216    })
217}
218
219#[derive(serde::Deserialize)]
220struct RefreshResponse {
221    access_token: String,
222    refresh_token: Option<String>,
223    id_token: Option<String>,
224    expires_in: Option<u64>,
225}
226
227/// Exchange a refresh token for a fresh access token. Expiry comes from the response's
228/// `expires_in` (authoritative — a token without an `exp` claim never thrashes the cache).
229async fn refresh_tokens(
230    http: &reqwest::Client,
231    refresh_token: &str,
232    prev_account_id: Option<&str>,
233) -> Result<CodexTokens> {
234    let resp = http
235        .post(TOKEN_URL)
236        .timeout(REFRESH_TIMEOUT)
237        .form(&[
238            ("grant_type", "refresh_token"),
239            ("refresh_token", refresh_token),
240            ("client_id", CLIENT_ID),
241        ])
242        .send()
243        .await
244        .wrap_err("Codex token refresh request failed")?;
245    let status = resp.status();
246    let body = resp.text().await.unwrap_or_default();
247    if !status.is_success() {
248        return Err(eyre::Report::new(ProviderError::from_http_response(
249            status,
250            compact_provider_error_body(&body, 1000),
251        )))
252        .wrap_err("Codex token refresh failed");
253    }
254    let parsed: RefreshResponse =
255        serde_json::from_str(&body).wrap_err("parsing Codex token refresh response")?;
256    // prefer the authoritative `expires_in`; if absent, derive from the new access token's JWT `exp`
257    // rather than guessing a fixed lifetime.
258    let expires_at = match parsed.expires_in {
259        // checked_add guards against an absurd `expires_in` overflowing SystemTime (panic);
260        // on overflow fall back to the access token's own `exp`.
261        Some(secs) => SystemTime::now()
262            .checked_add(Duration::from_secs(secs))
263            .unwrap_or_else(|| expiry_from_access_token(&parsed.access_token)),
264        None => expiry_from_access_token(&parsed.access_token),
265    };
266    let account_id = prev_account_id
267        .map(str::to_string)
268        .or_else(|| account_id_from_tokens(parsed.id_token.as_deref(), &parsed.access_token));
269    Ok(CodexTokens {
270        access_token: parsed.access_token,
271        refresh_token: parsed
272            .refresh_token
273            .unwrap_or_else(|| refresh_token.to_string()),
274        account_id,
275        expires_at,
276    })
277}
278
279// ============================================================================
280// Client
281// ============================================================================
282
283pub struct CodexClient {
284    http: reqwest::Client,
285    auth_path: PathBuf,
286    tokens: Mutex<CodexTokens>,
287}
288
289impl CodexClient {
290    /// Load tokens from `~/.codex/auth.json` (or `$CODEX_HOME`) and build the client.
291    pub fn new() -> Result<Self> {
292        let path = auth_path()?;
293        let tokens = load_tokens(&path)?;
294        Ok(Self {
295            http: build_http_client()?,
296            auth_path: path,
297            tokens: Mutex::new(tokens),
298        })
299    }
300
301    /// Refresh under the held lock. If the refresh token was rejected (4xx) the Codex CLI may have
302    /// rotated it on disk concurrently — reload `auth.json` once and retry before giving up.
303    ///
304    /// Read-only limitation: when the OAuth server rotates the refresh token, the new one is held
305    /// only in memory (we never write back to `auth.json` — that's the Codex CLI's file). A later
306    /// process therefore reads the pre-rotation token from disk; if the server invalidated it, the
307    /// reload-retry below hits the same stale token and can't self-heal — so it surfaces a clear
308    /// `run \`codex login\`` error rather than persisting a token behind the CLI's back.
309    async fn refresh_locked(&self, tokens: &mut CodexTokens) -> Result<()> {
310        match refresh_tokens(
311            &self.http,
312            &tokens.refresh_token,
313            tokens.account_id.as_deref(),
314        )
315        .await
316        {
317            Ok(fresh) => {
318                *tokens = fresh;
319                Ok(())
320            }
321            Err(err) if is_rotation_4xx(&err) => {
322                let disk = load_tokens(&self.auth_path)
323                    .wrap_err("Codex refresh token rejected and reloading auth.json failed")?;
324                let fresh = refresh_tokens(
325                    &self.http,
326                    &disk.refresh_token,
327                    disk.account_id.as_deref(),
328                )
329                .await
330                .wrap_err(
331                    "Codex refresh failed even after reloading auth.json (run `codex login`)",
332                )?;
333                *tokens = fresh;
334                Ok(())
335            }
336            Err(err) => Err(err),
337        }
338    }
339
340    /// Current access token + account id, refreshing first if within the expiry skew. Double-checked
341    /// under the lock so a concurrent wave of subagents triggers at most one refresh.
342    async fn current_access(&self) -> Result<(String, Option<String>)> {
343        let mut guard = self.tokens.lock().await;
344        if guard.is_expired() {
345            self.refresh_locked(&mut guard).await?;
346        }
347        Ok((guard.access_token.clone(), guard.account_id.clone()))
348    }
349
350    /// Force a refresh after a 401, gated on the rejected access token: if a concurrent 401 already
351    /// refreshed (the cached token differs from the one we used), reuse that instead of refetching.
352    async fn force_refresh(&self, used_access: &str) -> Result<(String, Option<String>)> {
353        let mut guard = self.tokens.lock().await;
354        if guard.access_token != used_access {
355            return Ok((guard.access_token.clone(), guard.account_id.clone()));
356        }
357        self.refresh_locked(&mut guard).await?;
358        Ok((guard.access_token.clone(), guard.account_id.clone()))
359    }
360
361    /// Use Rig's Codex dialect for stateless Responses framing and replay.
362    async fn send(
363        &self,
364        completion: &Completion,
365        access: &str,
366        account_id: Option<&str>,
367    ) -> Result<CompletionResponse> {
368        let wire = codex_wire(&completion.model, access, account_id);
369        let model = rig_core::Model::new(wire, rig_reqwest::ReqwestClient::from(self.http.clone()));
370        let response = model
371            .call(codex_request(completion)?)
372            .await
373            .wrap_err("Codex completion failed")?;
374        Ok(CompletionResponse::from_rig(
375            response,
376            completion.model.clone(),
377        ))
378    }
379}
380
381/// Process-wide shared Codex client (retry-wrapped), built once on first use.
382///
383/// The token store is inherently process-global — there is a single `~/.codex/auth.json` and a
384/// single live token chain — so every Codex reviewer/aggregator must share ONE [`CodexClient`].
385/// Per-client caches would each hold their own in-memory refresh token; after a rotation, one
386/// client's fresh token would be invisible to the others, and a concurrent refresh on the stale
387/// disk token could fail. Sharing one instance gives a single token cache with working
388/// concurrent-refresh dedup.
389pub fn shared_client() -> Result<Arc<dyn LLMClientDyn>> {
390    static CELL: OnceLock<StdMutex<Option<Arc<dyn LLMClientDyn>>>> = OnceLock::new();
391    let cell = CELL.get_or_init(|| StdMutex::new(None));
392    let mut guard = cell.lock().expect("codex shared-client mutex poisoned");
393    if let Some(existing) = guard.as_ref() {
394        return Ok(Arc::clone(existing));
395    }
396    let client = CodexClient::new()?.with_retry().into_arc();
397    *guard = Some(Arc::clone(&client));
398    Ok(client)
399}
400
401impl LLMClient for CodexClient {
402    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
403        let (access, account_id) = self.current_access().await?;
404        match self.send(&completion, &access, account_id.as_deref()).await {
405            Ok(response) => Ok(response),
406            // The token can lapse/revoke between our expiry check and the call landing. Force a
407            // single refresh-and-retry rather than surfacing a 401 (RetryingLLM treats it as fatal).
408            Err(err) if provider_http_status(&err) == Some(401) => {
409                let (access, account_id) = self.force_refresh(&access).await?;
410                self.send(&completion, &access, account_id.as_deref()).await
411            }
412            Err(err) => Err(err),
413        }
414    }
415}
416
417// ============================================================================
418// Request/response mapping
419// ============================================================================
420
421fn codex_wire(model: &str, access: &str, account_id: Option<&str>) -> Responses {
422    let mut config = openai::OpenAIConfig::with_key(&chatgpt::DIALECT, access);
423    config.instructions = None;
424    // The Codex backend leaves top-level `instructions` out of the cached prompt prefix, so it is
425    // re-prefilled on every turn; a leading developer message (what the Codex CLI sends) caches.
426    config.dialect.quirks.responses.system_role = "developer";
427    config.identity = Some(CallerIdentity {
428        originator: ORIGINATOR.into(),
429        user_agent: user_agent(),
430    });
431    config.account_id = account_id.map(str::to_owned);
432    Responses::new(config, model).with_system_instructions_as_messages()
433}
434
435fn codex_request(completion: &Completion) -> Result<CompletionRequest> {
436    eyre::ensure!(
437        completion
438            .preamble
439            .as_deref()
440            .is_some_and(|s| !s.trim().is_empty()),
441        "Codex auth requires a system prompt: this completion had no `instructions`"
442    );
443    let mut request = CompletionRequest::from(completion.clone());
444    request.max_tokens = None;
445    request.options.cache_key = Some(codex_prompt_cache_key(completion)?);
446    Ok(request)
447}
448
449/// Stable, opaque cache-routing key for the prefix that remains fixed during one conversation.
450/// OpenAI still matches the actual prompt prefix; this only keeps requests with the same
451/// model/system/tool family routed together. Including the project-aware system prompt naturally
452/// partitions unrelated reviews instead of concentrating all traffic on one hot key.
453fn codex_prompt_cache_key(completion: &Completion) -> Result<String> {
454    fn hash_part(hasher: &mut Sha256, bytes: &[u8]) {
455        hasher.update((bytes.len() as u64).to_be_bytes());
456        hasher.update(bytes);
457    }
458
459    let mut hasher = Sha256::new();
460    hash_part(&mut hasher, completion.model.as_bytes());
461    hash_part(
462        &mut hasher,
463        completion
464            .preamble
465            .as_deref()
466            .unwrap_or_default()
467            .as_bytes(),
468    );
469    let tools = serde_json::to_vec(&completion.tools)
470        .wrap_err("serializing Codex tools for prompt cache routing")?;
471    hash_part(&mut hasher, &tools);
472    let digest = hasher.finalize();
473    let suffix = digest[..16]
474        .iter()
475        .map(|byte| format!("{byte:02x}"))
476        .collect::<String>();
477    Ok(format!("nitpicker-{suffix}"))
478}
479
480/// A 4xx-other-than-429 status anywhere in the error chain — used to decide whether a failed token
481/// refresh warrants reloading a rotated refresh token from disk. 429 is excluded: a rate-limited
482/// refresh is transient and reloading `auth.json` can't fix it, so it should bubble up to the outer
483/// retry/backoff instead of immediately firing a second refresh.
484fn is_rotation_4xx(err: &eyre::Report) -> bool {
485    provider_http_status(err).is_some_and(|status| (400..500).contains(&status) && status != 429)
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491    use rig_core::completion::message::{
492        AssistantContent, AssistantMessage, CallId, Message, ToolCall, ToolFunction, ToolName,
493        ToolResultContent, UserContent,
494    };
495    use serde_json::json;
496
497    /// Build an unsigned JWT (`alg: none`) with the given claims — enough to exercise our
498    /// claims-reading code, which never verifies the signature.
499    fn jwt(claims: Value) -> String {
500        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
501        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
502        format!("{header}.{payload}.sig")
503    }
504
505    #[test]
506    fn account_id_resolution_order() {
507        assert_eq!(
508            account_id_from_claims(&json!({ "chatgpt_account_id": "root" })).as_deref(),
509            Some("root")
510        );
511        assert_eq!(
512            account_id_from_claims(
513                &json!({ "https://api.openai.com/auth": { "chatgpt_account_id": "nested" } })
514            )
515            .as_deref(),
516            Some("nested")
517        );
518        // root preferred over nested
519        assert_eq!(
520            account_id_from_claims(&json!({
521                "chatgpt_account_id": "root",
522                "https://api.openai.com/auth": { "chatgpt_account_id": "nested" }
523            }))
524            .as_deref(),
525            Some("root")
526        );
527        // organizations fallback
528        assert_eq!(
529            account_id_from_claims(
530                &json!({ "organizations": [{ "id": "org-1" }, { "id": "org-2" }] })
531            )
532            .as_deref(),
533            Some("org-1")
534        );
535        assert_eq!(account_id_from_claims(&json!({ "email": "x@y.z" })), None);
536    }
537
538    #[test]
539    fn account_id_prefers_id_token_then_access_token() {
540        let id_token = jwt(json!({ "chatgpt_account_id": "from-id" }));
541        let access = jwt(json!({ "chatgpt_account_id": "from-access" }));
542        assert_eq!(
543            account_id_from_tokens(Some(&id_token), &access).as_deref(),
544            Some("from-id")
545        );
546        let id_token_no_acct = jwt(json!({ "email": "x@y.z" }));
547        assert_eq!(
548            account_id_from_tokens(Some(&id_token_no_acct), &access).as_deref(),
549            Some("from-access")
550        );
551    }
552
553    #[test]
554    fn expiry_from_exp_claim_and_missing() {
555        let with_exp = jwt(json!({ "exp": 4_000_000_000u64 }));
556        assert_eq!(
557            expiry_from_access_token(&with_exp),
558            UNIX_EPOCH + Duration::from_secs(4_000_000_000)
559        );
560        // missing exp => already expired (UNIX_EPOCH) so first use refreshes
561        assert_eq!(expiry_from_access_token(&jwt(json!({}))), UNIX_EPOCH);
562        assert_eq!(expiry_from_access_token("not-a-jwt"), UNIX_EPOCH);
563    }
564
565    #[test]
566    fn parse_tokens_full_and_derived_account_id() {
567        let access = jwt(json!({ "exp": 4_000_000_000u64 }));
568        // explicit account_id wins
569        let raw = json!({
570            "tokens": { "access_token": access, "refresh_token": "rt", "account_id": "acct-explicit" }
571        })
572        .to_string();
573        let t = parse_tokens(&raw, "test").unwrap();
574        assert_eq!(t.account_id.as_deref(), Some("acct-explicit"));
575        assert!(!t.is_expired());
576
577        // derived from id_token when account_id absent
578        let id_token = jwt(json!({ "chatgpt_account_id": "acct-derived" }));
579        let raw = json!({
580            "tokens": { "access_token": access, "refresh_token": "rt", "id_token": id_token }
581        })
582        .to_string();
583        let t = parse_tokens(&raw, "test").unwrap();
584        assert_eq!(t.account_id.as_deref(), Some("acct-derived"));
585    }
586
587    #[test]
588    fn parse_tokens_rejects_api_key_mode_and_missing_fields() {
589        // API-key mode: no `tokens` object
590        let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
591        assert!(parse_tokens(&raw, "test").is_err());
592        // tokens present but no access_token
593        let raw = json!({ "tokens": { "refresh_token": "rt" } }).to_string();
594        assert!(parse_tokens(&raw, "test").is_err());
595    }
596
597    fn build_body_value(completion: &Completion) -> Result<Value> {
598        use rig_core::wire::{Body, Mode, Wire};
599        let wire = codex_wire(&completion.model, "unused", None);
600        let encoded = wire.encode(codex_request(completion)?, Mode::Unary)?;
601        let Body::Bytes(bytes) = encoded.request.into_body() else {
602            panic!("expected a JSON body")
603        };
604        Ok(serde_json::from_slice(&bytes)?)
605    }
606
607    #[test]
608    fn build_body_applies_codex_quirks() {
609        let completion = Completion {
610            model: "gpt-5.4".to_string(),
611            prompt: Message::user("hello"),
612            preamble: Some("You are a reviewer.".to_string()),
613            history: vec![],
614            tools: vec![],
615            tool_choice: None,
616            max_tokens: Some(4096),
617            additional_params: None,
618        };
619        let json = build_body_value(&completion).unwrap();
620        assert!(json.get("instructions").is_none());
621        assert_eq!(json["stream"], true);
622        assert!(json.get("max_output_tokens").is_none());
623        assert_eq!(json.get("store"), Some(&Value::Bool(false)));
624        assert!(
625            json.get("prompt_cache_key")
626                .and_then(Value::as_str)
627                .is_some_and(|key| key.starts_with("nitpicker-")),
628            "Codex requests must carry a stable prompt cache routing key"
629        );
630        // encrypted reasoning content is requested so reasoning items survive store:false round-trips
631        assert_eq!(
632            json.get("include").and_then(Value::as_array),
633            Some(&vec![Value::String(
634                "reasoning.encrypted_content".to_string()
635            )]),
636            "must request reasoning.encrypted_content to avoid bare rs_ id 404s"
637        );
638        // the backend rejects `system` items and does not cache top-level `instructions`
639        assert_eq!(
640            json["input"][0],
641            json!({
642                "type": "message",
643                "role": "developer",
644                "content": [{"type": "input_text", "text": "You are a reviewer."}],
645            })
646        );
647    }
648
649    #[test]
650    fn build_body_requires_a_system_prompt() {
651        let completion = Completion {
652            model: "gpt-5.4".to_string(),
653            prompt: Message::user("hello"),
654            preamble: None,
655            history: vec![],
656            tools: vec![],
657            tool_choice: None,
658            max_tokens: None,
659            additional_params: None,
660        };
661        assert!(build_body_value(&completion).is_err());
662    }
663
664    #[test]
665    fn prompt_cache_key_tracks_the_stable_prefix_not_the_conversation_tail() {
666        let first = Completion {
667            model: "gpt-5.4".to_string(),
668            prompt: Message::user("initial request"),
669            preamble: Some("stable reviewer and project context".to_string()),
670            history: vec![],
671            tools: vec![rig_core::completion::ToolDefinition {
672                name: ToolName::new("read_file").unwrap(),
673                annotations: Default::default(),
674                description: "Read a file".to_string(),
675                parameters: json!({
676                    "type": "object",
677                    "properties": { "path": { "type": "string" } }
678                }),
679            }],
680            tool_choice: None,
681            max_tokens: None,
682            additional_params: None,
683        };
684        let mut later_turn = first.clone();
685        later_turn.history = vec![
686            Message::user("initial request"),
687            Message::assistant("intermediate answer"),
688        ];
689        later_turn.prompt = Message::user("continue");
690
691        let first_key = codex_prompt_cache_key(&first).unwrap();
692        let later_key = codex_prompt_cache_key(&later_turn).unwrap();
693        assert_eq!(first_key, later_key);
694
695        let mut different_prefix = later_turn;
696        different_prefix.preamble = Some("different reviewer or project context".to_string());
697        let different_key = codex_prompt_cache_key(&different_prefix).unwrap();
698        assert_ne!(first_key, different_key);
699    }
700
701    #[test]
702    fn build_body_preserves_existing_additional_params() {
703        let completion = Completion {
704            model: "gpt-5.4".to_string(),
705            prompt: Message::user("hello"),
706            preamble: Some("sys".to_string()),
707            history: vec![],
708            tools: vec![],
709            tool_choice: None,
710            max_tokens: None,
711            additional_params: Some(json!({ "reasoning": { "effort": "low" } })),
712        };
713        let json = build_body_value(&completion).unwrap();
714        assert_eq!(json.get("store"), Some(&Value::Bool(false)));
715        assert!(json.get("reasoning").is_some());
716    }
717
718    #[test]
719    fn body_value_preserves_assistant_text_history() {
720        let completion = Completion {
721            model: "gpt-5.5".to_string(),
722            prompt: Message::user("continue"),
723            preamble: Some("sys".to_string()),
724            history: vec![Message::assistant("previous answer")],
725            tools: vec![],
726            tool_choice: None,
727            max_tokens: None,
728            additional_params: None,
729        };
730
731        let body = build_body_value(&completion).unwrap();
732        let assistant_message = body["input"]
733            .as_array()
734            .unwrap()
735            .iter()
736            .find(|item| item.get("role").and_then(Value::as_str) == Some("assistant"))
737            .unwrap();
738
739        assert_eq!(assistant_message["content"][0]["text"], "previous answer");
740    }
741
742    /// A tool id from another provider (an Alloy history replayed into Codex) is not a native
743    /// `fc_...` id, so it must be absent from `function_call` and pair by `call_id` alone.
744    #[test]
745    fn body_value_omits_foreign_function_call_item_id() {
746        let tool_id = "tool_5Xt5WpWtZ6Whah4Z2uZcZO34";
747        let call = ToolCall::new(
748            CallId::from_wire(tool_id),
749            ToolFunction::new(
750                ToolName::new("read_file").unwrap(),
751                json!({"path":"src/main.rs"}),
752            ),
753        );
754        let result = call.result(vec![ToolResultContent::text("ok")]);
755        let completion = Completion {
756            model: "gpt-5.5".to_string(),
757            prompt: Message::user("continue"),
758            preamble: Some("sys".to_string()),
759            history: vec![
760                Message::Assistant(AssistantMessage::new(vec![AssistantContent::ToolCall(
761                    call,
762                )])),
763                Message::User {
764                    content: vec![UserContent::ToolResult(result)],
765                },
766            ],
767            tools: vec![],
768            tool_choice: None,
769            max_tokens: None,
770            additional_params: None,
771        };
772
773        let body = build_body_value(&completion).unwrap();
774        let function_call = body["input"]
775            .as_array()
776            .unwrap()
777            .iter()
778            .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
779            .unwrap();
780
781        assert!(function_call.get("id").is_none());
782        assert_eq!(function_call["call_id"], tool_id);
783
784        // The paired tool output must carry the same call_id, or the backend cannot match them.
785        let function_call_output = body["input"]
786            .as_array()
787            .unwrap()
788            .iter()
789            .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output"))
790            .unwrap();
791        assert_eq!(function_call_output["call_id"], tool_id);
792    }
793
794    #[test]
795    fn resolve_auth_path_modes() {
796        // absolute CODEX_HOME wins
797        let p = resolve_auth_path(Some("/custom/codex"), Some(PathBuf::from("/home/u"))).unwrap();
798        assert_eq!(p, PathBuf::from("/custom/codex/auth.json"));
799        // relative CODEX_HOME errors
800        assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
801        // empty CODEX_HOME falls back to home
802        let p = resolve_auth_path(Some("  "), Some(PathBuf::from("/home/u"))).unwrap();
803        assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
804        // unset falls back to home
805        let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
806        assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
807        // no home and no CODEX_HOME errors
808        assert!(resolve_auth_path(None, None).is_err());
809    }
810
811    async fn codex_reply(sse: String) -> Result<CompletionResponse> {
812        use tokio::io::{AsyncReadExt, AsyncWriteExt};
813        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
814        let base_url = format!("http://{}", listener.local_addr()?);
815        let server = tokio::spawn(async move {
816            let (mut socket, _) = listener.accept().await.unwrap();
817            let mut request = Vec::new();
818            loop {
819                assert_ne!(socket.read_buf(&mut request).await.unwrap(), 0);
820                if let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") {
821                    let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
822                    let length: usize = headers
823                        .lines()
824                        .find_map(|line| line.strip_prefix("content-length: "))
825                        .unwrap()
826                        .parse()
827                        .unwrap();
828                    if request.len() >= end + 4 + length {
829                        break;
830                    }
831                }
832            }
833            let response = format!(
834                "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{sse}",
835                sse.len()
836            );
837            socket.write_all(response.as_bytes()).await.unwrap();
838        });
839        let mut wire = codex_wire("gpt-5.4", "unused", None);
840        wire.provider = wire.provider.with_base_url(base_url);
841        let model =
842            rig_core::Model::new(wire, rig_reqwest::ReqwestClient::from(build_http_client()?));
843        let response = model
844            .call(CompletionRequest::new("hello").preamble("sys"))
845            .await;
846        server.await?;
847        Ok(CompletionResponse::from_rig(response?, "gpt-5.4".into()))
848    }
849
850    #[tokio::test]
851    async fn parse_sse_accumulates_output_items_with_empty_completed() {
852        // mirrors the store:false stream: items arrive in output_item.done; completed has empty output
853        let item = json!({
854            "type": "message",
855            "id": "msg_1",
856            "role": "assistant",
857            "status": "completed",
858            "content": [{ "type": "output_text", "text": "pong" }]
859        });
860        let completed = json!({
861            "id": "resp_1",
862            "object": "response",
863            "created_at": 1,
864            "status": "completed",
865            "model": "gpt-5.4",
866            "output": [],
867            "usage": {
868                "input_tokens": 5000,
869                "input_tokens_details": { "cached_tokens": 4800 },
870                "output_tokens": 1,
871                "output_tokens_details": { "reasoning_tokens": 0 },
872                "total_tokens": 5001
873            }
874        });
875        let sse = format!(
876            "data: {}\n\ndata: {}\n\ndata: [DONE]\n",
877            json!({ "type": "response.output_item.done", "item": item }),
878            json!({ "type": "response.completed", "response": completed })
879        );
880        let resp = codex_reply(sse).await.unwrap();
881        assert_eq!(resp.text(), "pong");
882        assert_eq!(resp.finish_reason, crate::llm::FinishReason::Stop);
883        // cache reads are inside `input_tokens` here, so the prompt must not be inflated by them
884        assert_eq!(resp.usage.input_tokens, 5000);
885        assert_eq!(resp.usage.cached_input_tokens, 4800);
886        assert_eq!(resp.usage.total_tokens, 5001);
887    }
888
889    #[tokio::test]
890    async fn parse_sse_surfaces_error_events() {
891        let sse = format!(
892            "data: {}\n\n",
893            json!({ "type": "response.failed", "error": { "message": "boom" } })
894        );
895        assert!(codex_reply(sse).await.is_err());
896    }
897
898    #[tokio::test]
899    async fn parse_sse_preserves_codes_from_large_error_events() {
900        let sse = format!(
901            "data: {}\n\n",
902            json!({
903                "type": "response.failed",
904                "error": {
905                    "type": "usage_limit_reached",
906                    "message": "quota exhausted",
907                    "diagnostic": "x".repeat(4_000),
908                }
909            })
910        );
911        let err = codex_reply(sse).await.unwrap_err();
912        assert!(crate::llm::provider_error_has_code(
913            &err,
914            &["usage_limit_reached"]
915        ));
916    }
917
918    fn usage_json() -> Value {
919        json!({
920            "input_tokens": 5,
921            "input_tokens_details": { "cached_tokens": 0 },
922            "output_tokens": 1,
923            "output_tokens_details": { "reasoning_tokens": 0 },
924            "total_tokens": 6
925        })
926    }
927
928    #[tokio::test]
929    async fn parse_sse_handles_incomplete_as_max_tokens() {
930        // model stopped early on the output cap: terminal event is `response.incomplete`
931        let item = json!({
932            "type": "message", "id": "m", "role": "assistant", "status": "incomplete",
933            "content": [{ "type": "output_text", "text": "partial" }]
934        });
935        let response = json!({
936            "id": "r", "object": "response", "created_at": 1, "status": "incomplete",
937            "model": "gpt-5.4", "output": [],
938            "incomplete_details": { "reason": "max_output_tokens" },
939            "usage": usage_json()
940        });
941        let sse = format!(
942            "data: {}\n\ndata: {}\n\n",
943            json!({ "type": "response.output_item.done", "item": item }),
944            json!({ "type": "response.incomplete", "response": response })
945        );
946        let resp = codex_reply(sse).await.unwrap();
947        assert_eq!(resp.text(), "partial");
948        assert_eq!(resp.finish_reason, crate::llm::FinishReason::MaxTokens);
949    }
950
951    #[tokio::test]
952    async fn parse_sse_rejoins_multiline_data_fields() {
953        // a single event whose JSON payload is split across two `data:` lines (valid SSE);
954        // splitting after a `,` keeps each half from being valid alone but the `\n`-join valid.
955        let completed = json!({
956            "type": "response.completed",
957            "response": {
958                "id": "r", "object": "response", "created_at": 1, "status": "completed",
959                "model": "gpt-5.4",
960                "output": [{
961                    "type": "message", "id": "m", "role": "assistant", "status": "completed",
962                    "content": [{ "type": "output_text", "text": "hi" }]
963                }],
964                "usage": usage_json()
965            }
966        })
967        .to_string();
968        let comma = completed.find(',').unwrap();
969        let (head, tail) = completed.split_at(comma);
970        let sse = format!("data: {head}\ndata: {tail}\n\n");
971        let resp = codex_reply(sse).await.unwrap();
972        assert_eq!(resp.text(), "hi");
973    }
974
975    #[test]
976    fn is_rotation_4xx_excludes_429_and_5xx() {
977        let mk = |status| {
978            eyre::Report::new(ProviderError::from_http_response(
979                reqwest::StatusCode::from_u16(status).unwrap(),
980                r#"{"error":"test"}"#,
981            ))
982        };
983        assert!(is_rotation_4xx(&mk(400)));
984        assert!(is_rotation_4xx(&mk(401)));
985        // 429 is transient — must NOT trigger the reload-from-disk rotation path
986        assert!(!is_rotation_4xx(&mk(429)));
987        assert!(!is_rotation_4xx(&mk(500)));
988    }
989}