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 Completion, CompletionResponse, FinishReason, LLMClient, LLMClientDyn, TokenUsage,
27 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);
41
42fn user_agent() -> String {
43 format!(
44 "nitpicker/{} ({}; {})",
45 env!("CARGO_PKG_VERSION"),
46 std::env::consts::OS,
47 std::env::consts::ARCH
48 )
49}
50
51fn decode_jwt_claims(token: &str) -> Option<Value> {
56 let payload = token.split('.').nth(1)?;
57 let bytes = URL_SAFE_NO_PAD.decode(payload).ok()?;
58 serde_json::from_slice(&bytes).ok()
59}
60
61fn account_id_from_claims(claims: &Value) -> Option<String> {
63 let direct = claims.get("chatgpt_account_id").and_then(Value::as_str);
64 let nested = claims
65 .get("https://api.openai.com/auth")
66 .and_then(|a| a.get("chatgpt_account_id"))
67 .and_then(Value::as_str);
68 let org = claims
69 .get("organizations")
70 .and_then(Value::as_array)
71 .and_then(|orgs| orgs.first())
72 .and_then(|o| o.get("id"))
73 .and_then(Value::as_str);
74 direct.or(nested).or(org).map(str::to_string)
75}
76
77fn account_id_from_tokens(id_token: Option<&str>, access_token: &str) -> Option<String> {
78 id_token
79 .and_then(decode_jwt_claims)
80 .as_ref()
81 .and_then(account_id_from_claims)
82 .or_else(|| {
83 decode_jwt_claims(access_token)
84 .as_ref()
85 .and_then(account_id_from_claims)
86 })
87}
88
89fn expiry_from_access_token(access_token: &str) -> SystemTime {
93 decode_jwt_claims(access_token)
94 .and_then(|c| c.get("exp").and_then(Value::as_u64))
95 .and_then(|exp| UNIX_EPOCH.checked_add(Duration::from_secs(exp)))
98 .unwrap_or(UNIX_EPOCH)
99}
100
101#[derive(Clone)]
106struct CodexTokens {
107 access_token: String,
108 refresh_token: String,
109 account_id: Option<String>,
110 expires_at: SystemTime,
111}
112
113impl CodexTokens {
114 fn is_expired(&self) -> bool {
115 self.expires_at <= SystemTime::now() + EXPIRY_SKEW
116 }
117}
118
119fn auth_path() -> Result<PathBuf> {
121 resolve_auth_path(
122 std::env::var("CODEX_HOME").ok().as_deref(),
123 dirs::home_dir(),
124 )
125}
126
127fn resolve_auth_path(codex_home: Option<&str>, home_dir: Option<PathBuf>) -> Result<PathBuf> {
129 if let Some(home) = codex_home {
130 let trimmed = home.trim();
131 if !trimmed.is_empty() {
132 let path = Path::new(trimmed);
133 if path.is_absolute() {
134 return Ok(path.join("auth.json"));
135 }
136 eyre::bail!("CODEX_HOME must be an absolute path, got \"{home}\"");
137 }
138 }
139 let home =
140 home_dir.ok_or_else(|| eyre::eyre!("cannot resolve home directory (set CODEX_HOME)"))?;
141 Ok(home.join(".codex").join("auth.json"))
142}
143
144fn load_tokens(path: &Path) -> Result<CodexTokens> {
145 let raw = std::fs::read_to_string(path).wrap_err_with(|| {
146 format!(
147 "cannot read {} — run `codex login` with a ChatGPT subscription first",
148 path.display()
149 )
150 })?;
151 parse_tokens(&raw, &path.display().to_string())
152}
153
154pub fn auth_available() -> bool {
158 auth_path().and_then(|p| load_tokens(&p)).is_ok()
159}
160
161fn parse_tokens(raw: &str, source: &str) -> Result<CodexTokens> {
163 let v: Value =
164 serde_json::from_str(raw).wrap_err_with(|| format!("invalid JSON in {source}"))?;
165 let tokens = v.get("tokens").ok_or_else(|| {
166 eyre::eyre!(
167 "no ChatGPT subscription tokens in {source} — run `codex login` (API-key mode is not supported here)"
168 )
169 })?;
170 let access_token = tokens
171 .get("access_token")
172 .and_then(Value::as_str)
173 .filter(|s| !s.is_empty())
174 .ok_or_else(|| eyre::eyre!("no access_token in {source}"))?
175 .to_string();
176 let refresh_token = tokens
177 .get("refresh_token")
178 .and_then(Value::as_str)
179 .filter(|s| !s.is_empty())
180 .ok_or_else(|| eyre::eyre!("no refresh_token in {source}"))?
181 .to_string();
182 let account_id = tokens
183 .get("account_id")
184 .and_then(Value::as_str)
185 .filter(|s| !s.is_empty())
186 .map(str::to_string)
187 .or_else(|| {
188 account_id_from_tokens(
189 tokens.get("id_token").and_then(Value::as_str),
190 &access_token,
191 )
192 });
193 let expires_at = expiry_from_access_token(&access_token);
194 Ok(CodexTokens {
195 access_token,
196 refresh_token,
197 account_id,
198 expires_at,
199 })
200}
201
202#[derive(serde::Deserialize)]
203struct RefreshResponse {
204 access_token: String,
205 refresh_token: Option<String>,
206 id_token: Option<String>,
207 expires_in: Option<u64>,
208}
209
210async fn refresh_tokens(
213 http: &reqwest::Client,
214 refresh_token: &str,
215 prev_account_id: Option<&str>,
216) -> Result<CodexTokens> {
217 let resp = http
218 .post(TOKEN_URL)
219 .timeout(REFRESH_TIMEOUT)
220 .form(&[
221 ("grant_type", "refresh_token"),
222 ("refresh_token", refresh_token),
223 ("client_id", CLIENT_ID),
224 ])
225 .send()
226 .await
227 .wrap_err("Codex token refresh request failed")?;
228 let status = resp.status();
229 let body = resp.text().await.unwrap_or_default();
230 if !status.is_success() {
231 eyre::bail!(
235 "Codex token refresh returned HTTP {status}: {}",
236 truncate(&body, 1000)
237 );
238 }
239 let parsed: RefreshResponse =
240 serde_json::from_str(&body).wrap_err("parsing Codex token refresh response")?;
241 let expires_at = match parsed.expires_in {
244 Some(secs) => SystemTime::now()
247 .checked_add(Duration::from_secs(secs))
248 .unwrap_or_else(|| expiry_from_access_token(&parsed.access_token)),
249 None => expiry_from_access_token(&parsed.access_token),
250 };
251 let account_id = prev_account_id
252 .map(str::to_string)
253 .or_else(|| account_id_from_tokens(parsed.id_token.as_deref(), &parsed.access_token));
254 Ok(CodexTokens {
255 access_token: parsed.access_token,
256 refresh_token: parsed
257 .refresh_token
258 .unwrap_or_else(|| refresh_token.to_string()),
259 account_id,
260 expires_at,
261 })
262}
263
264pub struct CodexClient {
269 http: reqwest::Client,
270 auth_path: PathBuf,
271 tokens: Mutex<CodexTokens>,
272}
273
274impl CodexClient {
275 pub fn new() -> Result<Self> {
277 let path = auth_path()?;
278 let tokens = load_tokens(&path)?;
279 Ok(Self {
280 http: reqwest::Client::new(),
281 auth_path: path,
282 tokens: Mutex::new(tokens),
283 })
284 }
285
286 async fn refresh_locked(&self, tokens: &mut CodexTokens) -> Result<()> {
295 match refresh_tokens(
296 &self.http,
297 &tokens.refresh_token,
298 tokens.account_id.as_deref(),
299 )
300 .await
301 {
302 Ok(fresh) => {
303 *tokens = fresh;
304 Ok(())
305 }
306 Err(err) if is_rotation_4xx(&err) => {
307 let disk = load_tokens(&self.auth_path)
308 .wrap_err("Codex refresh token rejected and reloading auth.json failed")?;
309 let fresh = refresh_tokens(
310 &self.http,
311 &disk.refresh_token,
312 disk.account_id.as_deref(),
313 )
314 .await
315 .wrap_err(
316 "Codex refresh failed even after reloading auth.json (run `codex login`)",
317 )?;
318 *tokens = fresh;
319 Ok(())
320 }
321 Err(err) => Err(err),
322 }
323 }
324
325 async fn current_access(&self) -> Result<(String, Option<String>)> {
328 let mut guard = self.tokens.lock().await;
329 if guard.is_expired() {
330 self.refresh_locked(&mut guard).await?;
331 }
332 Ok((guard.access_token.clone(), guard.account_id.clone()))
333 }
334
335 async fn force_refresh(&self, used_access: &str) -> Result<(String, Option<String>)> {
338 let mut guard = self.tokens.lock().await;
339 if guard.access_token != used_access {
340 return Ok((guard.access_token.clone(), guard.account_id.clone()));
341 }
342 self.refresh_locked(&mut guard).await?;
343 Ok((guard.access_token.clone(), guard.account_id.clone()))
344 }
345
346 async fn send(
353 &self,
354 completion: &Completion,
355 access: &str,
356 account_id: Option<&str>,
357 ) -> Result<CompletionResponse> {
358 let body = build_body_value(completion)?;
359 let mut req = self
360 .http
361 .post(format!("{CODEX_BASE_URL}/responses"))
362 .bearer_auth(access)
363 .header("originator", ORIGINATOR)
364 .header(reqwest::header::USER_AGENT, user_agent())
365 .header(reqwest::header::ACCEPT, "text/event-stream")
366 .json(&body);
367 if let Some(id) = account_id {
368 req = req.header("ChatGPT-Account-Id", id);
369 }
370 let resp = req
371 .send()
372 .await
373 .wrap_err("Codex completion request failed")?;
374 let status = resp.status();
375 let text = resp
376 .text()
377 .await
378 .wrap_err("reading Codex completion response")?;
379 if !status.is_success() {
380 eyre::bail!("Codex API HTTP {status}: {}", truncate(&text, 1000));
382 }
383 let raw = parse_sse(&text)?;
384 let model = completion.model.clone();
385 to_completion_response(raw, model)
386 }
387}
388
389pub fn shared_client() -> Result<Arc<dyn LLMClientDyn>> {
398 static CELL: OnceLock<StdMutex<Option<Arc<dyn LLMClientDyn>>>> = OnceLock::new();
399 let cell = CELL.get_or_init(|| StdMutex::new(None));
400 let mut guard = cell.lock().expect("codex shared-client mutex poisoned");
401 if let Some(existing) = guard.as_ref() {
402 return Ok(Arc::clone(existing));
403 }
404 let client = CodexClient::new()?.with_retry().into_arc();
405 *guard = Some(Arc::clone(&client));
406 Ok(client)
407}
408
409impl LLMClient for CodexClient {
410 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
411 let (access, account_id) = self.current_access().await?;
412 match self.send(&completion, &access, account_id.as_deref()).await {
413 Ok(response) => Ok(response),
414 Err(err) if mentions_http_status(&format!("{err:#}"), 401) => {
417 let (access, account_id) = self.force_refresh(&access).await?;
418 self.send(&completion, &access, account_id.as_deref()).await
419 }
420 Err(err) => Err(err),
421 }
422 }
423}
424
425fn build_body(completion: &Completion) -> Result<ResponsesBody> {
431 let mut c = completion.clone();
432 normalize_codex_completion_history(&mut c);
433 c.max_tokens = None;
435 let instructions = c.preamble.take();
438 let instructions = match instructions {
439 Some(s) if !s.trim().is_empty() => s,
440 _ => eyre::bail!(
441 "Codex auth requires a system prompt: this completion had no `instructions`"
442 ),
443 };
444 let model = c.model.clone();
445 let rig_req: rig_core::completion::CompletionRequest = c.into();
446 let mut body = ResponsesBody::try_from((model, rig_req))
447 .map_err(|e| eyre::eyre!("lowering completion to Codex Responses body failed: {e}"))?;
448 body.instructions = Some(instructions);
449 body.stream = Some(true);
450 body.max_output_tokens = None;
451 let params = &mut body.additional_parameters;
459 params.store = Some(false);
460 let include = params.include.get_or_insert_with(Vec::new);
461 if !include
462 .iter()
463 .any(|i| matches!(i, Include::ReasoningEncryptedContent))
464 {
465 include.push(Include::ReasoningEncryptedContent);
466 }
467 Ok(body)
468}
469
470fn build_body_value(completion: &Completion) -> Result<Value> {
471 let body = build_body(completion)?;
472 let mut value = serde_json::to_value(&body).wrap_err("serializing Codex Responses request")?;
473 normalize_codex_responses_request(&mut value);
474 Ok(value)
475}
476
477fn normalize_codex_responses_request(body: &mut Value) {
478 let Some(items) = body.get_mut("input").and_then(Value::as_array_mut) else {
479 return;
480 };
481 for item in items {
482 normalize_codex_input_item(item);
483 }
484}
485
486fn normalize_codex_input_item(item: &mut Value) {
487 match item.get("type").and_then(Value::as_str) {
488 Some("function_call") => normalize_codex_function_call_item(item),
489 _ => normalize_codex_message_item(item),
490 }
491}
492
493fn normalize_codex_message_item(item: &mut Value) {
494 if item.get("role").and_then(Value::as_str) != Some("assistant") {
495 return;
496 }
497 let Some(content) = item.get_mut("content").and_then(Value::as_array_mut) else {
498 return;
499 };
500 for part in content {
501 match part.get("type").and_then(Value::as_str) {
502 Some("input_text" | "text") => {
503 if let Some(map) = part.as_object_mut() {
504 map.insert("type".to_string(), Value::String("output_text".to_string()));
505 }
506 }
507 _ => {}
508 }
509 }
510}
511
512fn normalize_codex_function_call_item(item: &mut Value) {
513 let replacement = item
514 .get("id")
515 .and_then(Value::as_str)
516 .filter(|id| !id.starts_with("fc"))
517 .map(|id| format!("fc_{id}"));
518 if let Some(id) = replacement {
519 item["id"] = Value::String(id);
520 }
521}
522
523fn normalize_codex_completion_history(completion: &mut Completion) {
524 for message in completion
525 .history
526 .iter_mut()
527 .chain(std::iter::once(&mut completion.prompt))
528 {
529 match message {
530 rig_core::completion::Message::Assistant { content, .. } => {
531 for item in content.iter_mut() {
532 match item {
533 AssistantContent::ToolCall(call) if call.call_id.is_none() => {
534 call.call_id = Some(call.id.clone());
535 }
536 _ => {}
537 }
538 }
539 }
540 rig_core::completion::Message::User { content } => {
541 for item in content.iter_mut() {
542 match item {
543 UserContent::ToolResult(result) if result.call_id.is_none() => {
544 result.call_id = Some(result.id.clone());
545 }
546 _ => {}
547 }
548 }
549 }
550 rig_core::completion::Message::System { .. } => {}
551 }
552 }
553}
554
555fn sse_event_payloads(text: &str) -> Vec<String> {
559 let mut events = vec![];
560 let mut current = String::new();
561 for line in text.lines() {
562 if line.is_empty() {
563 if !current.is_empty() {
564 events.push(std::mem::take(&mut current));
565 }
566 continue;
567 }
568 if let Some(rest) = line.strip_prefix("data:") {
569 if !current.is_empty() {
570 current.push('\n');
571 }
572 current.push_str(rest.strip_prefix(' ').unwrap_or(rest));
574 }
575 }
577 if !current.is_empty() {
578 events.push(current);
579 }
580 events
581}
582
583fn parse_sse(text: &str) -> Result<ResponsesResp> {
588 let mut items: Vec<Value> = vec![];
589 let mut last_parse_err: Option<String> = None;
590 for data in sse_event_payloads(text) {
591 let data = data.trim();
592 if data.is_empty() || data == "[DONE]" {
593 continue;
594 }
595 let ev: Value = match serde_json::from_str(data) {
596 Ok(v) => v,
597 Err(e) => {
600 last_parse_err = Some(e.to_string());
601 continue;
602 }
603 };
604 match ev.get("type").and_then(Value::as_str) {
605 Some("response.output_item.done") => {
606 if let Some(item) = ev.get("item") {
607 items.push(item.clone());
608 }
609 }
610 Some("response.completed") | Some("response.incomplete") => {
611 let mut response = ev
612 .get("response")
613 .cloned()
614 .ok_or_else(|| eyre::eyre!("Codex terminal SSE event missing `response`"))?;
615 let echoed_output = response
618 .get("output")
619 .and_then(Value::as_array)
620 .is_some_and(|a| !a.is_empty());
621 if !echoed_output {
622 response["output"] = Value::Array(std::mem::take(&mut items));
623 }
624 return serde_json::from_value::<ResponsesResp>(response)
625 .wrap_err("parsing Codex terminal response payload");
626 }
627 Some("response.failed") | Some("error") => {
628 eyre::bail!(
629 "Codex stream error event: {}",
630 truncate(&ev.to_string(), 1000)
631 );
632 }
633 _ => {}
634 }
635 }
636 match last_parse_err {
637 Some(e) => eyre::bail!("no terminal event in Codex SSE stream; last parse error: {e}"),
638 None => eyre::bail!(
639 "no terminal event in Codex SSE stream: {}",
640 truncate(text, 1000)
641 ),
642 }
643}
644
645fn to_completion_response(raw: ResponsesResp, model: String) -> Result<CompletionResponse> {
646 let incomplete_reason = raw.incomplete_details.as_ref().map(|d| d.reason.clone());
647 let parsed: rig_core::completion::CompletionResponse<ResponsesResp> = raw
648 .try_into()
649 .map_err(|e| eyre::eyre!("parsing Codex response into completion: {e}"))?;
650 let has_tool_call = parsed
651 .choice
652 .iter()
653 .any(|c| matches!(c, AssistantContent::ToolCall(_)));
654 let finish_reason = if has_tool_call {
655 FinishReason::ToolUse
656 } else {
657 match incomplete_reason.as_deref() {
658 Some("max_output_tokens") => FinishReason::MaxTokens,
659 Some(other) => FinishReason::Other(other.to_string()),
660 None => FinishReason::Stop,
661 }
662 };
663 Ok(CompletionResponse {
664 choice: parsed.choice,
666 finish_reason,
667 usage: TokenUsage::new(parsed.usage.input_tokens, parsed.usage.output_tokens),
668 selected_model: Some(model),
669 })
670}
671
672fn truncate(s: &str, max: usize) -> String {
673 if s.len() <= max {
674 return s.to_string();
675 }
676 let end = (0..=max)
677 .rev()
678 .find(|&i| s.is_char_boundary(i))
679 .unwrap_or(0);
680 format!("{}…", &s[..end])
681}
682
683fn is_rotation_4xx(err: &eyre::Report) -> bool {
688 let msg = format!("{err:#}");
689 (400..500)
690 .filter(|status| *status != 429)
691 .any(|status| mentions_http_status(&msg, status))
692}
693
694#[cfg(test)]
695mod tests {
696 use super::*;
697 use rig_core::OneOrMany;
698 use rig_core::completion::message::{
699 Message, ToolCall, ToolFunction, ToolResult, ToolResultContent,
700 };
701 use serde_json::json;
702
703 fn jwt(claims: Value) -> String {
706 let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
707 let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
708 format!("{header}.{payload}.sig")
709 }
710
711 #[test]
712 fn account_id_resolution_order() {
713 assert_eq!(
714 account_id_from_claims(&json!({ "chatgpt_account_id": "root" })).as_deref(),
715 Some("root")
716 );
717 assert_eq!(
718 account_id_from_claims(
719 &json!({ "https://api.openai.com/auth": { "chatgpt_account_id": "nested" } })
720 )
721 .as_deref(),
722 Some("nested")
723 );
724 assert_eq!(
726 account_id_from_claims(&json!({
727 "chatgpt_account_id": "root",
728 "https://api.openai.com/auth": { "chatgpt_account_id": "nested" }
729 }))
730 .as_deref(),
731 Some("root")
732 );
733 assert_eq!(
735 account_id_from_claims(
736 &json!({ "organizations": [{ "id": "org-1" }, { "id": "org-2" }] })
737 )
738 .as_deref(),
739 Some("org-1")
740 );
741 assert_eq!(account_id_from_claims(&json!({ "email": "x@y.z" })), None);
742 }
743
744 #[test]
745 fn account_id_prefers_id_token_then_access_token() {
746 let id_token = jwt(json!({ "chatgpt_account_id": "from-id" }));
747 let access = jwt(json!({ "chatgpt_account_id": "from-access" }));
748 assert_eq!(
749 account_id_from_tokens(Some(&id_token), &access).as_deref(),
750 Some("from-id")
751 );
752 let id_token_no_acct = jwt(json!({ "email": "x@y.z" }));
753 assert_eq!(
754 account_id_from_tokens(Some(&id_token_no_acct), &access).as_deref(),
755 Some("from-access")
756 );
757 }
758
759 #[test]
760 fn expiry_from_exp_claim_and_missing() {
761 let with_exp = jwt(json!({ "exp": 4_000_000_000u64 }));
762 assert_eq!(
763 expiry_from_access_token(&with_exp),
764 UNIX_EPOCH + Duration::from_secs(4_000_000_000)
765 );
766 assert_eq!(expiry_from_access_token(&jwt(json!({}))), UNIX_EPOCH);
768 assert_eq!(expiry_from_access_token("not-a-jwt"), UNIX_EPOCH);
769 }
770
771 #[test]
772 fn parse_tokens_full_and_derived_account_id() {
773 let access = jwt(json!({ "exp": 4_000_000_000u64 }));
774 let raw = json!({
776 "tokens": { "access_token": access, "refresh_token": "rt", "account_id": "acct-explicit" }
777 })
778 .to_string();
779 let t = parse_tokens(&raw, "test").unwrap();
780 assert_eq!(t.account_id.as_deref(), Some("acct-explicit"));
781 assert!(!t.is_expired());
782
783 let id_token = jwt(json!({ "chatgpt_account_id": "acct-derived" }));
785 let raw = json!({
786 "tokens": { "access_token": access, "refresh_token": "rt", "id_token": id_token }
787 })
788 .to_string();
789 let t = parse_tokens(&raw, "test").unwrap();
790 assert_eq!(t.account_id.as_deref(), Some("acct-derived"));
791 }
792
793 #[test]
794 fn parse_tokens_rejects_api_key_mode_and_missing_fields() {
795 let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
797 assert!(parse_tokens(&raw, "test").is_err());
798 let raw = json!({ "tokens": { "refresh_token": "rt" } }).to_string();
800 assert!(parse_tokens(&raw, "test").is_err());
801 }
802
803 #[test]
804 fn build_body_applies_codex_quirks() {
805 let completion = Completion {
806 model: "gpt-5.4".to_string(),
807 prompt: Message::user("hello"),
808 preamble: Some("You are a reviewer.".to_string()),
809 history: vec![],
810 tools: vec![],
811 tool_choice: None,
812 max_tokens: Some(4096),
813 additional_params: None,
814 };
815 let body = build_body(&completion).unwrap();
816 assert_eq!(body.instructions.as_deref(), Some("You are a reviewer."));
817 assert_eq!(body.stream, Some(true));
818 assert_eq!(body.max_output_tokens, None);
819 let json = serde_json::to_value(&body).unwrap();
821 assert_eq!(json.get("store"), Some(&Value::Bool(false)));
822 assert_eq!(
824 json.get("include").and_then(Value::as_array),
825 Some(&vec![Value::String(
826 "reasoning.encrypted_content".to_string()
827 )]),
828 "must request reasoning.encrypted_content to avoid bare rs_ id 404s"
829 );
830 let has_system_input = json
832 .get("input")
833 .and_then(Value::as_array)
834 .map(|items| {
835 items
836 .iter()
837 .any(|i| i.get("role").and_then(Value::as_str) == Some("system"))
838 })
839 .unwrap_or(false);
840 assert!(
841 !has_system_input,
842 "system must be in `instructions`, not `input`"
843 );
844 }
845
846 #[test]
847 fn build_body_requires_a_system_prompt() {
848 let completion = Completion {
849 model: "gpt-5.4".to_string(),
850 prompt: Message::user("hello"),
851 preamble: None,
852 history: vec![],
853 tools: vec![],
854 tool_choice: None,
855 max_tokens: None,
856 additional_params: None,
857 };
858 assert!(build_body(&completion).is_err());
859 }
860
861 #[test]
862 fn build_body_preserves_existing_additional_params() {
863 let completion = Completion {
864 model: "gpt-5.4".to_string(),
865 prompt: Message::user("hello"),
866 preamble: Some("sys".to_string()),
867 history: vec![],
868 tools: vec![],
869 tool_choice: None,
870 max_tokens: None,
871 additional_params: Some(json!({ "reasoning": { "effort": "low" } })),
872 };
873 let body = build_body(&completion).unwrap();
874 let json = serde_json::to_value(&body).unwrap();
875 assert_eq!(json.get("store"), Some(&Value::Bool(false)));
876 assert!(json.get("reasoning").is_some());
877 }
878
879 #[test]
880 fn build_body_fills_missing_tool_call_ids_for_mixed_provider_history() {
881 let tool_id = "toolu_1".to_string();
882 let completion = Completion {
883 model: "gpt-5.5".to_string(),
884 prompt: Message::user("continue"),
885 preamble: Some("sys".to_string()),
886 history: vec![
887 Message::Assistant {
888 id: None,
889 content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
890 tool_id.clone(),
891 ToolFunction::new(
892 "read_file".to_string(),
893 json!({ "path": "src/main.rs" }),
894 ),
895 ))),
896 },
897 Message::User {
898 content: OneOrMany::one(UserContent::ToolResult(ToolResult {
899 id: tool_id.clone(),
900 call_id: None,
901 content: OneOrMany::one(ToolResultContent::text("ok")),
902 })),
903 },
904 ],
905 tools: vec![],
906 tool_choice: None,
907 max_tokens: None,
908 additional_params: None,
909 };
910
911 let body = build_body(&completion).unwrap();
912 let json = serde_json::to_value(&body).unwrap();
913 assert!(
914 json.to_string()
915 .contains(&format!("\"call_id\":\"{tool_id}\""))
916 );
917 }
918
919 #[test]
920 fn body_value_rewrites_assistant_text_shape_for_codex() {
921 let mut body = json!({
922 "input": [
923 {
924 "type": "message",
925 "role": "assistant",
926 "content": [
927 { "type": "input_text", "text": "from another provider" },
928 { "type": "text", "text": "legacy text shape" },
929 { "type": "refusal", "refusal": "no" }
930 ]
931 },
932 {
933 "type": "message",
934 "role": "user",
935 "content": [{ "type": "input_text", "text": "keep user input shape" }]
936 }
937 ]
938 });
939
940 normalize_codex_responses_request(&mut body);
941
942 assert_eq!(body["input"][0]["content"][0]["type"], "output_text");
943 assert_eq!(body["input"][0]["content"][1]["type"], "output_text");
944 assert_eq!(body["input"][0]["content"][2]["type"], "refusal");
945 assert_eq!(body["input"][1]["content"][0]["type"], "input_text");
946 }
947
948 #[test]
949 fn body_value_uses_output_text_for_assistant_text_history() {
950 let completion = Completion {
951 model: "gpt-5.5".to_string(),
952 prompt: Message::user("continue"),
953 preamble: Some("sys".to_string()),
954 history: vec![Message::Assistant {
955 id: None,
956 content: OneOrMany::one(AssistantContent::text("previous answer")),
957 }],
958 tools: vec![],
959 tool_choice: None,
960 max_tokens: None,
961 additional_params: None,
962 };
963
964 let body = build_body_value(&completion).unwrap();
965 let assistant_message = body["input"]
966 .as_array()
967 .unwrap()
968 .iter()
969 .find(|item| item.get("role").and_then(Value::as_str) == Some("assistant"))
970 .unwrap();
971
972 assert_eq!(assistant_message["content"][0]["type"], "output_text");
973 }
974
975 #[test]
976 fn body_value_rewrites_function_call_item_id_for_codex() {
977 let tool_id = "tool_5Xt5WpWtZ6Whah4Z2uZcZO34".to_string();
978 let completion = Completion {
979 model: "gpt-5.5".to_string(),
980 prompt: Message::user("continue"),
981 preamble: Some("sys".to_string()),
982 history: vec![
983 Message::Assistant {
984 id: None,
985 content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
986 tool_id.clone(),
987 ToolFunction::new(
988 "read_file".to_string(),
989 json!({ "path": "src/main.rs" }),
990 ),
991 ))),
992 },
993 Message::User {
994 content: OneOrMany::one(UserContent::ToolResult(ToolResult {
995 id: tool_id.clone(),
996 call_id: None,
997 content: OneOrMany::one(ToolResultContent::text("ok")),
998 })),
999 },
1000 ],
1001 tools: vec![],
1002 tool_choice: None,
1003 max_tokens: None,
1004 additional_params: None,
1005 };
1006
1007 let body = build_body_value(&completion).unwrap();
1008 let function_call = body["input"]
1009 .as_array()
1010 .unwrap()
1011 .iter()
1012 .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
1013 .unwrap();
1014
1015 assert_eq!(function_call["id"], format!("fc_{tool_id}"));
1016 assert_eq!(function_call["call_id"], tool_id);
1017 }
1018
1019 #[test]
1020 fn resolve_auth_path_modes() {
1021 let p = resolve_auth_path(Some("/custom/codex"), Some(PathBuf::from("/home/u"))).unwrap();
1023 assert_eq!(p, PathBuf::from("/custom/codex/auth.json"));
1024 assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
1026 let p = resolve_auth_path(Some(" "), Some(PathBuf::from("/home/u"))).unwrap();
1028 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1029 let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
1031 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1032 assert!(resolve_auth_path(None, None).is_err());
1034 }
1035
1036 #[test]
1037 fn truncate_respects_char_boundaries() {
1038 assert_eq!(truncate("hello", 10), "hello");
1039 assert_eq!(truncate("hello", 3), "hel…");
1040 let s = "é".repeat(5); let out = truncate(&s, 3);
1043 assert!(out.ends_with('…'));
1044 assert!(out.chars().filter(|&c| c == 'é').count() <= 1);
1046 }
1047
1048 #[test]
1049 fn parse_sse_accumulates_output_items_with_empty_completed() {
1050 let item = json!({
1052 "type": "message",
1053 "id": "msg_1",
1054 "role": "assistant",
1055 "status": "completed",
1056 "content": [{ "type": "output_text", "text": "pong" }]
1057 });
1058 let completed = json!({
1059 "id": "resp_1",
1060 "object": "response",
1061 "created_at": 1,
1062 "status": "completed",
1063 "model": "gpt-5.4",
1064 "output": [],
1065 "usage": {
1066 "input_tokens": 5,
1067 "input_tokens_details": { "cached_tokens": 0 },
1068 "output_tokens": 1,
1069 "output_tokens_details": { "reasoning_tokens": 0 },
1070 "total_tokens": 6
1071 }
1072 });
1073 let sse = format!(
1074 "data: {}\n\ndata: {}\n\ndata: [DONE]\n",
1075 json!({ "type": "response.output_item.done", "item": item }),
1076 json!({ "type": "response.completed", "response": completed })
1077 );
1078 let raw = parse_sse(&sse).unwrap();
1079 let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1080 assert_eq!(resp.text(), "pong");
1081 assert_eq!(resp.finish_reason, FinishReason::Stop);
1082 assert_eq!(resp.usage.input_tokens, 5);
1083 }
1084
1085 #[test]
1086 fn parse_sse_surfaces_error_events() {
1087 let sse = format!(
1088 "data: {}\n",
1089 json!({ "type": "response.failed", "error": { "message": "boom" } })
1090 );
1091 assert!(parse_sse(&sse).is_err());
1092 }
1093
1094 fn usage_json() -> Value {
1095 json!({
1096 "input_tokens": 5,
1097 "input_tokens_details": { "cached_tokens": 0 },
1098 "output_tokens": 1,
1099 "output_tokens_details": { "reasoning_tokens": 0 },
1100 "total_tokens": 6
1101 })
1102 }
1103
1104 #[test]
1105 fn parse_sse_handles_incomplete_as_max_tokens() {
1106 let item = json!({
1108 "type": "message", "id": "m", "role": "assistant", "status": "incomplete",
1109 "content": [{ "type": "output_text", "text": "partial" }]
1110 });
1111 let response = json!({
1112 "id": "r", "object": "response", "created_at": 1, "status": "incomplete",
1113 "model": "gpt-5.4", "output": [],
1114 "incomplete_details": { "reason": "max_output_tokens" },
1115 "usage": usage_json()
1116 });
1117 let sse = format!(
1118 "data: {}\n\ndata: {}\n",
1119 json!({ "type": "response.output_item.done", "item": item }),
1120 json!({ "type": "response.incomplete", "response": response })
1121 );
1122 let raw = parse_sse(&sse).unwrap();
1123 let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1124 assert_eq!(resp.text(), "partial");
1125 assert_eq!(resp.finish_reason, FinishReason::MaxTokens);
1126 }
1127
1128 #[test]
1129 fn parse_sse_rejoins_multiline_data_fields() {
1130 let completed = json!({
1133 "type": "response.completed",
1134 "response": {
1135 "id": "r", "object": "response", "created_at": 1, "status": "completed",
1136 "model": "gpt-5.4",
1137 "output": [{
1138 "type": "message", "id": "m", "role": "assistant", "status": "completed",
1139 "content": [{ "type": "output_text", "text": "hi" }]
1140 }],
1141 "usage": usage_json()
1142 }
1143 })
1144 .to_string();
1145 let comma = completed.find(',').unwrap();
1146 let (head, tail) = completed.split_at(comma);
1147 let sse = format!("data: {head}\ndata: {tail}\n\n");
1148 let raw = parse_sse(&sse).unwrap();
1149 let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1150 assert_eq!(resp.text(), "hi");
1151 }
1152
1153 #[test]
1154 fn is_rotation_4xx_excludes_429_and_5xx() {
1155 let mk = |s: &str| eyre::eyre!("Codex token refresh returned HTTP {s}");
1156 assert!(is_rotation_4xx(&mk("400 Bad Request")));
1157 assert!(is_rotation_4xx(&mk("401 Unauthorized")));
1158 assert!(!is_rotation_4xx(&mk("429 Too Many Requests")));
1160 assert!(!is_rotation_4xx(&mk("500 Internal Server Error")));
1161 }
1162}