mirror of
https://github.com/openai/codex.git
synced 2026-11-18 22:20:48 +00:00
## Why When the Responses API sends a policy rejection in an `error` event without an HTTP status, the SSE client can wait until its idle timeout to report the failure. ## What changed Recognize `bio_policy` and `cyber_policy` in the shared terminal error parser so both SSE and WebSocket clients surface the corresponding policy error. Preserve the provider's message and use a default when it is missing or blank. End the SSE stream as soon as the error arrives. ## Testing Add SSE tests for both error codes, including when the stream stays open, and WebSocket cases that verify both errors surface without a close handshake. GitOrigin-RevId: 1b46b6557a39a61a1bb10bdd0d8ede48ecd6fa13
123 lines
4.4 KiB
Rust
123 lines
4.4 KiB
Rust
//! Classifies failed Responses events and their retry advice.
|
|
//! Only rate-limit codes derive retry delays from plaintext messages.
|
|
|
|
use crate::error::ApiError;
|
|
use crate::error::parse_terminal_provider_error;
|
|
use crate::responses_headers::json_headers_to_http_headers;
|
|
use codex_http_client::RetryAfter;
|
|
use codex_protocol::protocol::MisalignmentErrorDetails;
|
|
use serde::Deserialize;
|
|
use serde_json::Value;
|
|
use std::time::Duration;
|
|
|
|
// Keep decoding unused fields: malformed values currently produce a stream error.
|
|
#[derive(Debug, Deserialize)]
|
|
#[allow(dead_code)]
|
|
struct Error {
|
|
r#type: Option<String>,
|
|
code: Option<String>,
|
|
message: Option<String>,
|
|
plan_type: Option<String>,
|
|
resets_at: Option<i64>,
|
|
#[serde(default)]
|
|
misalignment: Option<Value>,
|
|
}
|
|
|
|
pub(super) fn parse_failed_response(response: Option<Value>) -> ApiError {
|
|
let error = response.as_ref().and_then(|response| response.get("error"));
|
|
let retry_after_header = error
|
|
.and_then(|error| error.get("headers"))
|
|
.and_then(Value::as_object)
|
|
.and_then(|headers| RetryAfter::from_headers(&json_headers_to_http_headers(headers)));
|
|
if let Some(error) = parse_terminal_provider_error(error, /*status*/ None) {
|
|
return error;
|
|
}
|
|
let Some(error) = error.and_then(|error| serde_json::from_value::<Error>(error.clone()).ok())
|
|
else {
|
|
let message = "response.failed event received".to_string();
|
|
return match retry_after_header {
|
|
Some(_) => ApiError::Retryable {
|
|
message,
|
|
retry_after: retry_after_header,
|
|
},
|
|
None => ApiError::Stream(message),
|
|
};
|
|
};
|
|
|
|
match error.code.as_deref() {
|
|
Some("insufficient_quota" | "credit_balance_exhausted") => ApiError::QuotaExceeded,
|
|
Some("usage_not_included") => ApiError::UsageNotIncluded,
|
|
Some("misalignment_policy_violation") => {
|
|
let message = error
|
|
.message
|
|
.filter(|message| !message.trim().is_empty())
|
|
.unwrap_or_else(|| {
|
|
"This request was blocked due to a misalignment policy violation.".to_string()
|
|
});
|
|
ApiError::MisalignmentPolicyViolation {
|
|
message,
|
|
misalignment: error.misalignment.and_then(|details| {
|
|
serde_json::from_value::<MisalignmentErrorDetails>(details).ok()
|
|
}),
|
|
}
|
|
}
|
|
Some("invalid_prompt") => ApiError::InvalidPrompt {
|
|
message: error
|
|
.message
|
|
.unwrap_or_else(|| "Invalid request.".to_string()),
|
|
},
|
|
Some("policy_capacity_unavailable") => ApiError::PolicyCapacityUnavailable {
|
|
retry_after: retry_after_header,
|
|
},
|
|
Some("server_is_overloaded") => ApiError::ServerOverloaded {
|
|
retry_after: retry_after_header,
|
|
},
|
|
Some("rate_limit_exceeded" | "slow_down") => {
|
|
let retry_after = retry_after_header
|
|
.or_else(|| try_parse_retry_delay(&error).and_then(RetryAfter::from_delay));
|
|
ApiError::RateLimitExceeded {
|
|
message: error.message.unwrap_or_default(),
|
|
retry_after,
|
|
}
|
|
}
|
|
_ => ApiError::Retryable {
|
|
message: error.message.unwrap_or_default(),
|
|
retry_after: retry_after_header,
|
|
},
|
|
}
|
|
}
|
|
|
|
fn try_parse_retry_delay(err: &Error) -> Option<Duration> {
|
|
let re = rate_limit_regex();
|
|
if let Some(message) = &err.message
|
|
&& let Some(captures) = re.captures(message)
|
|
{
|
|
let seconds = captures.get(1);
|
|
let unit = captures.get(2);
|
|
|
|
if let (Some(value), Some(unit)) = (seconds, unit) {
|
|
let value = value.as_str().parse::<f64>().ok()?;
|
|
let unit = unit.as_str().to_ascii_lowercase();
|
|
|
|
if unit == "s" || unit.starts_with("second") {
|
|
return Duration::try_from_secs_f64(value).ok();
|
|
} else if unit == "ms" {
|
|
return Some(Duration::from_millis(value as u64));
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn rate_limit_regex() -> &'static regex_lite::Regex {
|
|
static RE: std::sync::OnceLock<regex_lite::Regex> = std::sync::OnceLock::new();
|
|
#[expect(clippy::unwrap_used)]
|
|
RE.get_or_init(|| {
|
|
regex_lite::Regex::new(r"(?i)try again in\s*(\d+(?:\.\d+)?)\s*(s|ms|seconds?)").unwrap()
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "responses_error_parser_tests.rs"]
|
|
mod tests;
|