Skip to content

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

Rust

codex: stop re-sending a request after the response header timeout (#160)

Rik Brown505febd23e33
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 42b9441..1a1b916 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,14 @@ title: Changelog
description: Release notes for claude-code-proxy.
---
+## Unreleased
+
+- Long Codex requests on the HTTP transport no longer hang for minutes and then
+ fail: the proxy waits five minutes for the response headers instead of one,
+ configurable with `CCP_CODEX_HEADER_TIMEOUT_MS` or `codex.headerTimeoutMs`,
+ and a timeout there fails the request once rather than re-sending it.
+ ([#160](https://github.com/raine/claude-code-proxy/pull/160))
+
## v0.1.40 (2026-09-14)
- Attach one or more monitor dashboards to a background proxy with
diff --git a/docs/src/content/docs/providers/codex.md b/docs/src/content/docs/providers/codex.md
index a0061c5..1a4795a 100644
--- a/docs/src/content/docs/providers/codex.md
+++ b/docs/src/content/docs/providers/codex.md
@@ -58,6 +58,8 @@ Claude Code summary compaction requests are capped at low effort by default beca
WebSocket is the default transport. Set `CCP_CODEX_TRANSPORT=http` for HTTP SSE, or `auto` to use WebSocket with HTTP fallback only when setup fails before a request is sent.
+On the HTTP transport, the proxy waits five minutes for the response headers before failing the request. Codex withholds the response head until the model produces its first output, so a large request to a high-effort model can hold it for minutes. `CCP_CODEX_HEADER_TIMEOUT_MS` or `codex.headerTimeoutMs` changes that bound.
+
WebSocket setup honors `HTTP_PROXY` for `ws://`, `HTTPS_PROXY` for the default `wss://` endpoint, `ALL_PROXY` as a fallback, and `NO_PROXY` exclusions. A normal HTTP proxy can therefore carry the default WebSocket connection with CONNECT; TUN mode is not required. Set proxy variables before starting the process and restart after changing them. For example, setting `HTTPS_PROXY` to `http://127.0.0.1:7890` sends HTTPS/WSS destinations through the HTTP proxy at port 7890; it does not require an `https://` proxy URL.
`CCP_CODEX_PREVIOUS_RESPONSE_ID=1` enables append-only WebSocket continuation. A valid identity containing only a Claude Code session ID owns the Main continuation for that session. Each valid direct Agent ID owns an independent continuation and reusable WebSocket within the same session. Nested Agents are keyed by their direct child ID; the parent ID is validated but does not become part of the owner key. The proxy sends `previous_response_id` only when the translated request shape and transcript extension are safe, and only on the exact live WebSocket that produced that response.
diff --git a/docs/src/content/docs/reference/configuration.md b/docs/src/content/docs/reference/configuration.md
index f5936f2..9648e75 100644
--- a/docs/src/content/docs/reference/configuration.md
+++ b/docs/src/content/docs/reference/configuration.md
@@ -24,6 +24,7 @@ These settings configure the proxy process. Claude Code client settings such as
"serviceTier": "fast",
"baseUrl": "https://chatgpt.com/backend-api/codex/responses",
"transport": "websocket",
+ "headerTimeoutMs": 300000,
"previousResponseId": false,
"serverCompaction": false,
"responsesApi": false,
@@ -108,6 +109,7 @@ Proxy URLs may use `http`, `https`, `socks4`, `socks4a`, `socks5`, or `socks5h`.
| `CCP_CODEX_SERVICE_TIER` | `codex.serviceTier` | unset | Forces `fast` or `priority`, or `flex`. Fast is sent as `priority`. |
| `CCP_CODEX_BASE_URL` | `codex.baseUrl` | ChatGPT Codex Responses URL | Changes the Codex endpoint. |
| `CCP_CODEX_TRANSPORT` | `codex.transport` | `websocket` | Selects `websocket`, `http`, or `auto`. |
+| `CCP_CODEX_HEADER_TIMEOUT_MS` | `codex.headerTimeoutMs` | `300000` | Sets how long an HTTP-transport request waits for the Codex response headers. Values below `1000` are ignored. |
| `CCP_CODEX_PREVIOUS_RESPONSE_ID` | `codex.previousResponseId` | `false` | Enables append-only WebSocket continuation for `1`, `true`, or `yes`. |
| `CCP_CODEX_SERVER_COMPACTION` | `codex.serverCompaction` | `false` | Enables or disables native compaction for standard boolean words. |
| `CCP_CODEX_RESPONSES_API` | `codex.responsesApi` | `false` | Enables `/v1/responses` and `/v1/chat/completions` for every registered provider. Accepts `1`, `true`, or `yes`. |
diff --git a/src/config.rs b/src/config.rs
index 5e9cb33..23c371b 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -76,6 +76,8 @@ struct CodexConfig {
#[serde(rename = "model")]
pub model: Option<String>,
pub transport: Option<String>,
+ #[serde(rename = "headerTimeoutMs")]
+ pub header_timeout_ms: Option<u64>,
}
#[derive(Deserialize, Clone)]
@@ -367,6 +369,9 @@ pub fn config_override_summary_lines(cfg: &LoadedConfig) -> Vec<String> {
if codex.transcriptions_api == Some(true) {
out.push("codex.transcriptionsApi: true".to_string());
}
+ if let Some(ms) = codex.header_timeout_ms {
+ out.push(format!("codex.headerTimeoutMs: {ms}"));
+ }
}
}
out
@@ -892,6 +897,40 @@ pub fn codex_transport() -> CodexTransport {
CodexTransport::WebSocket
}
+/// How long an HTTP-transport request waits for the Codex response headers.
+///
+/// Codex withholds the response head until the model produces its first
+/// output, so the wait tracks how much reasoning the request asks for rather
+/// than the health of the connection. A large request to a high-effort model
+/// can hold the head for minutes, and the timeout firing fails the request
+/// outright, so the default is generous. Lower it only where a request that
+/// slow is better failed than waited out. Values below
+/// `CODEX_MIN_HEADER_TIMEOUT_MS` are ignored rather than clamped, so a typo
+/// does not hide behind a working default.
+pub const CODEX_DEFAULT_HEADER_TIMEOUT_MS: u64 = 300_000;
+pub const CODEX_MIN_HEADER_TIMEOUT_MS: u64 = 1_000;
+
+pub fn codex_header_timeout_ms() -> u64 {
+ let env: HashMap<_, _> = std::env::vars().collect();
+ if let Some(ms) = env
+ .get("CCP_CODEX_HEADER_TIMEOUT_MS")
+ .and_then(|raw| raw.trim().parse::<u64>().ok())
+ .filter(|ms| *ms >= CODEX_MIN_HEADER_TIMEOUT_MS)
+ {
+ return ms;
+ }
+ let config_dir = paths::config_dir();
+ if let Some(file) = read_file_config(&config_dir)
+ && let Some(codex) = file.codex
+ && let Some(ms) = codex
+ .header_timeout_ms
+ .filter(|ms| *ms >= CODEX_MIN_HEADER_TIMEOUT_MS)
+ {
+ return ms;
+ }
+ CODEX_DEFAULT_HEADER_TIMEOUT_MS
+}
+
// ---------------------------------------------------------------------------
// Cursor config
// ---------------------------------------------------------------------------
@@ -988,6 +1027,7 @@ mod tests {
EnvGuard::unset("CCP_CODEX_IMAGES_API"),
EnvGuard::unset("CCP_CODEX_IMAGES_BASE_URL"),
EnvGuard::unset("CCP_CODEX_TRANSCRIPTIONS_API"),
+ EnvGuard::unset("CCP_CODEX_HEADER_TIMEOUT_MS"),
EnvGuard::unset("CCP_AUTO_REVIEW_MODEL"),
];
guards.push(EnvGuard::set("CCP_CONFIG_DIR", config.path()));
@@ -1154,6 +1194,35 @@ mod tests {
assert_eq!(codex_transport(), CodexTransport::WebSocket);
}
+ #[test]
+ fn codex_header_timeout_defaults_overrides_and_floors() {
+ let _guard = ENV_LOCK.lock().unwrap();
+ let config = tempfile::TempDir::new().unwrap();
+ let _env = isolated_env(&config);
+
+ assert_eq!(codex_header_timeout_ms(), CODEX_DEFAULT_HEADER_TIMEOUT_MS);
+ std::fs::write(
+ config.path().join("config.json"),
+ r#"{"codex":{"headerTimeoutMs":600000}}"#,
+ )
+ .unwrap();
+ assert_eq!(codex_header_timeout_ms(), 600_000);
+ {
+ let _timeout_env = EnvGuard::set("CCP_CODEX_HEADER_TIMEOUT_MS", "120000");
+ assert_eq!(codex_header_timeout_ms(), 120_000);
+ }
+ // Below the floor is ignored, not clamped: a value that small is a typo,
+ // and clamping it would hide the typo behind a working default.
+ std::fs::write(
+ config.path().join("config.json"),
+ r#"{"codex":{"headerTimeoutMs":5}}"#,
+ )
+ .unwrap();
+ assert_eq!(codex_header_timeout_ms(), CODEX_DEFAULT_HEADER_TIMEOUT_MS);
+ let _timeout_env = EnvGuard::set("CCP_CODEX_HEADER_TIMEOUT_MS", "0");
+ assert_eq!(codex_header_timeout_ms(), CODEX_DEFAULT_HEADER_TIMEOUT_MS);
+ }
+
#[test]
fn parse_codex_transport_variants() {
assert_eq!(parse_codex_transport("http"), Some(CodexTransport::Http));
diff --git a/src/providers/codex/chat_completions/mod.rs b/src/providers/codex/chat_completions/mod.rs
index b50a36f..e27df63 100644
--- a/src/providers/codex/chat_completions/mod.rs
+++ b/src/providers/codex/chat_completions/mod.rs
@@ -365,7 +365,6 @@ mod tests {
format!("http://{address}/v1/responses"),
1_000,
1_000,
- 0,
);
client.auth_manager().set_test_auth(StoredAuth {
access: "test-token".into(),
diff --git a/src/providers/codex/client.rs b/src/providers/codex/client.rs
index b7c21cb..2466894 100644
--- a/src/providers/codex/client.rs
+++ b/src/providers/codex/client.rs
@@ -521,6 +521,9 @@ const MAX_BUFFERED_TRANSPORT_RETRIES: u32 = 3;
const MAX_BUFFERED_TRANSPORT_ATTEMPTS: u32 = MAX_BUFFERED_TRANSPORT_RETRIES + 1;
const HTTP_RESPONSE_BODY_IDLE_TIMEOUT_MS: u64 = 300_000;
const IMAGE_HEADER_TIMEOUT_MS: u64 = 300_000;
+/// Marks the error raised when the wait for the Codex response headers runs
+/// out, so the retry classifiers can tell it apart from a transport failure.
+const HTTP_RESPONSE_HEADERS_DETAIL: &str = "http_response_headers";
#[derive(Clone)]
struct ProxyEnvironment {
@@ -694,8 +697,6 @@ pub struct CodexHttpClient {
base_url: String,
header_timeout_ms: u64,
body_idle_timeout_ms: u64,
- #[allow(dead_code)]
- header_timeout_retries: u32,
}
impl Default for CodexHttpClient {
@@ -706,7 +707,7 @@ impl Default for CodexHttpClient {
impl CodexHttpClient {
pub fn new() -> Self {
- let timeout_ms = 60_000;
+ let timeout_ms = config::codex_header_timeout_ms();
let proxy_environment = ProxyEnvironment::from_env();
Self {
client: proxy_environment
@@ -721,7 +722,6 @@ impl CodexHttpClient {
base_url: config::codex_base_url(CODEX_API_ENDPOINT),
header_timeout_ms: timeout_ms,
body_idle_timeout_ms: HTTP_RESPONSE_BODY_IDLE_TIMEOUT_MS,
- header_timeout_retries: 1,
}
}
@@ -742,9 +742,8 @@ impl CodexHttpClient {
client,
auth_manager,
base_url,
- header_timeout_ms: 60_000,
+ header_timeout_ms: config::codex_header_timeout_ms(),
body_idle_timeout_ms: HTTP_RESPONSE_BODY_IDLE_TIMEOUT_MS,
- header_timeout_retries: 1,
}
}
@@ -754,7 +753,6 @@ impl CodexHttpClient {
base_url: String,
header_timeout_ms: u64,
body_idle_timeout_ms: u64,
- header_timeout_retries: u32,
) -> Self {
Self {
native_client: test_native_http_client(),
@@ -766,7 +764,6 @@ impl CodexHttpClient {
base_url,
header_timeout_ms,
body_idle_timeout_ms,
- header_timeout_retries,
}
}
@@ -2384,7 +2381,7 @@ impl CodexHttpClient {
"Timed out waiting {}ms for Codex response headers",
self.header_timeout_ms
),
- detail: None,
+ detail: Some(HTTP_RESPONSE_HEADERS_DETAIL.to_string()),
retry_after: None,
usage_limit: None,
origin: CodexErrorOrigin::Http,
@@ -2956,6 +2953,14 @@ fn log_buffered_retry_exhausted(
}
fn is_retryable_transport_error(err: &CodexError) -> bool {
+ // Running out of patience for the response headers is not a transport
+ // failure. The request reached Codex, which is holding the head while the
+ // model reasons, so re-sending it starts that reasoning again from scratch
+ // and the new attempt runs out of time exactly like the last one. Wait
+ // longer with CCP_CODEX_HEADER_TIMEOUT_MS instead.
+ if err.detail.as_deref() == Some(HTTP_RESPONSE_HEADERS_DETAIL) {
+ return false;
+ }
if err.origin == CodexErrorOrigin::WebSocketHandshake {
if err.detail.as_deref() == Some(super::websocket::WEBSOCKET_PROXY_TUNNEL_REJECTED_DETAIL) {
return false;
@@ -3207,7 +3212,6 @@ mod tests {
base_url,
100,
body_idle_timeout_ms,
- 0,
)
}
@@ -3670,6 +3674,62 @@ mod tests {
server.await.unwrap();
}
+ #[tokio::test]
+ async fn http_stream_does_not_resend_after_a_header_timeout() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ let mut attempts = 0_u32;
+ // Hold every accepted connection open. Closing one would look like
+ // a transport failure and mask the header timeout under test.
+ let mut held = Vec::new();
+ while let Ok(Ok((mut stream, _))) =
+ tokio::time::timeout(Duration::from_millis(400), listener.accept()).await
+ {
+ let mut request = [0_u8; 16 * 1024];
+ assert!(stream.read(&mut request).await.unwrap() > 0);
+ attempts += 1;
+ held.push(stream);
+ }
+ attempts
+ });
+
+ let client = Arc::new(http_test_client(format!("http://{addr}/responses"), 1_000));
+ client.auth_manager().set_test_auth(http_test_auth());
+ let started_at = Instant::now();
+ let error = match client
+ .stream_codex_http_events(&buffered_test_request(), &http_test_context())
+ .await
+ {
+ Ok(_) => panic!("a silent upstream must fail the request"),
+ Err(error) => error,
+ };
+ let elapsed = started_at.elapsed();
+
+ assert_eq!(error.status, 0);
+ assert!(
+ error
+ .message
+ .contains("Timed out waiting 100ms for Codex response headers"),
+ "{}",
+ error.message
+ );
+ assert_eq!(
+ error.detail.as_deref(),
+ Some(HTTP_RESPONSE_HEADERS_DETAIL),
+ "the header timeout must stay distinguishable from a transport failure"
+ );
+ assert!(
+ elapsed < Duration::from_millis(crate::retry::RETRY_INITIAL_DELAY_MS),
+ "the header timeout must fail before the first retry backoff, took {elapsed:?}"
+ );
+ assert_eq!(
+ server.await.unwrap(),
+ 1,
+ "a header timeout must not re-send the request"
+ );
+ }
+
#[tokio::test]
async fn http_stream_bounds_initial_status_retries() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -5030,6 +5090,21 @@ mod tests {
assert!(display.contains("Rate limited"));
}
+ #[test]
+ fn header_timeout_is_not_retried_by_either_classifier() {
+ let err = CodexError {
+ status: 0,
+ message: "Timed out waiting 300000ms for Codex response headers".to_string(),
+ detail: Some(HTTP_RESPONSE_HEADERS_DETAIL.to_string()),
+ retry_after: None,
+ usage_limit: None,
+ origin: CodexErrorOrigin::Http,
+ };
+
+ assert!(!is_retryable_transport_error(&err));
+ assert!(!retryable_http_stream_error(&err));
+ }
+
#[test]
fn websocket_pre_request_502_is_retryable() {
let err = CodexError {
diff --git a/src/providers/codex/images.rs b/src/providers/codex/images.rs
index 646ea1d..03e27c7 100644
--- a/src/providers/codex/images.rs
+++ b/src/providers/codex/images.rs
@@ -793,7 +793,6 @@ mod tests {
format!("http://{addr}/responses"),
1_000,
1_000,
- 0,
);
client
.auth_manager()
@@ -849,7 +848,6 @@ mod tests {
format!("http://{addr}/responses"),
1_000,
1_000,
- 0,
);
client
.auth_manager()
diff --git a/src/providers/codex/mod.rs b/src/providers/codex/mod.rs
index 85154b6..1b2e3f6 100644
--- a/src/providers/codex/mod.rs
+++ b/src/providers/codex/mod.rs
@@ -1712,7 +1712,6 @@ mod tests {
base_url,
1_000,
1_000,
- 0,
);
client
.auth_manager()
diff --git a/src/providers/codex/transcription.rs b/src/providers/codex/transcription.rs
index a2843a8..a15d20d 100644
--- a/src/providers/codex/transcription.rs
+++ b/src/providers/codex/transcription.rs
@@ -457,7 +457,6 @@ mod tests {
format!("http://{addr}/responses"),
1_000,
1_000,
- 0,
);
client
.auth_manager()