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    config.identity = Some(CallerIdentity {
425        originator: ORIGINATOR.into(),
426        user_agent: user_agent(),
427    });
428    config.account_id = account_id.map(str::to_owned);
429    Responses::new(config, model)
430}
431
432fn codex_request(completion: &Completion) -> Result<CompletionRequest> {
433    eyre::ensure!(
434        completion
435            .preamble
436            .as_deref()
437            .is_some_and(|s| !s.trim().is_empty()),
438        "Codex auth requires a system prompt: this completion had no `instructions`"
439    );
440    let mut request = CompletionRequest::from(completion.clone());
441    request.max_tokens = None;
442    request.options.cache_key = Some(codex_prompt_cache_key(completion)?);
443    Ok(request)
444}
445
446/// Stable, opaque cache-routing key for the prefix that remains fixed during one conversation.
447/// OpenAI still matches the actual prompt prefix; this only keeps requests with the same
448/// model/system/tool family routed together. Including the project-aware system prompt naturally
449/// partitions unrelated reviews instead of concentrating all traffic on one hot key.
450fn codex_prompt_cache_key(completion: &Completion) -> Result<String> {
451    fn hash_part(hasher: &mut Sha256, bytes: &[u8]) {
452        hasher.update((bytes.len() as u64).to_be_bytes());
453        hasher.update(bytes);
454    }
455
456    let mut hasher = Sha256::new();
457    hash_part(&mut hasher, completion.model.as_bytes());
458    hash_part(
459        &mut hasher,
460        completion
461            .preamble
462            .as_deref()
463            .unwrap_or_default()
464            .as_bytes(),
465    );
466    let tools = serde_json::to_vec(&completion.tools)
467        .wrap_err("serializing Codex tools for prompt cache routing")?;
468    hash_part(&mut hasher, &tools);
469    let digest = hasher.finalize();
470    let suffix = digest[..16]
471        .iter()
472        .map(|byte| format!("{byte:02x}"))
473        .collect::<String>();
474    Ok(format!("nitpicker-{suffix}"))
475}
476
477/// A 4xx-other-than-429 status anywhere in the error chain — used to decide whether a failed token
478/// refresh warrants reloading a rotated refresh token from disk. 429 is excluded: a rate-limited
479/// refresh is transient and reloading `auth.json` can't fix it, so it should bubble up to the outer
480/// retry/backoff instead of immediately firing a second refresh.
481fn is_rotation_4xx(err: &eyre::Report) -> bool {
482    provider_http_status(err).is_some_and(|status| (400..500).contains(&status) && status != 429)
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488    use rig_core::completion::message::{
489        AssistantContent, AssistantMessage, CallId, Message, ToolCall, ToolFunction, ToolName,
490        ToolResultContent, UserContent,
491    };
492    use serde_json::json;
493
494    /// Build an unsigned JWT (`alg: none`) with the given claims — enough to exercise our
495    /// claims-reading code, which never verifies the signature.
496    fn jwt(claims: Value) -> String {
497        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
498        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
499        format!("{header}.{payload}.sig")
500    }
501
502    #[test]
503    fn account_id_resolution_order() {
504        assert_eq!(
505            account_id_from_claims(&json!({ "chatgpt_account_id": "root" })).as_deref(),
506            Some("root")
507        );
508        assert_eq!(
509            account_id_from_claims(
510                &json!({ "https://api.openai.com/auth": { "chatgpt_account_id": "nested" } })
511            )
512            .as_deref(),
513            Some("nested")
514        );
515        // root preferred over nested
516        assert_eq!(
517            account_id_from_claims(&json!({
518                "chatgpt_account_id": "root",
519                "https://api.openai.com/auth": { "chatgpt_account_id": "nested" }
520            }))
521            .as_deref(),
522            Some("root")
523        );
524        // organizations fallback
525        assert_eq!(
526            account_id_from_claims(
527                &json!({ "organizations": [{ "id": "org-1" }, { "id": "org-2" }] })
528            )
529            .as_deref(),
530            Some("org-1")
531        );
532        assert_eq!(account_id_from_claims(&json!({ "email": "x@y.z" })), None);
533    }
534
535    #[test]
536    fn account_id_prefers_id_token_then_access_token() {
537        let id_token = jwt(json!({ "chatgpt_account_id": "from-id" }));
538        let access = jwt(json!({ "chatgpt_account_id": "from-access" }));
539        assert_eq!(
540            account_id_from_tokens(Some(&id_token), &access).as_deref(),
541            Some("from-id")
542        );
543        let id_token_no_acct = jwt(json!({ "email": "x@y.z" }));
544        assert_eq!(
545            account_id_from_tokens(Some(&id_token_no_acct), &access).as_deref(),
546            Some("from-access")
547        );
548    }
549
550    #[test]
551    fn expiry_from_exp_claim_and_missing() {
552        let with_exp = jwt(json!({ "exp": 4_000_000_000u64 }));
553        assert_eq!(
554            expiry_from_access_token(&with_exp),
555            UNIX_EPOCH + Duration::from_secs(4_000_000_000)
556        );
557        // missing exp => already expired (UNIX_EPOCH) so first use refreshes
558        assert_eq!(expiry_from_access_token(&jwt(json!({}))), UNIX_EPOCH);
559        assert_eq!(expiry_from_access_token("not-a-jwt"), UNIX_EPOCH);
560    }
561
562    #[test]
563    fn parse_tokens_full_and_derived_account_id() {
564        let access = jwt(json!({ "exp": 4_000_000_000u64 }));
565        // explicit account_id wins
566        let raw = json!({
567            "tokens": { "access_token": access, "refresh_token": "rt", "account_id": "acct-explicit" }
568        })
569        .to_string();
570        let t = parse_tokens(&raw, "test").unwrap();
571        assert_eq!(t.account_id.as_deref(), Some("acct-explicit"));
572        assert!(!t.is_expired());
573
574        // derived from id_token when account_id absent
575        let id_token = jwt(json!({ "chatgpt_account_id": "acct-derived" }));
576        let raw = json!({
577            "tokens": { "access_token": access, "refresh_token": "rt", "id_token": id_token }
578        })
579        .to_string();
580        let t = parse_tokens(&raw, "test").unwrap();
581        assert_eq!(t.account_id.as_deref(), Some("acct-derived"));
582    }
583
584    #[test]
585    fn parse_tokens_rejects_api_key_mode_and_missing_fields() {
586        // API-key mode: no `tokens` object
587        let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
588        assert!(parse_tokens(&raw, "test").is_err());
589        // tokens present but no access_token
590        let raw = json!({ "tokens": { "refresh_token": "rt" } }).to_string();
591        assert!(parse_tokens(&raw, "test").is_err());
592    }
593
594    fn build_body_value(completion: &Completion) -> Result<Value> {
595        use rig_core::wire::{Body, Mode, Wire};
596        let wire = codex_wire(&completion.model, "unused", None);
597        let encoded = wire.encode(codex_request(completion)?, Mode::Unary)?;
598        let Body::Bytes(bytes) = encoded.request.into_body() else {
599            panic!("expected a JSON body")
600        };
601        Ok(serde_json::from_slice(&bytes)?)
602    }
603
604    #[test]
605    fn build_body_applies_codex_quirks() {
606        let completion = Completion {
607            model: "gpt-5.4".to_string(),
608            prompt: Message::user("hello"),
609            preamble: Some("You are a reviewer.".to_string()),
610            history: vec![],
611            tools: vec![],
612            tool_choice: None,
613            max_tokens: Some(4096),
614            additional_params: None,
615        };
616        let json = build_body_value(&completion).unwrap();
617        assert_eq!(json["instructions"], "You are a reviewer.");
618        assert_eq!(json["stream"], true);
619        assert!(json.get("max_output_tokens").is_none());
620        assert_eq!(json.get("store"), Some(&Value::Bool(false)));
621        assert!(
622            json.get("prompt_cache_key")
623                .and_then(Value::as_str)
624                .is_some_and(|key| key.starts_with("nitpicker-")),
625            "Codex requests must carry a stable prompt cache routing key"
626        );
627        // encrypted reasoning content is requested so reasoning items survive store:false round-trips
628        assert_eq!(
629            json.get("include").and_then(Value::as_array),
630            Some(&vec![Value::String(
631                "reasoning.encrypted_content".to_string()
632            )]),
633            "must request reasoning.encrypted_content to avoid bare rs_ id 404s"
634        );
635        // instructions is top-level, not folded into an input system item
636        let has_system_input = json
637            .get("input")
638            .and_then(Value::as_array)
639            .map(|items| {
640                items
641                    .iter()
642                    .any(|i| i.get("role").and_then(Value::as_str) == Some("system"))
643            })
644            .unwrap_or(false);
645        assert!(
646            !has_system_input,
647            "system must be in `instructions`, not `input`"
648        );
649    }
650
651    #[test]
652    fn build_body_requires_a_system_prompt() {
653        let completion = Completion {
654            model: "gpt-5.4".to_string(),
655            prompt: Message::user("hello"),
656            preamble: None,
657            history: vec![],
658            tools: vec![],
659            tool_choice: None,
660            max_tokens: None,
661            additional_params: None,
662        };
663        assert!(build_body_value(&completion).is_err());
664    }
665
666    #[test]
667    fn prompt_cache_key_tracks_the_stable_prefix_not_the_conversation_tail() {
668        let first = Completion {
669            model: "gpt-5.4".to_string(),
670            prompt: Message::user("initial request"),
671            preamble: Some("stable reviewer and project context".to_string()),
672            history: vec![],
673            tools: vec![rig_core::completion::ToolDefinition {
674                name: ToolName::new("read_file").unwrap(),
675                annotations: Default::default(),
676                description: "Read a file".to_string(),
677                parameters: json!({
678                    "type": "object",
679                    "properties": { "path": { "type": "string" } }
680                }),
681            }],
682            tool_choice: None,
683            max_tokens: None,
684            additional_params: None,
685        };
686        let mut later_turn = first.clone();
687        later_turn.history = vec![
688            Message::user("initial request"),
689            Message::assistant("intermediate answer"),
690        ];
691        later_turn.prompt = Message::user("continue");
692
693        let first_key = codex_prompt_cache_key(&first).unwrap();
694        let later_key = codex_prompt_cache_key(&later_turn).unwrap();
695        assert_eq!(first_key, later_key);
696
697        let mut different_prefix = later_turn;
698        different_prefix.preamble = Some("different reviewer or project context".to_string());
699        let different_key = codex_prompt_cache_key(&different_prefix).unwrap();
700        assert_ne!(first_key, different_key);
701    }
702
703    #[test]
704    fn build_body_preserves_existing_additional_params() {
705        let completion = Completion {
706            model: "gpt-5.4".to_string(),
707            prompt: Message::user("hello"),
708            preamble: Some("sys".to_string()),
709            history: vec![],
710            tools: vec![],
711            tool_choice: None,
712            max_tokens: None,
713            additional_params: Some(json!({ "reasoning": { "effort": "low" } })),
714        };
715        let json = build_body_value(&completion).unwrap();
716        assert_eq!(json.get("store"), Some(&Value::Bool(false)));
717        assert!(json.get("reasoning").is_some());
718    }
719
720    #[test]
721    fn body_value_preserves_assistant_text_history() {
722        let completion = Completion {
723            model: "gpt-5.5".to_string(),
724            prompt: Message::user("continue"),
725            preamble: Some("sys".to_string()),
726            history: vec![Message::assistant("previous answer")],
727            tools: vec![],
728            tool_choice: None,
729            max_tokens: None,
730            additional_params: None,
731        };
732
733        let body = build_body_value(&completion).unwrap();
734        let assistant_message = body["input"]
735            .as_array()
736            .unwrap()
737            .iter()
738            .find(|item| item.get("role").and_then(Value::as_str) == Some("assistant"))
739            .unwrap();
740
741        assert_eq!(assistant_message["content"][0]["text"], "previous answer");
742    }
743
744    /// A tool id from another provider (an Alloy history replayed into Codex) is not a native
745    /// `fc_...` id, so it must be absent from `function_call` and pair by `call_id` alone.
746    #[test]
747    fn body_value_omits_foreign_function_call_item_id() {
748        let tool_id = "tool_5Xt5WpWtZ6Whah4Z2uZcZO34";
749        let call = ToolCall::new(
750            CallId::from_wire(tool_id),
751            ToolFunction::new(
752                ToolName::new("read_file").unwrap(),
753                json!({"path":"src/main.rs"}),
754            ),
755        );
756        let result = call.result(vec![ToolResultContent::text("ok")]);
757        let completion = Completion {
758            model: "gpt-5.5".to_string(),
759            prompt: Message::user("continue"),
760            preamble: Some("sys".to_string()),
761            history: vec![
762                Message::Assistant(AssistantMessage::new(vec![AssistantContent::ToolCall(
763                    call,
764                )])),
765                Message::User {
766                    content: vec![UserContent::ToolResult(result)],
767                },
768            ],
769            tools: vec![],
770            tool_choice: None,
771            max_tokens: None,
772            additional_params: None,
773        };
774
775        let body = build_body_value(&completion).unwrap();
776        let function_call = body["input"]
777            .as_array()
778            .unwrap()
779            .iter()
780            .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
781            .unwrap();
782
783        assert!(function_call.get("id").is_none());
784        assert_eq!(function_call["call_id"], tool_id);
785
786        // The paired tool output must carry the same call_id, or the backend cannot match them.
787        let function_call_output = body["input"]
788            .as_array()
789            .unwrap()
790            .iter()
791            .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output"))
792            .unwrap();
793        assert_eq!(function_call_output["call_id"], tool_id);
794    }
795
796    #[test]
797    fn resolve_auth_path_modes() {
798        // absolute CODEX_HOME wins
799        let p = resolve_auth_path(Some("/custom/codex"), Some(PathBuf::from("/home/u"))).unwrap();
800        assert_eq!(p, PathBuf::from("/custom/codex/auth.json"));
801        // relative CODEX_HOME errors
802        assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
803        // empty CODEX_HOME falls back to home
804        let p = resolve_auth_path(Some("  "), Some(PathBuf::from("/home/u"))).unwrap();
805        assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
806        // unset falls back to home
807        let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
808        assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
809        // no home and no CODEX_HOME errors
810        assert!(resolve_auth_path(None, None).is_err());
811    }
812
813    async fn codex_reply(sse: String) -> Result<CompletionResponse> {
814        use tokio::io::{AsyncReadExt, AsyncWriteExt};
815        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
816        let base_url = format!("http://{}", listener.local_addr()?);
817        let server = tokio::spawn(async move {
818            let (mut socket, _) = listener.accept().await.unwrap();
819            let mut request = Vec::new();
820            loop {
821                assert_ne!(socket.read_buf(&mut request).await.unwrap(), 0);
822                if let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") {
823                    let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
824                    let length: usize = headers
825                        .lines()
826                        .find_map(|line| line.strip_prefix("content-length: "))
827                        .unwrap()
828                        .parse()
829                        .unwrap();
830                    if request.len() >= end + 4 + length {
831                        break;
832                    }
833                }
834            }
835            let response = format!(
836                "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{sse}",
837                sse.len()
838            );
839            socket.write_all(response.as_bytes()).await.unwrap();
840        });
841        let mut wire = codex_wire("gpt-5.4", "unused", None);
842        wire.provider = wire.provider.with_base_url(base_url);
843        let model =
844            rig_core::Model::new(wire, rig_reqwest::ReqwestClient::from(build_http_client()?));
845        let response = model
846            .call(CompletionRequest::new("hello").preamble("sys"))
847            .await;
848        server.await?;
849        Ok(CompletionResponse::from_rig(response?, "gpt-5.4".into()))
850    }
851
852    #[tokio::test]
853    async fn parse_sse_accumulates_output_items_with_empty_completed() {
854        // mirrors the store:false stream: items arrive in output_item.done; completed has empty output
855        let item = json!({
856            "type": "message",
857            "id": "msg_1",
858            "role": "assistant",
859            "status": "completed",
860            "content": [{ "type": "output_text", "text": "pong" }]
861        });
862        let completed = json!({
863            "id": "resp_1",
864            "object": "response",
865            "created_at": 1,
866            "status": "completed",
867            "model": "gpt-5.4",
868            "output": [],
869            "usage": {
870                "input_tokens": 5000,
871                "input_tokens_details": { "cached_tokens": 4800 },
872                "output_tokens": 1,
873                "output_tokens_details": { "reasoning_tokens": 0 },
874                "total_tokens": 5001
875            }
876        });
877        let sse = format!(
878            "data: {}\n\ndata: {}\n\ndata: [DONE]\n",
879            json!({ "type": "response.output_item.done", "item": item }),
880            json!({ "type": "response.completed", "response": completed })
881        );
882        let resp = codex_reply(sse).await.unwrap();
883        assert_eq!(resp.text(), "pong");
884        assert_eq!(resp.finish_reason, crate::llm::FinishReason::Stop);
885        // cache reads are inside `input_tokens` here, so the prompt must not be inflated by them
886        assert_eq!(resp.usage.input_tokens, 5000);
887        assert_eq!(resp.usage.cached_input_tokens, 4800);
888        assert_eq!(resp.usage.total_tokens, 5001);
889    }
890
891    #[tokio::test]
892    async fn parse_sse_surfaces_error_events() {
893        let sse = format!(
894            "data: {}\n\n",
895            json!({ "type": "response.failed", "error": { "message": "boom" } })
896        );
897        assert!(codex_reply(sse).await.is_err());
898    }
899
900    #[tokio::test]
901    async fn parse_sse_preserves_codes_from_large_error_events() {
902        let sse = format!(
903            "data: {}\n\n",
904            json!({
905                "type": "response.failed",
906                "error": {
907                    "type": "usage_limit_reached",
908                    "message": "quota exhausted",
909                    "diagnostic": "x".repeat(4_000),
910                }
911            })
912        );
913        let err = codex_reply(sse).await.unwrap_err();
914        assert!(crate::llm::provider_error_has_code(
915            &err,
916            &["usage_limit_reached"]
917        ));
918    }
919
920    fn usage_json() -> Value {
921        json!({
922            "input_tokens": 5,
923            "input_tokens_details": { "cached_tokens": 0 },
924            "output_tokens": 1,
925            "output_tokens_details": { "reasoning_tokens": 0 },
926            "total_tokens": 6
927        })
928    }
929
930    #[tokio::test]
931    async fn parse_sse_handles_incomplete_as_max_tokens() {
932        // model stopped early on the output cap: terminal event is `response.incomplete`
933        let item = json!({
934            "type": "message", "id": "m", "role": "assistant", "status": "incomplete",
935            "content": [{ "type": "output_text", "text": "partial" }]
936        });
937        let response = json!({
938            "id": "r", "object": "response", "created_at": 1, "status": "incomplete",
939            "model": "gpt-5.4", "output": [],
940            "incomplete_details": { "reason": "max_output_tokens" },
941            "usage": usage_json()
942        });
943        let sse = format!(
944            "data: {}\n\ndata: {}\n\n",
945            json!({ "type": "response.output_item.done", "item": item }),
946            json!({ "type": "response.incomplete", "response": response })
947        );
948        let resp = codex_reply(sse).await.unwrap();
949        assert_eq!(resp.text(), "partial");
950        assert_eq!(resp.finish_reason, crate::llm::FinishReason::MaxTokens);
951    }
952
953    #[tokio::test]
954    async fn parse_sse_rejoins_multiline_data_fields() {
955        // a single event whose JSON payload is split across two `data:` lines (valid SSE);
956        // splitting after a `,` keeps each half from being valid alone but the `\n`-join valid.
957        let completed = json!({
958            "type": "response.completed",
959            "response": {
960                "id": "r", "object": "response", "created_at": 1, "status": "completed",
961                "model": "gpt-5.4",
962                "output": [{
963                    "type": "message", "id": "m", "role": "assistant", "status": "completed",
964                    "content": [{ "type": "output_text", "text": "hi" }]
965                }],
966                "usage": usage_json()
967            }
968        })
969        .to_string();
970        let comma = completed.find(',').unwrap();
971        let (head, tail) = completed.split_at(comma);
972        let sse = format!("data: {head}\ndata: {tail}\n\n");
973        let resp = codex_reply(sse).await.unwrap();
974        assert_eq!(resp.text(), "hi");
975    }
976
977    #[test]
978    fn is_rotation_4xx_excludes_429_and_5xx() {
979        let mk = |status| {
980            eyre::Report::new(ProviderError::from_http_response(
981                reqwest::StatusCode::from_u16(status).unwrap(),
982                r#"{"error":"test"}"#,
983            ))
984        };
985        assert!(is_rotation_4xx(&mk(400)));
986        assert!(is_rotation_4xx(&mk(401)));
987        // 429 is transient — must NOT trigger the reload-from-disk rotation path
988        assert!(!is_rotation_4xx(&mk(429)));
989        assert!(!is_rotation_4xx(&mk(500)));
990    }
991}