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