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