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::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
30const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
32const TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
33const CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
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 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 let expires_at = match parsed.expires_in {
261 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
281pub struct CodexClient {
286 http: reqwest::Client,
287 auth_path: PathBuf,
288 tokens: Mutex<CodexTokens>,
289}
290
291impl CodexClient {
292 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 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 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 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 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 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
406pub 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 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
442fn build_body(completion: &Completion) -> Result<ResponsesBody> {
448 let mut c = completion.clone();
449 normalize_codex_completion_history(&mut c);
450 c.max_tokens = None;
452 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 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> {
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
527fn 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 current.push_str(rest.strip_prefix(' ').unwrap_or(rest));
546 }
547 }
549 if !current.is_empty() {
550 events.push(current);
551 }
552 events
553}
554
555fn 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 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 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 choice: parsed.choice,
638 finish_reason,
639 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
656fn 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 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 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 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 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 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 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 let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
770 assert!(parse_tokens(&raw, "test").is_err());
771 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 let json = serde_json::to_value(&body).unwrap();
794 assert_eq!(json.get("store"), Some(&Value::Bool(false)));
795 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 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 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 #[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 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 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 assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
985 let p = resolve_auth_path(Some(" "), Some(PathBuf::from("/home/u"))).unwrap();
987 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
988 let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
990 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
991 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 let s = "é".repeat(5); let out = truncate(&s, 3);
1002 assert!(out.ends_with('…'));
1003 assert!(out.chars().filter(|&c| c == 'é').count() <= 1);
1005 }
1006
1007 #[test]
1008 fn parse_sse_accumulates_output_items_with_empty_completed() {
1009 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 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 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 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 assert!(!is_rotation_4xx(&mk("429 Too Many Requests")));
1122 assert!(!is_rotation_4xx(&mk("500 Internal Server Error")));
1123 }
1124}