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 sha2::{Digest, Sha256};
25use tokio::sync::Mutex;
26
27use crate::llm::{
28 CacheAccounting, Completion, CompletionResponse, FinishReason, LLMClient, LLMClientDyn,
29 TokenUsage, WithRetryExt, compact_provider_error_body, provider_http_status,
30};
31
32const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
34const TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
35const CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
37const ORIGINATOR: &str = "nitpicker";
38const EXPIRY_SKEW: Duration = Duration::from_secs(60);
40const REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
43const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
45const READ_TIMEOUT: Duration = Duration::from_secs(120);
50
51fn build_http_client() -> Result<reqwest::Client> {
54 reqwest::Client::builder()
55 .connect_timeout(CONNECT_TIMEOUT)
56 .read_timeout(READ_TIMEOUT)
57 .build()
58 .wrap_err("building Codex HTTP client")
59}
60
61fn user_agent() -> String {
62 format!(
63 "nitpicker/{} ({}; {})",
64 env!("CARGO_PKG_VERSION"),
65 std::env::consts::OS,
66 std::env::consts::ARCH
67 )
68}
69
70fn decode_jwt_claims(token: &str) -> Option<Value> {
75 let payload = token.split('.').nth(1)?;
76 let bytes = URL_SAFE_NO_PAD.decode(payload).ok()?;
77 serde_json::from_slice(&bytes).ok()
78}
79
80fn account_id_from_claims(claims: &Value) -> Option<String> {
82 let direct = claims.get("chatgpt_account_id").and_then(Value::as_str);
83 let nested = claims
84 .get("https://api.openai.com/auth")
85 .and_then(|a| a.get("chatgpt_account_id"))
86 .and_then(Value::as_str);
87 let org = claims
88 .get("organizations")
89 .and_then(Value::as_array)
90 .and_then(|orgs| orgs.first())
91 .and_then(|o| o.get("id"))
92 .and_then(Value::as_str);
93 direct.or(nested).or(org).map(str::to_string)
94}
95
96fn account_id_from_tokens(id_token: Option<&str>, access_token: &str) -> Option<String> {
97 id_token
98 .and_then(decode_jwt_claims)
99 .as_ref()
100 .and_then(account_id_from_claims)
101 .or_else(|| {
102 decode_jwt_claims(access_token)
103 .as_ref()
104 .and_then(account_id_from_claims)
105 })
106}
107
108fn expiry_from_access_token(access_token: &str) -> SystemTime {
112 decode_jwt_claims(access_token)
113 .and_then(|c| c.get("exp").and_then(Value::as_u64))
114 .and_then(|exp| UNIX_EPOCH.checked_add(Duration::from_secs(exp)))
117 .unwrap_or(UNIX_EPOCH)
118}
119
120#[derive(Clone)]
125struct CodexTokens {
126 access_token: String,
127 refresh_token: String,
128 account_id: Option<String>,
129 expires_at: SystemTime,
130}
131
132impl CodexTokens {
133 fn is_expired(&self) -> bool {
134 self.expires_at <= SystemTime::now() + EXPIRY_SKEW
135 }
136}
137
138fn auth_path() -> Result<PathBuf> {
140 resolve_auth_path(
141 std::env::var("CODEX_HOME").ok().as_deref(),
142 dirs::home_dir(),
143 )
144}
145
146fn resolve_auth_path(codex_home: Option<&str>, home_dir: Option<PathBuf>) -> Result<PathBuf> {
148 if let Some(home) = codex_home {
149 let trimmed = home.trim();
150 if !trimmed.is_empty() {
151 let path = Path::new(trimmed);
152 if path.is_absolute() {
153 return Ok(path.join("auth.json"));
154 }
155 eyre::bail!("CODEX_HOME must be an absolute path, got \"{home}\"");
156 }
157 }
158 let home =
159 home_dir.ok_or_else(|| eyre::eyre!("cannot resolve home directory (set CODEX_HOME)"))?;
160 Ok(home.join(".codex").join("auth.json"))
161}
162
163fn load_tokens(path: &Path) -> Result<CodexTokens> {
164 let raw = std::fs::read_to_string(path).wrap_err_with(|| {
165 format!(
166 "cannot read {} — run `codex login` with a ChatGPT subscription first",
167 path.display()
168 )
169 })?;
170 parse_tokens(&raw, &path.display().to_string())
171}
172
173pub fn auth_available() -> bool {
177 auth_path().and_then(|p| load_tokens(&p)).is_ok()
178}
179
180fn parse_tokens(raw: &str, source: &str) -> Result<CodexTokens> {
182 let v: Value =
183 serde_json::from_str(raw).wrap_err_with(|| format!("invalid JSON in {source}"))?;
184 let tokens = v.get("tokens").ok_or_else(|| {
185 eyre::eyre!(
186 "no ChatGPT subscription tokens in {source} — run `codex login` (API-key mode is not supported here)"
187 )
188 })?;
189 let access_token = tokens
190 .get("access_token")
191 .and_then(Value::as_str)
192 .filter(|s| !s.is_empty())
193 .ok_or_else(|| eyre::eyre!("no access_token in {source}"))?
194 .to_string();
195 let refresh_token = tokens
196 .get("refresh_token")
197 .and_then(Value::as_str)
198 .filter(|s| !s.is_empty())
199 .ok_or_else(|| eyre::eyre!("no refresh_token in {source}"))?
200 .to_string();
201 let account_id = tokens
202 .get("account_id")
203 .and_then(Value::as_str)
204 .filter(|s| !s.is_empty())
205 .map(str::to_string)
206 .or_else(|| {
207 account_id_from_tokens(
208 tokens.get("id_token").and_then(Value::as_str),
209 &access_token,
210 )
211 });
212 let expires_at = expiry_from_access_token(&access_token);
213 Ok(CodexTokens {
214 access_token,
215 refresh_token,
216 account_id,
217 expires_at,
218 })
219}
220
221#[derive(serde::Deserialize)]
222struct RefreshResponse {
223 access_token: String,
224 refresh_token: Option<String>,
225 id_token: Option<String>,
226 expires_in: Option<u64>,
227}
228
229async fn refresh_tokens(
232 http: &reqwest::Client,
233 refresh_token: &str,
234 prev_account_id: Option<&str>,
235) -> Result<CodexTokens> {
236 let resp = http
237 .post(TOKEN_URL)
238 .timeout(REFRESH_TIMEOUT)
239 .form(&[
240 ("grant_type", "refresh_token"),
241 ("refresh_token", refresh_token),
242 ("client_id", CLIENT_ID),
243 ])
244 .send()
245 .await
246 .wrap_err("Codex token refresh request failed")?;
247 let status = resp.status();
248 let body = resp.text().await.unwrap_or_default();
249 if !status.is_success() {
250 return Err(eyre::Report::new(CompletionError::from_http_response(
251 status,
252 compact_provider_error_body(&body, 1000),
253 )))
254 .wrap_err("Codex token refresh failed");
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 return Err(eyre::Report::new(CompletionError::from_http_response(
398 status,
399 compact_provider_error_body(&text, 1000),
400 )))
401 .wrap_err("Codex completion failed");
402 }
403 let raw = parse_sse(&text)?;
404 let model = completion.model.clone();
405 to_completion_response(raw, model)
406 }
407}
408
409pub fn shared_client() -> Result<Arc<dyn LLMClientDyn>> {
418 static CELL: OnceLock<StdMutex<Option<Arc<dyn LLMClientDyn>>>> = OnceLock::new();
419 let cell = CELL.get_or_init(|| StdMutex::new(None));
420 let mut guard = cell.lock().expect("codex shared-client mutex poisoned");
421 if let Some(existing) = guard.as_ref() {
422 return Ok(Arc::clone(existing));
423 }
424 let client = CodexClient::new()?.with_retry().into_arc();
425 *guard = Some(Arc::clone(&client));
426 Ok(client)
427}
428
429impl LLMClient for CodexClient {
430 async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
431 let (access, account_id) = self.current_access().await?;
432 match self.send(&completion, &access, account_id.as_deref()).await {
433 Ok(response) => Ok(response),
434 Err(err) if provider_http_status(&err) == Some(401) => {
437 let (access, account_id) = self.force_refresh(&access).await?;
438 self.send(&completion, &access, account_id.as_deref()).await
439 }
440 Err(err) => Err(err),
441 }
442 }
443}
444
445fn build_body(completion: &Completion) -> Result<ResponsesBody> {
451 let mut c = completion.clone();
452 normalize_codex_completion_history(&mut c);
453 let prompt_cache_key = codex_prompt_cache_key(&c)?;
454 c.max_tokens = None;
456 let instructions = c.preamble.take();
459 let instructions = match instructions {
460 Some(s) if !s.trim().is_empty() => s,
461 _ => eyre::bail!(
462 "Codex auth requires a system prompt: this completion had no `instructions`"
463 ),
464 };
465 let model = c.model.clone();
466 let rig_req: rig_core::completion::CompletionRequest = c.into();
467 let mut body = ResponsesBody::try_from((model, rig_req))
468 .map_err(|e| eyre::eyre!("lowering completion to Codex Responses body failed: {e}"))?;
469 body.instructions = Some(instructions);
470 body.stream = Some(true);
471 body.max_output_tokens = None;
472 let params = &mut body.additional_parameters;
480 params.store = Some(false);
481 params.prompt_cache_key = Some(prompt_cache_key);
482 let include = params.include.get_or_insert_with(Vec::new);
483 if !include
484 .iter()
485 .any(|i| matches!(i, Include::ReasoningEncryptedContent))
486 {
487 include.push(Include::ReasoningEncryptedContent);
488 }
489 Ok(body)
490}
491
492fn codex_prompt_cache_key(completion: &Completion) -> Result<String> {
497 fn hash_part(hasher: &mut Sha256, bytes: &[u8]) {
498 hasher.update((bytes.len() as u64).to_be_bytes());
499 hasher.update(bytes);
500 }
501
502 let mut hasher = Sha256::new();
503 hash_part(&mut hasher, completion.model.as_bytes());
504 hash_part(
505 &mut hasher,
506 completion
507 .preamble
508 .as_deref()
509 .unwrap_or_default()
510 .as_bytes(),
511 );
512 let tools = serde_json::to_vec(&completion.tools)
513 .wrap_err("serializing Codex tools for prompt cache routing")?;
514 hash_part(&mut hasher, &tools);
515 let digest = hasher.finalize();
516 let suffix = digest[..16]
517 .iter()
518 .map(|byte| format!("{byte:02x}"))
519 .collect::<String>();
520 Ok(format!("nitpicker-{suffix}"))
521}
522
523fn build_body_value(completion: &Completion) -> Result<Value> {
527 let body = build_body(completion)?;
528 serde_json::to_value(&body).wrap_err("serializing Codex Responses request")
529}
530
531fn normalize_codex_completion_history(completion: &mut Completion) {
532 for message in completion
533 .history
534 .iter_mut()
535 .chain(std::iter::once(&mut completion.prompt))
536 {
537 match message {
538 rig_core::completion::Message::Assistant { content, .. } => {
539 for item in content.iter_mut() {
540 match item {
541 AssistantContent::ToolCall(call) if call.call_id.is_none() => {
542 call.call_id = Some(call.id.clone());
543 }
544 _ => {}
545 }
546 }
547 }
548 rig_core::completion::Message::User { content } => {
549 for item in content.iter_mut() {
550 match item {
551 UserContent::ToolResult(result) if result.call_id.is_none() => {
552 result.call_id = Some(result.id.clone());
553 }
554 _ => {}
555 }
556 }
557 }
558 rig_core::completion::Message::System { .. } => {}
559 }
560 }
561}
562
563fn sse_event_payloads(text: &str) -> Vec<String> {
567 let mut events = vec![];
568 let mut current = String::new();
569 for line in text.lines() {
570 if line.is_empty() {
571 if !current.is_empty() {
572 events.push(std::mem::take(&mut current));
573 }
574 continue;
575 }
576 if let Some(rest) = line.strip_prefix("data:") {
577 if !current.is_empty() {
578 current.push('\n');
579 }
580 current.push_str(rest.strip_prefix(' ').unwrap_or(rest));
582 }
583 }
585 if !current.is_empty() {
586 events.push(current);
587 }
588 events
589}
590
591fn parse_sse(text: &str) -> Result<ResponsesResp> {
596 let mut items: Vec<Value> = vec![];
597 let mut last_parse_err: Option<String> = None;
598 for data in sse_event_payloads(text) {
599 let data = data.trim();
600 if data.is_empty() || data == "[DONE]" {
601 continue;
602 }
603 let ev: Value = match serde_json::from_str(data) {
604 Ok(v) => v,
605 Err(e) => {
608 last_parse_err = Some(e.to_string());
609 continue;
610 }
611 };
612 match ev.get("type").and_then(Value::as_str) {
613 Some("response.output_item.done") => {
614 if let Some(item) = ev.get("item") {
615 items.push(item.clone());
616 }
617 }
618 Some("response.completed") | Some("response.incomplete") => {
619 let mut response = ev
620 .get("response")
621 .cloned()
622 .ok_or_else(|| eyre::eyre!("Codex terminal SSE event missing `response`"))?;
623 let echoed_output = response
626 .get("output")
627 .and_then(Value::as_array)
628 .is_some_and(|a| !a.is_empty());
629 if !echoed_output {
630 response["output"] = Value::Array(std::mem::take(&mut items));
631 }
632 return serde_json::from_value::<ResponsesResp>(response)
633 .wrap_err("parsing Codex terminal response payload");
634 }
635 Some("response.failed") | Some("error") => {
636 return Err(eyre::Report::new(CompletionError::from_provider_body(
637 compact_provider_error_body(&ev.to_string(), 1000),
638 )))
639 .wrap_err("Codex stream error event");
640 }
641 _ => {}
642 }
643 }
644 match last_parse_err {
645 Some(e) => eyre::bail!("no terminal event in Codex SSE stream; last parse error: {e}"),
646 None => eyre::bail!(
647 "no terminal event in Codex SSE stream: {}",
648 truncate(text, 1000)
649 ),
650 }
651}
652
653fn to_completion_response(raw: ResponsesResp, model: String) -> Result<CompletionResponse> {
654 let incomplete_reason = raw.incomplete_details.as_ref().map(|d| d.reason.clone());
655 let parsed: rig_core::completion::CompletionResponse<ResponsesResp> = raw
656 .try_into()
657 .map_err(|e| eyre::eyre!("parsing Codex response into completion: {e}"))?;
658 let has_tool_call = parsed
659 .choice
660 .iter()
661 .any(|c| matches!(c, AssistantContent::ToolCall(_)));
662 let finish_reason = if has_tool_call {
663 FinishReason::ToolUse
664 } else {
665 match incomplete_reason.as_deref() {
666 Some("max_output_tokens") => FinishReason::MaxTokens,
667 Some(other) => FinishReason::Other(other.to_string()),
668 None => FinishReason::Stop,
669 }
670 };
671 Ok(CompletionResponse {
672 choice: parsed.choice,
674 finish_reason,
675 usage: TokenUsage::from_provider(&parsed.usage, CacheAccounting::InsidePrompt),
677 selected_model: Some(model),
678 })
679}
680
681fn truncate(s: &str, max: usize) -> String {
682 if s.len() <= max {
683 return s.to_string();
684 }
685 let end = (0..=max)
686 .rev()
687 .find(|&i| s.is_char_boundary(i))
688 .unwrap_or(0);
689 format!("{}…", &s[..end])
690}
691
692fn is_rotation_4xx(err: &eyre::Report) -> bool {
697 provider_http_status(err).is_some_and(|status| (400..500).contains(&status) && status != 429)
698}
699
700#[cfg(test)]
701mod tests {
702 use super::*;
703 use rig_core::OneOrMany;
704 use rig_core::completion::message::{
705 Message, ToolCall, ToolFunction, ToolResult, ToolResultContent,
706 };
707 use serde_json::json;
708
709 fn jwt(claims: Value) -> String {
712 let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
713 let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
714 format!("{header}.{payload}.sig")
715 }
716
717 #[test]
718 fn account_id_resolution_order() {
719 assert_eq!(
720 account_id_from_claims(&json!({ "chatgpt_account_id": "root" })).as_deref(),
721 Some("root")
722 );
723 assert_eq!(
724 account_id_from_claims(
725 &json!({ "https://api.openai.com/auth": { "chatgpt_account_id": "nested" } })
726 )
727 .as_deref(),
728 Some("nested")
729 );
730 assert_eq!(
732 account_id_from_claims(&json!({
733 "chatgpt_account_id": "root",
734 "https://api.openai.com/auth": { "chatgpt_account_id": "nested" }
735 }))
736 .as_deref(),
737 Some("root")
738 );
739 assert_eq!(
741 account_id_from_claims(
742 &json!({ "organizations": [{ "id": "org-1" }, { "id": "org-2" }] })
743 )
744 .as_deref(),
745 Some("org-1")
746 );
747 assert_eq!(account_id_from_claims(&json!({ "email": "x@y.z" })), None);
748 }
749
750 #[test]
751 fn account_id_prefers_id_token_then_access_token() {
752 let id_token = jwt(json!({ "chatgpt_account_id": "from-id" }));
753 let access = jwt(json!({ "chatgpt_account_id": "from-access" }));
754 assert_eq!(
755 account_id_from_tokens(Some(&id_token), &access).as_deref(),
756 Some("from-id")
757 );
758 let id_token_no_acct = jwt(json!({ "email": "x@y.z" }));
759 assert_eq!(
760 account_id_from_tokens(Some(&id_token_no_acct), &access).as_deref(),
761 Some("from-access")
762 );
763 }
764
765 #[test]
766 fn expiry_from_exp_claim_and_missing() {
767 let with_exp = jwt(json!({ "exp": 4_000_000_000u64 }));
768 assert_eq!(
769 expiry_from_access_token(&with_exp),
770 UNIX_EPOCH + Duration::from_secs(4_000_000_000)
771 );
772 assert_eq!(expiry_from_access_token(&jwt(json!({}))), UNIX_EPOCH);
774 assert_eq!(expiry_from_access_token("not-a-jwt"), UNIX_EPOCH);
775 }
776
777 #[test]
778 fn parse_tokens_full_and_derived_account_id() {
779 let access = jwt(json!({ "exp": 4_000_000_000u64 }));
780 let raw = json!({
782 "tokens": { "access_token": access, "refresh_token": "rt", "account_id": "acct-explicit" }
783 })
784 .to_string();
785 let t = parse_tokens(&raw, "test").unwrap();
786 assert_eq!(t.account_id.as_deref(), Some("acct-explicit"));
787 assert!(!t.is_expired());
788
789 let id_token = jwt(json!({ "chatgpt_account_id": "acct-derived" }));
791 let raw = json!({
792 "tokens": { "access_token": access, "refresh_token": "rt", "id_token": id_token }
793 })
794 .to_string();
795 let t = parse_tokens(&raw, "test").unwrap();
796 assert_eq!(t.account_id.as_deref(), Some("acct-derived"));
797 }
798
799 #[test]
800 fn parse_tokens_rejects_api_key_mode_and_missing_fields() {
801 let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
803 assert!(parse_tokens(&raw, "test").is_err());
804 let raw = json!({ "tokens": { "refresh_token": "rt" } }).to_string();
806 assert!(parse_tokens(&raw, "test").is_err());
807 }
808
809 #[test]
810 fn build_body_applies_codex_quirks() {
811 let completion = Completion {
812 model: "gpt-5.4".to_string(),
813 prompt: Message::user("hello"),
814 preamble: Some("You are a reviewer.".to_string()),
815 history: vec![],
816 tools: vec![],
817 tool_choice: None,
818 max_tokens: Some(4096),
819 additional_params: None,
820 };
821 let body = build_body(&completion).unwrap();
822 assert_eq!(body.instructions.as_deref(), Some("You are a reviewer."));
823 assert_eq!(body.stream, Some(true));
824 assert_eq!(body.max_output_tokens, None);
825 let json = serde_json::to_value(&body).unwrap();
827 assert_eq!(json.get("store"), Some(&Value::Bool(false)));
828 assert!(
829 json.get("prompt_cache_key")
830 .and_then(Value::as_str)
831 .is_some_and(|key| key.starts_with("nitpicker-")),
832 "Codex requests must carry a stable prompt cache routing key"
833 );
834 assert_eq!(
836 json.get("include").and_then(Value::as_array),
837 Some(&vec![Value::String(
838 "reasoning.encrypted_content".to_string()
839 )]),
840 "must request reasoning.encrypted_content to avoid bare rs_ id 404s"
841 );
842 let has_system_input = json
844 .get("input")
845 .and_then(Value::as_array)
846 .map(|items| {
847 items
848 .iter()
849 .any(|i| i.get("role").and_then(Value::as_str) == Some("system"))
850 })
851 .unwrap_or(false);
852 assert!(
853 !has_system_input,
854 "system must be in `instructions`, not `input`"
855 );
856 }
857
858 #[test]
859 fn build_body_requires_a_system_prompt() {
860 let completion = Completion {
861 model: "gpt-5.4".to_string(),
862 prompt: Message::user("hello"),
863 preamble: None,
864 history: vec![],
865 tools: vec![],
866 tool_choice: None,
867 max_tokens: None,
868 additional_params: None,
869 };
870 assert!(build_body(&completion).is_err());
871 }
872
873 #[test]
874 fn prompt_cache_key_tracks_the_stable_prefix_not_the_conversation_tail() {
875 let first = Completion {
876 model: "gpt-5.4".to_string(),
877 prompt: Message::user("initial request"),
878 preamble: Some("stable reviewer and project context".to_string()),
879 history: vec![],
880 tools: vec![rig_core::completion::ToolDefinition {
881 name: "read_file".to_string(),
882 description: "Read a file".to_string(),
883 parameters: json!({
884 "type": "object",
885 "properties": { "path": { "type": "string" } }
886 }),
887 }],
888 tool_choice: None,
889 max_tokens: None,
890 additional_params: None,
891 };
892 let mut later_turn = first.clone();
893 later_turn.history = vec![
894 Message::user("initial request"),
895 Message::assistant("intermediate answer"),
896 ];
897 later_turn.prompt = Message::user("continue");
898
899 let first_key = build_body(&first)
900 .unwrap()
901 .additional_parameters
902 .prompt_cache_key
903 .unwrap();
904 let later_key = build_body(&later_turn)
905 .unwrap()
906 .additional_parameters
907 .prompt_cache_key
908 .unwrap();
909 assert_eq!(first_key, later_key);
910
911 let mut different_prefix = later_turn;
912 different_prefix.preamble = Some("different reviewer or project context".to_string());
913 let different_key = build_body(&different_prefix)
914 .unwrap()
915 .additional_parameters
916 .prompt_cache_key
917 .unwrap();
918 assert_ne!(first_key, different_key);
919 }
920
921 #[test]
922 fn build_body_preserves_existing_additional_params() {
923 let completion = Completion {
924 model: "gpt-5.4".to_string(),
925 prompt: Message::user("hello"),
926 preamble: Some("sys".to_string()),
927 history: vec![],
928 tools: vec![],
929 tool_choice: None,
930 max_tokens: None,
931 additional_params: Some(json!({ "reasoning": { "effort": "low" } })),
932 };
933 let body = build_body(&completion).unwrap();
934 let json = serde_json::to_value(&body).unwrap();
935 assert_eq!(json.get("store"), Some(&Value::Bool(false)));
936 assert!(json.get("reasoning").is_some());
937 }
938
939 #[test]
940 fn build_body_fills_missing_tool_call_ids_for_mixed_provider_history() {
941 let tool_id = "toolu_1".to_string();
942 let completion = Completion {
943 model: "gpt-5.5".to_string(),
944 prompt: Message::user("continue"),
945 preamble: Some("sys".to_string()),
946 history: vec![
947 Message::Assistant {
948 id: None,
949 content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
950 tool_id.clone(),
951 ToolFunction::new(
952 "read_file".to_string(),
953 json!({ "path": "src/main.rs" }),
954 ),
955 ))),
956 },
957 Message::User {
958 content: OneOrMany::one(UserContent::ToolResult(ToolResult {
959 id: tool_id.clone(),
960 call_id: None,
961 content: OneOrMany::one(ToolResultContent::text("ok")),
962 })),
963 },
964 ],
965 tools: vec![],
966 tool_choice: None,
967 max_tokens: None,
968 additional_params: None,
969 };
970
971 let body = build_body(&completion).unwrap();
972 let json = serde_json::to_value(&body).unwrap();
973 assert!(
974 json.to_string()
975 .contains(&format!("\"call_id\":\"{tool_id}\""))
976 );
977 }
978
979 #[test]
980 fn body_value_preserves_assistant_text_history() {
981 let completion = Completion {
986 model: "gpt-5.5".to_string(),
987 prompt: Message::user("continue"),
988 preamble: Some("sys".to_string()),
989 history: vec![Message::Assistant {
990 id: None,
991 content: OneOrMany::one(AssistantContent::text("previous answer")),
992 }],
993 tools: vec![],
994 tool_choice: None,
995 max_tokens: None,
996 additional_params: None,
997 };
998
999 let body = build_body_value(&completion).unwrap();
1000 let assistant_message = body["input"]
1001 .as_array()
1002 .unwrap()
1003 .iter()
1004 .find(|item| item.get("role").and_then(Value::as_str) == Some("assistant"))
1005 .unwrap();
1006
1007 assert_eq!(assistant_message["content"], "previous answer");
1008 }
1009
1010 #[test]
1013 fn body_value_omits_foreign_function_call_item_id() {
1014 let tool_id = "tool_5Xt5WpWtZ6Whah4Z2uZcZO34".to_string();
1015 let completion = Completion {
1016 model: "gpt-5.5".to_string(),
1017 prompt: Message::user("continue"),
1018 preamble: Some("sys".to_string()),
1019 history: vec![
1020 Message::Assistant {
1021 id: None,
1022 content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
1023 tool_id.clone(),
1024 ToolFunction::new(
1025 "read_file".to_string(),
1026 json!({ "path": "src/main.rs" }),
1027 ),
1028 ))),
1029 },
1030 Message::User {
1031 content: OneOrMany::one(UserContent::ToolResult(ToolResult {
1032 id: tool_id.clone(),
1033 call_id: None,
1034 content: OneOrMany::one(ToolResultContent::text("ok")),
1035 })),
1036 },
1037 ],
1038 tools: vec![],
1039 tool_choice: None,
1040 max_tokens: None,
1041 additional_params: None,
1042 };
1043
1044 let body = build_body_value(&completion).unwrap();
1045 let function_call = body["input"]
1046 .as_array()
1047 .unwrap()
1048 .iter()
1049 .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
1050 .unwrap();
1051
1052 assert!(function_call.get("id").is_none());
1053 assert_eq!(function_call["call_id"], tool_id);
1054
1055 let function_call_output = body["input"]
1057 .as_array()
1058 .unwrap()
1059 .iter()
1060 .find(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output"))
1061 .unwrap();
1062 assert_eq!(function_call_output["call_id"], tool_id);
1063 }
1064
1065 #[test]
1066 fn resolve_auth_path_modes() {
1067 let p = resolve_auth_path(Some("/custom/codex"), Some(PathBuf::from("/home/u"))).unwrap();
1069 assert_eq!(p, PathBuf::from("/custom/codex/auth.json"));
1070 assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
1072 let p = resolve_auth_path(Some(" "), Some(PathBuf::from("/home/u"))).unwrap();
1074 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1075 let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
1077 assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
1078 assert!(resolve_auth_path(None, None).is_err());
1080 }
1081
1082 #[test]
1083 fn truncate_respects_char_boundaries() {
1084 assert_eq!(truncate("hello", 10), "hello");
1085 assert_eq!(truncate("hello", 3), "hel…");
1086 let s = "é".repeat(5); let out = truncate(&s, 3);
1089 assert!(out.ends_with('…'));
1090 assert!(out.chars().filter(|&c| c == 'é').count() <= 1);
1092 }
1093
1094 #[test]
1095 fn parse_sse_accumulates_output_items_with_empty_completed() {
1096 let item = json!({
1098 "type": "message",
1099 "id": "msg_1",
1100 "role": "assistant",
1101 "status": "completed",
1102 "content": [{ "type": "output_text", "text": "pong" }]
1103 });
1104 let completed = json!({
1105 "id": "resp_1",
1106 "object": "response",
1107 "created_at": 1,
1108 "status": "completed",
1109 "model": "gpt-5.4",
1110 "output": [],
1111 "usage": {
1112 "input_tokens": 5000,
1113 "input_tokens_details": { "cached_tokens": 4800 },
1114 "output_tokens": 1,
1115 "output_tokens_details": { "reasoning_tokens": 0 },
1116 "total_tokens": 5001
1117 }
1118 });
1119 let sse = format!(
1120 "data: {}\n\ndata: {}\n\ndata: [DONE]\n",
1121 json!({ "type": "response.output_item.done", "item": item }),
1122 json!({ "type": "response.completed", "response": completed })
1123 );
1124 let raw = parse_sse(&sse).unwrap();
1125 let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1126 assert_eq!(resp.text(), "pong");
1127 assert_eq!(resp.finish_reason, FinishReason::Stop);
1128 assert_eq!(resp.usage.input_tokens, 5000);
1130 assert_eq!(resp.usage.cached_input_tokens, 4800);
1131 assert_eq!(resp.usage.total_tokens, 5001);
1132 }
1133
1134 #[test]
1135 fn parse_sse_surfaces_error_events() {
1136 let sse = format!(
1137 "data: {}\n",
1138 json!({ "type": "response.failed", "error": { "message": "boom" } })
1139 );
1140 assert!(parse_sse(&sse).is_err());
1141 }
1142
1143 #[test]
1144 fn parse_sse_preserves_codes_from_large_error_events() {
1145 let sse = format!(
1146 "data: {}\n",
1147 json!({
1148 "type": "response.failed",
1149 "error": {
1150 "type": "usage_limit_reached",
1151 "message": "quota exhausted",
1152 "diagnostic": "x".repeat(4_000),
1153 }
1154 })
1155 );
1156 let err = parse_sse(&sse).unwrap_err();
1157 assert!(crate::llm::provider_error_has_code(
1158 &err,
1159 &["usage_limit_reached"]
1160 ));
1161 }
1162
1163 fn usage_json() -> Value {
1164 json!({
1165 "input_tokens": 5,
1166 "input_tokens_details": { "cached_tokens": 0 },
1167 "output_tokens": 1,
1168 "output_tokens_details": { "reasoning_tokens": 0 },
1169 "total_tokens": 6
1170 })
1171 }
1172
1173 #[test]
1174 fn parse_sse_handles_incomplete_as_max_tokens() {
1175 let item = json!({
1177 "type": "message", "id": "m", "role": "assistant", "status": "incomplete",
1178 "content": [{ "type": "output_text", "text": "partial" }]
1179 });
1180 let response = json!({
1181 "id": "r", "object": "response", "created_at": 1, "status": "incomplete",
1182 "model": "gpt-5.4", "output": [],
1183 "incomplete_details": { "reason": "max_output_tokens" },
1184 "usage": usage_json()
1185 });
1186 let sse = format!(
1187 "data: {}\n\ndata: {}\n",
1188 json!({ "type": "response.output_item.done", "item": item }),
1189 json!({ "type": "response.incomplete", "response": response })
1190 );
1191 let raw = parse_sse(&sse).unwrap();
1192 let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1193 assert_eq!(resp.text(), "partial");
1194 assert_eq!(resp.finish_reason, FinishReason::MaxTokens);
1195 }
1196
1197 #[test]
1198 fn parse_sse_rejoins_multiline_data_fields() {
1199 let completed = json!({
1202 "type": "response.completed",
1203 "response": {
1204 "id": "r", "object": "response", "created_at": 1, "status": "completed",
1205 "model": "gpt-5.4",
1206 "output": [{
1207 "type": "message", "id": "m", "role": "assistant", "status": "completed",
1208 "content": [{ "type": "output_text", "text": "hi" }]
1209 }],
1210 "usage": usage_json()
1211 }
1212 })
1213 .to_string();
1214 let comma = completed.find(',').unwrap();
1215 let (head, tail) = completed.split_at(comma);
1216 let sse = format!("data: {head}\ndata: {tail}\n\n");
1217 let raw = parse_sse(&sse).unwrap();
1218 let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
1219 assert_eq!(resp.text(), "hi");
1220 }
1221
1222 #[test]
1223 fn is_rotation_4xx_excludes_429_and_5xx() {
1224 let mk = |status| {
1225 eyre::Report::new(CompletionError::from_http_response(
1226 reqwest::StatusCode::from_u16(status).unwrap(),
1227 r#"{"error":"test"}"#,
1228 ))
1229 };
1230 assert!(is_rotation_4xx(&mk(400)));
1231 assert!(is_rotation_4xx(&mk(401)));
1232 assert!(!is_rotation_4xx(&mk(429)));
1234 assert!(!is_rotation_4xx(&mk(500)));
1235 }
1236}