use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex as StdMutex, OnceLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use eyre::{Result, WrapErr};
use rig_core::completion::CompletionError;
use rig_core::completion::message::{AssistantContent, UserContent};
use rig_core::providers::openai::responses_api::{
CompletionRequest as ResponsesBody, CompletionResponse as ResponsesResp, Include,
};
use serde_json::Value;
use sha2::{Digest, Sha256};
use tokio::sync::Mutex;
use crate::llm::{
CacheAccounting, Completion, CompletionResponse, FinishReason, LLMClient, LLMClientDyn,
TokenUsage, WithRetryExt, compact_provider_error_body, provider_http_status,
};
const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
const TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
const CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
const ORIGINATOR: &str = "nitpicker";
const EXPIRY_SKEW: Duration = Duration::from_secs(60);
const REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
const READ_TIMEOUT: Duration = Duration::from_secs(120);
fn build_http_client() -> Result<reqwest::Client> {
reqwest::Client::builder()
.connect_timeout(CONNECT_TIMEOUT)
.read_timeout(READ_TIMEOUT)
.build()
.wrap_err("building Codex HTTP client")
}
fn user_agent() -> String {
format!(
"nitpicker/{} ({}; {})",
env!("CARGO_PKG_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH
)
}
fn decode_jwt_claims(token: &str) -> Option<Value> {
let payload = token.split('.').nth(1)?;
let bytes = URL_SAFE_NO_PAD.decode(payload).ok()?;
serde_json::from_slice(&bytes).ok()
}
fn account_id_from_claims(claims: &Value) -> Option<String> {
let direct = claims.get("chatgpt_account_id").and_then(Value::as_str);
let nested = claims
.get("https://api.openai.com/auth")
.and_then(|a| a.get("chatgpt_account_id"))
.and_then(Value::as_str);
let org = claims
.get("organizations")
.and_then(Value::as_array)
.and_then(|orgs| orgs.first())
.and_then(|o| o.get("id"))
.and_then(Value::as_str);
direct.or(nested).or(org).map(str::to_string)
}
fn account_id_from_tokens(id_token: Option<&str>, access_token: &str) -> Option<String> {
id_token
.and_then(decode_jwt_claims)
.as_ref()
.and_then(account_id_from_claims)
.or_else(|| {
decode_jwt_claims(access_token)
.as_ref()
.and_then(account_id_from_claims)
})
}
fn expiry_from_access_token(access_token: &str) -> SystemTime {
decode_jwt_claims(access_token)
.and_then(|c| c.get("exp").and_then(Value::as_u64))
.and_then(|exp| UNIX_EPOCH.checked_add(Duration::from_secs(exp)))
.unwrap_or(UNIX_EPOCH)
}
#[derive(Clone)]
struct CodexTokens {
access_token: String,
refresh_token: String,
account_id: Option<String>,
expires_at: SystemTime,
}
impl CodexTokens {
fn is_expired(&self) -> bool {
self.expires_at <= SystemTime::now() + EXPIRY_SKEW
}
}
fn auth_path() -> Result<PathBuf> {
resolve_auth_path(
std::env::var("CODEX_HOME").ok().as_deref(),
dirs::home_dir(),
)
}
fn resolve_auth_path(codex_home: Option<&str>, home_dir: Option<PathBuf>) -> Result<PathBuf> {
if let Some(home) = codex_home {
let trimmed = home.trim();
if !trimmed.is_empty() {
let path = Path::new(trimmed);
if path.is_absolute() {
return Ok(path.join("auth.json"));
}
eyre::bail!("CODEX_HOME must be an absolute path, got \"{home}\"");
}
}
let home =
home_dir.ok_or_else(|| eyre::eyre!("cannot resolve home directory (set CODEX_HOME)"))?;
Ok(home.join(".codex").join("auth.json"))
}
fn load_tokens(path: &Path) -> Result<CodexTokens> {
let raw = std::fs::read_to_string(path).wrap_err_with(|| {
format!(
"cannot read {} — run `codex login` with a ChatGPT subscription first",
path.display()
)
})?;
parse_tokens(&raw, &path.display().to_string())
}
pub fn auth_available() -> bool {
auth_path().and_then(|p| load_tokens(&p)).is_ok()
}
fn parse_tokens(raw: &str, source: &str) -> Result<CodexTokens> {
let v: Value =
serde_json::from_str(raw).wrap_err_with(|| format!("invalid JSON in {source}"))?;
let tokens = v.get("tokens").ok_or_else(|| {
eyre::eyre!(
"no ChatGPT subscription tokens in {source} — run `codex login` (API-key mode is not supported here)"
)
})?;
let access_token = tokens
.get("access_token")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| eyre::eyre!("no access_token in {source}"))?
.to_string();
let refresh_token = tokens
.get("refresh_token")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| eyre::eyre!("no refresh_token in {source}"))?
.to_string();
let account_id = tokens
.get("account_id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_string)
.or_else(|| {
account_id_from_tokens(
tokens.get("id_token").and_then(Value::as_str),
&access_token,
)
});
let expires_at = expiry_from_access_token(&access_token);
Ok(CodexTokens {
access_token,
refresh_token,
account_id,
expires_at,
})
}
#[derive(serde::Deserialize)]
struct RefreshResponse {
access_token: String,
refresh_token: Option<String>,
id_token: Option<String>,
expires_in: Option<u64>,
}
async fn refresh_tokens(
http: &reqwest::Client,
refresh_token: &str,
prev_account_id: Option<&str>,
) -> Result<CodexTokens> {
let resp = http
.post(TOKEN_URL)
.timeout(REFRESH_TIMEOUT)
.form(&[
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", CLIENT_ID),
])
.send()
.await
.wrap_err("Codex token refresh request failed")?;
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
if !status.is_success() {
return Err(eyre::Report::new(CompletionError::from_http_response(
status,
compact_provider_error_body(&body, 1000),
)))
.wrap_err("Codex token refresh failed");
}
let parsed: RefreshResponse =
serde_json::from_str(&body).wrap_err("parsing Codex token refresh response")?;
let expires_at = match parsed.expires_in {
Some(secs) => SystemTime::now()
.checked_add(Duration::from_secs(secs))
.unwrap_or_else(|| expiry_from_access_token(&parsed.access_token)),
None => expiry_from_access_token(&parsed.access_token),
};
let account_id = prev_account_id
.map(str::to_string)
.or_else(|| account_id_from_tokens(parsed.id_token.as_deref(), &parsed.access_token));
Ok(CodexTokens {
access_token: parsed.access_token,
refresh_token: parsed
.refresh_token
.unwrap_or_else(|| refresh_token.to_string()),
account_id,
expires_at,
})
}
pub struct CodexClient {
http: reqwest::Client,
auth_path: PathBuf,
tokens: Mutex<CodexTokens>,
}
impl CodexClient {
pub fn new() -> Result<Self> {
let path = auth_path()?;
let tokens = load_tokens(&path)?;
Ok(Self {
http: build_http_client()?,
auth_path: path,
tokens: Mutex::new(tokens),
})
}
async fn refresh_locked(&self, tokens: &mut CodexTokens) -> Result<()> {
match refresh_tokens(
&self.http,
&tokens.refresh_token,
tokens.account_id.as_deref(),
)
.await
{
Ok(fresh) => {
*tokens = fresh;
Ok(())
}
Err(err) if is_rotation_4xx(&err) => {
let disk = load_tokens(&self.auth_path)
.wrap_err("Codex refresh token rejected and reloading auth.json failed")?;
let fresh = refresh_tokens(
&self.http,
&disk.refresh_token,
disk.account_id.as_deref(),
)
.await
.wrap_err(
"Codex refresh failed even after reloading auth.json (run `codex login`)",
)?;
*tokens = fresh;
Ok(())
}
Err(err) => Err(err),
}
}
async fn current_access(&self) -> Result<(String, Option<String>)> {
let mut guard = self.tokens.lock().await;
if guard.is_expired() {
self.refresh_locked(&mut guard).await?;
}
Ok((guard.access_token.clone(), guard.account_id.clone()))
}
async fn force_refresh(&self, used_access: &str) -> Result<(String, Option<String>)> {
let mut guard = self.tokens.lock().await;
if guard.access_token != used_access {
return Ok((guard.access_token.clone(), guard.account_id.clone()));
}
self.refresh_locked(&mut guard).await?;
Ok((guard.access_token.clone(), guard.account_id.clone()))
}
async fn send(
&self,
completion: &Completion,
access: &str,
account_id: Option<&str>,
) -> Result<CompletionResponse> {
let body = build_body_value(completion)?;
let mut req = self
.http
.post(format!("{CODEX_BASE_URL}/responses"))
.bearer_auth(access)
.header("originator", ORIGINATOR)
.header(reqwest::header::USER_AGENT, user_agent())
.header(reqwest::header::ACCEPT, "text/event-stream")
.json(&body);
if let Some(id) = account_id {
req = req.header("ChatGPT-Account-Id", id);
}
let resp = req
.send()
.await
.wrap_err("Codex completion request failed")?;
let status = resp.status();
let text = resp
.text()
.await
.wrap_err("reading Codex completion response")?;
if !status.is_success() {
return Err(eyre::Report::new(CompletionError::from_http_response(
status,
compact_provider_error_body(&text, 1000),
)))
.wrap_err("Codex completion failed");
}
let raw = parse_sse(&text)?;
let model = completion.model.clone();
to_completion_response(raw, model)
}
}
pub fn shared_client() -> Result<Arc<dyn LLMClientDyn>> {
static CELL: OnceLock<StdMutex<Option<Arc<dyn LLMClientDyn>>>> = OnceLock::new();
let cell = CELL.get_or_init(|| StdMutex::new(None));
let mut guard = cell.lock().expect("codex shared-client mutex poisoned");
if let Some(existing) = guard.as_ref() {
return Ok(Arc::clone(existing));
}
let client = CodexClient::new()?.with_retry().into_arc();
*guard = Some(Arc::clone(&client));
Ok(client)
}
impl LLMClient for CodexClient {
async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
let (access, account_id) = self.current_access().await?;
match self.send(&completion, &access, account_id.as_deref()).await {
Ok(response) => Ok(response),
Err(err) if provider_http_status(&err) == Some(401) => {
let (access, account_id) = self.force_refresh(&access).await?;
self.send(&completion, &access, account_id.as_deref()).await
}
Err(err) => Err(err),
}
}
}
fn build_body(completion: &Completion) -> Result<ResponsesBody> {
let mut c = completion.clone();
normalize_codex_completion_history(&mut c);
let prompt_cache_key = codex_prompt_cache_key(&c)?;
c.max_tokens = None;
let instructions = c.preamble.take();
let instructions = match instructions {
Some(s) if !s.trim().is_empty() => s,
_ => eyre::bail!(
"Codex auth requires a system prompt: this completion had no `instructions`"
),
};
let model = c.model.clone();
let rig_req: rig_core::completion::CompletionRequest = c.into();
let mut body = ResponsesBody::try_from((model, rig_req))
.map_err(|e| eyre::eyre!("lowering completion to Codex Responses body failed: {e}"))?;
body.instructions = Some(instructions);
body.stream = Some(true);
body.max_output_tokens = None;
let params = &mut body.additional_parameters;
params.store = Some(false);
params.prompt_cache_key = Some(prompt_cache_key);
let include = params.include.get_or_insert_with(Vec::new);
if !include
.iter()
.any(|i| matches!(i, Include::ReasoningEncryptedContent))
{
include.push(Include::ReasoningEncryptedContent);
}
Ok(body)
}
fn codex_prompt_cache_key(completion: &Completion) -> Result<String> {
fn hash_part(hasher: &mut Sha256, bytes: &[u8]) {
hasher.update((bytes.len() as u64).to_be_bytes());
hasher.update(bytes);
}
let mut hasher = Sha256::new();
hash_part(&mut hasher, completion.model.as_bytes());
hash_part(
&mut hasher,
completion
.preamble
.as_deref()
.unwrap_or_default()
.as_bytes(),
);
let tools = serde_json::to_vec(&completion.tools)
.wrap_err("serializing Codex tools for prompt cache routing")?;
hash_part(&mut hasher, &tools);
let digest = hasher.finalize();
let suffix = digest[..16]
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
Ok(format!("nitpicker-{suffix}"))
}
fn build_body_value(completion: &Completion) -> Result<Value> {
let body = build_body(completion)?;
serde_json::to_value(&body).wrap_err("serializing Codex Responses request")
}
fn normalize_codex_completion_history(completion: &mut Completion) {
for message in completion
.history
.iter_mut()
.chain(std::iter::once(&mut completion.prompt))
{
match message {
rig_core::completion::Message::Assistant { content, .. } => {
for item in content.iter_mut() {
match item {
AssistantContent::ToolCall(call) if call.call_id.is_none() => {
call.call_id = Some(call.id.clone());
}
_ => {}
}
}
}
rig_core::completion::Message::User { content } => {
for item in content.iter_mut() {
match item {
UserContent::ToolResult(result) if result.call_id.is_none() => {
result.call_id = Some(result.id.clone());
}
_ => {}
}
}
}
rig_core::completion::Message::System { .. } => {}
}
}
}
fn sse_event_payloads(text: &str) -> Vec<String> {
let mut events = vec![];
let mut current = String::new();
for line in text.lines() {
if line.is_empty() {
if !current.is_empty() {
events.push(std::mem::take(&mut current));
}
continue;
}
if let Some(rest) = line.strip_prefix("data:") {
if !current.is_empty() {
current.push('\n');
}
current.push_str(rest.strip_prefix(' ').unwrap_or(rest));
}
}
if !current.is_empty() {
events.push(current);
}
events
}
fn parse_sse(text: &str) -> Result<ResponsesResp> {
let mut items: Vec<Value> = vec![];
let mut last_parse_err: Option<String> = None;
for data in sse_event_payloads(text) {
let data = data.trim();
if data.is_empty() || data == "[DONE]" {
continue;
}
let ev: Value = match serde_json::from_str(data) {
Ok(v) => v,
Err(e) => {
last_parse_err = Some(e.to_string());
continue;
}
};
match ev.get("type").and_then(Value::as_str) {
Some("response.output_item.done") => {
if let Some(item) = ev.get("item") {
items.push(item.clone());
}
}
Some("response.completed") | Some("response.incomplete") => {
let mut response = ev
.get("response")
.cloned()
.ok_or_else(|| eyre::eyre!("Codex terminal SSE event missing `response`"))?;
let echoed_output = response
.get("output")
.and_then(Value::as_array)
.is_some_and(|a| !a.is_empty());
if !echoed_output {
response["output"] = Value::Array(std::mem::take(&mut items));
}
return serde_json::from_value::<ResponsesResp>(response)
.wrap_err("parsing Codex terminal response payload");
}
Some("response.failed") | Some("error") => {
return Err(eyre::Report::new(CompletionError::from_provider_body(
compact_provider_error_body(&ev.to_string(), 1000),
)))
.wrap_err("Codex stream error event");
}
_ => {}
}
}
match last_parse_err {
Some(e) => eyre::bail!("no terminal event in Codex SSE stream; last parse error: {e}"),
None => eyre::bail!(
"no terminal event in Codex SSE stream: {}",
truncate(text, 1000)
),
}
}
fn to_completion_response(raw: ResponsesResp, model: String) -> Result<CompletionResponse> {
let incomplete_reason = raw.incomplete_details.as_ref().map(|d| d.reason.clone());
let parsed: rig_core::completion::CompletionResponse<ResponsesResp> = raw
.try_into()
.map_err(|e| eyre::eyre!("parsing Codex response into completion: {e}"))?;
let has_tool_call = parsed
.choice
.iter()
.any(|c| matches!(c, AssistantContent::ToolCall(_)));
let finish_reason = if has_tool_call {
FinishReason::ToolUse
} else {
match incomplete_reason.as_deref() {
Some("max_output_tokens") => FinishReason::MaxTokens,
Some(other) => FinishReason::Other(other.to_string()),
None => FinishReason::Stop,
}
};
Ok(CompletionResponse {
choice: parsed.choice,
finish_reason,
usage: TokenUsage::from_provider(&parsed.usage, CacheAccounting::InsidePrompt),
selected_model: Some(model),
})
}
fn truncate(s: &str, max: usize) -> String {
if s.len() <= max {
return s.to_string();
}
let end = (0..=max)
.rev()
.find(|&i| s.is_char_boundary(i))
.unwrap_or(0);
format!("{}…", &s[..end])
}
fn is_rotation_4xx(err: &eyre::Report) -> bool {
provider_http_status(err).is_some_and(|status| (400..500).contains(&status) && status != 429)
}
#[cfg(test)]
mod tests {
use super::*;
use rig_core::OneOrMany;
use rig_core::completion::message::{
Message, ToolCall, ToolFunction, ToolResult, ToolResultContent,
};
use serde_json::json;
fn jwt(claims: Value) -> String {
let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"none"}"#);
let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims).unwrap());
format!("{header}.{payload}.sig")
}
#[test]
fn account_id_resolution_order() {
assert_eq!(
account_id_from_claims(&json!({ "chatgpt_account_id": "root" })).as_deref(),
Some("root")
);
assert_eq!(
account_id_from_claims(
&json!({ "https://api.openai.com/auth": { "chatgpt_account_id": "nested" } })
)
.as_deref(),
Some("nested")
);
assert_eq!(
account_id_from_claims(&json!({
"chatgpt_account_id": "root",
"https://api.openai.com/auth": { "chatgpt_account_id": "nested" }
}))
.as_deref(),
Some("root")
);
assert_eq!(
account_id_from_claims(
&json!({ "organizations": [{ "id": "org-1" }, { "id": "org-2" }] })
)
.as_deref(),
Some("org-1")
);
assert_eq!(account_id_from_claims(&json!({ "email": "x@y.z" })), None);
}
#[test]
fn account_id_prefers_id_token_then_access_token() {
let id_token = jwt(json!({ "chatgpt_account_id": "from-id" }));
let access = jwt(json!({ "chatgpt_account_id": "from-access" }));
assert_eq!(
account_id_from_tokens(Some(&id_token), &access).as_deref(),
Some("from-id")
);
let id_token_no_acct = jwt(json!({ "email": "x@y.z" }));
assert_eq!(
account_id_from_tokens(Some(&id_token_no_acct), &access).as_deref(),
Some("from-access")
);
}
#[test]
fn expiry_from_exp_claim_and_missing() {
let with_exp = jwt(json!({ "exp": 4_000_000_000u64 }));
assert_eq!(
expiry_from_access_token(&with_exp),
UNIX_EPOCH + Duration::from_secs(4_000_000_000)
);
assert_eq!(expiry_from_access_token(&jwt(json!({}))), UNIX_EPOCH);
assert_eq!(expiry_from_access_token("not-a-jwt"), UNIX_EPOCH);
}
#[test]
fn parse_tokens_full_and_derived_account_id() {
let access = jwt(json!({ "exp": 4_000_000_000u64 }));
let raw = json!({
"tokens": { "access_token": access, "refresh_token": "rt", "account_id": "acct-explicit" }
})
.to_string();
let t = parse_tokens(&raw, "test").unwrap();
assert_eq!(t.account_id.as_deref(), Some("acct-explicit"));
assert!(!t.is_expired());
let id_token = jwt(json!({ "chatgpt_account_id": "acct-derived" }));
let raw = json!({
"tokens": { "access_token": access, "refresh_token": "rt", "id_token": id_token }
})
.to_string();
let t = parse_tokens(&raw, "test").unwrap();
assert_eq!(t.account_id.as_deref(), Some("acct-derived"));
}
#[test]
fn parse_tokens_rejects_api_key_mode_and_missing_fields() {
let raw = json!({ "auth_mode": "apikey", "OPENAI_API_KEY": "sk-x" }).to_string();
assert!(parse_tokens(&raw, "test").is_err());
let raw = json!({ "tokens": { "refresh_token": "rt" } }).to_string();
assert!(parse_tokens(&raw, "test").is_err());
}
#[test]
fn build_body_applies_codex_quirks() {
let completion = Completion {
model: "gpt-5.4".to_string(),
prompt: Message::user("hello"),
preamble: Some("You are a reviewer.".to_string()),
history: vec![],
tools: vec![],
tool_choice: None,
max_tokens: Some(4096),
additional_params: None,
};
let body = build_body(&completion).unwrap();
assert_eq!(body.instructions.as_deref(), Some("You are a reviewer."));
assert_eq!(body.stream, Some(true));
assert_eq!(body.max_output_tokens, None);
let json = serde_json::to_value(&body).unwrap();
assert_eq!(json.get("store"), Some(&Value::Bool(false)));
assert!(
json.get("prompt_cache_key")
.and_then(Value::as_str)
.is_some_and(|key| key.starts_with("nitpicker-")),
"Codex requests must carry a stable prompt cache routing key"
);
assert_eq!(
json.get("include").and_then(Value::as_array),
Some(&vec![Value::String(
"reasoning.encrypted_content".to_string()
)]),
"must request reasoning.encrypted_content to avoid bare rs_ id 404s"
);
let has_system_input = json
.get("input")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.any(|i| i.get("role").and_then(Value::as_str) == Some("system"))
})
.unwrap_or(false);
assert!(
!has_system_input,
"system must be in `instructions`, not `input`"
);
}
#[test]
fn build_body_requires_a_system_prompt() {
let completion = Completion {
model: "gpt-5.4".to_string(),
prompt: Message::user("hello"),
preamble: None,
history: vec![],
tools: vec![],
tool_choice: None,
max_tokens: None,
additional_params: None,
};
assert!(build_body(&completion).is_err());
}
#[test]
fn prompt_cache_key_tracks_the_stable_prefix_not_the_conversation_tail() {
let first = Completion {
model: "gpt-5.4".to_string(),
prompt: Message::user("initial request"),
preamble: Some("stable reviewer and project context".to_string()),
history: vec![],
tools: vec![rig_core::completion::ToolDefinition {
name: "read_file".to_string(),
description: "Read a file".to_string(),
parameters: json!({
"type": "object",
"properties": { "path": { "type": "string" } }
}),
}],
tool_choice: None,
max_tokens: None,
additional_params: None,
};
let mut later_turn = first.clone();
later_turn.history = vec![
Message::user("initial request"),
Message::assistant("intermediate answer"),
];
later_turn.prompt = Message::user("continue");
let first_key = build_body(&first)
.unwrap()
.additional_parameters
.prompt_cache_key
.unwrap();
let later_key = build_body(&later_turn)
.unwrap()
.additional_parameters
.prompt_cache_key
.unwrap();
assert_eq!(first_key, later_key);
let mut different_prefix = later_turn;
different_prefix.preamble = Some("different reviewer or project context".to_string());
let different_key = build_body(&different_prefix)
.unwrap()
.additional_parameters
.prompt_cache_key
.unwrap();
assert_ne!(first_key, different_key);
}
#[test]
fn build_body_preserves_existing_additional_params() {
let completion = Completion {
model: "gpt-5.4".to_string(),
prompt: Message::user("hello"),
preamble: Some("sys".to_string()),
history: vec![],
tools: vec![],
tool_choice: None,
max_tokens: None,
additional_params: Some(json!({ "reasoning": { "effort": "low" } })),
};
let body = build_body(&completion).unwrap();
let json = serde_json::to_value(&body).unwrap();
assert_eq!(json.get("store"), Some(&Value::Bool(false)));
assert!(json.get("reasoning").is_some());
}
#[test]
fn build_body_fills_missing_tool_call_ids_for_mixed_provider_history() {
let tool_id = "toolu_1".to_string();
let completion = Completion {
model: "gpt-5.5".to_string(),
prompt: Message::user("continue"),
preamble: Some("sys".to_string()),
history: vec![
Message::Assistant {
id: None,
content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
tool_id.clone(),
ToolFunction::new(
"read_file".to_string(),
json!({ "path": "src/main.rs" }),
),
))),
},
Message::User {
content: OneOrMany::one(UserContent::ToolResult(ToolResult {
id: tool_id.clone(),
call_id: None,
content: OneOrMany::one(ToolResultContent::text("ok")),
})),
},
],
tools: vec![],
tool_choice: None,
max_tokens: None,
additional_params: None,
};
let body = build_body(&completion).unwrap();
let json = serde_json::to_value(&body).unwrap();
assert!(
json.to_string()
.contains(&format!("\"call_id\":\"{tool_id}\""))
);
}
#[test]
fn body_value_preserves_assistant_text_history() {
let completion = Completion {
model: "gpt-5.5".to_string(),
prompt: Message::user("continue"),
preamble: Some("sys".to_string()),
history: vec![Message::Assistant {
id: None,
content: OneOrMany::one(AssistantContent::text("previous answer")),
}],
tools: vec![],
tool_choice: None,
max_tokens: None,
additional_params: None,
};
let body = build_body_value(&completion).unwrap();
let assistant_message = body["input"]
.as_array()
.unwrap()
.iter()
.find(|item| item.get("role").and_then(Value::as_str) == Some("assistant"))
.unwrap();
assert_eq!(assistant_message["content"], "previous answer");
}
#[test]
fn body_value_omits_foreign_function_call_item_id() {
let tool_id = "tool_5Xt5WpWtZ6Whah4Z2uZcZO34".to_string();
let completion = Completion {
model: "gpt-5.5".to_string(),
prompt: Message::user("continue"),
preamble: Some("sys".to_string()),
history: vec![
Message::Assistant {
id: None,
content: OneOrMany::one(AssistantContent::ToolCall(ToolCall::new(
tool_id.clone(),
ToolFunction::new(
"read_file".to_string(),
json!({ "path": "src/main.rs" }),
),
))),
},
Message::User {
content: OneOrMany::one(UserContent::ToolResult(ToolResult {
id: tool_id.clone(),
call_id: None,
content: OneOrMany::one(ToolResultContent::text("ok")),
})),
},
],
tools: vec![],
tool_choice: None,
max_tokens: None,
additional_params: None,
};
let body = build_body_value(&completion).unwrap();
let function_call = body["input"]
.as_array()
.unwrap()
.iter()
.find(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
.unwrap();
assert!(function_call.get("id").is_none());
assert_eq!(function_call["call_id"], tool_id);
let function_call_output = body["input"]
.as_array()
.unwrap()
.iter()
.find(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output"))
.unwrap();
assert_eq!(function_call_output["call_id"], tool_id);
}
#[test]
fn resolve_auth_path_modes() {
let p = resolve_auth_path(Some("/custom/codex"), Some(PathBuf::from("/home/u"))).unwrap();
assert_eq!(p, PathBuf::from("/custom/codex/auth.json"));
assert!(resolve_auth_path(Some("relative/dir"), Some(PathBuf::from("/home/u"))).is_err());
let p = resolve_auth_path(Some(" "), Some(PathBuf::from("/home/u"))).unwrap();
assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
let p = resolve_auth_path(None, Some(PathBuf::from("/home/u"))).unwrap();
assert_eq!(p, PathBuf::from("/home/u/.codex/auth.json"));
assert!(resolve_auth_path(None, None).is_err());
}
#[test]
fn truncate_respects_char_boundaries() {
assert_eq!(truncate("hello", 10), "hello");
assert_eq!(truncate("hello", 3), "hel…");
let s = "é".repeat(5); let out = truncate(&s, 3);
assert!(out.ends_with('…'));
assert!(out.chars().filter(|&c| c == 'é').count() <= 1);
}
#[test]
fn parse_sse_accumulates_output_items_with_empty_completed() {
let item = json!({
"type": "message",
"id": "msg_1",
"role": "assistant",
"status": "completed",
"content": [{ "type": "output_text", "text": "pong" }]
});
let completed = json!({
"id": "resp_1",
"object": "response",
"created_at": 1,
"status": "completed",
"model": "gpt-5.4",
"output": [],
"usage": {
"input_tokens": 5000,
"input_tokens_details": { "cached_tokens": 4800 },
"output_tokens": 1,
"output_tokens_details": { "reasoning_tokens": 0 },
"total_tokens": 5001
}
});
let sse = format!(
"data: {}\n\ndata: {}\n\ndata: [DONE]\n",
json!({ "type": "response.output_item.done", "item": item }),
json!({ "type": "response.completed", "response": completed })
);
let raw = parse_sse(&sse).unwrap();
let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
assert_eq!(resp.text(), "pong");
assert_eq!(resp.finish_reason, FinishReason::Stop);
assert_eq!(resp.usage.input_tokens, 5000);
assert_eq!(resp.usage.cached_input_tokens, 4800);
assert_eq!(resp.usage.total_tokens, 5001);
}
#[test]
fn parse_sse_surfaces_error_events() {
let sse = format!(
"data: {}\n",
json!({ "type": "response.failed", "error": { "message": "boom" } })
);
assert!(parse_sse(&sse).is_err());
}
#[test]
fn parse_sse_preserves_codes_from_large_error_events() {
let sse = format!(
"data: {}\n",
json!({
"type": "response.failed",
"error": {
"type": "usage_limit_reached",
"message": "quota exhausted",
"diagnostic": "x".repeat(4_000),
}
})
);
let err = parse_sse(&sse).unwrap_err();
assert!(crate::llm::provider_error_has_code(
&err,
&["usage_limit_reached"]
));
}
fn usage_json() -> Value {
json!({
"input_tokens": 5,
"input_tokens_details": { "cached_tokens": 0 },
"output_tokens": 1,
"output_tokens_details": { "reasoning_tokens": 0 },
"total_tokens": 6
})
}
#[test]
fn parse_sse_handles_incomplete_as_max_tokens() {
let item = json!({
"type": "message", "id": "m", "role": "assistant", "status": "incomplete",
"content": [{ "type": "output_text", "text": "partial" }]
});
let response = json!({
"id": "r", "object": "response", "created_at": 1, "status": "incomplete",
"model": "gpt-5.4", "output": [],
"incomplete_details": { "reason": "max_output_tokens" },
"usage": usage_json()
});
let sse = format!(
"data: {}\n\ndata: {}\n",
json!({ "type": "response.output_item.done", "item": item }),
json!({ "type": "response.incomplete", "response": response })
);
let raw = parse_sse(&sse).unwrap();
let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
assert_eq!(resp.text(), "partial");
assert_eq!(resp.finish_reason, FinishReason::MaxTokens);
}
#[test]
fn parse_sse_rejoins_multiline_data_fields() {
let completed = json!({
"type": "response.completed",
"response": {
"id": "r", "object": "response", "created_at": 1, "status": "completed",
"model": "gpt-5.4",
"output": [{
"type": "message", "id": "m", "role": "assistant", "status": "completed",
"content": [{ "type": "output_text", "text": "hi" }]
}],
"usage": usage_json()
}
})
.to_string();
let comma = completed.find(',').unwrap();
let (head, tail) = completed.split_at(comma);
let sse = format!("data: {head}\ndata: {tail}\n\n");
let raw = parse_sse(&sse).unwrap();
let resp = to_completion_response(raw, "gpt-5.4".to_string()).unwrap();
assert_eq!(resp.text(), "hi");
}
#[test]
fn is_rotation_4xx_excludes_429_and_5xx() {
let mk = |status| {
eyre::Report::new(CompletionError::from_http_response(
reqwest::StatusCode::from_u16(status).unwrap(),
r#"{"error":"test"}"#,
))
};
assert!(is_rotation_4xx(&mk(400)));
assert!(is_rotation_4xx(&mk(401)));
assert!(!is_rotation_4xx(&mk(429)));
assert!(!is_rotation_4xx(&mk(500)));
}
}