claude-codex 0.3.1

Run Claude Code on your Claude and ChatGPT subscriptions at once, routed per model name
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use axum::response::{IntoResponse, Response};
use bytes::Bytes;
use http::StatusCode;
use serde::Deserialize;

pub const MAX_AUDIO_BYTES: usize = 25 * 1024 * 1024;
pub const MAX_TRANSCRIPTION_REQUEST_BYTES: usize = MAX_AUDIO_BYTES + 1024 * 1024;
const MAX_TRANSCRIPTION_RESPONSE_BYTES: usize = 1024 * 1024;
const TRANSCRIPTION_BASE_URL: &str = "https://chatgpt.com/backend-api";

#[derive(Debug)]
pub struct TranscriptionRequestError {
    pub status: StatusCode,
    pub message: String,
    pub param: Option<&'static str>,
    pub code: &'static str,
}

impl TranscriptionRequestError {
    pub fn invalid(message: impl Into<String>, param: Option<&'static str>) -> Self {
        Self {
            status: StatusCode::BAD_REQUEST,
            message: message.into(),
            param,
            code: "invalid_request",
        }
    }

    fn upstream(message: impl Into<String>) -> Self {
        Self {
            status: StatusCode::BAD_GATEWAY,
            message: message.into(),
            param: None,
            code: "invalid_upstream_response",
        }
    }
}

#[derive(Debug, Clone)]
pub struct PreparedTranscription {
    pub audio: Bytes,
    pub filename: String,
    pub content_type: String,
    pub language: Option<String>,
}

#[derive(Debug, Deserialize)]
struct TranscriptionResponse<'a> {
    #[serde(borrow)]
    text: &'a str,
}

pub struct CodexTranscriptionBackend {
    client: std::sync::Arc<super::client::CodexHttpClient>,
    base_url: String,
    limiter: std::sync::Arc<tokio::sync::Semaphore>,
}

impl CodexTranscriptionBackend {
    pub fn new() -> Self {
        Self {
            client: std::sync::Arc::new(super::client::CodexHttpClient::new()),
            base_url: TRANSCRIPTION_BASE_URL.to_string(),
            limiter: std::sync::Arc::new(tokio::sync::Semaphore::new(4)),
        }
    }

    #[cfg(test)]
    fn new_for_test(
        client: std::sync::Arc<super::client::CodexHttpClient>,
        base_url: String,
    ) -> Self {
        Self {
            client,
            base_url: base_url.trim_end_matches('/').to_string(),
            limiter: std::sync::Arc::new(tokio::sync::Semaphore::new(4)),
        }
    }

    pub async fn handle(
        &self,
        input: PreparedTranscription,
        ctx: crate::provider::RequestContext,
    ) -> Response {
        let _permit = match self.limiter.clone().try_acquire_owned() {
            Ok(permit) => permit,
            Err(_) => {
                return transcription_error_response(TranscriptionRequestError {
                    status: StatusCode::TOO_MANY_REQUESTS,
                    message: "Too many concurrent transcription requests".to_string(),
                    param: None,
                    code: "local_capacity_exceeded",
                });
            }
        };
        if let Some(monitor) = ctx.monitor.as_ref() {
            monitor.upstream_started(&ctx.req_id);
        }
        let upstream = match self
            .client
            .post_transcription(&self.base_url, &input, &ctx)
            .await
        {
            Ok(response) => response,
            Err(error) => return transcription_transport_error_response(error),
        };
        let status = upstream.status();
        let headers = upstream.headers().clone();
        if status.is_redirection() {
            return transcription_error_response(TranscriptionRequestError::upstream(
                "Codex transcription service returned an unexpected redirect",
            ));
        }
        if !status.is_success() {
            let mut response = transcription_error_response(TranscriptionRequestError {
                status,
                message: format!(
                    "Codex transcription service returned HTTP {}",
                    status.as_u16()
                ),
                param: None,
                code: "upstream_error",
            });
            copy_safe_headers(&headers, response.headers_mut());
            return response;
        }
        let body = match collect_response_body(upstream, self.client.body_idle_timeout_ms()).await {
            Ok(body) => body,
            Err(error) => return transcription_error_response(error),
        };
        if let Err(error) = validate_success_response(&body) {
            return transcription_error_response(error);
        }
        if let Some(monitor) = ctx.monitor.as_ref() {
            monitor.generation_started(&ctx.req_id);
        }
        let mut response = (
            StatusCode::OK,
            [(http::header::CONTENT_TYPE, "application/json")],
            body,
        )
            .into_response();
        response.headers_mut().insert(
            http::header::CACHE_CONTROL,
            http::HeaderValue::from_static("no-store"),
        );
        response.headers_mut().insert(
            http::header::X_CONTENT_TYPE_OPTIONS,
            http::HeaderValue::from_static("nosniff"),
        );
        copy_safe_headers(&headers, response.headers_mut());
        response
    }
}

impl Default for CodexTranscriptionBackend {
    fn default() -> Self {
        Self::new()
    }
}

pub fn prepare_transcription(
    audio: Option<Bytes>,
    filename: Option<String>,
    content_type: Option<String>,
    language: Option<String>,
) -> Result<PreparedTranscription, TranscriptionRequestError> {
    let audio = audio.ok_or_else(|| {
        TranscriptionRequestError::invalid("Missing required 'file' field", Some("file"))
    })?;
    if audio.is_empty() {
        return Err(TranscriptionRequestError::invalid(
            "Uploaded audio file is empty",
            Some("file"),
        ));
    }
    if audio.len() > MAX_AUDIO_BYTES {
        return Err(TranscriptionRequestError {
            status: StatusCode::PAYLOAD_TOO_LARGE,
            message: format!("Audio file must be at most {MAX_AUDIO_BYTES} bytes"),
            param: Some("file"),
            code: "request_too_large",
        });
    }
    let content_type = content_type.unwrap_or_else(|| "application/octet-stream".to_string());
    if !supported_audio_content_type(&content_type) {
        return Err(TranscriptionRequestError::invalid(
            format!("Unsupported audio content type '{content_type}'"),
            Some("file"),
        ));
    }
    let language = language
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty());
    if language.as_ref().is_some_and(|value| value.len() > 64) {
        return Err(TranscriptionRequestError::invalid(
            "'language' must be at most 64 characters",
            Some("language"),
        ));
    }
    Ok(PreparedTranscription {
        audio,
        filename: safe_filename(filename.as_deref().unwrap_or("audio.webm")),
        content_type,
        language,
    })
}

fn safe_filename(filename: &str) -> String {
    std::path::Path::new(filename)
        .file_name()
        .and_then(|name| name.to_str())
        .map(|name| name.replace(['\r', '\n', '"'], ""))
        .filter(|name| !name.is_empty())
        .unwrap_or_else(|| "audio.webm".to_string())
}

fn supported_audio_content_type(content_type: &str) -> bool {
    matches!(
        content_type
            .split(';')
            .next()
            .unwrap_or_default()
            .trim()
            .to_ascii_lowercase()
            .as_str(),
        "audio/flac"
            | "audio/m4a"
            | "audio/mp3"
            | "audio/mp4"
            | "audio/mpeg"
            | "audio/ogg"
            | "audio/wav"
            | "audio/wave"
            | "audio/webm"
            | "audio/x-m4a"
            | "audio/x-wav"
    )
}

async fn collect_response_body(
    mut response: reqwest::Response,
    idle_timeout_ms: u64,
) -> Result<Vec<u8>, TranscriptionRequestError> {
    if response
        .content_length()
        .is_some_and(|length| length > MAX_TRANSCRIPTION_RESPONSE_BYTES as u64)
    {
        return Err(TranscriptionRequestError::upstream(
            "Codex transcription response exceeded the size limit",
        ));
    }
    let mut body = Vec::new();
    loop {
        let chunk = tokio::time::timeout(
            std::time::Duration::from_millis(idle_timeout_ms),
            response.chunk(),
        )
        .await
        .map_err(|_| {
            TranscriptionRequestError::upstream("Timed out reading Codex transcription response")
        })?
        .map_err(|_| {
            TranscriptionRequestError::upstream("Failed to read Codex transcription response")
        })?;
        let Some(chunk) = chunk else {
            break;
        };
        if body.len().saturating_add(chunk.len()) > MAX_TRANSCRIPTION_RESPONSE_BYTES {
            return Err(TranscriptionRequestError::upstream(
                "Codex transcription response exceeded the size limit",
            ));
        }
        body.extend_from_slice(&chunk);
    }
    Ok(body)
}

fn validate_success_response(body: &[u8]) -> Result<(), TranscriptionRequestError> {
    let response: TranscriptionResponse<'_> = serde_json::from_slice(body).map_err(|_| {
        TranscriptionRequestError::upstream("Codex transcription service returned invalid JSON")
    })?;
    if response.text.trim().is_empty() {
        return Err(TranscriptionRequestError::upstream(
            "Codex transcription service returned no text",
        ));
    }
    Ok(())
}

fn copy_safe_headers(source: &http::HeaderMap, target: &mut http::HeaderMap) {
    for name in ["retry-after", "x-request-id", "openai-processing-ms"] {
        if let Some(value) = source.get(name) {
            target.insert(http::HeaderName::from_static(name), value.clone());
        }
    }
}

fn transcription_transport_error_response(error: super::client::CodexError) -> Response {
    let status = match error.status {
        401 => StatusCode::UNAUTHORIZED,
        403 => StatusCode::FORBIDDEN,
        429 => StatusCode::TOO_MANY_REQUESTS,
        value if (400..=599).contains(&value) => {
            StatusCode::from_u16(value).unwrap_or(StatusCode::BAD_GATEWAY)
        }
        _ => StatusCode::BAD_GATEWAY,
    };
    let mut response = transcription_error_response(TranscriptionRequestError {
        status,
        message: if error.status == 0 {
            "Codex transcription service is unavailable".to_string()
        } else {
            format!("Codex transcription service returned HTTP {}", error.status)
        },
        param: None,
        code: if status == StatusCode::UNAUTHORIZED {
            "authentication_error"
        } else if status == StatusCode::FORBIDDEN {
            "permission_error"
        } else if status == StatusCode::TOO_MANY_REQUESTS {
            "rate_limit_error"
        } else {
            "upstream_error"
        },
    });
    if let Some(retry_after) = error.retry_after
        && let Ok(value) = http::HeaderValue::from_str(&retry_after)
    {
        response
            .headers_mut()
            .insert(http::header::RETRY_AFTER, value);
    }
    response
}

pub fn transcription_error_response(error: TranscriptionRequestError) -> Response {
    let error_type = match error.status {
        StatusCode::UNAUTHORIZED => "authentication_error",
        StatusCode::FORBIDDEN => "permission_error",
        StatusCode::TOO_MANY_REQUESTS => "rate_limit_error",
        status if status.is_client_error() => "invalid_request_error",
        _ => "api_error",
    };
    (
        error.status,
        [
            (http::header::CONTENT_TYPE, "application/json"),
            (http::header::CACHE_CONTROL, "no-store"),
        ],
        axum::Json(serde_json::json!({
            "error": {
                "message": error.message,
                "type": error_type,
                "param": error.param,
                "code": error.code,
            }
        })),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn context() -> crate::provider::RequestContext {
        crate::provider::RequestContext {
            req_id: "transcription-test".to_string(),
            session_id: None,
            session_seq: None,
            provider: "codex".to_string(),
            traffic: None,
            monitor: None,
            passthrough: None,
        }
    }

    #[test]
    fn validates_audio_and_normalizes_filename() {
        let prepared = prepare_transcription(
            Some(Bytes::from_static(b"audio")),
            Some("../recording.webm".to_string()),
            Some("audio/webm;codecs=opus".to_string()),
            Some(" en ".to_string()),
        )
        .unwrap();
        assert_eq!(prepared.filename, "recording.webm");
        assert_eq!(prepared.language.as_deref(), Some("en"));

        assert!(prepare_transcription(None, None, None, None).is_err());
        assert!(
            prepare_transcription(
                Some(Bytes::from_static(b"audio")),
                None,
                Some("text/plain".to_string()),
                None,
            )
            .is_err()
        );
    }

    #[tokio::test]
    async fn backend_forwards_multipart_with_codex_auth() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        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 stream, _) = listener.accept().await.unwrap();
            let mut request = Vec::new();
            let mut chunk = [0_u8; 4096];
            loop {
                let read = stream.read(&mut chunk).await.unwrap();
                assert!(read > 0);
                request.extend_from_slice(&chunk[..read]);
                let Some(header_end) = request.windows(4).position(|part| part == b"\r\n\r\n")
                else {
                    continue;
                };
                let headers = String::from_utf8_lossy(&request[..header_end]);
                let content_length = headers
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().ok())
                            .flatten()
                    })
                    .unwrap();
                if request.len() >= header_end + 4 + content_length {
                    break;
                }
            }
            let request_text = String::from_utf8_lossy(&request);
            assert!(request_text.starts_with("POST /root/transcribe HTTP/1.1"));
            assert!(request_text.contains("authorization: Bearer test"));
            assert!(request_text.contains("chatgpt-account-id: acct"));
            assert!(request_text.contains("originator: Codex Desktop"));
            assert!(request_text.contains("name=\"file\""));
            assert!(request_text.contains("filename=\"recording.webm\""));
            assert!(request_text.contains("name=\"language\""));
            assert!(request_text.contains("\r\nen\r\n"));
            assert!(request_text.contains("audio-bytes"));

            let body = br#"{"text":"hello world"}"#;
            let head = format!(
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\nx-request-id: upstream-transcribe\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
                body.len()
            );
            stream.write_all(head.as_bytes()).await.unwrap();
            stream.write_all(body).await.unwrap();
        });

        let client = super::super::client::CodexHttpClient::new_for_test(
            reqwest::Client::builder().no_proxy().build().unwrap(),
            format!("http://{addr}/responses"),
            1_000,
            1_000,
            0,
        );
        client
            .auth_manager()
            .set_test_auth(super::super::auth::token_store::StoredAuth {
                access: "test".into(),
                refresh: String::new(),
                account_id: Some("acct".into()),
                expires: u64::MAX,
            });
        let backend = CodexTranscriptionBackend::new_for_test(
            std::sync::Arc::new(client),
            format!("http://{addr}/root"),
        );
        let response = backend
            .handle(
                prepare_transcription(
                    Some(Bytes::from_static(b"audio-bytes")),
                    Some("recording.webm".to_string()),
                    Some("audio/webm".to_string()),
                    Some("en".to_string()),
                )
                .unwrap(),
                context(),
            )
            .await;
        server.await.unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.headers()["x-request-id"], "upstream-transcribe");
        let body = axum::body::to_bytes(response.into_body(), 1024)
            .await
            .unwrap();
        assert_eq!(body, br#"{"text":"hello world"}"#.as_slice());
    }

    #[test]
    fn validates_success_payload() {
        assert!(validate_success_response(br#"{"text":"hello"}"#).is_ok());
        assert!(validate_success_response(br#"{"text":""}"#).is_err());
        assert!(validate_success_response(br#"{}"#).is_err());
    }
}