1use crate::TransportError;
2use crate::error::ApiError;
3use crate::rate_limits::parse_promo_message;
4use crate::rate_limits::parse_rate_limit_for_limit;
5use crate::rate_limits::parse_rate_limit_reached_type;
6use base64::Engine;
7use chrono::DateTime;
8use chrono::Utc;
9use codex_protocol::auth::PlanType;
10use codex_protocol::error::CodexErr;
11use codex_protocol::error::RetryLimitReachedError;
12use codex_protocol::error::UnexpectedResponseError;
13use codex_protocol::error::UsageLimitReachedError;
14use http::HeaderMap;
15use serde::Deserialize;
16use serde_json::Value;
17
18pub fn map_api_error(err: ApiError) -> CodexErr {
19 match err {
20 ApiError::ContextWindowExceeded => CodexErr::ContextWindowExceeded,
21 ApiError::QuotaExceeded => CodexErr::QuotaExceeded,
22 ApiError::UsageNotIncluded => CodexErr::UsageNotIncluded,
23 ApiError::Retryable { message, delay } => CodexErr::Stream(message, delay),
24 ApiError::Stream(msg) => CodexErr::Stream(msg, None),
25 ApiError::ServerOverloaded => CodexErr::ServerOverloaded,
26 ApiError::Api { status, message } => {
27 let user_message = api_error_user_message(status, &message);
28 CodexErr::UnexpectedStatus(UnexpectedResponseError {
29 status,
30 body: message,
31 user_message,
32 url: None,
33 cf_ray: None,
34 request_id: None,
35 identity_authorization_error: None,
36 identity_error_code: None,
37 })
38 }
39 ApiError::InvalidRequest { message } => CodexErr::InvalidRequest(message),
40 ApiError::CyberPolicy { message } => CodexErr::CyberPolicy { message },
41 ApiError::Transport(transport) => match transport {
42 TransportError::Http {
43 status,
44 url,
45 headers,
46 body,
47 } => {
48 let body_text = body.unwrap_or_default();
49
50 if status == http::StatusCode::SERVICE_UNAVAILABLE
51 && let Ok(value) = serde_json::from_str::<serde_json::Value>(&body_text)
52 && matches!(
53 value
54 .get("error")
55 .and_then(|error| error.get("code"))
56 .and_then(serde_json::Value::as_str),
57 Some("server_is_overloaded" | "slow_down")
58 )
59 {
60 return CodexErr::ServerOverloaded;
61 }
62
63 if status == http::StatusCode::BAD_REQUEST {
64 if let Ok(parsed) = serde_json::from_str::<Value>(&body_text)
65 && let Some(error) = parsed.get("error")
66 && error.get("code").and_then(Value::as_str)
67 == Some(CYBER_POLICY_ERROR_CODE)
68 {
69 let message = error
70 .get("message")
71 .and_then(Value::as_str)
72 .filter(|message| !message.trim().is_empty())
73 .map(str::to_string)
74 .unwrap_or_else(|| CYBER_POLICY_FALLBACK_MESSAGE.to_string());
75 CodexErr::CyberPolicy { message }
76 } else if body_text
77 .contains("The image data you provided does not represent a valid image")
78 {
79 CodexErr::InvalidImageRequest()
80 } else {
81 CodexErr::InvalidRequest(body_text)
82 }
83 } else if status == http::StatusCode::INTERNAL_SERVER_ERROR {
84 CodexErr::InternalServerError
85 } else if status == http::StatusCode::TOO_MANY_REQUESTS {
86 if let Ok(err) = serde_json::from_str::<UsageErrorResponse>(&body_text) {
87 if err.error.error_type.as_deref() == Some("usage_limit_reached") {
88 let limit_id = extract_header(headers.as_ref(), ACTIVE_LIMIT_HEADER);
89 let promo_message = headers.as_ref().and_then(parse_promo_message);
90 let rate_limit_reached_type =
91 headers.as_ref().and_then(parse_rate_limit_reached_type);
92 let rate_limits = headers
93 .as_ref()
94 .and_then(|map| {
95 parse_rate_limit_for_limit(map, limit_id.as_deref())
96 })
97 .map(|mut snapshot| {
98 snapshot.rate_limit_reached_type = rate_limit_reached_type;
99 snapshot
100 });
101 let resets_at = err
102 .error
103 .resets_at
104 .and_then(|seconds| DateTime::<Utc>::from_timestamp(seconds, 0));
105 return CodexErr::UsageLimitReached(UsageLimitReachedError {
106 plan_type: err.error.plan_type,
107 resets_at,
108 rate_limits: rate_limits.map(Box::new),
109 promo_message,
110 rate_limit_reached_type,
111 });
112 } else if err.error.error_type.as_deref() == Some("usage_not_included") {
113 return CodexErr::UsageNotIncluded;
114 }
115 }
116
117 CodexErr::RetryLimit(RetryLimitReachedError {
118 status,
119 request_id: extract_request_tracking_id(headers.as_ref()),
120 })
121 } else {
122 CodexErr::UnexpectedStatus(UnexpectedResponseError {
123 status,
124 user_message: api_error_user_message(status, &body_text),
125 body: body_text,
126 url,
127 cf_ray: extract_header(headers.as_ref(), CF_RAY_HEADER),
128 request_id: extract_request_id(headers.as_ref()),
129 identity_authorization_error: extract_header(
130 headers.as_ref(),
131 X_OPENAI_AUTHORIZATION_ERROR_HEADER,
132 ),
133 identity_error_code: extract_x_error_json_code(headers.as_ref()),
134 })
135 }
136 }
137 TransportError::RetryLimit => CodexErr::RetryLimit(RetryLimitReachedError {
138 status: http::StatusCode::INTERNAL_SERVER_ERROR,
139 request_id: None,
140 }),
141 TransportError::Timeout => CodexErr::RequestTimeout,
142 TransportError::Network(msg) | TransportError::Build(msg) => {
143 CodexErr::Stream(msg, None)
144 }
145 },
146 ApiError::RateLimit(msg) => CodexErr::Stream(msg, None),
147 }
148}
149
150const ACTIVE_LIMIT_HEADER: &str = "x-codex-active-limit";
151const REQUEST_ID_HEADER: &str = "x-request-id";
152const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id";
153const CF_RAY_HEADER: &str = "cf-ray";
154const X_OPENAI_AUTHORIZATION_ERROR_HEADER: &str = "x-openai-authorization-error";
155const X_ERROR_JSON_HEADER: &str = "x-error-json";
156const CYBER_POLICY_ERROR_CODE: &str = "cyber_policy";
157const CYBER_POLICY_FALLBACK_MESSAGE: &str =
158 "This request has been flagged for possible cybersecurity risk.";
159const CLOUDFLARE_BLOCKED_MESSAGE: &str =
160 "Access blocked by Cloudflare. This usually happens when connecting from a restricted region";
161
162#[cfg(test)]
163#[path = "api_bridge_tests.rs"]
164mod tests;
165
166fn extract_request_tracking_id(headers: Option<&HeaderMap>) -> Option<String> {
167 extract_request_id(headers).or_else(|| extract_header(headers, CF_RAY_HEADER))
168}
169
170fn api_error_user_message(status: http::StatusCode, body: &str) -> Option<String> {
171 if status == http::StatusCode::FORBIDDEN
172 && body.contains("Cloudflare")
173 && body.contains("blocked")
174 {
175 Some(format!("{CLOUDFLARE_BLOCKED_MESSAGE} (status {status})"))
176 } else {
177 None
178 }
179}
180
181fn extract_request_id(headers: Option<&HeaderMap>) -> Option<String> {
182 extract_header(headers, REQUEST_ID_HEADER)
183 .or_else(|| extract_header(headers, OAI_REQUEST_ID_HEADER))
184}
185
186fn extract_header(headers: Option<&HeaderMap>, name: &str) -> Option<String> {
187 headers.and_then(|map| {
188 map.get(name)
189 .and_then(|value| value.to_str().ok())
190 .map(str::to_string)
191 })
192}
193
194fn extract_x_error_json_code(headers: Option<&HeaderMap>) -> Option<String> {
195 let encoded = extract_header(headers, X_ERROR_JSON_HEADER)?;
196 let decoded = base64::engine::general_purpose::STANDARD
197 .decode(encoded)
198 .ok()?;
199 let parsed = serde_json::from_slice::<Value>(&decoded).ok()?;
200 parsed
201 .get("error")
202 .and_then(|error| error.get("code"))
203 .and_then(Value::as_str)
204 .map(str::to_string)
205}
206
207#[derive(Debug, Deserialize)]
208struct UsageErrorResponse {
209 error: UsageErrorBody,
210}
211
212#[derive(Debug, Deserialize)]
213struct UsageErrorBody {
214 #[serde(rename = "type")]
215 error_type: Option<String>,
216 plan_type: Option<PlanType>,
217 resets_at: Option<i64>,
218}