1use 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::ProviderError;
19use rig_core::completion::CompletionRequest;
20use rig_core::providers::openai::responses_api::wire::Responses;
21use rig_core::providers::openai::wire::CallerIdentity;
22use rig_core::providers::{chatgpt, openai};
23use serde_json::Value;
24use sha2::{Digest, Sha256};
25use tokio::sync::Mutex;
26
27use crate::llm::{
28 Completion, CompletionResponse, LLMClient, LLMClientDyn, WithRetryExt,
29 compact_provider_error_body, provider_http_status,
30};
31
32const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
34const TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
35const ORIGINATOR: &str = "nitpicker";
36const EXPIRY_SKEW: Duration = Duration::from_secs(60);
38const REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
41const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
43const READ_TIMEOUT: Duration = Duration::from_secs(120);
48
49fn 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
68fn 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
78fn 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
106fn 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 .and_then(|exp| UNIX_EPOCH.checked_add(Duration::from_secs(exp)))
115 .unwrap_or(UNIX_EPOCH)
116}
117
118#[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
136fn auth_path() -> Result<PathBuf> {
138 resolve_auth_path(
139 std::env::var("CODEX_HOME").ok().as_deref(),
140 dirs::home_dir(),
141 )
142}
143
144fn 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
171pub fn auth_available() -> bool {
175 auth_path().and_then(|p| load_tokens(&p)).is_ok()
176}
177
178fn 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
227async 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 return Err(eyre::Report::new(ProviderError::from_http_response(
249 status,
250 compact_provider_error_body(&body, 1000),
251 )))
252 .wrap_err("Codex token refresh failed");
253 }
254 let parsed: RefreshResponse =
255 serde_json::from_str(&body).wrap_err("parsing Codex token refresh response")?;
256 let expires_at = match parsed.expires_in {
259 Some(secs) => SystemTime::now()
262 .checked_add(Duration::from_secs(secs))
263 .unwrap_or_else(|| expiry_from_access_token(&parsed.access_token)),
264 None => expiry_from_access_token(&parsed.access_token),
265 };
266 let account_id = prev_account_id
267 .map(str::to_string)
268 .or_else(|| account_id_from_tokens(parsed.id_token.as_deref(), &parsed.access_token));
269 Ok(CodexTokens {
270 access_token: parsed.access_token,
271 refresh_token: parsed
272 .refresh_token
273 .unwrap_or_else(|| refresh_token.to_string()),
274 account_id,
275 expires_at,
276 })
277}
278
279pub struct CodexClient {
284 http: reqwest::Client,
285 auth_path: PathBuf,
286 tokens: Mutex<CodexTokens>,
287}
288
289impl CodexClient {
290 pub fn new() -> Result<Self> {
292 let path = auth_path()?;
293 let tokens = load_tokens(&path)?;
294 Ok(Self {
295 http: build_http_client()?,
296 auth_path: path,
297 tokens: Mutex::new(tokens),
298 })
299 }
300
301 async fn refresh_locked(&self, tokens: &mut CodexTokens) -> Result<()> {
310 match refresh_tokens(
311 &self.http,
312 &tokens.refresh_token,
313 tokens.account_id.as_deref(),
314 )
315 .await
316 {
317 Ok(fresh) => {
318 *tokens = fresh;
319 Ok(())
320 }
321 Err(err) if is_rotation_4xx(&err) => {
322 let disk = load_tokens(&self.auth_path)
323 .wrap_err("Codex refresh token rejected and reloading auth.json failed")?;
324 let fresh = refresh_tokens(
325 &self.http,
326 &disk.refresh_token,
327 disk.account_id.as_deref(),
328 )
329 .await
330 .wrap_err(
331 "Codex refresh failed even after reloading auth.json (run `codex login`)",
332 )?;
333 *tokens = fresh;
334 Ok(())
335 }
336 Err(err) => Err(err),
337 }
338 }
339
340 async fn current_access(&self) -> Result<(String, Option<String>)> {
343 let mut guard = self.tokens.lock().await;
344 if guard.is_expired() {
345 self.refresh_locked(&mut guard).await?;
346 }
347 Ok((guard.access_token.clone(), guard.account_id.clone()))
348 }
349
350 async fn force_refresh(&self, used_access: &str) -> Result<(String, Option<String>)> {
353 let mut guard = self.tokens.lock().await;
354 if guard.access_token != used_access {
355 return Ok((guard.access_token.clone(), guard.account_id.clone()));
356 }
357 self.refresh_locked(&mut guard).await?;
358 Ok((guard.access_token.clone(), guard.account_id.clone()))
359 }
360
361 async fn send(
363 &self,
364 completion: &Completion,
365 access: &str,
366 account_id: Option<&str>,
367 ) -> Result<CompletionResponse> {
368 let wire = codex_wire(&completion.model, access, account_id);
369 let model = rig_core::Model::new(wire, rig_reqwest::ReqwestClient::from(self.http.clone()));
370 let response = model
371 .call(codex_request(completion)?)
372 .await
373 .wrap_err("Codex completion failed")?;
374 Ok(CompletionResponse::from_rig(
375 response,
376 completion.model.clone(),
377 ))
378 }
379}
380
381pub fn shared_client() -> Result<Arc<dyn LLMClientDyn>> {
390 static CELL: OnceLock<StdMutex<Option<Arc<dyn LLMClientDyn>>>> = OnceLock::new();
391 let cell = CELL.get_or_init(|| StdMutex::new(None));
392 let mut guard = cell.lock().expect("codex shared-client mutex poisoned");
393 if let Some(existing) = guard.as_ref() {
394 return Ok(Arc::clone(existing));
395 }
396 let client = CodexClient::new()?.with_retry().into_arc();
397 *guard = Some(Arc::clone(&client));
398 Ok(client)
399}
400
401impl LLMClient for CodexClient {
402 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
403 let (access, account_id) = self.current_access().await?;
404 match self.send(&completion, &access, account_id.as_deref()).await {
405 Ok(response) => Ok(response),
406 Err(err) if provider_http_status(&err) == Some(401) => {
409 let (access, account_id) = self.force_refresh(&access).await?;
410 self.send(&completion, &access, account_id.as_deref()).await
411 }
412 Err(err) => Err(err),
413 }
414 }
415}
416
417fn codex_wire(model: &str, access: &str, account_id: Option<&str>) -> Responses {
422 let mut config = openai::OpenAIConfig::with_key(&chatgpt::DIALECT, access);
423 config.instructions = None;
424 config.dialect.quirks.responses.system_role = "developer";
427 config.identity = Some(CallerIdentity {
428 originator: ORIGINATOR.into(),
429 user_agent: user_agent(),
430 });
431 config.account_id = account_id.map(str::to_owned);
432 Responses::new(config, model).with_system_instructions_as_messages()
433}
434
435fn codex_request(completion: &Completion) -> Result<CompletionRequest> {
436 eyre::ensure!(
437 completion
438 .preamble
439 .as_deref()
440 .is_some_and(|s| !s.trim().is_empty()),
441 "Codex auth requires a system prompt: this completion had no `instructions`"
442 );
443 let mut request = CompletionRequest::from(completion.clone());
444 request.max_tokens = None;
445 request.options.cache_key = Some(codex_prompt_cache_key(completion)?);
446 Ok(request)
447}
448
449fn codex_prompt_cache_key(completion: &Completion) -> Result<String> {
454 fn hash_part(hasher: &mut Sha256, bytes: &[u8]) {
455 hasher.update((bytes.len() as u64).to_be_bytes());
456 hasher.update(bytes);
457 }
458
459 let mut hasher = Sha256::new();
460 hash_part(&mut hasher, completion.model.as_bytes());
461 hash_part(
462 &mut hasher,
463 completion
464 .preamble
465 .as_deref()
466 .unwrap_or_default()
467 .as_bytes(),
468 );
469 let tools = serde_json::to_vec(&completion.tools)
470 .wrap_err("serializing Codex tools for prompt cache routing")?;
471 hash_part(&mut hasher, &tools);
472 let digest = hasher.finalize();
473 let suffix = digest[..16]
474 .iter()
475 .map(|byte| format!("{byte:02x}"))
476 .collect::<String>();
477 Ok(format!("nitpicker-{suffix}"))
478}
479
480fn is_rotation_4xx(err: &eyre::Report) -> bool {
485 provider_http_status(err).is_some_and(|status| (400..500).contains(&status) && status != 429)
486}
487
488#[cfg(test)]
489mod tests {
490 use super::*;
491 use rig_core::completion::message::{
492 AssistantContent, AssistantMessage, CallId, Message, ToolCall, ToolFunction, ToolName,
493 ToolResultContent, UserContent,
494 };
495 use serde_json::json;
496
497 fn jwt(claims: Value) -> String {
500 let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
501 let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
502 format!("{header}.{payload}.sig")
503 }
504
505 #[test]
506 fn account_id_resolution_order() {
507 assert_eq!(
508 account_id_from_claims(&json!({ "chatgpt_account_id": "root" })).as_deref(),
509 Some("root")
510 );
511 assert_eq!(
512 account_id_from_claims(
513 &json!({ "https://api.openai.com/auth": { "chatgpt_account_id": "nested" } })
514 )
515 .as_deref(),
516 Some("nested")
517 );
518 assert_eq!(
520 account_id_from_claims(&json!({
521 "chatgpt_account_id": "root",
522 "https://api.openai.com/auth": { "chatgpt_account_id": "nested" }
523 }))
524 .as_deref(),
525 Some("root")
526 );
527 assert_eq!(
529 account_id_from_claims(
530 &json!({ "organizations": [{ "id": "org-1" }, { "id": "org-2" }] })
531 )
532 .as_deref(),
533 Some("org-1")
534 );
535 assert_eq!(account_id_from_claims(&json!({ "email": "x@y.z" })), None);
536 }
537
538 #[test]
539 fn account_id_prefers_id_token_then_access_token() {
540 let id_token = jwt(json!({ "chatgpt_account_id": "from-id" }));
541 let access = jwt(json!({ "chatgpt_account_id": "from-access" }));
542 assert_eq!(
543 account_id_from_tokens(Some(&id_token), &access).as_deref(),
544 Some("from-id")
545 );
546 let id_token_no_acct = jwt(json!({ "email": "x@y.z" }));
547 assert_eq!(
548 account_id_from_tokens(Some(&id_token_no_acct), &access).as_deref(),
549 Some("from-access")
550 );
551 }
552
553 #[test]
554 fn expiry_from_exp_claim_and_missing() {
555 let with_exp = jwt(json!({ "exp": 4_000_000_000u64 }));
556 assert_eq!(
557 expiry_from_access_token(&with_exp),
558 UNIX_EPOCH + Duration::from_secs(4_000_000_000)
559 );
560 assert_eq!(expiry_from_access_token(&jwt(json!({}))), UNIX_EPOCH);
562 assert_eq!(expiry_from_access_token("not-a-jwt"), UNIX_EPOCH);
563 }
564
565 #[test]
566 fn parse_tokens_full_and_derived_account_id() {
567 let access = jwt(json!({ "exp": 4_000_000_000u64 }));
568 let raw = json!({
570 "tokens": { "access_token": access, "refresh_token": "rt", "account_id": "acct-explicit" }
571 })
572 .to_string();
573 let t = parse_tokens(&raw, "test").unwrap();
574 assert_eq!(t.account_id.as_deref(), Some("acct-explicit"));
575 assert!(!t.is_expired());
576
577 let id_token = jwt(json!({ "chatgpt_account_id": "acct-derived" }));
579 let raw = json!({
580 "tokens": { "access_token": access, "refresh_token": "rt", "id_token": id_token }
581 })
582 .to_string();
583 let t = parse_tokens(&raw, "test").unwrap();
584 assert_eq!(t.account_id.as_deref(), Some("acct-derived"));
585 }
586
587 #[test]
588 fn parse_tokens_rejects_api_key_mode_and_missing_fields() {
589 let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
591 assert!(parse_tokens(&raw, "test").is_err());
592 let raw = json!({ "tokens": { "refresh_token": "rt" } }).to_string();
594 assert!(parse_tokens(&raw, "test").is_err());
595 }
596
597 fn build_body_value(completion: &Completion) -> Result<Value> {
598 use rig_core::wire::{Body, Mode, Wire};
599 let wire = codex_wire(&completion.model, "unused", None);
600 let encoded = wire.encode(codex_request(completion)?, Mode::Unary)?;
601 let Body::Bytes(bytes) = encoded.request.into_body() else {
602 panic!("expected a JSON body")
603 };
604 Ok(serde_json::from_slice(&bytes)?)
605 }
606
607 #[test]
608 fn build_body_applies_codex_quirks() {
609 let completion = Completion {
610 model: "gpt-5.4".to_string(),
611 prompt: Message::user("hello"),
612 preamble: Some("You are a reviewer.".to_string()),
613 history: vec![],
614 tools: vec![],
615 tool_choice: None,
616 max_tokens: Some(4096),
617 additional_params: None,
618 };
619 let json = build_body_value(&completion).unwrap();
620 assert!(json.get("instructions").is_none());
621 assert_eq!(json["stream"], true);
622 assert!(json.get("max_output_tokens").is_none());
623 assert_eq!(json.get("store"), Some(&Value::Bool(false)));
624 assert!(
625 json.get("prompt_cache_key")
626 .and_then(Value::as_str)
627 .is_some_and(|key| key.starts_with("nitpicker-")),
628 "Codex requests must carry a stable prompt cache routing key"
629 );
630 assert_eq!(
632 json.get("include").and_then(Value::as_array),
633 Some(&vec![Value::String(
634 "reasoning.encrypted_content".to_string()
635 )]),
636 "must request reasoning.encrypted_content to avoid bare rs_ id 404s"
637 );
638 assert_eq!(
640 json["input"][0],
641 json!({
642 "type": "message",
643 "role": "developer",
644 "content": [{"type": "input_text", "text": "You are a reviewer."}],
645 })
646 );
647 }
648
649 #[test]
650 fn build_body_requires_a_system_prompt() {
651 let completion = Completion {
652 model: "gpt-5.4".to_string(),
653 prompt: Message::user("hello"),
654 preamble: None,
655 history: vec![],
656 tools: vec![],
657 tool_choice: None,
658 max_tokens: None,
659 additional_params: None,
660 };
661 assert!(build_body_value(&completion).is_err());
662 }
663
664 #[test]
665 fn prompt_cache_key_tracks_the_stable_prefix_not_the_conversation_tail() {
666 let first = Completion {
667 model: "gpt-5.4".to_string(),
668 prompt: Message::user("initial request"),
669 preamble: Some("stable reviewer and project context".to_string()),
670 history: vec![],
671 tools: vec![rig_core::completion::ToolDefinition {
672 name: ToolName::new("read_file").unwrap(),
673 annotations: Default::default(),
674 description: "Read a file".to_string(),
675 parameters: json!({
676 "type": "object",
677 "properties": { "path": { "type": "string" } }
678 }),
679 }],
680 tool_choice: None,
681 max_tokens: None,
682 additional_params: None,
683 };
684 let mut later_turn = first.clone();
685 later_turn.history = vec![
686 Message::user("initial request"),
687 Message::assistant("intermediate answer"),
688 ];
689 later_turn.prompt = Message::user("continue");
690
691 let first_key = codex_prompt_cache_key(&first).unwrap();
692 let later_key = codex_prompt_cache_key(&later_turn).unwrap();
693 assert_eq!(first_key, later_key);
694
695 let mut different_prefix = later_turn;
696 different_prefix.preamble = Some("different reviewer or project context".to_string());
697 let different_key = codex_prompt_cache_key(&different_prefix).unwrap();
698 assert_ne!(first_key, different_key);
699 }
700
701 #[test]
702 fn build_body_preserves_existing_additional_params() {
703 let completion = Completion {
704 model: "gpt-5.4".to_string(),
705 prompt: Message::user("hello"),
706 preamble: Some("sys".to_string()),
707 history: vec![],
708 tools: vec![],
709 tool_choice: None,
710 max_tokens: None,
711 additional_params: Some(json!({ "reasoning": { "effort": "low" } })),
712 };
713 let json = build_body_value(&completion).unwrap();
714 assert_eq!(json.get("store"), Some(&Value::Bool(false)));
715 assert!(json.get("reasoning").is_some());
716 }
717
718 #[test]
719 fn body_value_preserves_assistant_text_history() {
720 let completion = Completion {
721 model: "gpt-5.5".to_string(),
722 prompt: Message::user("continue"),
723 preamble: Some("sys".to_string()),
724 history: vec![Message::assistant("previous answer")],
725 tools: vec![],
726 tool_choice: None,
727 max_tokens: None,
728 additional_params: None,
729 };
730
731 let body = build_body_value(&completion).unwrap();
732 let assistant_message = body["input"]
733 .as_array()
734 .unwrap()
735 .iter()
736 .find(|item| item.get("role").and_then(Value::as_str) == Some("assistant"))
737 .unwrap();
738
739 assert_eq!(assistant_message["content"][0]["text"], "previous answer");
740 }
741
742 #[test]
745 fn body_value_omits_foreign_function_call_item_id() {
746 let tool_id = "tool_5Xt5WpWtZ6Whah4Z2uZcZO34";
747 let call = ToolCall::new(
748 CallId::from_wire(tool_id),
749 ToolFunction::new(
750 ToolName::new("read_file").unwrap(),
751 json!({"path":"src/main.rs"}),
752 ),
753 );
754 let result = call.result(vec![ToolResultContent::text("ok")]);
755 let completion = Completion {
756 model: "gpt-5.5".to_string(),
757 prompt: Message::user("continue"),
758 preamble: Some("sys".to_string()),
759 history: vec![
760 Message::Assistant(AssistantMessage::new(vec![AssistantContent::ToolCall(
761 call,
762 )])),
763 Message::User {
764 content: vec![UserContent::ToolResult(result)],
765 },
766 ],
767 tools: vec![],
768 tool_choice: None,
769 max_tokens: None,
770 additional_params: None,
771 };
772
773 let body = build_body_value(&completion).unwrap();
774 let function_call = body["input"]
775 .as_array()
776 .unwrap()
777 .iter()
778 .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
779 .unwrap();
780
781 assert!(function_call.get("id").is_none());
782 assert_eq!(function_call["call_id"], tool_id);
783
784 let function_call_output = body["input"]
786 .as_array()
787 .unwrap()
788 .iter()
789 .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output"))
790 .unwrap();
791 assert_eq!(function_call_output["call_id"], tool_id);
792 }
793
794 #[test]
795 fn resolve_auth_path_modes() {
796 let p = resolve_auth_path(Some("/custom/codex"), Some(PathBuf::from("/home/u"))).unwrap();
798 assert_eq!(p, PathBuf::from("/custom/codex/auth.json"));
799 assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
801 let p = resolve_auth_path(Some(" "), Some(PathBuf::from("/home/u"))).unwrap();
803 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
804 let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
806 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
807 assert!(resolve_auth_path(None, None).is_err());
809 }
810
811 async fn codex_reply(sse: String) -> Result<CompletionResponse> {
812 use tokio::io::{AsyncReadExt, AsyncWriteExt};
813 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
814 let base_url = format!("http://{}", listener.local_addr()?);
815 let server = tokio::spawn(async move {
816 let (mut socket, _) = listener.accept().await.unwrap();
817 let mut request = Vec::new();
818 loop {
819 assert_ne!(socket.read_buf(&mut request).await.unwrap(), 0);
820 if let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") {
821 let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
822 let length: usize = headers
823 .lines()
824 .find_map(|line| line.strip_prefix("content-length: "))
825 .unwrap()
826 .parse()
827 .unwrap();
828 if request.len() >= end + 4 + length {
829 break;
830 }
831 }
832 }
833 let response = format!(
834 "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{sse}",
835 sse.len()
836 );
837 socket.write_all(response.as_bytes()).await.unwrap();
838 });
839 let mut wire = codex_wire("gpt-5.4", "unused", None);
840 wire.provider = wire.provider.with_base_url(base_url);
841 let model =
842 rig_core::Model::new(wire, rig_reqwest::ReqwestClient::from(build_http_client()?));
843 let response = model
844 .call(CompletionRequest::new("hello").preamble("sys"))
845 .await;
846 server.await?;
847 Ok(CompletionResponse::from_rig(response?, "gpt-5.4".into()))
848 }
849
850 #[tokio::test]
851 async fn parse_sse_accumulates_output_items_with_empty_completed() {
852 let item = json!({
854 "type": "message",
855 "id": "msg_1",
856 "role": "assistant",
857 "status": "completed",
858 "content": [{ "type": "output_text", "text": "pong" }]
859 });
860 let completed = json!({
861 "id": "resp_1",
862 "object": "response",
863 "created_at": 1,
864 "status": "completed",
865 "model": "gpt-5.4",
866 "output": [],
867 "usage": {
868 "input_tokens": 5000,
869 "input_tokens_details": { "cached_tokens": 4800 },
870 "output_tokens": 1,
871 "output_tokens_details": { "reasoning_tokens": 0 },
872 "total_tokens": 5001
873 }
874 });
875 let sse = format!(
876 "data: {}\n\ndata: {}\n\ndata: [DONE]\n",
877 json!({ "type": "response.output_item.done", "item": item }),
878 json!({ "type": "response.completed", "response": completed })
879 );
880 let resp = codex_reply(sse).await.unwrap();
881 assert_eq!(resp.text(), "pong");
882 assert_eq!(resp.finish_reason, crate::llm::FinishReason::Stop);
883 assert_eq!(resp.usage.input_tokens, 5000);
885 assert_eq!(resp.usage.cached_input_tokens, 4800);
886 assert_eq!(resp.usage.total_tokens, 5001);
887 }
888
889 #[tokio::test]
890 async fn parse_sse_surfaces_error_events() {
891 let sse = format!(
892 "data: {}\n\n",
893 json!({ "type": "response.failed", "error": { "message": "boom" } })
894 );
895 assert!(codex_reply(sse).await.is_err());
896 }
897
898 #[tokio::test]
899 async fn parse_sse_preserves_codes_from_large_error_events() {
900 let sse = format!(
901 "data: {}\n\n",
902 json!({
903 "type": "response.failed",
904 "error": {
905 "type": "usage_limit_reached",
906 "message": "quota exhausted",
907 "diagnostic": "x".repeat(4_000),
908 }
909 })
910 );
911 let err = codex_reply(sse).await.unwrap_err();
912 assert!(crate::llm::provider_error_has_code(
913 &err,
914 &["usage_limit_reached"]
915 ));
916 }
917
918 fn usage_json() -> Value {
919 json!({
920 "input_tokens": 5,
921 "input_tokens_details": { "cached_tokens": 0 },
922 "output_tokens": 1,
923 "output_tokens_details": { "reasoning_tokens": 0 },
924 "total_tokens": 6
925 })
926 }
927
928 #[tokio::test]
929 async fn parse_sse_handles_incomplete_as_max_tokens() {
930 let item = json!({
932 "type": "message", "id": "m", "role": "assistant", "status": "incomplete",
933 "content": [{ "type": "output_text", "text": "partial" }]
934 });
935 let response = json!({
936 "id": "r", "object": "response", "created_at": 1, "status": "incomplete",
937 "model": "gpt-5.4", "output": [],
938 "incomplete_details": { "reason": "max_output_tokens" },
939 "usage": usage_json()
940 });
941 let sse = format!(
942 "data: {}\n\ndata: {}\n\n",
943 json!({ "type": "response.output_item.done", "item": item }),
944 json!({ "type": "response.incomplete", "response": response })
945 );
946 let resp = codex_reply(sse).await.unwrap();
947 assert_eq!(resp.text(), "partial");
948 assert_eq!(resp.finish_reason, crate::llm::FinishReason::MaxTokens);
949 }
950
951 #[tokio::test]
952 async fn parse_sse_rejoins_multiline_data_fields() {
953 let completed = json!({
956 "type": "response.completed",
957 "response": {
958 "id": "r", "object": "response", "created_at": 1, "status": "completed",
959 "model": "gpt-5.4",
960 "output": [{
961 "type": "message", "id": "m", "role": "assistant", "status": "completed",
962 "content": [{ "type": "output_text", "text": "hi" }]
963 }],
964 "usage": usage_json()
965 }
966 })
967 .to_string();
968 let comma = completed.find(',').unwrap();
969 let (head, tail) = completed.split_at(comma);
970 let sse = format!("data: {head}\ndata: {tail}\n\n");
971 let resp = codex_reply(sse).await.unwrap();
972 assert_eq!(resp.text(), "hi");
973 }
974
975 #[test]
976 fn is_rotation_4xx_excludes_429_and_5xx() {
977 let mk = |status| {
978 eyre::Report::new(ProviderError::from_http_response(
979 reqwest::StatusCode::from_u16(status).unwrap(),
980 r#"{"error":"test"}"#,
981 ))
982 };
983 assert!(is_rotation_4xx(&mk(400)));
984 assert!(is_rotation_4xx(&mk(401)));
985 assert!(!is_rotation_4xx(&mk(429)));
987 assert!(!is_rotation_4xx(&mk(500)));
988 }
989}