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);
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> {
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
503fn 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
556fn 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 current.push_str(rest.strip_prefix(' ').unwrap_or(rest));
575 }
576 }
578 if !current.is_empty() {
579 events.push(current);
580 }
581 events
582}
583
584fn 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 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 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 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
684fn 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 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 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 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 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 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 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 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 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 let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
816 assert!(parse_tokens(&raw, "test").is_err());
817 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 let json = serde_json::to_value(&body).unwrap();
840 assert_eq!(json.get("store"), Some(&Value::Bool(false)));
841 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 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 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 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 assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
1020 let p = resolve_auth_path(Some(" "), Some(PathBuf::from("/home/u"))).unwrap();
1022 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1023 let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
1025 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1026 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 let s = "é".repeat(5); let out = truncate(&s, 3);
1037 assert!(out.ends_with('…'));
1038 assert!(out.chars().filter(|&c| c == 'é').count() <= 1);
1040 }
1041
1042 #[test]
1043 fn parse_sse_accumulates_output_items_with_empty_completed() {
1044 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 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 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 assert!(!is_rotation_4xx(&mk("429 Too Many Requests")));
1154 assert!(!is_rotation_4xx(&mk("500 Internal Server Error")));
1155 }
1156}