Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

fix(codex): honor credits after included limit (#68)

Kunaiic6ac077db107
diff --git a/src/providers/codex/events.rs b/src/providers/codex/events.rs
index dece3ef..21f7e6d 100644
--- a/src/providers/codex/events.rs
+++ b/src/providers/codex/events.rs
@@ -23,14 +23,26 @@ impl CodexEventFailure {
}
}
-pub(crate) fn classify_event_failure(payload: &Value) -> Option<CodexEventFailure> {
- let event_type = payload.get("type").and_then(Value::as_str)?;
- if event_type == "codex.rate_limits" {
- if payload
+pub(crate) fn is_terminal_rate_limit_event(payload: &Value) -> bool {
+ payload.get("type").and_then(Value::as_str) == Some("codex.rate_limits")
+ && payload
.pointer("/rate_limits/limit_reached")
.and_then(Value::as_bool)
+ == Some(true)
+ && payload
+ .pointer("/credits/has_credits")
+ .and_then(Value::as_bool)
!= Some(true)
- {
+ && payload
+ .pointer("/credits/unlimited")
+ .and_then(Value::as_bool)
+ != Some(true)
+}
+
+pub(crate) fn classify_event_failure(payload: &Value) -> Option<CodexEventFailure> {
+ let event_type = payload.get("type").and_then(Value::as_str)?;
+ if event_type == "codex.rate_limits" {
+ if !is_terminal_rate_limit_event(payload) {
return None;
}
return Some(CodexEventFailure {
@@ -204,6 +216,61 @@ mod tests {
assert!(overload.retryable());
}
+ #[test]
+ fn terminal_rate_limit_honors_credits() {
+ // No credits field at all: legacy payload stays terminal.
+ assert!(is_terminal_rate_limit_event(&serde_json::json!({
+ "type": "codex.rate_limits",
+ "rate_limits": {"limit_reached": true}
+ })));
+
+ // Credits exhausted: terminal.
+ assert!(is_terminal_rate_limit_event(&serde_json::json!({
+ "type": "codex.rate_limits",
+ "rate_limits": {"limit_reached": true},
+ "credits": {"has_credits": false, "unlimited": false}
+ })));
+
+ // Usable credits remain: informational.
+ assert!(!is_terminal_rate_limit_event(&serde_json::json!({
+ "type": "codex.rate_limits",
+ "rate_limits": {"limit_reached": true},
+ "credits": {"has_credits": true, "unlimited": false}
+ })));
+
+ // Unlimited plan: informational.
+ assert!(!is_terminal_rate_limit_event(&serde_json::json!({
+ "type": "codex.rate_limits",
+ "rate_limits": {"limit_reached": true},
+ "credits": {"has_credits": false, "unlimited": true}
+ })));
+
+ // Limit not reached: never terminal, credits irrelevant.
+ assert!(!is_terminal_rate_limit_event(&serde_json::json!({
+ "type": "codex.rate_limits",
+ "rate_limits": {"limit_reached": false},
+ "credits": {"has_credits": false, "unlimited": false}
+ })));
+
+ // Wrong event type never matches.
+ assert!(!is_terminal_rate_limit_event(&serde_json::json!({
+ "type": "response.completed",
+ "rate_limits": {"limit_reached": true}
+ })));
+ }
+
+ #[test]
+ fn classifier_skips_credited_rate_limit_snapshots() {
+ assert!(
+ classify_event_failure(&serde_json::json!({
+ "type": "codex.rate_limits",
+ "rate_limits": {"limit_reached": true},
+ "credits": {"has_credits": true, "unlimited": false}
+ }))
+ .is_none()
+ );
+ }
+
#[test]
fn ignores_informational_and_permanent_events() {
assert!(
diff --git a/src/providers/codex/translate/live_stream.rs b/src/providers/codex/translate/live_stream.rs
index cfc4844..3ae5d34 100644
--- a/src/providers/codex/translate/live_stream.rs
+++ b/src/providers/codex/translate/live_stream.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use crate::anthropic::sse::encode_sse_event;
+use crate::providers::codex::events::is_terminal_rate_limit_event;
use crate::traffic::TrafficCapture;
use super::read_rewrite::sanitize_read_args;
@@ -99,12 +100,7 @@ impl LiveStreamTranslator {
match kind {
"codex.rate_limits" => {
- if payload
- .get("rate_limits")
- .and_then(|r| r.get("limit_reached"))
- .and_then(|v| v.as_bool())
- == Some(true)
- {
+ if is_terminal_rate_limit_event(payload) {
return Err("rate limit reached".to_string());
}
}
diff --git a/src/providers/codex/translate/reducer.rs b/src/providers/codex/translate/reducer.rs
index 79a9635..b9b628a 100644
--- a/src/providers/codex/translate/reducer.rs
+++ b/src/providers/codex/translate/reducer.rs
@@ -1,4 +1,5 @@
use crate::anthropic::sse::parse_sse_events;
+use crate::providers::codex::events::is_terminal_rate_limit_event;
use super::read_rewrite::sanitize_read_args;
use super::reasoning_signature::{PendingReasoning, ReasoningReplay, encode_reasoning_signature};
@@ -329,11 +330,7 @@ pub fn reduce_upstream_bytes(input: &[u8]) -> Result<Vec<ReducerEvent>, Upstream
last_event_type = Some(t.clone());
if t == "codex.rate_limits" {
- if let Some(true) = p
- .get("rate_limits")
- .and_then(|r| r.get("limit_reached"))
- .and_then(|v| v.as_bool())
- {
+ if is_terminal_rate_limit_event(&p) {
let retry_after = p
.get("rate_limits")
.and_then(|r| r.get("primary"))
diff --git a/tests/smoke_cutover.rs b/tests/smoke_cutover.rs
index afb5927..ea54456 100644
--- a/tests/smoke_cutover.rs
+++ b/tests/smoke_cutover.rs
@@ -212,6 +212,36 @@ async fn spawn_websocket_upstream(captured: Arc<Mutex<Option<Value>>>) -> String
addr_str
}
+/// Reproduce the Codex subscription-credit response observed in production:
+/// the included window is exhausted, but usable credits remain and the model
+/// still completes the response after the rate-limit snapshot.
+async fn spawn_websocket_credited_rate_limit_upstream() -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let addr_str = format!("http://{addr}");
+
+ tokio::spawn(async move {
+ if let Ok((stream, _)) = listener.accept().await
+ && let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await
+ {
+ let _ = ws.next().await;
+ let events = [
+ r#"{"type":"codex.rate_limits","rate_limits":{"allowed":false,"limit_reached":true,"primary":{"used_percent":100,"window_minutes":10080,"reset_after_seconds":509821}},"credits":{"has_credits":true,"unlimited":false,"balance":null}}"#,
+ r#"{"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_up"}}"#,
+ r#"{"type":"response.output_text.delta","output_index":0,"delta":"credited codex ok"}"#,
+ r#"{"type":"response.output_item.done","output_index":0,"item":{"type":"message"}}"#,
+ r#"{"type":"response.completed","response":{"id":"resp_1","usage":{"input_tokens":5,"output_tokens":2}}}"#,
+ ];
+
+ for event in &events {
+ let _ = ws.send(Message::Text(event.to_string())).await;
+ }
+ }
+ });
+
+ addr_str
+}
+
async fn spawn_websocket_delayed_terminal_upstream() -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
@@ -876,6 +906,72 @@ async fn smoke_codex_websocket_messages_uses_mock_upstream() {
assert!(sent.get("stream").is_none());
}
+#[allow(clippy::await_holding_lock)]
+#[tokio::test(flavor = "multi_thread")]
+async fn smoke_codex_websocket_uses_credits_after_included_limit() {
+ let _guard = env_lock();
+ let config = TempDir::new().unwrap();
+ write_auth(config.path(), "codex");
+ clear_codex_websocket_pool_for_tests();
+
+ let upstream = spawn_websocket_credited_rate_limit_upstream().await;
+ let _config_env = EnvGuard::set("CCP_CONFIG_DIR", config.path());
+ let _base_url_env = EnvGuard::set("CCP_CODEX_BASE_URL", &upstream);
+ let _transport_env = EnvGuard::set("CCP_CODEX_TRANSPORT", "websocket");
+
+ let response = call_messages("gpt-5.5").await;
+ let status = response.status();
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "credited Codex response must not be discarded: {}",
+ String::from_utf8_lossy(&body)
+ );
+ let value: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(value["content"][0]["text"], "credited codex ok");
+}
+
+#[allow(clippy::await_holding_lock)]
+#[tokio::test(flavor = "multi_thread")]
+async fn smoke_codex_websocket_stream_uses_credits_after_included_limit() {
+ let _guard = env_lock();
+ let config = TempDir::new().unwrap();
+ write_auth(config.path(), "codex");
+ clear_codex_websocket_pool_for_tests();
+
+ let upstream = spawn_websocket_credited_rate_limit_upstream().await;
+ let _config_env = EnvGuard::set("CCP_CONFIG_DIR", config.path());
+ let _base_url_env = EnvGuard::set("CCP_CODEX_BASE_URL", &upstream);
+ let _transport_env = EnvGuard::set("CCP_CODEX_TRANSPORT", "websocket");
+
+ let response = call_messages_body(json!({
+ "model": "gpt-5.5",
+ "max_tokens": 64,
+ "stream": true,
+ "messages": [{"role":"user","content":"hello"}]
+ }))
+ .await;
+ let status = response.status();
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "credited Codex stream must not be discarded: {}",
+ String::from_utf8_lossy(&body)
+ );
+ let text = String::from_utf8_lossy(&body);
+ assert!(text.contains("credited codex ok"), "stream body: {text}");
+ assert!(text.contains("message_stop"), "stream body: {text}");
+ assert!(!text.contains("event: error"), "stream body: {text}");
+}
+
#[allow(clippy::await_holding_lock)]
#[tokio::test(flavor = "multi_thread")]
async fn smoke_codex_websocket_stream_returns_delta_before_terminal() {