Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy
Rust
stamp the request id on error responses too
Raine Virta8279b3af6a5e
diff --git a/src/server.rs b/src/server.rsindex 8a84255..913a71c 100644--- a/src/server.rs+++ b/src/server.rs@@ -1452,7 +1452,7 @@ async fn dispatch_request(.map(|details| details.message.as_str()).unwrap_or("Invalid JSON"),);- return response;+ return with_request_id(response, &req_id);}};@@ -1492,7 +1492,7 @@ async fn dispatch_request(.map(|details| details.message.as_str()).unwrap_or("Invalid JSON"),);- return response;+ return with_request_id(response, &req_id);}};@@ -1547,7 +1547,7 @@ async fn dispatch_request(.map(|details| details.message.as_str()).unwrap_or("Missing model"),);- return response;+ return with_request_id(response, &req_id);}};@@ -1634,7 +1634,7 @@ async fn dispatch_request(.map(|details| details.message.as_str()).unwrap_or("Unknown model"),);- return response;+ return with_request_id(response, &req_id);}};@@ -1780,12 +1780,33 @@ async fn dispatch_request(format!("HTTP {}", status.as_u16()),);}- response+ with_request_id(response, &req_id)}/// Header Claude Code reads to populate the `requestId` field it writes into/// every transcript record.-pub const REQUEST_ID_HEADER: &str = "request-id";+const REQUEST_ID_HEADER: &str = "request-id";++/// Publish the per-request id this proxy mints. Anthropic returns `request-id`,+/// and Claude Code records it as `requestId`; without it every downstream+/// consumer that de-duplicates transcript records by request id (its own+/// parser, usage dashboards) counts each request twice, because a transcript+/// legitimately repeats a record and the id is what resolves it.+///+/// An upstream-supplied id is preserved: relabelling a real provider id with a+/// local uuid would lose the more useful value.+fn stamp_request_id(headers: &mut http::HeaderMap, req_id: &str) {+ if !headers.contains_key(REQUEST_ID_HEADER)+ && let Ok(value) = http::HeaderValue::from_str(req_id)+ {+ headers.insert(REQUEST_ID_HEADER, value);+ }+}++fn with_request_id(mut response: Response, req_id: &str) -> Response {+ stamp_request_id(response.headers_mut(), req_id);+ response+}fn monitor_response_body(response: Response, guard: RequestMonitorGuard) -> Response {let status = response.status();@@ -1794,20 +1815,9 @@ fn monitor_response_body(response: Response, guard: RequestMonitorGuard) -> Resp.get::<NativeResponseOutcome>().cloned();let (mut parts, body) = response.into_parts();- // Publish the per-request id this proxy already mints. Anthropic returns- // `request-id`, and Claude Code records it as `requestId`; without it every- // downstream consumer that de-duplicates transcript records by request id- // (its own parser, usage dashboards) counts each request twice, because a- // transcript legitimately repeats a record and the id is what resolves it.- //- // Stamped here rather than at each `return` because every response path in- // this module funnels through this function, and it is applied to the parts- // before the body is streamed, so a streaming SSE response carries it too.- if !parts.headers.contains_key(REQUEST_ID_HEADER)- && let Ok(value) = http::HeaderValue::from_str(&guard.req_id)- {- parts.headers.insert(REQUEST_ID_HEADER, value);- }+ // Stamped on the parts before the body is streamed, so a streaming SSE+ // response carries the header too.+ stamp_request_id(&mut parts.headers, &guard.req_id);let stream = futures_util::stream::unfold((body, guard, outcome),move |(mut body, mut guard, outcome)| async move {@@ -2225,17 +2235,6 @@ mod request_id_header_tests {"upstream-owned");}-- // Error responses are de-duplicated by the same key as successes.- #[test]- fn stamps_error_responses_too() {- let response = Response::builder()- .status(StatusCode::TOO_MANY_REQUESTS)- .body(Body::from("{\"error\":\"rate limited\"}"))- .unwrap();- let stamped = monitor_response_body(response, guard("req-429"));- assert_eq!(stamped.headers().get(REQUEST_ID_HEADER).unwrap(), "req-429");- }}#[cfg(test)]diff --git a/tests/server.rs b/tests/server.rsindex 3c87490..bf21a20 100644--- a/tests/server.rs+++ b/tests/server.rs@@ -516,6 +516,73 @@ async fn unknown_model_returns_400_with_summary() {assert!(message.contains("Supported:"));}+fn request_id(response: &axum::response::Response) -> &str {+ response+ .headers()+ .get("request-id")+ .and_then(|value| value.to_str().ok())+ .unwrap_or_default()+}++async fn messages_response(app: axum::Router, model: &str) -> axum::response::Response {+ app.oneshot(+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages")+ .header("content-type", "application/json")+ .body(body_string(+ &json!({"model": model, "messages": [{"role": "user", "content": "hello"}]})+ .to_string(),+ ))+ .unwrap(),+ )+ .await+ .unwrap()+}++// Claude Code populates the `requestId` field of every transcript record from+// the `request-id` response header. Consumers that de-duplicate those records+// by request id count each request twice without it, because a transcript+// legitimately repeats a record and the id is what resolves the repeat.+#[tokio::test]+async fn successful_response_carries_a_request_id() {+ let registry = || {+ Arc::new(Registry::from_providers(+ AliasProvider::Codex,+ [Arc::new(IdentityCaptureProvider {+ captured: Arc::new(Mutex::new(Vec::new())),+ }) as Arc<dyn Provider>],+ ))+ };+ let first = messages_response(app(registry()), "gpt-5.5").await;+ let second = messages_response(app(registry()), "gpt-5.5").await;++ assert_eq!(first.status(), StatusCode::OK);+ assert!(!request_id(&first).is_empty());+ assert_ne!(request_id(&first), request_id(&second));+}++// Errors are de-duplicated by the same key as successes, and a failed turn is+// the record most worth correlating with a proxy log.+#[tokio::test]+async fn rejected_request_carries_a_request_id() {+ let response =+ messages_response(app(Arc::new(Registry::with_default_alias())), "not-a-model").await;++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(!request_id(&response).is_empty());+}++// A provider that answers with a failure status leaves through a different+// return path than a success.+#[tokio::test]+async fn provider_failure_response_carries_a_request_id() {+ let response = messages_response(app(routed_registry()), "kimi-k2.6").await;++ assert_eq!(response.status(), StatusCode::NOT_IMPLEMENTED);+ assert!(!request_id(&response).is_empty());+}+#[tokio::test]async fn missing_model_returns_400() {let app = app(Arc::new(Registry::with_default_alias()));