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/// 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
487fn build_body_value(completion: &Completion) -> Result<Value> {
488    let body = build_body(completion)?;
489    let mut value = serde_json::to_value(&body).wrap_err("serializing Codex Responses request")?;
490    normalize_codex_responses_request(&mut value);
491    Ok(value)
492}
493
494fn normalize_codex_responses_request(body: &mut Value) {
495    let Some(items) = body.get_mut("input").and_then(Value::as_array_mut) else {
496        return;
497    };
498    for item in items {
499        normalize_codex_input_item(item);
500    }
501}
502
503// rig 0.39 lowers assistant text into a valid Responses shape itself (a bare-string
504// `AssistantInput` when the message has no id — nitpicker's only case — or an `output_text`
505// array when it does), so no assistant-content rewrite is needed here. Only function-call item
506// ids still need the `fc_` normalization for cross-provider (Alloy) replay.
507fn normalize_codex_input_item(item: &mut Value) {
508    if item.get("type").and_then(Value::as_str) == Some("function_call") {
509        normalize_codex_function_call_item(item);
510    }
511}
512
513fn normalize_codex_function_call_item(item: &mut Value) {
514    let replacement = item
515        .get("id")
516        .and_then(Value::as_str)
517        .filter(|id| !id.starts_with("fc_"))
518        .map(|id| format!("fc_{id}"));
519    if let Some(id) = replacement {
520        item["id"] = Value::String(id);
521    }
522}
523
524fn normalize_codex_completion_history(completion: &mut Completion) {
525    for message in completion
526        .history
527        .iter_mut()
528        .chain(std::iter::once(&mut completion.prompt))
529    {
530        match message {
531            rig_core::completion::Message::Assistant { content, .. } => {
532                for item in content.iter_mut() {
533                    match item {
534                        AssistantContent::ToolCall(call) if call.call_id.is_none() => {
535                            call.call_id = Some(call.id.clone());
536                        }
537                        _ => {}
538                    }
539                }
540            }
541            rig_core::completion::Message::User { content } => {
542                for item in content.iter_mut() {
543                    match item {
544                        UserContent::ToolResult(result) if result.call_id.is_none() => {
545                            result.call_id = Some(result.id.clone());
546                        }
547                        _ => {}
548                    }
549                }
550            }
551            rig_core::completion::Message::System { .. } => {}
552        }
553    }
554}
555
556/// Split an SSE stream into per-event payloads. Events are separated by a blank line, and a single
557/// event may carry its payload across several `data:` fields that must be rejoined with `\n`
558/// (per the SSE spec). `str::lines()` strips a trailing `\r`, so this handles `\n` and `\r\n`.
559fn sse_event_payloads(text: &str) -> Vec<String> {
560    let mut events = vec![];
561    let mut current = String::new();
562    for line in text.lines() {
563        if line.is_empty() {
564            if !current.is_empty() {
565                events.push(std::mem::take(&mut current));
566            }
567            continue;
568        }
569        if let Some(rest) = line.strip_prefix("data:") {
570            if !current.is_empty() {
571                current.push('\n');
572            }
573            // an optional single leading space after the colon is part of the SSE framing, not data
574            current.push_str(rest.strip_prefix(' ').unwrap_or(rest));
575        }
576        // other field lines (`event:`, `id:`, comments) are not needed here
577    }
578    if !current.is_empty() {
579        events.push(current);
580    }
581    events
582}
583
584/// Parse the Codex SSE stream into rig's response type. The terminal event is `response.completed`
585/// or `response.incomplete` (the latter when the model stops early, e.g. hitting the output cap);
586/// both carry the full `response` object. With `store:false` that object's `output` is empty, so the
587/// real items are accumulated from the per-item `response.output_item.done` events and injected.
588fn parse_sse(text: &str) -> Result<ResponsesResp> {
589    let mut items: Vec<Value> = vec![];
590    let mut last_parse_err: Option<String> = None;
591    for data in sse_event_payloads(text) {
592        let data = data.trim();
593        if data.is_empty() || data == "[DONE]" {
594            continue;
595        }
596        let ev: Value = match serde_json::from_str(data) {
597            Ok(v) => v,
598            // keep going (most events are deltas we ignore), but remember the failure so a missing
599            // terminal event reports the real parse error instead of a generic "not found".
600            Err(e) => {
601                last_parse_err = Some(e.to_string());
602                continue;
603            }
604        };
605        match ev.get("type").and_then(Value::as_str) {
606            Some("response.output_item.done") => {
607                if let Some(item) = ev.get("item") {
608                    items.push(item.clone());
609                }
610            }
611            Some("response.completed") | Some("response.incomplete") => {
612                let mut response = ev
613                    .get("response")
614                    .cloned()
615                    .ok_or_else(|| eyre::eyre!("Codex terminal SSE event missing `response`"))?;
616                // only inject accumulated items when the event didn't echo its own output
617                // (store:false leaves it empty; a future stored mode might populate it).
618                let echoed_output = response
619                    .get("output")
620                    .and_then(Value::as_array)
621                    .is_some_and(|a| !a.is_empty());
622                if !echoed_output {
623                    response["output"] = Value::Array(std::mem::take(&mut items));
624                }
625                return serde_json::from_value::<ResponsesResp>(response)
626                    .wrap_err("parsing Codex terminal response payload");
627            }
628            Some("response.failed") | Some("error") => {
629                eyre::bail!(
630                    "Codex stream error event: {}",
631                    truncate(&ev.to_string(), 1000)
632                );
633            }
634            _ => {}
635        }
636    }
637    match last_parse_err {
638        Some(e) => eyre::bail!("no terminal event in Codex SSE stream; last parse error: {e}"),
639        None => eyre::bail!(
640            "no terminal event in Codex SSE stream: {}",
641            truncate(text, 1000)
642        ),
643    }
644}
645
646fn to_completion_response(raw: ResponsesResp, model: String) -> Result<CompletionResponse> {
647    let incomplete_reason = raw.incomplete_details.as_ref().map(|d| d.reason.clone());
648    let parsed: rig_core::completion::CompletionResponse<ResponsesResp> = raw
649        .try_into()
650        .map_err(|e| eyre::eyre!("parsing Codex response into completion: {e}"))?;
651    let has_tool_call = parsed
652        .choice
653        .iter()
654        .any(|c| matches!(c, AssistantContent::ToolCall(_)));
655    let finish_reason = if has_tool_call {
656        FinishReason::ToolUse
657    } else {
658        match incomplete_reason.as_deref() {
659            Some("max_output_tokens") => FinishReason::MaxTokens,
660            Some(other) => FinishReason::Other(other.to_string()),
661            None => FinishReason::Stop,
662        }
663    };
664    Ok(CompletionResponse {
665        // rig's `TryFrom` above already errors on an empty response, so `choice` is non-empty here.
666        choice: parsed.choice,
667        finish_reason,
668        usage: TokenUsage::new(parsed.usage.input_tokens, parsed.usage.output_tokens),
669        selected_model: Some(model),
670    })
671}
672
673fn truncate(s: &str, max: usize) -> String {
674    if s.len() <= max {
675        return s.to_string();
676    }
677    let end = (0..=max)
678        .rev()
679        .find(|&i| s.is_char_boundary(i))
680        .unwrap_or(0);
681    format!("{}…", &s[..end])
682}
683
684/// A 4xx-other-than-429 status anywhere in the error chain — used to decide whether a failed token
685/// refresh warrants reloading a rotated refresh token from disk. 429 is excluded: a rate-limited
686/// refresh is transient and reloading `auth.json` can't fix it, so it should bubble up to the outer
687/// retry/backoff instead of immediately firing a second refresh.
688fn is_rotation_4xx(err: &eyre::Report) -> bool {
689    let msg = format!("{err:#}");
690    (400..500)
691        .filter(|status| *status != 429)
692        .any(|status| mentions_http_status(&msg, status))
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698    use rig_core::OneOrMany;
699    use rig_core::completion::message::{
700        Message, ToolCall, ToolFunction, ToolResult, ToolResultContent,
701    };
702    use serde_json::json;
703
704    /// Build an unsigned JWT (`alg: none`) with the given claims — enough to exercise our
705    /// claims-reading code, which never verifies the signature.
706    fn jwt(claims: Value) -> String {
707        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
708        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
709        format!("{header}.{payload}.sig")
710    }
711
712    #[test]
713    fn normalize_function_call_id_only_skips_fc_underscore_prefix() {
714        // A non-Codex id that merely starts with the letters "fc" (but not "fc_") must still be
715        // normalized to the `fc_...` shape the backend expects.
716        let mut item = json!({ "id": "fcall_1" });
717        normalize_codex_function_call_item(&mut item);
718        assert_eq!(item["id"], "fc_fcall_1");
719
720        let mut generic = json!({ "id": "toolu_9" });
721        normalize_codex_function_call_item(&mut generic);
722        assert_eq!(generic["id"], "fc_toolu_9");
723
724        // An already-correct id is left untouched (no double-prefixing).
725        let mut already = json!({ "id": "fc_abc" });
726        normalize_codex_function_call_item(&mut already);
727        assert_eq!(already["id"], "fc_abc");
728    }
729
730    #[test]
731    fn account_id_resolution_order() {
732        assert_eq!(
733            account_id_from_claims(&json!({ "chatgpt_account_id": "root" })).as_deref(),
734            Some("root")
735        );
736        assert_eq!(
737            account_id_from_claims(
738                &json!({ "https://api.openai.com/auth": { "chatgpt_account_id": "nested" } })
739            )
740            .as_deref(),
741            Some("nested")
742        );
743        // root preferred over nested
744        assert_eq!(
745            account_id_from_claims(&json!({
746                "chatgpt_account_id": "root",
747                "https://api.openai.com/auth": { "chatgpt_account_id": "nested" }
748            }))
749            .as_deref(),
750            Some("root")
751        );
752        // organizations fallback
753        assert_eq!(
754            account_id_from_claims(
755                &json!({ "organizations": [{ "id": "org-1" }, { "id": "org-2" }] })
756            )
757            .as_deref(),
758            Some("org-1")
759        );
760        assert_eq!(account_id_from_claims(&json!({ "email": "x@y.z" })), None);
761    }
762
763    #[test]
764    fn account_id_prefers_id_token_then_access_token() {
765        let id_token = jwt(json!({ "chatgpt_account_id": "from-id" }));
766        let access = jwt(json!({ "chatgpt_account_id": "from-access" }));
767        assert_eq!(
768            account_id_from_tokens(Some(&id_token), &access).as_deref(),
769            Some("from-id")
770        );
771        let id_token_no_acct = jwt(json!({ "email": "x@y.z" }));
772        assert_eq!(
773            account_id_from_tokens(Some(&id_token_no_acct), &access).as_deref(),
774            Some("from-access")
775        );
776    }
777
778    #[test]
779    fn expiry_from_exp_claim_and_missing() {
780        let with_exp = jwt(json!({ "exp": 4_000_000_000u64 }));
781        assert_eq!(
782            expiry_from_access_token(&with_exp),
783            UNIX_EPOCH + Duration::from_secs(4_000_000_000)
784        );
785        // missing exp => already expired (UNIX_EPOCH) so first use refreshes
786        assert_eq!(expiry_from_access_token(&jwt(json!({}))), UNIX_EPOCH);
787        assert_eq!(expiry_from_access_token("not-a-jwt"), UNIX_EPOCH);
788    }
789
790    #[test]
791    fn parse_tokens_full_and_derived_account_id() {
792        let access = jwt(json!({ "exp": 4_000_000_000u64 }));
793        // explicit account_id wins
794        let raw = json!({
795            "tokens": { "access_token": access, "refresh_token": "rt", "account_id": "acct-explicit" }
796        })
797        .to_string();
798        let t = parse_tokens(&raw, "test").unwrap();
799        assert_eq!(t.account_id.as_deref(), Some("acct-explicit"));
800        assert!(!t.is_expired());
801
802        // derived from id_token when account_id absent
803        let id_token = jwt(json!({ "chatgpt_account_id": "acct-derived" }));
804        let raw = json!({
805            "tokens": { "access_token": access, "refresh_token": "rt", "id_token": id_token }
806        })
807        .to_string();
808        let t = parse_tokens(&raw, "test").unwrap();
809        assert_eq!(t.account_id.as_deref(), Some("acct-derived"));
810    }
811
812    #[test]
813    fn parse_tokens_rejects_api_key_mode_and_missing_fields() {
814        // API-key mode: no `tokens` object
815        let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
816        assert!(parse_tokens(&raw, "test").is_err());
817        // tokens present but no access_token
818        let raw = json!({ "tokens": { "refresh_token": "rt" } }).to_string();
819        assert!(parse_tokens(&raw, "test").is_err());
820    }
821
822    #[test]
823    fn build_body_applies_codex_quirks() {
824        let completion = Completion {
825            model: "gpt-5.4".to_string(),
826            prompt: Message::user("hello"),
827            preamble: Some("You are a reviewer.".to_string()),
828            history: vec![],
829            tools: vec![],
830            tool_choice: None,
831            max_tokens: Some(4096),
832            additional_params: None,
833        };
834        let body = build_body(&completion).unwrap();
835        assert_eq!(body.instructions.as_deref(), Some("You are a reviewer."));
836        assert_eq!(body.stream, Some(true));
837        assert_eq!(body.max_output_tokens, None);
838        // store:false ends up in the flattened additional parameters
839        let json = serde_json::to_value(&body).unwrap();
840        assert_eq!(json.get("store"), Some(&Value::Bool(false)));
841        // encrypted reasoning content is requested so reasoning items survive store:false round-trips
842        assert_eq!(
843            json.get("include").and_then(Value::as_array),
844            Some(&vec![Value::String(
845                "reasoning.encrypted_content".to_string()
846            )]),
847            "must request reasoning.encrypted_content to avoid bare rs_ id 404s"
848        );
849        // instructions is top-level, not folded into an input system item
850        let has_system_input = json
851            .get("input")
852            .and_then(Value::as_array)
853            .map(|items| {
854                items
855                    .iter()
856                    .any(|i| i.get("role").and_then(Value::as_str) == Some("system"))
857            })
858            .unwrap_or(false);
859        assert!(
860            !has_system_input,
861            "system must be in `instructions`, not `input`"
862        );
863    }
864
865    #[test]
866    fn build_body_requires_a_system_prompt() {
867        let completion = Completion {
868            model: "gpt-5.4".to_string(),
869            prompt: Message::user("hello"),
870            preamble: None,
871            history: vec![],
872            tools: vec![],
873            tool_choice: None,
874            max_tokens: None,
875            additional_params: None,
876        };
877        assert!(build_body(&completion).is_err());
878    }
879
880    #[test]
881    fn build_body_preserves_existing_additional_params() {
882        let completion = Completion {
883            model: "gpt-5.4".to_string(),
884            prompt: Message::user("hello"),
885            preamble: Some("sys".to_string()),
886            history: vec![],
887            tools: vec![],
888            tool_choice: None,
889            max_tokens: None,
890            additional_params: Some(json!({ "reasoning": { "effort": "low" } })),
891        };
892        let body = build_body(&completion).unwrap();
893        let json = serde_json::to_value(&body).unwrap();
894        assert_eq!(json.get("store"), Some(&Value::Bool(false)));
895        assert!(json.get("reasoning").is_some());
896    }
897
898    #[test]
899    fn build_body_fills_missing_tool_call_ids_for_mixed_provider_history() {
900        let tool_id = "toolu_1".to_string();
901        let completion = Completion {
902            model: "gpt-5.5".to_string(),
903            prompt: Message::user("continue"),
904            preamble: Some("sys".to_string()),
905            history: vec![
906                Message::Assistant {
907                    id: None,
908                    content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
909                        tool_id.clone(),
910                        ToolFunction::new(
911                            "read_file".to_string(),
912                            json!({ "path": "src/main.rs" }),
913                        ),
914                    ))),
915                },
916                Message::User {
917                    content: OneOrMany::one(UserContent::ToolResult(ToolResult {
918                        id: tool_id.clone(),
919                        call_id: None,
920                        content: OneOrMany::one(ToolResultContent::text("ok")),
921                    })),
922                },
923            ],
924            tools: vec![],
925            tool_choice: None,
926            max_tokens: None,
927            additional_params: None,
928        };
929
930        let body = build_body(&completion).unwrap();
931        let json = serde_json::to_value(&body).unwrap();
932        assert!(
933            json.to_string()
934                .contains(&format!("\"call_id\":\"{tool_id}\""))
935        );
936    }
937
938    #[test]
939    fn body_value_preserves_assistant_text_history() {
940        // An id-less assistant message (nitpicker's only shape — `.message()` sets `id: None`,
941        // including for Alloy histories from non-Responses providers) must survive lowering into a
942        // valid Codex Responses item. rig 0.39 emits the bare-string `AssistantInput` shape, so the
943        // text is carried verbatim as the item's `content`.
944        let completion = Completion {
945            model: "gpt-5.5".to_string(),
946            prompt: Message::user("continue"),
947            preamble: Some("sys".to_string()),
948            history: vec![Message::Assistant {
949                id: None,
950                content: OneOrMany::one(AssistantContent::text("previous answer")),
951            }],
952            tools: vec![],
953            tool_choice: None,
954            max_tokens: None,
955            additional_params: None,
956        };
957
958        let body = build_body_value(&completion).unwrap();
959        let assistant_message = body["input"]
960            .as_array()
961            .unwrap()
962            .iter()
963            .find(|item| item.get("role").and_then(Value::as_str) == Some("assistant"))
964            .unwrap();
965
966        assert_eq!(assistant_message["content"], "previous answer");
967    }
968
969    #[test]
970    fn body_value_rewrites_function_call_item_id_for_codex() {
971        let tool_id = "tool_5Xt5WpWtZ6Whah4Z2uZcZO34".to_string();
972        let completion = Completion {
973            model: "gpt-5.5".to_string(),
974            prompt: Message::user("continue"),
975            preamble: Some("sys".to_string()),
976            history: vec![
977                Message::Assistant {
978                    id: None,
979                    content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
980                        tool_id.clone(),
981                        ToolFunction::new(
982                            "read_file".to_string(),
983                            json!({ "path": "src/main.rs" }),
984                        ),
985                    ))),
986                },
987                Message::User {
988                    content: OneOrMany::one(UserContent::ToolResult(ToolResult {
989                        id: tool_id.clone(),
990                        call_id: None,
991                        content: OneOrMany::one(ToolResultContent::text("ok")),
992                    })),
993                },
994            ],
995            tools: vec![],
996            tool_choice: None,
997            max_tokens: None,
998            additional_params: None,
999        };
1000
1001        let body = build_body_value(&completion).unwrap();
1002        let function_call = body["input"]
1003            .as_array()
1004            .unwrap()
1005            .iter()
1006            .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
1007            .unwrap();
1008
1009        assert_eq!(function_call["id"], format!("fc_{tool_id}"));
1010        assert_eq!(function_call["call_id"], tool_id);
1011    }
1012
1013    #[test]
1014    fn resolve_auth_path_modes() {
1015        // absolute CODEX_HOME wins
1016        let p = resolve_auth_path(Some("/custom/codex"), Some(PathBuf::from("/home/u"))).unwrap();
1017        assert_eq!(p, PathBuf::from("/custom/codex/auth.json"));
1018        // relative CODEX_HOME errors
1019        assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
1020        // empty CODEX_HOME falls back to home
1021        let p = resolve_auth_path(Some("  "), Some(PathBuf::from("/home/u"))).unwrap();
1022        assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1023        // unset falls back to home
1024        let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
1025        assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1026        // no home and no CODEX_HOME errors
1027        assert!(resolve_auth_path(None, None).is_err());
1028    }
1029
1030    #[test]
1031    fn truncate_respects_char_boundaries() {
1032        assert_eq!(truncate("hello", 10), "hello");
1033        assert_eq!(truncate("hello", 3), "hel…");
1034        // multibyte: "é" is 2 bytes; truncating at 1 byte must not split it
1035        let s = "é".repeat(5); // 10 bytes
1036        let out = truncate(&s, 3);
1037        assert!(out.ends_with('…'));
1038        // the kept prefix is valid UTF-8 (no panic) and has whole chars only
1039        assert!(out.chars().filter(|&c| c == 'é').count() <= 1);
1040    }
1041
1042    #[test]
1043    fn parse_sse_accumulates_output_items_with_empty_completed() {
1044        // mirrors the store:false stream: items arrive in output_item.done; completed has empty output
1045        let item = json!({
1046            "type": "message",
1047            "id": "msg_1",
1048            "role": "assistant",
1049            "status": "completed",
1050            "content": [{ "type": "output_text", "text": "pong" }]
1051        });
1052        let completed = json!({
1053            "id": "resp_1",
1054            "object": "response",
1055            "created_at": 1,
1056            "status": "completed",
1057            "model": "gpt-5.4",
1058            "output": [],
1059            "usage": {
1060                "input_tokens": 5,
1061                "input_tokens_details": { "cached_tokens": 0 },
1062                "output_tokens": 1,
1063                "output_tokens_details": { "reasoning_tokens": 0 },
1064                "total_tokens": 6
1065            }
1066        });
1067        let sse = format!(
1068            "data: {}\n\ndata: {}\n\ndata: [DONE]\n",
1069            json!({ "type": "response.output_item.done", "item": item }),
1070            json!({ "type": "response.completed", "response": completed })
1071        );
1072        let raw = parse_sse(&sse).unwrap();
1073        let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1074        assert_eq!(resp.text(), "pong");
1075        assert_eq!(resp.finish_reason, FinishReason::Stop);
1076        assert_eq!(resp.usage.input_tokens, 5);
1077    }
1078
1079    #[test]
1080    fn parse_sse_surfaces_error_events() {
1081        let sse = format!(
1082            "data: {}\n",
1083            json!({ "type": "response.failed", "error": { "message": "boom" } })
1084        );
1085        assert!(parse_sse(&sse).is_err());
1086    }
1087
1088    fn usage_json() -> Value {
1089        json!({
1090            "input_tokens": 5,
1091            "input_tokens_details": { "cached_tokens": 0 },
1092            "output_tokens": 1,
1093            "output_tokens_details": { "reasoning_tokens": 0 },
1094            "total_tokens": 6
1095        })
1096    }
1097
1098    #[test]
1099    fn parse_sse_handles_incomplete_as_max_tokens() {
1100        // model stopped early on the output cap: terminal event is `response.incomplete`
1101        let item = json!({
1102            "type": "message", "id": "m", "role": "assistant", "status": "incomplete",
1103            "content": [{ "type": "output_text", "text": "partial" }]
1104        });
1105        let response = json!({
1106            "id": "r", "object": "response", "created_at": 1, "status": "incomplete",
1107            "model": "gpt-5.4", "output": [],
1108            "incomplete_details": { "reason": "max_output_tokens" },
1109            "usage": usage_json()
1110        });
1111        let sse = format!(
1112            "data: {}\n\ndata: {}\n",
1113            json!({ "type": "response.output_item.done", "item": item }),
1114            json!({ "type": "response.incomplete", "response": response })
1115        );
1116        let raw = parse_sse(&sse).unwrap();
1117        let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1118        assert_eq!(resp.text(), "partial");
1119        assert_eq!(resp.finish_reason, FinishReason::MaxTokens);
1120    }
1121
1122    #[test]
1123    fn parse_sse_rejoins_multiline_data_fields() {
1124        // a single event whose JSON payload is split across two `data:` lines (valid SSE);
1125        // splitting after a `,` keeps each half from being valid alone but the `\n`-join valid.
1126        let completed = json!({
1127            "type": "response.completed",
1128            "response": {
1129                "id": "r", "object": "response", "created_at": 1, "status": "completed",
1130                "model": "gpt-5.4",
1131                "output": [{
1132                    "type": "message", "id": "m", "role": "assistant", "status": "completed",
1133                    "content": [{ "type": "output_text", "text": "hi" }]
1134                }],
1135                "usage": usage_json()
1136            }
1137        })
1138        .to_string();
1139        let comma = completed.find(',').unwrap();
1140        let (head, tail) = completed.split_at(comma);
1141        let sse = format!("data: {head}\ndata: {tail}\n\n");
1142        let raw = parse_sse(&sse).unwrap();
1143        let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1144        assert_eq!(resp.text(), "hi");
1145    }
1146
1147    #[test]
1148    fn is_rotation_4xx_excludes_429_and_5xx() {
1149        let mk = |s: &str| eyre::eyre!("Codex token refresh returned HTTP {s}");
1150        assert!(is_rotation_4xx(&mk("400 Bad Request")));
1151        assert!(is_rotation_4xx(&mk("401 Unauthorized")));
1152        // 429 is transient — must NOT trigger the reload-from-disk rotation path
1153        assert!(!is_rotation_4xx(&mk("429 Too Many Requests")));
1154        assert!(!is_rotation_4xx(&mk("500 Internal Server Error")));
1155    }
1156}