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