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