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::completion::CompletionError;
19use rig_core::completion::message::{AssistantContent, UserContent};
20use rig_core::providers::openai::responses_api::{
21    CompletionRequest as ResponsesBody, CompletionResponse as ResponsesResp, Include,
22};
23use serde_json::Value;
24use sha2::{Digest, Sha256};
25use tokio::sync::Mutex;
26
27use crate::llm::{
28    CacheAccounting, Completion, CompletionResponse, FinishReason, LLMClient, LLMClientDyn,
29    TokenUsage, WithRetryExt, 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";
35/// rig appends the `/responses` path; this is the Codex subscription base.
36const CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
37const ORIGINATOR: &str = "nitpicker";
38/// Refresh this long before the token's stated expiry to avoid racing the deadline.
39const EXPIRY_SKEW: Duration = Duration::from_secs(60);
40/// Bound the token refresh so a stalled auth request can't pin the token mutex (and thus every
41/// concurrent completion sharing the client) indefinitely.
42const REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
43/// Give up establishing a connection after this long (dead host / no route).
44const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
45/// Abort a stalled response: if no bytes arrive for this long, the connection is hung. This is an
46/// idle (per-read) timeout, not a total cap, so a legitimately long streaming turn is not aborted
47/// as long as it keeps making progress — but a hung completion can no longer pin an
48/// `llm_semaphore` permit indefinitely.
49const READ_TIMEOUT: Duration = Duration::from_secs(120);
50
51/// Shared reqwest client for the Codex endpoints, configured so a hung connection can't pin a
52/// shared concurrency permit forever (`reqwest::Client::new()` sets no timeouts).
53fn build_http_client() -> Result<reqwest::Client> {
54    reqwest::Client::builder()
55        .connect_timeout(CONNECT_TIMEOUT)
56        .read_timeout(READ_TIMEOUT)
57        .build()
58        .wrap_err("building Codex HTTP client")
59}
60
61fn user_agent() -> String {
62    format!(
63        "nitpicker/{} ({}; {})",
64        env!("CARGO_PKG_VERSION"),
65        std::env::consts::OS,
66        std::env::consts::ARCH
67    )
68}
69
70// ============================================================================
71// JWT claim parsing (no signature verification — we only read public claims)
72// ============================================================================
73
74fn decode_jwt_claims(token: &str) -> Option<Value> {
75    let payload = token.split('.').nth(1)?;
76    let bytes = URL_SAFE_NO_PAD.decode(payload).ok()?;
77    serde_json::from_slice(&bytes).ok()
78}
79
80/// Mirror the Codex CLI / opencode account-id resolution order.
81fn account_id_from_claims(claims: &Value) -> Option<String> {
82    let direct = claims.get("chatgpt_account_id").and_then(Value::as_str);
83    let nested = claims
84        .get("https://api.openai.com/auth")
85        .and_then(|a| a.get("chatgpt_account_id"))
86        .and_then(Value::as_str);
87    let org = claims
88        .get("organizations")
89        .and_then(Value::as_array)
90        .and_then(|orgs| orgs.first())
91        .and_then(|o| o.get("id"))
92        .and_then(Value::as_str);
93    direct.or(nested).or(org).map(str::to_string)
94}
95
96fn account_id_from_tokens(id_token: Option<&str>, access_token: &str) -> Option<String> {
97    id_token
98        .and_then(decode_jwt_claims)
99        .as_ref()
100        .and_then(account_id_from_claims)
101        .or_else(|| {
102            decode_jwt_claims(access_token)
103                .as_ref()
104                .and_then(account_id_from_claims)
105        })
106}
107
108/// Expiry from the access token's `exp` claim. Missing/unparseable → `UNIX_EPOCH` (already expired),
109/// forcing a refresh on first use; that's not a thrash because the refresh response carries an
110/// authoritative `expires_in`.
111fn expiry_from_access_token(access_token: &str) -> SystemTime {
112    decode_jwt_claims(access_token)
113        .and_then(|c| c.get("exp").and_then(Value::as_u64))
114        // checked_add: a garbage/huge `exp` would otherwise overflow SystemTime and panic; treat
115        // overflow as already-expired (forces a refresh) rather than aborting the process.
116        .and_then(|exp| UNIX_EPOCH.checked_add(Duration::from_secs(exp)))
117        .unwrap_or(UNIX_EPOCH)
118}
119
120// ============================================================================
121// Token store (~/.codex/auth.json)
122// ============================================================================
123
124#[derive(Clone)]
125struct CodexTokens {
126    access_token: String,
127    refresh_token: String,
128    account_id: Option<String>,
129    expires_at: SystemTime,
130}
131
132impl CodexTokens {
133    fn is_expired(&self) -> bool {
134        self.expires_at <= SystemTime::now() + EXPIRY_SKEW
135    }
136}
137
138/// `$CODEX_HOME/auth.json` (when CODEX_HOME is set, non-empty, absolute) else `~/.codex/auth.json`.
139fn auth_path() -> Result<PathBuf> {
140    resolve_auth_path(
141        std::env::var("CODEX_HOME").ok().as_deref(),
142        dirs::home_dir(),
143    )
144}
145
146/// Pure resolution split from env/dirs lookup so it can be unit-tested.
147fn resolve_auth_path(codex_home: Option<&str>, home_dir: Option<PathBuf>) -> Result<PathBuf> {
148    if let Some(home) = codex_home {
149        let trimmed = home.trim();
150        if !trimmed.is_empty() {
151            let path = Path::new(trimmed);
152            if path.is_absolute() {
153                return Ok(path.join("auth.json"));
154            }
155            eyre::bail!("CODEX_HOME must be an absolute path, got \"{home}\"");
156        }
157    }
158    let home =
159        home_dir.ok_or_else(|| eyre::eyre!("cannot resolve home directory (set CODEX_HOME)"))?;
160    Ok(home.join(".codex").join("auth.json"))
161}
162
163fn load_tokens(path: &Path) -> Result<CodexTokens> {
164    let raw = std::fs::read_to_string(path).wrap_err_with(|| {
165        format!(
166            "cannot read {} — run `codex login` with a ChatGPT subscription first",
167            path.display()
168        )
169    })?;
170    parse_tokens(&raw, &path.display().to_string())
171}
172
173/// True when a usable Codex CLI OAuth token file is present (CODEX_HOME or `~/.codex/auth.json`).
174/// Used by `init` detection; reuses the same parse the client does, so API-key-mode files (which
175/// the client rejects) don't surface as a codex provider.
176pub fn auth_available() -> bool {
177    auth_path().and_then(|p| load_tokens(&p)).is_ok()
178}
179
180/// Parse a Codex `auth.json` payload. Split from IO so it is unit-testable without a real file.
181fn parse_tokens(raw: &str, source: &str) -> Result<CodexTokens> {
182    let v: Value =
183        serde_json::from_str(raw).wrap_err_with(|| format!("invalid JSON in {source}"))?;
184    let tokens = v.get("tokens").ok_or_else(|| {
185        eyre::eyre!(
186            "no ChatGPT subscription tokens in {source} — run `codex login` (API-key mode is not supported here)"
187        )
188    })?;
189    let access_token = tokens
190        .get("access_token")
191        .and_then(Value::as_str)
192        .filter(|s| !s.is_empty())
193        .ok_or_else(|| eyre::eyre!("no access_token in {source}"))?
194        .to_string();
195    let refresh_token = tokens
196        .get("refresh_token")
197        .and_then(Value::as_str)
198        .filter(|s| !s.is_empty())
199        .ok_or_else(|| eyre::eyre!("no refresh_token in {source}"))?
200        .to_string();
201    let account_id = tokens
202        .get("account_id")
203        .and_then(Value::as_str)
204        .filter(|s| !s.is_empty())
205        .map(str::to_string)
206        .or_else(|| {
207            account_id_from_tokens(
208                tokens.get("id_token").and_then(Value::as_str),
209                &access_token,
210            )
211        });
212    let expires_at = expiry_from_access_token(&access_token);
213    Ok(CodexTokens {
214        access_token,
215        refresh_token,
216        account_id,
217        expires_at,
218    })
219}
220
221#[derive(serde::Deserialize)]
222struct RefreshResponse {
223    access_token: String,
224    refresh_token: Option<String>,
225    id_token: Option<String>,
226    expires_in: Option<u64>,
227}
228
229/// Exchange a refresh token for a fresh access token. Expiry comes from the response's
230/// `expires_in` (authoritative — a token without an `exp` claim never thrashes the cache).
231async fn refresh_tokens(
232    http: &reqwest::Client,
233    refresh_token: &str,
234    prev_account_id: Option<&str>,
235) -> Result<CodexTokens> {
236    let resp = http
237        .post(TOKEN_URL)
238        .timeout(REFRESH_TIMEOUT)
239        .form(&[
240            ("grant_type", "refresh_token"),
241            ("refresh_token", refresh_token),
242            ("client_id", CLIENT_ID),
243        ])
244        .send()
245        .await
246        .wrap_err("Codex token refresh request failed")?;
247    let status = resp.status();
248    let body = resp.text().await.unwrap_or_default();
249    if !status.is_success() {
250        return Err(eyre::Report::new(CompletionError::from_http_response(
251            status,
252            compact_provider_error_body(&body, 1000),
253        )))
254        .wrap_err("Codex token refresh failed");
255    }
256    let parsed: RefreshResponse =
257        serde_json::from_str(&body).wrap_err("parsing Codex token refresh response")?;
258    // prefer the authoritative `expires_in`; if absent, derive from the new access token's JWT `exp`
259    // rather than guessing a fixed lifetime.
260    let expires_at = match parsed.expires_in {
261        // checked_add guards against an absurd `expires_in` overflowing SystemTime (panic);
262        // on overflow fall back to the access token's own `exp`.
263        Some(secs) => SystemTime::now()
264            .checked_add(Duration::from_secs(secs))
265            .unwrap_or_else(|| expiry_from_access_token(&parsed.access_token)),
266        None => expiry_from_access_token(&parsed.access_token),
267    };
268    let account_id = prev_account_id
269        .map(str::to_string)
270        .or_else(|| account_id_from_tokens(parsed.id_token.as_deref(), &parsed.access_token));
271    Ok(CodexTokens {
272        access_token: parsed.access_token,
273        refresh_token: parsed
274            .refresh_token
275            .unwrap_or_else(|| refresh_token.to_string()),
276        account_id,
277        expires_at,
278    })
279}
280
281// ============================================================================
282// Client
283// ============================================================================
284
285pub struct CodexClient {
286    http: reqwest::Client,
287    auth_path: PathBuf,
288    tokens: Mutex<CodexTokens>,
289}
290
291impl CodexClient {
292    /// Load tokens from `~/.codex/auth.json` (or `$CODEX_HOME`) and build the client.
293    pub fn new() -> Result<Self> {
294        let path = auth_path()?;
295        let tokens = load_tokens(&path)?;
296        Ok(Self {
297            http: build_http_client()?,
298            auth_path: path,
299            tokens: Mutex::new(tokens),
300        })
301    }
302
303    /// Refresh under the held lock. If the refresh token was rejected (4xx) the Codex CLI may have
304    /// rotated it on disk concurrently — reload `auth.json` once and retry before giving up.
305    ///
306    /// Read-only limitation: when the OAuth server rotates the refresh token, the new one is held
307    /// only in memory (we never write back to `auth.json` — that's the Codex CLI's file). A later
308    /// process therefore reads the pre-rotation token from disk; if the server invalidated it, the
309    /// reload-retry below hits the same stale token and can't self-heal — so it surfaces a clear
310    /// `run \`codex login\`` error rather than persisting a token behind the CLI's back.
311    async fn refresh_locked(&self, tokens: &mut CodexTokens) -> Result<()> {
312        match refresh_tokens(
313            &self.http,
314            &tokens.refresh_token,
315            tokens.account_id.as_deref(),
316        )
317        .await
318        {
319            Ok(fresh) => {
320                *tokens = fresh;
321                Ok(())
322            }
323            Err(err) if is_rotation_4xx(&err) => {
324                let disk = load_tokens(&self.auth_path)
325                    .wrap_err("Codex refresh token rejected and reloading auth.json failed")?;
326                let fresh = refresh_tokens(
327                    &self.http,
328                    &disk.refresh_token,
329                    disk.account_id.as_deref(),
330                )
331                .await
332                .wrap_err(
333                    "Codex refresh failed even after reloading auth.json (run `codex login`)",
334                )?;
335                *tokens = fresh;
336                Ok(())
337            }
338            Err(err) => Err(err),
339        }
340    }
341
342    /// Current access token + account id, refreshing first if within the expiry skew. Double-checked
343    /// under the lock so a concurrent wave of subagents triggers at most one refresh.
344    async fn current_access(&self) -> Result<(String, Option<String>)> {
345        let mut guard = self.tokens.lock().await;
346        if guard.is_expired() {
347            self.refresh_locked(&mut guard).await?;
348        }
349        Ok((guard.access_token.clone(), guard.account_id.clone()))
350    }
351
352    /// Force a refresh after a 401, gated on the rejected access token: if a concurrent 401 already
353    /// refreshed (the cached token differs from the one we used), reuse that instead of refetching.
354    async fn force_refresh(&self, used_access: &str) -> Result<(String, Option<String>)> {
355        let mut guard = self.tokens.lock().await;
356        if guard.access_token != used_access {
357            return Ok((guard.access_token.clone(), guard.account_id.clone()));
358        }
359        self.refresh_locked(&mut guard).await?;
360        Ok((guard.access_token.clone(), guard.account_id.clone()))
361    }
362
363    /// Build the Responses body, POST it over SSE, and parse the result. Reuses rig's request
364    /// lowering and response parsing; the DIY HTTP exists only to satisfy the backend's quirks:
365    /// top-level `instructions` (required; rig hardcodes it to None), `stream: true` (required),
366    /// `store: false` + omitted `max_output_tokens` (required), and — because store:false is
367    /// stateless — output items arrive via `response.output_item.done` rather than in the terminal
368    /// `response.completed` event.
369    async fn send(
370        &self,
371        completion: &Completion,
372        access: &str,
373        account_id: Option<&str>,
374    ) -> Result<CompletionResponse> {
375        let body = build_body_value(completion)?;
376        let mut req = self
377            .http
378            .post(format!("{CODEX_BASE_URL}/responses"))
379            .bearer_auth(access)
380            .header("originator", ORIGINATOR)
381            .header(reqwest::header::USER_AGENT, user_agent())
382            .header(reqwest::header::ACCEPT, "text/event-stream")
383            .json(&body);
384        if let Some(id) = account_id {
385            req = req.header("ChatGPT-Account-Id", id);
386        }
387        let resp = req
388            .send()
389            .await
390            .wrap_err("Codex completion request failed")?;
391        let status = resp.status();
392        let text = resp
393            .text()
394            .await
395            .wrap_err("reading Codex completion response")?;
396        if !status.is_success() {
397            return Err(eyre::Report::new(CompletionError::from_http_response(
398                status,
399                compact_provider_error_body(&text, 1000),
400            )))
401            .wrap_err("Codex completion failed");
402        }
403        let raw = parse_sse(&text)?;
404        let model = completion.model.clone();
405        to_completion_response(raw, model)
406    }
407}
408
409/// Process-wide shared Codex client (retry-wrapped), built once on first use.
410///
411/// The token store is inherently process-global — there is a single `~/.codex/auth.json` and a
412/// single live token chain — so every Codex reviewer/aggregator must share ONE [`CodexClient`].
413/// Per-client caches would each hold their own in-memory refresh token; after a rotation, one
414/// client's fresh token would be invisible to the others, and a concurrent refresh on the stale
415/// disk token could fail. Sharing one instance gives a single token cache with working
416/// concurrent-refresh dedup.
417pub fn shared_client() -> Result<Arc<dyn LLMClientDyn>> {
418    static CELL: OnceLock<StdMutex<Option<Arc<dyn LLMClientDyn>>>> = OnceLock::new();
419    let cell = CELL.get_or_init(|| StdMutex::new(None));
420    let mut guard = cell.lock().expect("codex shared-client mutex poisoned");
421    if let Some(existing) = guard.as_ref() {
422        return Ok(Arc::clone(existing));
423    }
424    let client = CodexClient::new()?.with_retry().into_arc();
425    *guard = Some(Arc::clone(&client));
426    Ok(client)
427}
428
429impl LLMClient for CodexClient {
430    async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
431        let (access, account_id) = self.current_access().await?;
432        match self.send(&completion, &access, account_id.as_deref()).await {
433            Ok(response) => Ok(response),
434            // The token can lapse/revoke between our expiry check and the call landing. Force a
435            // single refresh-and-retry rather than surfacing a 401 (RetryingLLM treats it as fatal).
436            Err(err) if provider_http_status(&err) == Some(401) => {
437                let (access, account_id) = self.force_refresh(&access).await?;
438                self.send(&completion, &access, account_id.as_deref()).await
439            }
440            Err(err) => Err(err),
441        }
442    }
443}
444
445// ============================================================================
446// Request/response mapping
447// ============================================================================
448
449/// Lower a nitpicker [`Completion`] to the Codex Responses body, applying the backend quirks.
450fn build_body(completion: &Completion) -> Result<ResponsesBody> {
451    let mut c = completion.clone();
452    normalize_codex_completion_history(&mut c);
453    let prompt_cache_key = codex_prompt_cache_key(&c)?;
454    // codex rejects max_output_tokens outright (matches the Codex CLI, which omits it).
455    c.max_tokens = None;
456    // the system prompt must be sent as top-level `instructions`, not an input item, so take it out
457    // of the rig request (None preamble => rig adds no system input item).
458    let instructions = c.preamble.take();
459    let instructions = match instructions {
460        Some(s) if !s.trim().is_empty() => s,
461        _ => eyre::bail!(
462            "Codex auth requires a system prompt: this completion had no `instructions`"
463        ),
464    };
465    let model = c.model.clone();
466    let rig_req: rig_core::completion::CompletionRequest = c.into();
467    let mut body = ResponsesBody::try_from((model, rig_req))
468        .map_err(|e| eyre::eyre!("lowering completion to Codex Responses body failed: {e}"))?;
469    body.instructions = Some(instructions);
470    body.stream = Some(true);
471    body.max_output_tokens = None;
472    // store:false is mandatory, but it makes the stream stateless: a reasoning item the model
473    // returns this turn would be echoed back next turn as a bare `rs_...` id the backend can no
474    // longer resolve ("Items are not persisted when `store` is set to false" → HTTP 404). Asking
475    // for `reasoning.encrypted_content` makes the backend return each reasoning item's opaque blob,
476    // which rig round-trips through the core Reasoning type, so the next turn replays it inline
477    // instead of by id. Set both on the lowered body (rig only auto-adds the include when a
478    // `reasoning` config is present, which we don't set) so any caller additional_params survive.
479    let params = &mut body.additional_parameters;
480    params.store = Some(false);
481    params.prompt_cache_key = Some(prompt_cache_key);
482    let include = params.include.get_or_insert_with(Vec::new);
483    if !include
484        .iter()
485        .any(|i| matches!(i, Include::ReasoningEncryptedContent))
486    {
487        include.push(Include::ReasoningEncryptedContent);
488    }
489    Ok(body)
490}
491
492/// Stable, opaque cache-routing key for the prefix that remains fixed during one conversation.
493/// OpenAI still matches the actual prompt prefix; this only keeps requests with the same
494/// model/system/tool family routed together. Including the project-aware system prompt naturally
495/// partitions unrelated reviews instead of concentrating all traffic on one hot key.
496fn codex_prompt_cache_key(completion: &Completion) -> Result<String> {
497    fn hash_part(hasher: &mut Sha256, bytes: &[u8]) {
498        hasher.update((bytes.len() as u64).to_be_bytes());
499        hasher.update(bytes);
500    }
501
502    let mut hasher = Sha256::new();
503    hash_part(&mut hasher, completion.model.as_bytes());
504    hash_part(
505        &mut hasher,
506        completion
507            .preamble
508            .as_deref()
509            .unwrap_or_default()
510            .as_bytes(),
511    );
512    let tools = serde_json::to_vec(&completion.tools)
513        .wrap_err("serializing Codex tools for prompt cache routing")?;
514    hash_part(&mut hasher, &tools);
515    let digest = hasher.finalize();
516    let suffix = digest[..16]
517        .iter()
518        .map(|byte| format!("{byte:02x}"))
519        .collect::<String>();
520    Ok(format!("nitpicker-{suffix}"))
521}
522
523// rig lowers assistant text into a valid Responses shape itself, and since 0.41 also drops
524// function-call item ids that aren't native `fc_...` ids, pairing by `call_id` alone. Both
525// rewrites nitpicker used to apply here are upstream now, so serialization needs no fixups.
526fn build_body_value(completion: &Completion) -> Result<Value> {
527    let body = build_body(completion)?;
528    serde_json::to_value(&body).wrap_err("serializing Codex Responses request")
529}
530
531fn normalize_codex_completion_history(completion: &mut Completion) {
532    for message in completion
533        .history
534        .iter_mut()
535        .chain(std::iter::once(&mut completion.prompt))
536    {
537        match message {
538            rig_core::completion::Message::Assistant { content, .. } => {
539                for item in content.iter_mut() {
540                    match item {
541                        AssistantContent::ToolCall(call) if call.call_id.is_none() => {
542                            call.call_id = Some(call.id.clone());
543                        }
544                        _ => {}
545                    }
546                }
547            }
548            rig_core::completion::Message::User { content } => {
549                for item in content.iter_mut() {
550                    match item {
551                        UserContent::ToolResult(result) if result.call_id.is_none() => {
552                            result.call_id = Some(result.id.clone());
553                        }
554                        _ => {}
555                    }
556                }
557            }
558            rig_core::completion::Message::System { .. } => {}
559        }
560    }
561}
562
563/// Split an SSE stream into per-event payloads. Events are separated by a blank line, and a single
564/// event may carry its payload across several `data:` fields that must be rejoined with `\n`
565/// (per the SSE spec). `str::lines()` strips a trailing `\r`, so this handles `\n` and `\r\n`.
566fn sse_event_payloads(text: &str) -> Vec<String> {
567    let mut events = vec![];
568    let mut current = String::new();
569    for line in text.lines() {
570        if line.is_empty() {
571            if !current.is_empty() {
572                events.push(std::mem::take(&mut current));
573            }
574            continue;
575        }
576        if let Some(rest) = line.strip_prefix("data:") {
577            if !current.is_empty() {
578                current.push('\n');
579            }
580            // an optional single leading space after the colon is part of the SSE framing, not data
581            current.push_str(rest.strip_prefix(' ').unwrap_or(rest));
582        }
583        // other field lines (`event:`, `id:`, comments) are not needed here
584    }
585    if !current.is_empty() {
586        events.push(current);
587    }
588    events
589}
590
591/// Parse the Codex SSE stream into rig's response type. The terminal event is `response.completed`
592/// or `response.incomplete` (the latter when the model stops early, e.g. hitting the output cap);
593/// both carry the full `response` object. With `store:false` that object's `output` is empty, so the
594/// real items are accumulated from the per-item `response.output_item.done` events and injected.
595fn parse_sse(text: &str) -> Result<ResponsesResp> {
596    let mut items: Vec<Value> = vec![];
597    let mut last_parse_err: Option<String> = None;
598    for data in sse_event_payloads(text) {
599        let data = data.trim();
600        if data.is_empty() || data == "[DONE]" {
601            continue;
602        }
603        let ev: Value = match serde_json::from_str(data) {
604            Ok(v) => v,
605            // keep going (most events are deltas we ignore), but remember the failure so a missing
606            // terminal event reports the real parse error instead of a generic "not found".
607            Err(e) => {
608                last_parse_err = Some(e.to_string());
609                continue;
610            }
611        };
612        match ev.get("type").and_then(Value::as_str) {
613            Some("response.output_item.done") => {
614                if let Some(item) = ev.get("item") {
615                    items.push(item.clone());
616                }
617            }
618            Some("response.completed") | Some("response.incomplete") => {
619                let mut response = ev
620                    .get("response")
621                    .cloned()
622                    .ok_or_else(|| eyre::eyre!("Codex terminal SSE event missing `response`"))?;
623                // only inject accumulated items when the event didn't echo its own output
624                // (store:false leaves it empty; a future stored mode might populate it).
625                let echoed_output = response
626                    .get("output")
627                    .and_then(Value::as_array)
628                    .is_some_and(|a| !a.is_empty());
629                if !echoed_output {
630                    response["output"] = Value::Array(std::mem::take(&mut items));
631                }
632                return serde_json::from_value::<ResponsesResp>(response)
633                    .wrap_err("parsing Codex terminal response payload");
634            }
635            Some("response.failed") | Some("error") => {
636                return Err(eyre::Report::new(CompletionError::from_provider_body(
637                    compact_provider_error_body(&ev.to_string(), 1000),
638                )))
639                .wrap_err("Codex stream error event");
640            }
641            _ => {}
642        }
643    }
644    match last_parse_err {
645        Some(e) => eyre::bail!("no terminal event in Codex SSE stream; last parse error: {e}"),
646        None => eyre::bail!(
647            "no terminal event in Codex SSE stream: {}",
648            truncate(text, 1000)
649        ),
650    }
651}
652
653fn to_completion_response(raw: ResponsesResp, model: String) -> Result<CompletionResponse> {
654    let incomplete_reason = raw.incomplete_details.as_ref().map(|d| d.reason.clone());
655    let parsed: rig_core::completion::CompletionResponse<ResponsesResp> = raw
656        .try_into()
657        .map_err(|e| eyre::eyre!("parsing Codex response into completion: {e}"))?;
658    let has_tool_call = parsed
659        .choice
660        .iter()
661        .any(|c| matches!(c, AssistantContent::ToolCall(_)));
662    let finish_reason = if has_tool_call {
663        FinishReason::ToolUse
664    } else {
665        match incomplete_reason.as_deref() {
666            Some("max_output_tokens") => FinishReason::MaxTokens,
667            Some(other) => FinishReason::Other(other.to_string()),
668            None => FinishReason::Stop,
669        }
670    };
671    Ok(CompletionResponse {
672        // rig's `TryFrom` above already errors on an empty response, so `choice` is non-empty here.
673        choice: parsed.choice,
674        finish_reason,
675        // the Responses API reports cache reads inside `input_tokens`
676        usage: TokenUsage::from_provider(&parsed.usage, CacheAccounting::InsidePrompt),
677        selected_model: Some(model),
678    })
679}
680
681fn truncate(s: &str, max: usize) -> String {
682    if s.len() <= max {
683        return s.to_string();
684    }
685    let end = (0..=max)
686        .rev()
687        .find(|&i| s.is_char_boundary(i))
688        .unwrap_or(0);
689    format!("{}…", &s[..end])
690}
691
692/// A 4xx-other-than-429 status anywhere in the error chain — used to decide whether a failed token
693/// refresh warrants reloading a rotated refresh token from disk. 429 is excluded: a rate-limited
694/// refresh is transient and reloading `auth.json` can't fix it, so it should bubble up to the outer
695/// retry/backoff instead of immediately firing a second refresh.
696fn is_rotation_4xx(err: &eyre::Report) -> bool {
697    provider_http_status(err).is_some_and(|status| (400..500).contains(&status) && status != 429)
698}
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703    use rig_core::OneOrMany;
704    use rig_core::completion::message::{
705        Message, ToolCall, ToolFunction, ToolResult, ToolResultContent,
706    };
707    use serde_json::json;
708
709    /// Build an unsigned JWT (`alg: none`) with the given claims — enough to exercise our
710    /// claims-reading code, which never verifies the signature.
711    fn jwt(claims: Value) -> String {
712        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
713        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
714        format!("{header}.{payload}.sig")
715    }
716
717    #[test]
718    fn account_id_resolution_order() {
719        assert_eq!(
720            account_id_from_claims(&json!({ "chatgpt_account_id": "root" })).as_deref(),
721            Some("root")
722        );
723        assert_eq!(
724            account_id_from_claims(
725                &json!({ "https://api.openai.com/auth": { "chatgpt_account_id": "nested" } })
726            )
727            .as_deref(),
728            Some("nested")
729        );
730        // root preferred over nested
731        assert_eq!(
732            account_id_from_claims(&json!({
733                "chatgpt_account_id": "root",
734                "https://api.openai.com/auth": { "chatgpt_account_id": "nested" }
735            }))
736            .as_deref(),
737            Some("root")
738        );
739        // organizations fallback
740        assert_eq!(
741            account_id_from_claims(
742                &json!({ "organizations": [{ "id": "org-1" }, { "id": "org-2" }] })
743            )
744            .as_deref(),
745            Some("org-1")
746        );
747        assert_eq!(account_id_from_claims(&json!({ "email": "x@y.z" })), None);
748    }
749
750    #[test]
751    fn account_id_prefers_id_token_then_access_token() {
752        let id_token = jwt(json!({ "chatgpt_account_id": "from-id" }));
753        let access = jwt(json!({ "chatgpt_account_id": "from-access" }));
754        assert_eq!(
755            account_id_from_tokens(Some(&id_token), &access).as_deref(),
756            Some("from-id")
757        );
758        let id_token_no_acct = jwt(json!({ "email": "x@y.z" }));
759        assert_eq!(
760            account_id_from_tokens(Some(&id_token_no_acct), &access).as_deref(),
761            Some("from-access")
762        );
763    }
764
765    #[test]
766    fn expiry_from_exp_claim_and_missing() {
767        let with_exp = jwt(json!({ "exp": 4_000_000_000u64 }));
768        assert_eq!(
769            expiry_from_access_token(&with_exp),
770            UNIX_EPOCH + Duration::from_secs(4_000_000_000)
771        );
772        // missing exp => already expired (UNIX_EPOCH) so first use refreshes
773        assert_eq!(expiry_from_access_token(&jwt(json!({}))), UNIX_EPOCH);
774        assert_eq!(expiry_from_access_token("not-a-jwt"), UNIX_EPOCH);
775    }
776
777    #[test]
778    fn parse_tokens_full_and_derived_account_id() {
779        let access = jwt(json!({ "exp": 4_000_000_000u64 }));
780        // explicit account_id wins
781        let raw = json!({
782            "tokens": { "access_token": access, "refresh_token": "rt", "account_id": "acct-explicit" }
783        })
784        .to_string();
785        let t = parse_tokens(&raw, "test").unwrap();
786        assert_eq!(t.account_id.as_deref(), Some("acct-explicit"));
787        assert!(!t.is_expired());
788
789        // derived from id_token when account_id absent
790        let id_token = jwt(json!({ "chatgpt_account_id": "acct-derived" }));
791        let raw = json!({
792            "tokens": { "access_token": access, "refresh_token": "rt", "id_token": id_token }
793        })
794        .to_string();
795        let t = parse_tokens(&raw, "test").unwrap();
796        assert_eq!(t.account_id.as_deref(), Some("acct-derived"));
797    }
798
799    #[test]
800    fn parse_tokens_rejects_api_key_mode_and_missing_fields() {
801        // API-key mode: no `tokens` object
802        let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
803        assert!(parse_tokens(&raw, "test").is_err());
804        // tokens present but no access_token
805        let raw = json!({ "tokens": { "refresh_token": "rt" } }).to_string();
806        assert!(parse_tokens(&raw, "test").is_err());
807    }
808
809    #[test]
810    fn build_body_applies_codex_quirks() {
811        let completion = Completion {
812            model: "gpt-5.4".to_string(),
813            prompt: Message::user("hello"),
814            preamble: Some("You are a reviewer.".to_string()),
815            history: vec![],
816            tools: vec![],
817            tool_choice: None,
818            max_tokens: Some(4096),
819            additional_params: None,
820        };
821        let body = build_body(&completion).unwrap();
822        assert_eq!(body.instructions.as_deref(), Some("You are a reviewer."));
823        assert_eq!(body.stream, Some(true));
824        assert_eq!(body.max_output_tokens, None);
825        // store:false ends up in the flattened additional parameters
826        let json = serde_json::to_value(&body).unwrap();
827        assert_eq!(json.get("store"), Some(&Value::Bool(false)));
828        assert!(
829            json.get("prompt_cache_key")
830                .and_then(Value::as_str)
831                .is_some_and(|key| key.starts_with("nitpicker-")),
832            "Codex requests must carry a stable prompt cache routing key"
833        );
834        // encrypted reasoning content is requested so reasoning items survive store:false round-trips
835        assert_eq!(
836            json.get("include").and_then(Value::as_array),
837            Some(&vec![Value::String(
838                "reasoning.encrypted_content".to_string()
839            )]),
840            "must request reasoning.encrypted_content to avoid bare rs_ id 404s"
841        );
842        // instructions is top-level, not folded into an input system item
843        let has_system_input = json
844            .get("input")
845            .and_then(Value::as_array)
846            .map(|items| {
847                items
848                    .iter()
849                    .any(|i| i.get("role").and_then(Value::as_str) == Some("system"))
850            })
851            .unwrap_or(false);
852        assert!(
853            !has_system_input,
854            "system must be in `instructions`, not `input`"
855        );
856    }
857
858    #[test]
859    fn build_body_requires_a_system_prompt() {
860        let completion = Completion {
861            model: "gpt-5.4".to_string(),
862            prompt: Message::user("hello"),
863            preamble: None,
864            history: vec![],
865            tools: vec![],
866            tool_choice: None,
867            max_tokens: None,
868            additional_params: None,
869        };
870        assert!(build_body(&completion).is_err());
871    }
872
873    #[test]
874    fn prompt_cache_key_tracks_the_stable_prefix_not_the_conversation_tail() {
875        let first = Completion {
876            model: "gpt-5.4".to_string(),
877            prompt: Message::user("initial request"),
878            preamble: Some("stable reviewer and project context".to_string()),
879            history: vec![],
880            tools: vec![rig_core::completion::ToolDefinition {
881                name: "read_file".to_string(),
882                description: "Read a file".to_string(),
883                parameters: json!({
884                    "type": "object",
885                    "properties": { "path": { "type": "string" } }
886                }),
887            }],
888            tool_choice: None,
889            max_tokens: None,
890            additional_params: None,
891        };
892        let mut later_turn = first.clone();
893        later_turn.history = vec![
894            Message::user("initial request"),
895            Message::assistant("intermediate answer"),
896        ];
897        later_turn.prompt = Message::user("continue");
898
899        let first_key = build_body(&first)
900            .unwrap()
901            .additional_parameters
902            .prompt_cache_key
903            .unwrap();
904        let later_key = build_body(&later_turn)
905            .unwrap()
906            .additional_parameters
907            .prompt_cache_key
908            .unwrap();
909        assert_eq!(first_key, later_key);
910
911        let mut different_prefix = later_turn;
912        different_prefix.preamble = Some("different reviewer or project context".to_string());
913        let different_key = build_body(&different_prefix)
914            .unwrap()
915            .additional_parameters
916            .prompt_cache_key
917            .unwrap();
918        assert_ne!(first_key, different_key);
919    }
920
921    #[test]
922    fn build_body_preserves_existing_additional_params() {
923        let completion = Completion {
924            model: "gpt-5.4".to_string(),
925            prompt: Message::user("hello"),
926            preamble: Some("sys".to_string()),
927            history: vec![],
928            tools: vec![],
929            tool_choice: None,
930            max_tokens: None,
931            additional_params: Some(json!({ "reasoning": { "effort": "low" } })),
932        };
933        let body = build_body(&completion).unwrap();
934        let json = serde_json::to_value(&body).unwrap();
935        assert_eq!(json.get("store"), Some(&Value::Bool(false)));
936        assert!(json.get("reasoning").is_some());
937    }
938
939    #[test]
940    fn build_body_fills_missing_tool_call_ids_for_mixed_provider_history() {
941        let tool_id = "toolu_1".to_string();
942        let completion = Completion {
943            model: "gpt-5.5".to_string(),
944            prompt: Message::user("continue"),
945            preamble: Some("sys".to_string()),
946            history: vec![
947                Message::Assistant {
948                    id: None,
949                    content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
950                        tool_id.clone(),
951                        ToolFunction::new(
952                            "read_file".to_string(),
953                            json!({ "path": "src/main.rs" }),
954                        ),
955                    ))),
956                },
957                Message::User {
958                    content: OneOrMany::one(UserContent::ToolResult(ToolResult {
959                        id: tool_id.clone(),
960                        call_id: None,
961                        content: OneOrMany::one(ToolResultContent::text("ok")),
962                    })),
963                },
964            ],
965            tools: vec![],
966            tool_choice: None,
967            max_tokens: None,
968            additional_params: None,
969        };
970
971        let body = build_body(&completion).unwrap();
972        let json = serde_json::to_value(&body).unwrap();
973        assert!(
974            json.to_string()
975                .contains(&format!("\"call_id\":\"{tool_id}\""))
976        );
977    }
978
979    #[test]
980    fn body_value_preserves_assistant_text_history() {
981        // An id-less assistant message (nitpicker's only shape — `.message()` sets `id: None`,
982        // including for Alloy histories from non-Responses providers) must survive lowering into a
983        // valid Codex Responses item. rig 0.39 emits the bare-string `AssistantInput` shape, so the
984        // text is carried verbatim as the item's `content`.
985        let completion = Completion {
986            model: "gpt-5.5".to_string(),
987            prompt: Message::user("continue"),
988            preamble: Some("sys".to_string()),
989            history: vec![Message::Assistant {
990                id: None,
991                content: OneOrMany::one(AssistantContent::text("previous answer")),
992            }],
993            tools: vec![],
994            tool_choice: None,
995            max_tokens: None,
996            additional_params: None,
997        };
998
999        let body = build_body_value(&completion).unwrap();
1000        let assistant_message = body["input"]
1001            .as_array()
1002            .unwrap()
1003            .iter()
1004            .find(|item| item.get("role").and_then(Value::as_str) == Some("assistant"))
1005            .unwrap();
1006
1007        assert_eq!(assistant_message["content"], "previous answer");
1008    }
1009
1010    /// A tool id from another provider (an Alloy history replayed into Codex) is not a native
1011    /// `fc_...` id, so it must be absent from `function_call` and pair by `call_id` alone.
1012    #[test]
1013    fn body_value_omits_foreign_function_call_item_id() {
1014        let tool_id = "tool_5Xt5WpWtZ6Whah4Z2uZcZO34".to_string();
1015        let completion = Completion {
1016            model: "gpt-5.5".to_string(),
1017            prompt: Message::user("continue"),
1018            preamble: Some("sys".to_string()),
1019            history: vec![
1020                Message::Assistant {
1021                    id: None,
1022                    content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
1023                        tool_id.clone(),
1024                        ToolFunction::new(
1025                            "read_file".to_string(),
1026                            json!({ "path": "src/main.rs" }),
1027                        ),
1028                    ))),
1029                },
1030                Message::User {
1031                    content: OneOrMany::one(UserContent::ToolResult(ToolResult {
1032                        id: tool_id.clone(),
1033                        call_id: None,
1034                        content: OneOrMany::one(ToolResultContent::text("ok")),
1035                    })),
1036                },
1037            ],
1038            tools: vec![],
1039            tool_choice: None,
1040            max_tokens: None,
1041            additional_params: None,
1042        };
1043
1044        let body = build_body_value(&completion).unwrap();
1045        let function_call = body["input"]
1046            .as_array()
1047            .unwrap()
1048            .iter()
1049            .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
1050            .unwrap();
1051
1052        assert!(function_call.get("id").is_none());
1053        assert_eq!(function_call["call_id"], tool_id);
1054
1055        // The paired tool output must carry the same call_id, or the backend cannot match them.
1056        let function_call_output = body["input"]
1057            .as_array()
1058            .unwrap()
1059            .iter()
1060            .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output"))
1061            .unwrap();
1062        assert_eq!(function_call_output["call_id"], tool_id);
1063    }
1064
1065    #[test]
1066    fn resolve_auth_path_modes() {
1067        // absolute CODEX_HOME wins
1068        let p = resolve_auth_path(Some("/custom/codex"), Some(PathBuf::from("/home/u"))).unwrap();
1069        assert_eq!(p, PathBuf::from("/custom/codex/auth.json"));
1070        // relative CODEX_HOME errors
1071        assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
1072        // empty CODEX_HOME falls back to home
1073        let p = resolve_auth_path(Some("  "), Some(PathBuf::from("/home/u"))).unwrap();
1074        assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1075        // unset falls back to home
1076        let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
1077        assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1078        // no home and no CODEX_HOME errors
1079        assert!(resolve_auth_path(None, None).is_err());
1080    }
1081
1082    #[test]
1083    fn truncate_respects_char_boundaries() {
1084        assert_eq!(truncate("hello", 10), "hello");
1085        assert_eq!(truncate("hello", 3), "hel…");
1086        // multibyte: "é" is 2 bytes; truncating at 1 byte must not split it
1087        let s = "é".repeat(5); // 10 bytes
1088        let out = truncate(&s, 3);
1089        assert!(out.ends_with('…'));
1090        // the kept prefix is valid UTF-8 (no panic) and has whole chars only
1091        assert!(out.chars().filter(|&c| c == 'é').count() <= 1);
1092    }
1093
1094    #[test]
1095    fn parse_sse_accumulates_output_items_with_empty_completed() {
1096        // mirrors the store:false stream: items arrive in output_item.done; completed has empty output
1097        let item = json!({
1098            "type": "message",
1099            "id": "msg_1",
1100            "role": "assistant",
1101            "status": "completed",
1102            "content": [{ "type": "output_text", "text": "pong" }]
1103        });
1104        let completed = json!({
1105            "id": "resp_1",
1106            "object": "response",
1107            "created_at": 1,
1108            "status": "completed",
1109            "model": "gpt-5.4",
1110            "output": [],
1111            "usage": {
1112                "input_tokens": 5000,
1113                "input_tokens_details": { "cached_tokens": 4800 },
1114                "output_tokens": 1,
1115                "output_tokens_details": { "reasoning_tokens": 0 },
1116                "total_tokens": 5001
1117            }
1118        });
1119        let sse = format!(
1120            "data: {}\n\ndata: {}\n\ndata: [DONE]\n",
1121            json!({ "type": "response.output_item.done", "item": item }),
1122            json!({ "type": "response.completed", "response": completed })
1123        );
1124        let raw = parse_sse(&sse).unwrap();
1125        let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1126        assert_eq!(resp.text(), "pong");
1127        assert_eq!(resp.finish_reason, FinishReason::Stop);
1128        // cache reads are inside `input_tokens` here, so the prompt must not be inflated by them
1129        assert_eq!(resp.usage.input_tokens, 5000);
1130        assert_eq!(resp.usage.cached_input_tokens, 4800);
1131        assert_eq!(resp.usage.total_tokens, 5001);
1132    }
1133
1134    #[test]
1135    fn parse_sse_surfaces_error_events() {
1136        let sse = format!(
1137            "data: {}\n",
1138            json!({ "type": "response.failed", "error": { "message": "boom" } })
1139        );
1140        assert!(parse_sse(&sse).is_err());
1141    }
1142
1143    #[test]
1144    fn parse_sse_preserves_codes_from_large_error_events() {
1145        let sse = format!(
1146            "data: {}\n",
1147            json!({
1148                "type": "response.failed",
1149                "error": {
1150                    "type": "usage_limit_reached",
1151                    "message": "quota exhausted",
1152                    "diagnostic": "x".repeat(4_000),
1153                }
1154            })
1155        );
1156        let err = parse_sse(&sse).unwrap_err();
1157        assert!(crate::llm::provider_error_has_code(
1158            &err,
1159            &["usage_limit_reached"]
1160        ));
1161    }
1162
1163    fn usage_json() -> Value {
1164        json!({
1165            "input_tokens": 5,
1166            "input_tokens_details": { "cached_tokens": 0 },
1167            "output_tokens": 1,
1168            "output_tokens_details": { "reasoning_tokens": 0 },
1169            "total_tokens": 6
1170        })
1171    }
1172
1173    #[test]
1174    fn parse_sse_handles_incomplete_as_max_tokens() {
1175        // model stopped early on the output cap: terminal event is `response.incomplete`
1176        let item = json!({
1177            "type": "message", "id": "m", "role": "assistant", "status": "incomplete",
1178            "content": [{ "type": "output_text", "text": "partial" }]
1179        });
1180        let response = json!({
1181            "id": "r", "object": "response", "created_at": 1, "status": "incomplete",
1182            "model": "gpt-5.4", "output": [],
1183            "incomplete_details": { "reason": "max_output_tokens" },
1184            "usage": usage_json()
1185        });
1186        let sse = format!(
1187            "data: {}\n\ndata: {}\n",
1188            json!({ "type": "response.output_item.done", "item": item }),
1189            json!({ "type": "response.incomplete", "response": response })
1190        );
1191        let raw = parse_sse(&sse).unwrap();
1192        let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1193        assert_eq!(resp.text(), "partial");
1194        assert_eq!(resp.finish_reason, FinishReason::MaxTokens);
1195    }
1196
1197    #[test]
1198    fn parse_sse_rejoins_multiline_data_fields() {
1199        // a single event whose JSON payload is split across two `data:` lines (valid SSE);
1200        // splitting after a `,` keeps each half from being valid alone but the `\n`-join valid.
1201        let completed = json!({
1202            "type": "response.completed",
1203            "response": {
1204                "id": "r", "object": "response", "created_at": 1, "status": "completed",
1205                "model": "gpt-5.4",
1206                "output": [{
1207                    "type": "message", "id": "m", "role": "assistant", "status": "completed",
1208                    "content": [{ "type": "output_text", "text": "hi" }]
1209                }],
1210                "usage": usage_json()
1211            }
1212        })
1213        .to_string();
1214        let comma = completed.find(',').unwrap();
1215        let (head, tail) = completed.split_at(comma);
1216        let sse = format!("data: {head}\ndata: {tail}\n\n");
1217        let raw = parse_sse(&sse).unwrap();
1218        let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1219        assert_eq!(resp.text(), "hi");
1220    }
1221
1222    #[test]
1223    fn is_rotation_4xx_excludes_429_and_5xx() {
1224        let mk = |status| {
1225            eyre::Report::new(CompletionError::from_http_response(
1226                reqwest::StatusCode::from_u16(status).unwrap(),
1227                r#"{"error":"test"}"#,
1228            ))
1229        };
1230        assert!(is_rotation_4xx(&mk(400)));
1231        assert!(is_rotation_4xx(&mk(401)));
1232        // 429 is transient — must NOT trigger the reload-from-disk rotation path
1233        assert!(!is_rotation_4xx(&mk(429)));
1234        assert!(!is_rotation_4xx(&mk(500)));
1235    }
1236}