1use cpa_core::gostr::GoStr;
7use std::time::Duration;
8
9use cpa_core::config::Config;
10use cpa_core::credential::Credential;
11use cpa_core::exec::{ExecError, ExecRequest, FailureScope};
12use cpa_core::format::Format;
13use gjson::Kind;
14use http::{HeaderMap, HeaderName, HeaderValue};
15use sha2::{Digest, Sha256};
16
17use crate::codex_json::{delete, set_bool_if_different, set_raw, set_str, set_str_if_different};
18
19pub const DEFAULT_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
20pub(crate) const USER_AGENT: &str = "codex-tui/0.154.0 (Mac OS 26.5.2; arm64) iTerm.app/3.6.11 (codex-tui; 0.154.0)";
21pub(crate) const ORIGINATOR: &str = "codex-tui";
22pub(crate) const WS_BETA: &str = "responses_websockets=2026-02-06";
23const ROUTING_HINT: &str = "x-codex-routing-hint";
24const LITE_HEADER: &str = "x-openai-internal-codex-responses-lite";
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub(crate) enum Call {
29 Stream,
30 NonStream,
31 Compact,
32 Websocket,
33}
34
35impl Call {
36 pub fn target(self) -> Format {
38 if self == Call::Compact {
39 Format::OpenAIResponse
40 } else {
41 Format::Codex
42 }
43 }
44}
45
46#[derive(Debug, Clone, Default)]
48pub(crate) struct Settings {
49 pub disable_cloaking: bool,
50 pub bootstrap_buffering: bool,
51 pub bootstrap_timeout: Option<Duration>,
52 pub model_level_cooling: bool,
53 pub default_user_agent: String,
54 pub default_beta_features: String,
55 pub image_generation: bool,
56 pub payload: cpa_common::payload::Rules,
58 pub client: cpa_common::codex_client::Settings,
60 pub key_models: Vec<serde_json::Value>,
62 pub home: Option<cpa_core::credential::Credential>,
65 pub response_steering: bool,
67 pub image_base_model: String,
69 pub siwc_user_agent: String,
71}
72
73pub(crate) fn response_steering(cfg: &Config) -> bool {
75 setting(cfg, &["upstream", "codex", "response-steering"])
76 .and_then(serde_yaml_ng::Value::as_bool)
77 .unwrap_or(false)
78}
79
80pub(crate) fn chatgpt_keep_alive(cfg: &Config) -> bool {
83 setting(cfg, &["oauth", "providers", "codex", "chatgpt-keep-alive"])
84 .and_then(serde_yaml_ng::Value::as_bool)
85 .unwrap_or(false)
86}
87
88fn setting<'a>(cfg: &'a Config, path: &[&str]) -> Option<&'a serde_yaml_ng::Value> {
89 path.iter().try_fold(&cfg.document, |v, k| v.get(*k))
90}
91
92impl Settings {
93 pub fn scoped(cfg: &Config, view: &View<'_>) -> Self {
97 let mut settings = if view.api_key {
98 Self::from(&cfg.for_api_key())
99 } else {
100 Self::from(cfg)
101 };
102 settings.siwc_user_agent = crate::codex_siwc::user_agent(cfg);
103 settings.key_models = cpa_core::config::credentials::resolve_api_key_entry(cfg, "codex", view.credential)
106 .map(|entry| entry.models)
107 .unwrap_or_default();
108 if view
109 .credential
110 .attributes
111 .contains_key(cpa_core::config::credentials::HOME_PROVIDER)
112 {
113 settings.home = Some(view.credential.clone());
114 }
115 settings
116 }
117
118 pub fn is_compat(&self, req: &ExecRequest) -> bool {
124 if let Some(resolved) = &req.resolved_model {
125 return resolved.is_compat();
126 }
127 let fold = |a: &str, b: &str| !b.is_empty() && a.go_eq_fold(b);
128 let requested = req.model.trim();
129 let base = base_model(&req.model);
130 let target = base.trim();
131 if self.key_models.is_empty() {
132 let home = |model: &str| {
133 self.home
134 .as_ref()
135 .and_then(|c| cpa_home::dispatch::credential_model_options(c, model, model))
136 .is_some_and(|options| options.get("is-compat") == Some(&serde_json::Value::Bool(true)))
137 };
138 return home(target) || home(&req.model);
139 }
140 self.key_models
141 .iter()
142 .find(|m| {
143 let field = |k: &str| m.get(k).and_then(serde_json::Value::as_str).unwrap_or_default().trim();
144 let (name, alias) = (field("name"), field("alias"));
145 fold(name, target) || fold(alias, target) || fold(name, requested) || fold(alias, requested)
146 })
147 .and_then(|m| m.get("is-compat"))
148 .and_then(serde_json::Value::as_bool)
149 .unwrap_or(false)
150 }
151
152 pub fn from(cfg: &Config) -> Self {
153 let codex = |k: &str| setting(cfg, &["upstream", "codex", k]);
155 let flag = |k: &str| codex(k).and_then(|v| v.as_bool()).unwrap_or(false);
156 let text = |path: &[&str]| {
157 setting(cfg, path)
158 .and_then(|v| v.as_str())
159 .unwrap_or_default()
160 .trim()
161 .to_owned()
162 };
163 let image_off = match setting(cfg, &["multimedia", "disable-image-generation"]) {
164 None => true,
165 Some(v) => v.as_bool() == Some(false) || v.as_str().is_some_and(|s| matches!(s.trim(), "" | "false")),
166 };
167 Self {
168 disable_cloaking: flag("disable-codex-cloaking"),
169 bootstrap_buffering: flag("stream-bootstrap-buffering"),
170 bootstrap_timeout: codex("stream-bootstrap-timeout")
171 .and_then(|v| {
172 v.as_str()
173 .map(str::to_owned)
174 .or_else(|| v.as_i64().map(|n| n.to_string()))
175 })
176 .and_then(|s| go_duration(&s))
177 .filter(|d| !d.is_zero()),
178 model_level_cooling: flag("model-level-cooling"),
179 default_user_agent: text(&["oauth", "providers", "codex", "header-defaults", "user-agent"]),
180 default_beta_features: text(&["oauth", "providers", "codex", "header-defaults", "beta-features"]),
181 image_generation: image_off,
182 payload: cpa_common::payload::Rules::from_config(cfg),
183 client: cpa_common::codex_client::Settings::from_config(cfg),
184 key_models: Vec::new(),
185 home: None,
186 response_steering: response_steering(cfg),
187 image_base_model: text(&["multimedia", "gpt-image-2-base-model"]),
188 siwc_user_agent: crate::codex_siwc::user_agent(cfg),
189 }
190 }
191}
192
193fn go_duration(raw: &str) -> Option<Duration> {
196 let raw = raw.trim();
197 if raw.is_empty()
198 || raw == "0"
199 || ["none", "unlimited", "disabled", "off", "never"]
200 .iter()
201 .any(|w| raw.eq_ignore_ascii_case(w))
202 {
203 return None;
204 }
205 if let Some(nanos) = cpa_core::config::parse_duration(raw).filter(|n| *n >= 0) {
206 return Some(Duration::from_nanos(nanos as u64));
207 }
208 raw.parse::<i64>()
210 .ok()
211 .filter(|secs| (0..=i64::MAX / 1_000_000_000).contains(secs))
212 .map(|secs| Duration::from_secs(secs as u64))
213}
214
215pub(crate) struct View<'a> {
217 pub credential: &'a Credential,
218 pub token: &'a str,
219 pub api_key: bool,
220 pub siwc: bool,
222 pub base_url: &'a str,
223 pub proxy: crate::proxy::Proxy,
225 pub session: Option<String>,
227 pub chatgpt_keep_alive: bool,
231 pub handshake: Option<std::time::Duration>,
233}
234
235impl<'a> View<'a> {
236 pub fn for_request(credential: &'a Credential, cfg: &Config) -> Self {
238 Self {
239 proxy: crate::proxy::Proxy::effective(credential, cfg),
240 chatgpt_keep_alive: chatgpt_keep_alive(cfg),
241 handshake: crate::tls::handshake_timeout(cfg),
242 ..Self::new(credential)
243 }
244 }
245
246 pub fn with_session(mut self, session: Option<String>) -> Self {
248 self.session = session;
249 self
250 }
251
252 pub fn new(credential: &'a Credential) -> Self {
253 let attr = |k: &str| credential.attributes.get(k).map(String::as_str).unwrap_or_default();
254 let api_key = attr("api_key");
255 let siwc = crate::codex_siwc::enabled(credential);
256 let (token, base_url) = if siwc {
259 let base = attr("base_url");
260 (
261 crate::codex_siwc::access_token(credential),
262 if base.trim().is_empty() {
263 crate::codex_siwc::RESOURCE
264 } else {
265 base
266 },
267 )
268 } else {
269 let token = if api_key.is_empty() {
270 credential.str("access_token").unwrap_or_default()
271 } else {
272 api_key
273 };
274 let base = match attr("base_url") {
275 "" => DEFAULT_BASE_URL,
276 url => url,
277 };
278 (token, base)
279 };
280 let kind = attr("auth_kind").trim().to_ascii_lowercase().replace(['_', '-'], "");
281 let is_api_key = kind == "apikey" || (kind.is_empty() && !api_key.trim().is_empty());
282 Self {
283 credential,
284 token,
285 api_key: is_api_key,
286 siwc,
287 base_url: base_url.trim_end_matches('/'),
288 proxy: crate::proxy::Proxy::Inherit,
289 session: None,
290 chatgpt_keep_alive: false,
291 handshake: None,
292 }
293 }
294
295 pub fn attr(&self, key: &str) -> &str {
296 self.credential
297 .attributes
298 .get(key)
299 .map(String::as_str)
300 .unwrap_or_default()
301 }
302
303 fn plan_type(&self) -> &str {
306 self.credential
307 .str("plan_type")
308 .map(str::trim)
309 .filter(|s| !s.is_empty())
310 .unwrap_or(self.attr("plan_type"))
311 }
312
313 pub fn cloaking_disabled(&self, settings: &Settings) -> bool {
316 go_bool(self.attr("codex_disable_cloaking")).unwrap_or(settings.disable_cloaking)
317 }
318
319 pub fn websockets(&self) -> bool {
321 match self.attr("websockets").trim() {
322 "" => match self.credential.metadata.get("websockets") {
323 Some(serde_json::Value::Bool(b)) => *b,
324 Some(serde_json::Value::String(s)) => go_bool(s).unwrap_or(false),
325 _ => false,
326 },
327 raw => go_bool(raw).unwrap_or(false),
328 }
329 }
330}
331
332fn go_bool(s: &str) -> Option<bool> {
334 match s.trim() {
335 "1" | "t" | "T" | "true" | "TRUE" | "True" => Some(true),
336 "0" | "f" | "F" | "false" | "FALSE" | "False" => Some(false),
337 _ => None,
338 }
339}
340
341pub(crate) fn base_model(model: &str) -> String {
343 cpa_common::thinking::parse_suffix(model).model_name
344}
345
346pub(crate) fn header<'a>(headers: &'a HeaderMap, name: &str) -> &'a str {
347 headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or_default()
348}
349
350pub(crate) fn is_lite(body: &str, headers: &HeaderMap) -> bool {
353 let lite = headers
354 .get(LITE_HEADER)
355 .and_then(|v| std::str::from_utf8(v.as_bytes()).ok())
356 .unwrap_or_default();
357 if lite.trim().go_eq_fold("true") {
358 return true;
359 }
360 let v = gjson::get(
361 body,
362 "client_metadata.ws_request_header_x_openai_internal_codex_responses_lite",
363 );
364 v.kind() == Kind::True || (v.kind() == Kind::String && v.str().trim().eq_ignore_ascii_case("true"))
365}
366
367pub(crate) fn is_native(req: &ExecRequest) -> bool {
369 let codexish = |f: Format| matches!(f, Format::Codex | Format::OpenAIResponse);
370 codexish(req.source_format)
371 && codexish(req.response_format)
372 && is_lite(&String::from_utf8_lossy(&req.body), &req.headers)
373}
374
375fn translate_request(req: &ExecRequest, call: Call, is_compat: bool) -> Result<(String, Vec<u8>), ExecError> {
381 let target = call.target();
382 let registered = cpa_translate::pair(req.source_format, target).is_some();
383 if !registered && !matches!(req.source_format, Format::Codex | Format::OpenAIResponse) {
384 return Err(ExecError::local(
386 501,
387 FailureScope::Request,
388 format!(
389 "{} -> {} request translation is not registered",
390 req.source_format.as_str(),
391 target.as_str()
392 ),
393 ));
394 }
395 let model = base_model(&req.model);
396 let ctx = cpa_translate::RequestCtx {
397 model: &model,
398 stream: matches!(call, Call::Stream | Call::Websocket),
399 tool_search: false,
400 };
401 let no_headers = HeaderMap::new();
404 let compat = crate::codex_client::Client {
405 headers: &no_headers,
406 settings: Default::default(),
407 target_executor: "",
408 is_compat: true,
409 };
410 let translate = |raw: &[u8]| {
411 if is_compat && req.source_format == Format::Claude && target == Format::Codex {
412 crate::codex_client::translate_request(req.source_format, target, &ctx, raw, &compat)
413 } else {
414 cpa_translate::translate_request_tracked(req.source_format, target, &ctx, raw)
415 }
416 .map_err(|e| ExecError::local(400, FailureScope::Request, e.to_string()))
417 };
418 let (original, working) = if req.original_body.is_empty() || req.original_body == req.body {
420 let working = translate(&req.body)?;
421 (working.body.clone(), working)
422 } else {
423 (translate(&req.original_body)?.body, translate(&req.body)?)
424 };
425 let body = working.body;
426 let caps = req
427 .resolved_model
428 .as_ref()
429 .map(|r| cpa_common::thinking::ModelCaps::from(&r.info));
430 let thought = cpa_common::thinking::apply_request_thinking(&cpa_common::thinking::RequestThinking {
431 body: &body,
432 payload: &req.body,
433 original: &req.original_body,
434 model: &req.model,
435 from: req.source_format.as_str(),
436 to: target.as_str(),
437 provider: "codex",
438 resolved: caps.as_ref().map(Some),
439 has_request_transformer: registered,
440 updates_changed: working.configuration_updates_changed,
441 })
442 .map_err(|e| ExecError::local(e.status(), FailureScope::Request, e.message))?;
443 let body = String::from_utf8(thought)
444 .map_err(|_| ExecError::local(400, FailureScope::Request, "request body is not valid UTF-8 JSON"))?;
445 Ok((body, original))
446}
447
448pub(crate) struct Finalizer {
451 call: Call,
452 original: Vec<u8>,
454}
455
456impl Finalizer {
457 pub(crate) fn apply(&self, req: &ExecRequest, settings: &Settings, body: String) -> String {
458 apply_payload(req, settings, self.call, &base_model(&req.model), body, &self.original)
459 }
460}
461
462pub(crate) fn steer_rules(req: &ExecRequest, settings: &Settings, payload: String) -> String {
465 let original = payload.clone().into_bytes();
466 let out = apply_payload(
467 req,
468 settings,
469 Call::Websocket,
470 &base_model(&req.model),
471 payload,
472 &original,
473 );
474 set_str(&out, "type", "response.steer")
475}
476
477fn apply_payload(
479 req: &ExecRequest,
480 settings: &Settings,
481 call: Call,
482 model: &str,
483 body: String,
484 original: &[u8],
485) -> String {
486 let requested = if req.requested_model.trim().is_empty() {
487 req.model.trim()
488 } else {
489 req.requested_model.trim()
490 };
491 let rules = cpa_common::payload::Request {
492 target_executor: if call == Call::Websocket {
493 "codex-websockets"
494 } else {
495 "codex"
496 },
497 model,
498 requested_model: requested,
499 protocol: call.target().as_str(),
500 from_protocol: req.source_format.as_str(),
501 root: "",
502 original,
503 request_path: &req.request_path,
504 headers: Some(&req.headers),
505 };
506 let out = cpa_common::payload::apply(&settings.payload, &rules, body.into_bytes());
507 String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
508}
509
510pub(crate) struct Shaped {
512 pub body: String,
513 pub optimized: bool,
516 pub conflict: bool,
519 pub finalize: Finalizer,
521}
522
523pub(crate) fn shape(req: &ExecRequest, view: &View<'_>, settings: &Settings, call: Call) -> Result<Shaped, ExecError> {
535 let model = base_model(&req.model);
536 let model = model.as_str();
537 let is_compat = settings.is_compat(req);
538 let (mut body, original) = translate_request(req, call, is_compat)?;
539 match call {
540 Call::NonStream => {
541 body = set_str_if_different(body, "model", model);
542 body = set_bool_if_different(body, "stream", true);
543 for key in [
544 "previous_response_id",
545 "generate",
546 "prompt_cache_retention",
547 "safety_identifier",
548 "stream_options",
549 ] {
550 body = delete(&body, key);
551 }
552 }
553 Call::Stream => {
554 for key in [
555 "previous_response_id",
556 "generate",
557 "prompt_cache_retention",
558 "safety_identifier",
559 ] {
560 body = delete(&body, key);
561 }
562 let delivery = gjson::get(&body, "stream_options.reasoning_summary_delivery");
563 let delivery = delivery
564 .exists()
565 .then(|| (delivery.kind(), delivery.str().to_owned(), delivery.json().to_owned()));
566 body = delete(&body, "stream_options");
567 if let Some((kind, text, raw)) = delivery {
568 body = if kind == Kind::String {
570 set_str(&body, "stream_options.reasoning_summary_delivery", &text)
571 } else {
572 set_raw(&body, "stream_options.reasoning_summary_delivery", &raw)
573 };
574 }
575 body = set_str_if_different(body, "model", model);
576 }
577 Call::Websocket => {
578 body = set_str_if_different(body, "model", model);
579 body = set_bool_if_different(body, "stream", true);
580 body = delete(&body, "prompt_cache_retention");
581 body = delete(&body, "safety_identifier");
582 }
583 Call::Compact => {
584 body = set_str_if_different(body, "model", model);
585 body = delete(&body, "stream");
586 }
587 }
588 if call != Call::Compact {
591 body = ensure_web_search_for_history(body, &req.headers);
592 }
593 if view.siwc {
594 if call != Call::Websocket {
596 body = siwc_request_body(body, req, call);
597 }
598 } else if !is_native(req) {
599 let instructions = gjson::get(&body, "instructions");
600 if !instructions.exists() || instructions.kind() == Kind::Null {
601 body = set_str(&body, "instructions", "");
602 }
603 }
604 if call == Call::Compact {
605 body = ensure_web_search_for_history(body, &req.headers);
606 }
607 if call != Call::Compact && settings.image_generation && !view.siwc {
608 body = ensure_image_tool(body, model, view, &req.headers);
609 }
610 body = sanitize_reasoning(body, is_compat);
611 body = if call == Call::Websocket {
612 if is_lite(&body, &req.headers) {
613 set_bool_if_different(body, "parallel_tool_calls", false)
614 } else {
615 body
616 }
617 } else {
618 normalize_parallel_tool_calls(body, &req.headers)
619 };
620 let body = normalize_tool_schemas(body);
621 let conflict = cpa_common::codex_client::has_namespace_conflict(body.as_bytes());
622 let (body, optimized) = crate::codex_client::optimize_for_auth(
623 &req.headers,
624 body.as_bytes(),
625 &settings.client,
626 is_compat,
627 crate::codex_client::tools_prepared(&req.request_path),
628 );
629 let body = String::from_utf8(body).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned());
630 Ok(Shaped {
631 body,
632 optimized,
633 conflict,
634 finalize: Finalizer { call, original },
635 })
636}
637
638pub(crate) fn siwc_body(mut body: String, call: Call, explicit_instructions: bool, keep_effort: bool) -> String {
645 match call {
646 Call::Stream | Call::NonStream => {
647 body = set_bool_if_different(body, "store", false);
648 body = set_bool_if_different(body, "stream", true);
649 }
650 Call::Websocket => {
651 body = set_bool_if_different(body, "store", false);
652 body = delete(&body, "stream");
653 body = delete(&body, "background");
654 }
655 Call::Compact => {
656 body = delete(&body, "stream");
657 body = delete(&body, "store");
658 }
659 }
660 let collapsed = cpa_common::thinking::collapse_configuration_updates(body.as_bytes(), keep_effort);
663 if collapsed != body.as_bytes() {
664 body = String::from_utf8(collapsed).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned());
665 }
666 for key in [
667 "prompt_cache_retention",
668 "prompt_cache_options",
669 "max_output_tokens",
670 "max_completion_tokens",
671 "temperature",
672 ] {
673 body = delete(&body, key);
674 }
675 if !explicit_instructions {
676 let instructions = gjson::get(&body, "instructions");
677 let blank = match instructions.kind() {
678 Kind::Null => instructions.exists(),
679 Kind::String => instructions.str().trim().is_empty(),
680 _ => false,
681 };
682 if blank {
683 body = delete(&body, "instructions");
684 }
685 }
686 body
687}
688
689pub(crate) fn explicit_instructions(payload: &[u8]) -> bool {
692 let value = cpa_common::json::get(payload, "instructions");
693 match value.kind {
694 cpa_common::json::Kind::Null => false,
695 cpa_common::json::Kind::String => !value.str().trim().is_empty(),
696 _ => value.exists(),
697 }
698}
699
700pub(crate) fn siwc_request_body(body: String, req: &ExecRequest, call: Call) -> String {
702 siwc_body(
703 body,
704 call,
705 explicit_instructions(&req.body),
706 cpa_common::thinking::has_thinking_suffix(&req.model),
707 )
708}
709
710fn ensure_web_search_for_history(body: String, headers: &HeaderMap) -> String {
715 use cpa_common::json as gj;
716 if !body.contains("web_search_call") {
717 return body;
718 }
719 let input = gj::get(body.as_bytes(), "input");
720 if !input.is_array() {
721 return body;
722 }
723 let is_call = |item: &gj::Res<'_>| item.get("type").str().trim() == "web_search_call";
724 let mut has_call = false;
727 input.each(|_, item| {
728 has_call = is_call(&item);
729 !has_call
730 });
731 if !has_call {
732 return body;
733 }
734 let tools = gj::get(body.as_bytes(), "tools");
735 if tools.is_array()
736 && tools.array().iter().any(|t| {
737 matches!(
738 t.get("type").str().trim(),
739 "web_search" | "web_search_preview" | "web_search_preview_2025_03_11"
740 )
741 })
742 {
743 return body;
744 }
745 if is_lite(&body, headers) {
746 let items = input.array();
747 let kept: Vec<&[u8]> = items.iter().filter(|i| !is_call(i)).map(|i| i.raw()).collect();
748 let joined = kept.join(&b","[..]);
749 return set_raw(&body, "input", &format!("[{}]", String::from_utf8_lossy(&joined)));
750 }
751 if !tools.is_array() {
752 return set_raw(&body, "tools", r#"[{"type":"web_search"}]"#);
753 }
754 set_raw(&body, "tools.-1", r#"{"type":"web_search"}"#)
755}
756
757fn ensure_image_tool(body: String, model: &str, view: &View<'_>, headers: &HeaderMap) -> String {
758 const TOOL: &str = r#"{"type":"image_generation","output_format":"png"}"#;
759 if is_lite(&body, headers)
760 || model.ends_with("spark")
761 || (view.credential.provider.eq_ignore_ascii_case("codex") && view.plan_type().eq_ignore_ascii_case("free"))
762 {
763 return body;
764 }
765 let tools = gjson::get(&body, "tools");
766 if !tools.exists() || tools.kind() != Kind::Array {
767 return set_raw(&body, "tools", &format!("[{TOOL}]"));
768 }
769 let present = tools.array().iter().any(|t| {
770 let kind = t.get("type");
771 let name = t.get("name");
772 match kind.str() {
773 "image_generation" => true,
774 "function" => name.str() == "image_gen.imagegen",
775 "namespace" => {
776 name.str() == "image_gen"
777 && t.get("tools")
778 .array()
779 .iter()
780 .any(|n| n.get("type").str() == "function" && n.get("name").str() == "imagegen")
781 }
782 _ => false,
783 }
784 });
785 if present {
786 body
787 } else {
788 set_raw(&body, "tools.-1", TOOL)
789 }
790}
791
792fn normalize_parallel_tool_calls(body: String, headers: &HeaderMap) -> String {
793 if is_lite(&body, headers) {
794 return set_bool_if_different(body, "parallel_tool_calls", false);
795 }
796 if !gjson::get(&body, "parallel_tool_calls").exists() {
797 return body;
798 }
799 let tools = gjson::get(&body, "tools");
800 if tools.kind() == Kind::Array && !tools.array().is_empty() {
801 return body;
802 }
803 delete(&body, "parallel_tool_calls")
804}
805
806fn sanitize_reasoning(body: String, is_compat: bool) -> String {
810 let input = gjson::get(&body, "input");
811 if input.kind() != Kind::Array {
812 return body;
813 }
814 let strip_orphan_ids = !gjson::get(&body, "store").bool();
815 let items = input.array();
816 let mut rebuilt: Option<Vec<String>> = None;
817 for (index, item) in items.iter().enumerate() {
818 let mut next = item.json().to_owned();
819 let mut changed = false;
820 if item.get("type").str().trim() == "reasoning" {
821 let content = item.get("content");
822 if !is_compat && content.kind() == Kind::Array && !content.array().is_empty() {
823 let summary = item.get("summary");
824 let empty_summary = !summary.exists()
825 || summary.kind() == Kind::Null
826 || (summary.kind() == Kind::Array && summary.array().is_empty());
827 if empty_summary {
828 let parts: Vec<String> = content
829 .array()
830 .iter()
831 .filter(|p| p.get("type").str().trim() == "reasoning_text" && !p.get("text").str().is_empty())
832 .map(|p| set_str(r#"{"type":"summary_text"}"#, "text", p.get("text").str()))
833 .collect();
834 if !parts.is_empty() {
835 next = set_raw(&next, "summary", &format!("[{}]", parts.join(",")));
836 }
837 }
838 next = set_raw(&next, "content", "[]");
839 changed = true;
840 }
841 let encrypted = item.get("encrypted_content");
842 let has_id = item.get("id").exists();
843 if !encrypted.exists() {
844 if !is_compat && strip_orphan_ids && has_id {
845 next = delete(&next, "id");
846 changed = true;
847 }
848 } else {
849 let valid = encrypted.kind() == Kind::String
850 && encrypted.str() == encrypted.str().trim()
851 && cpa_common::signature::is_valid_gpt_reasoning_signature(encrypted.str());
852 if !valid {
853 next = delete(&next, "encrypted_content");
854 changed = true;
855 if !is_compat && strip_orphan_ids && has_id {
856 next = delete(&next, "id");
857 }
858 }
859 }
860 }
861 if changed && rebuilt.is_none() {
862 rebuilt = Some(items[..index].iter().map(|i| i.json().to_owned()).collect());
863 }
864 if let Some(rebuilt) = rebuilt.as_mut() {
865 rebuilt.push(if changed { next } else { item.json().to_owned() });
866 }
867 }
868 match rebuilt {
869 Some(items) => set_raw(&body, "input", &format!("[{}]", items.join(","))),
870 None => body,
871 }
872}
873
874fn normalize_tool_schemas(body: String) -> String {
878 let tools = gjson::get(&body, "tools");
879 match normalize_tool_list(&tools) {
880 Some(updated) => set_raw(&body, "tools", &updated),
881 None => body,
882 }
883}
884
885fn normalize_tool_list(tools: &gjson::Value<'_>) -> Option<String> {
886 if tools.kind() != Kind::Array {
887 return None;
888 }
889 let raw = tools.json();
890 let mut out = String::new();
891 let mut offset = 0;
892 let mut changed = false;
893 tools.each(|_, tool| {
894 if let Some(updated) = normalize_tool(&tool) {
895 let start = tool.json().as_ptr() as usize - raw.as_ptr() as usize;
896 out.push_str(&raw[offset..start]);
897 out.push_str(&updated);
898 offset = start + tool.json().len();
899 changed = true;
900 }
901 true
902 });
903 changed.then(|| {
904 out.push_str(&raw[offset..]);
905 out
906 })
907}
908
909fn normalize_tool(tool: &gjson::Value<'_>) -> Option<String> {
910 let kind = tool.get("type");
911 match kind.str() {
912 "namespace" => {
913 let inner = normalize_tool_list(&tool.get("tools"))?;
914 Some(set_raw(tool.json(), "tools", &inner))
915 }
916 "function" | "custom" => {
917 let params = tool.get("parameters");
918 if params.kind() != Kind::Object {
919 return None;
920 }
921 let stripped = strip_incompatible(params.json());
922 let mut changed = stripped.is_some();
923 let mut raw = stripped.unwrap_or_else(|| params.json().to_owned());
924 let params = gjson::parse(&raw);
925 let mut updates = Vec::new();
926 let properties = params.get("properties");
927 if properties.kind() == Kind::Object {
928 properties.each(|name, prop| {
929 if let Some(updated) = normalize_property(&prop) {
930 updates.push((name.str().to_owned(), updated));
931 }
932 true
933 });
934 }
935 for (name, updated) in updates {
936 let key = name.replace('\\', "\\\\").replace('.', "\\.").replace(':', "\\:");
937 raw = set_raw(&raw, &format!("properties.{key}"), &updated);
938 changed = true;
939 }
940 changed.then(|| set_raw(tool.json(), "parameters", &raw))
941 }
942 _ => None,
943 }
944}
945
946fn strip_incompatible(raw: &str) -> Option<String> {
951 if !["\\p{", "\\P{", "\\u", "\\\\0", "inimum", "aximum"]
954 .iter()
955 .any(|needle| raw.contains(needle))
956 {
957 return None;
958 }
959 let mut root = cpa_common::json::GoValue::parse(raw.as_bytes())?;
960 if root == cpa_common::json::GoValue::Null || !strip_schema(&mut root) {
961 return None;
962 }
963 String::from_utf8(root.marshal_no_html()).ok()
964}
965
966const NUMERIC_BOUNDS: [&str; 4] = ["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"];
968
969fn strip_schema(value: &mut cpa_common::json::GoValue) -> bool {
971 use cpa_common::json::GoValue;
972 let escape = |s: &str| cpa_common::schema::has_unsupported_unicode_property_escape(s.as_bytes());
973 let mut changed = false;
974 match value {
975 GoValue::Object(map) => {
976 if matches!(map.get("pattern"), Some(GoValue::String(p)) if escape(p)) {
977 map.remove("pattern");
978 changed = true;
979 }
980 for key in NUMERIC_BOUNDS {
981 if matches!(map.get(key), Some(GoValue::Number(n)) if bound_out_of_int64(n)) {
982 map.remove(key);
983 changed = true;
984 }
985 }
986 if let Some(GoValue::Object(patterns)) = map.get_mut("patternProperties") {
987 patterns.retain(|key, sub| {
988 if escape(key) {
989 changed = true;
990 return false;
991 }
992 changed |= strip_schema(sub);
993 true
994 });
995 }
996 for key in cpa_common::schema::SCHEMA_MAP_KEYWORDS {
997 let key = std::str::from_utf8(key).unwrap_or_default();
998 if key == "patternProperties" {
999 continue;
1000 }
1001 if let Some(GoValue::Object(sub)) = map.get_mut(key) {
1002 for schema in sub.values_mut() {
1003 changed |= strip_schema(schema);
1004 }
1005 }
1006 }
1007 for key in cpa_common::schema::SCHEMA_VALUE_KEYWORDS {
1008 match map.get_mut(std::str::from_utf8(key).unwrap_or_default()) {
1009 Some(sub @ GoValue::Object(_)) => changed |= strip_schema(sub),
1010 Some(GoValue::Array(items)) => {
1011 for item in items {
1012 changed |= strip_schema(item);
1013 }
1014 }
1015 _ => {}
1016 }
1017 }
1018 }
1019 GoValue::Array(items) => {
1020 for item in items {
1021 changed |= strip_schema(item);
1022 }
1023 }
1024 _ => {}
1025 }
1026 changed
1027}
1028
1029fn bound_out_of_int64(number: &str) -> bool {
1032 use std::num::IntErrorKind::{NegOverflow, PosOverflow};
1033 let overflows = |text: &str| matches!(text.parse::<i64>(), Err(e) if matches!(e.kind(), PosOverflow | NegOverflow));
1034 let raw = number.trim();
1035 if raw.is_empty() {
1036 return false;
1037 }
1038 if !raw.contains(['.', 'e', 'E']) {
1039 return overflows(raw);
1040 }
1041 let (negative, s) = match raw.strip_prefix('-') {
1042 Some(rest) => (true, rest),
1043 None => (false, raw.strip_prefix('+').unwrap_or(raw)),
1044 };
1045 let (mantissa, exp) = match s.find(['e', 'E']) {
1046 Some(at) => {
1047 let (mantissa, exp) = (&s[..at], &s[at + 1..]);
1048 match exp.parse::<i64>() {
1049 Ok(exp) => (mantissa, exp),
1050 Err(e) if matches!(e.kind(), PosOverflow | NegOverflow) => {
1051 return !exp.starts_with('-') && !mantissa.trim_matches(['0', '.']).is_empty();
1052 }
1053 Err(_) => return false,
1054 }
1055 }
1056 None => (s, 0),
1057 };
1058 let (int_part, frac_part) = match mantissa.split_once('.') {
1059 Some((_, frac)) if frac.contains('.') => return false,
1060 Some(parts) => parts,
1061 None => (mantissa, ""),
1062 };
1063 if int_part.is_empty() && frac_part.is_empty() {
1064 return false;
1065 }
1066 if !int_part.bytes().chain(frac_part.bytes()).all(|b| b.is_ascii_digit()) {
1067 return false;
1068 }
1069 let digits = format!("{int_part}{frac_part}");
1070 let significant = digits.trim_start_matches('0');
1071 if significant.is_empty() {
1072 return false;
1073 }
1074 let len = raw.len() as i64;
1075 if exp < -len {
1076 return false;
1077 }
1078 if exp > len + 20 {
1079 return true;
1080 }
1081 let trimmed = significant.trim_end_matches('0');
1082 let trailing_zeros = (significant.len() - trimmed.len()) as i64;
1083 let effective = exp - frac_part.len() as i64 + trailing_zeros;
1084 if effective < 0 {
1085 return false;
1086 }
1087 if effective > 19 || trimmed.len() as i64 + effective > 19 {
1088 return true;
1089 }
1090 let sign = if negative { "-" } else { "" };
1091 overflows(&format!("{sign}{trimmed}{}", "0".repeat(effective as usize)))
1092}
1093
1094fn normalize_property(prop: &gjson::Value<'_>) -> Option<String> {
1095 if prop.kind() != Kind::Object {
1096 return None;
1097 }
1098 let name = match (prop.get("oneOf").exists(), prop.get("anyOf").exists()) {
1099 (true, false) => "oneOf",
1100 (false, true) => "anyOf",
1101 _ => return None,
1102 };
1103 let union = prop.get(name);
1104 let branches = union.array();
1105 if union.kind() != Kind::Array || branches.len() < 8 {
1106 return None;
1107 }
1108 let mut keys = Vec::new();
1109 let mut raws = Vec::new();
1110 for branch in &branches {
1111 if branch.kind() != Kind::Object {
1112 return None;
1113 }
1114 let mut only_const = true;
1115 branch.each(|k, _| {
1116 only_const &= matches!(k.str(), "const" | "description" | "title");
1117 true
1118 });
1119 let value = branch.get("const");
1120 if !only_const || !value.exists() {
1121 return None;
1122 }
1123 let key = canonical_key(&value)?;
1124 if keys.contains(&key) {
1125 return None;
1126 }
1127 keys.push(key);
1128 raws.push(value.json().to_owned());
1129 }
1130 let existing = prop.get("enum");
1131 if existing.exists() && existing.kind() == Kind::Array {
1132 let mut existing_keys = Vec::new();
1133 for v in existing.array() {
1134 existing_keys.push(canonical_key(&v)?);
1135 }
1136 let mut unique = existing_keys.clone();
1137 unique.sort();
1138 unique.dedup();
1139 let mut wanted = keys.clone();
1140 wanted.sort();
1141 let same = existing_keys.len() == keys.len() && unique.len() == existing_keys.len() && unique == wanted;
1142 return same.then(|| delete(prop.json(), name));
1143 }
1144 let with_enum = set_raw(prop.json(), "enum", &format!("[{}]", raws.join(",")));
1145 Some(delete(&with_enum, name))
1146}
1147
1148fn canonical_key(value: &gjson::Value<'_>) -> Option<String> {
1150 Some(match value.kind() {
1151 Kind::String => format!("s:{}", value.str()),
1152 Kind::Number => format!("n:{}", rational(value.json().trim())),
1153 Kind::True => "b:true".into(),
1154 Kind::False => "b:false".into(),
1155 Kind::Null => "null".into(),
1156 _ => return None,
1157 })
1158}
1159
1160fn rational(raw: &str) -> String {
1162 let (mantissa, exp) = match raw.find(['e', 'E']) {
1163 Some(i) => (&raw[..i], raw[i + 1..].parse::<i64>().unwrap_or(0)),
1164 None => (raw, 0),
1165 };
1166 let negative = mantissa.starts_with('-');
1167 let mantissa = mantissa.trim_start_matches(['-', '+']);
1168 let (int, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
1169 let digits = format!("{int}{frac}");
1170 let exp = exp - frac.len() as i64;
1171 let digits = digits.trim_start_matches('0');
1172 if digits.is_empty() {
1173 return "0".into();
1174 }
1175 let trimmed = digits.trim_end_matches('0');
1176 let exp = exp + (digits.len() - trimmed.len()) as i64;
1177 format!("{}{trimmed}e{exp}", if negative { "-" } else { "" })
1178}
1179
1180pub(crate) fn sanitize_input_ids(body: String) -> String {
1183 const LIMIT: usize = 64;
1184 const OCCUPIED: u8 = 1;
1185 const PRESERVED: u8 = 2;
1186 let input = gjson::get(&body, "input");
1187 if input.kind() != Kind::Array {
1188 return body;
1189 }
1190 let items = input.array();
1191 let normalize = |item: &gjson::Value<'_>, id: &str| -> String {
1192 let prefix = match item.get("type").str() {
1193 "message" => "msg",
1194 "reasoning" => "rs",
1195 "function_call" => "fc",
1196 "custom_tool_call" => "ctc",
1197 "custom_tool_call_output" => "ctco",
1198 _ => return id.to_owned(),
1199 };
1200 if id.is_empty() || id.starts_with(prefix) {
1201 id.to_owned()
1202 } else {
1203 format!("{prefix}_{id}")
1204 }
1205 };
1206 let dropped = |item: &gjson::Value<'_>| {
1207 let id = item.get("id");
1208 let enc = item.get("encrypted_content");
1209 item.get("type").str() == "reasoning"
1210 && id.kind() == Kind::String
1211 && id.str().chars().count() > LIMIT
1212 && enc.kind() == Kind::String
1213 && !enc.str().is_empty()
1214 };
1215 let mut states: std::collections::HashMap<String, u8> = Default::default();
1216 for item in &items {
1217 let id = item.get("id");
1218 if dropped(item) || id.kind() != Kind::String {
1219 continue;
1220 }
1221 let normalized = normalize(item, id.str());
1222 let mut state = states.get(&normalized).copied().unwrap_or(0);
1223 if normalized == id.str() {
1224 state |= PRESERVED;
1225 }
1226 if normalized.chars().count() <= LIMIT {
1227 state |= OCCUPIED;
1228 }
1229 if state != 0 {
1230 states.insert(normalized, state);
1231 }
1232 }
1233 let hashed = |id: &str, attempt: usize| {
1234 let mut input = id.to_owned();
1235 if attempt > 0 {
1236 input.push('\0');
1237 input.push_str(&attempt.to_string());
1238 }
1239 let digest = Sha256::digest(input.as_bytes());
1240 let suffix = format!(
1241 "_{}",
1242 digest[..8].iter().map(|b| format!("{b:02x}")).collect::<String>()
1243 );
1244 let keep = (LIMIT - suffix.len()).min(id.chars().count());
1245 format!("{}{suffix}", id.chars().take(keep).collect::<String>())
1246 };
1247 let mut shortened: std::collections::HashMap<String, String> = Default::default();
1248 let mut collisions: std::collections::HashMap<String, String> = Default::default();
1249 let mut rebuilt = Vec::with_capacity(items.len());
1250 let mut changed = false;
1251 for item in &items {
1252 if dropped(item) {
1253 changed = true;
1254 continue;
1255 }
1256 let mut raw = item.json().to_owned();
1257 let id = item.get("id");
1258 if id.kind() == Kind::String {
1259 let original = id.str();
1260 let mut next = normalize(item, original);
1261 if next != original && states.get(&next).is_some_and(|s| s & PRESERVED != 0) {
1262 next = match collisions.get(&next) {
1263 Some(c) => c.clone(),
1264 None => {
1265 let mut attempt = 0;
1266 let candidate = loop {
1267 let candidate = hashed(&next, attempt);
1268 if states.get(&candidate).is_some_and(|s| s & OCCUPIED != 0) {
1269 attempt += 1;
1270 continue;
1271 }
1272 break candidate;
1273 };
1274 collisions.insert(next.clone(), candidate.clone());
1275 *states.entry(candidate.clone()).or_default() |= OCCUPIED;
1276 candidate
1277 }
1278 };
1279 }
1280 if next.chars().count() > LIMIT {
1281 next = match shortened.get(&next) {
1282 Some(s) => s.clone(),
1283 None => {
1284 let mut candidate = hashed(&next, 0);
1285 let mut attempt = 1;
1286 while states.get(&candidate).is_some_and(|s| s & OCCUPIED != 0) {
1287 candidate = hashed(&next, attempt);
1288 attempt += 1;
1289 }
1290 shortened.insert(next.clone(), candidate.clone());
1291 *states.entry(candidate.clone()).or_default() |= OCCUPIED;
1292 candidate
1293 }
1294 };
1295 }
1296 if next != original {
1297 raw = set_str(&raw, "id", &next);
1298 changed = true;
1299 }
1300 }
1301 rebuilt.push(raw);
1302 }
1303 if changed {
1304 set_raw(&body, "input", &format!("[{}]", rebuilt.join(",")))
1305 } else {
1306 body
1307 }
1308}
1309
1310pub(crate) fn random_uuid() -> String {
1312 let mut bytes = [0u8; 16];
1313 let _ = getrandom::fill(&mut bytes);
1314 uuid::Builder::from_random_bytes(bytes).into_uuid().to_string()
1315}
1316
1317pub(crate) fn provider_session_uuid(kind: &str, id: &str) -> Option<String> {
1319 let id = id.trim();
1320 (!id.is_empty()).then(|| {
1321 uuid::Uuid::new_v5(
1322 &uuid::Uuid::NAMESPACE_OID,
1323 format!("cli-proxy-api\0codex\0{kind}\0{id}").as_bytes(),
1324 )
1325 .to_string()
1326 })
1327}
1328
1329pub(crate) fn session_uuid(req: &ExecRequest, ws_session: Option<&str>) -> Option<String> {
1332 let execution = ws_session
1333 .or(req.execution_session.as_deref())
1334 .filter(|id| !id.trim().is_empty());
1335 match execution {
1336 Some(id) => provider_session_uuid("execution-session", id),
1337 None => req
1338 .derived_session
1339 .as_deref()
1340 .and_then(|id| provider_session_uuid("derived-session", id)),
1341 }
1342}
1343
1344fn claude_code_prompt_cache(model: &str, payload: &[u8], headers: &HeaderMap) -> Option<String> {
1346 let model = model.trim();
1347 let scope = crate::replay::claude_code_session(payload, headers)?;
1348 (!model.is_empty()).then(|| {
1349 let identity = format!("cli-proxy-api:codex:claude-code\0{model}\0{scope}");
1350 uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, identity.as_bytes()).to_string()
1351 })
1352}
1353
1354pub(crate) fn prompt_cache(
1358 req: &ExecRequest,
1359 body: String,
1360 ws_session: Option<&str>,
1361 websocket: bool,
1362) -> (String, Option<String>) {
1363 let original = String::from_utf8_lossy(&req.body);
1364 let client_key = gjson::get(&original, "prompt_cache_key");
1365 let mut id = match req.source_format {
1366 Format::Claude => {
1367 let mut model = gjson::get(&body, "model").str().trim().to_owned();
1368 if model.is_empty() {
1369 model = base_model(&req.model);
1370 }
1371 claude_code_prompt_cache(&model, &req.body, &req.headers).unwrap_or_default()
1372 }
1373 Format::OpenAIResponse if client_key.exists() => client_key.str().to_owned(),
1374 Format::OpenAI if client_key.exists() && !websocket => client_key.str().trim().to_owned(),
1375 _ => String::new(),
1376 };
1377 if id.is_empty() {
1378 id = session_uuid(req, ws_session).unwrap_or_default();
1379 }
1380 if id.is_empty() && !websocket && req.source_format == Format::OpenAI && !req.caller.principal.trim().is_empty() {
1381 id = uuid::Uuid::new_v5(
1382 &uuid::Uuid::NAMESPACE_OID,
1383 format!("cli-proxy-api:codex:prompt-cache:{}", req.caller.principal.trim()).as_bytes(),
1384 )
1385 .to_string();
1386 }
1387 if id.is_empty() {
1388 return (body, None);
1389 }
1390 (set_str_if_different(body, "prompt_cache_key", &id), Some(id))
1391}
1392
1393fn set(headers: &mut HeaderMap, name: &str, value: &str) {
1394 if let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::from_str(value)) {
1395 headers.insert(name, value);
1396 }
1397}
1398
1399fn ensure_from_client(headers: &mut HeaderMap, client: &HeaderMap, name: &str) {
1401 let value = header(client, name).trim();
1402 if !value.is_empty() {
1403 set(headers, name, value);
1404 }
1405}
1406
1407fn ensure_config_first(headers: &mut HeaderMap, client: &HeaderMap, name: &str, config: &str, fallback: &str) {
1409 if !header(headers, name).trim().is_empty() {
1410 return;
1411 }
1412 for value in [config, header(client, name), fallback] {
1413 if !value.trim().is_empty() {
1414 set(headers, name, value.trim());
1415 return;
1416 }
1417 }
1418}
1419
1420pub(crate) fn custom_headers(view: &View<'_>, client: &HeaderMap) -> Vec<(String, String)> {
1423 cpa_common::headers::custom_headers(&view.credential.attributes, client, view.session.as_deref())
1424}
1425
1426fn model_overrides(model: &str) -> Vec<(String, String)> {
1428 let Some(info) = cpa_core::registry::pinned().lookup(model) else {
1429 return Vec::new();
1430 };
1431 info.raw
1432 .get("config")
1433 .and_then(|c| c.get("override_header"))
1434 .and_then(serde_json::Value::as_object)
1435 .map(|m| {
1436 m.iter()
1437 .filter(|(k, _)| !k.trim().is_empty())
1438 .filter_map(|(k, v)| Some((k.trim().to_owned(), v.as_str()?.to_owned())))
1439 .collect()
1440 })
1441 .unwrap_or_default()
1442}
1443
1444pub(crate) fn http_headers(
1446 view: &View<'_>,
1447 settings: &Settings,
1448 client: &HeaderMap,
1449 body: &str,
1450 model: &str,
1451 cache_id: Option<&str>,
1452 stream: bool,
1453) -> HeaderMap {
1454 let mut h = source_headers(view, settings, client, cache_id, stream);
1455 routing_hint(&mut h, view, client, body, model);
1456 model_header_overrides(&mut h, model);
1457 h
1458}
1459
1460pub(crate) fn image_headers(
1464 view: &View<'_>,
1465 settings: &Settings,
1466 client: &HeaderMap,
1467 model: &str,
1468 cache_id: Option<&str>,
1469 stream: bool,
1470) -> HeaderMap {
1471 let mut h = source_headers(view, settings, client, cache_id, stream);
1472 model_header_overrides(&mut h, model);
1473 h
1474}
1475
1476fn source_headers(
1478 view: &View<'_>,
1479 settings: &Settings,
1480 client: &HeaderMap,
1481 cache_id: Option<&str>,
1482 stream: bool,
1483) -> HeaderMap {
1484 if view.siwc {
1485 return siwc_http_headers(view, settings, client, cache_id, stream);
1486 }
1487 let mut h = HeaderMap::new();
1488 if let Some(id) = cache_id {
1489 set(&mut h, "session-id", id);
1490 }
1491 set(&mut h, "content-type", "application/json");
1492 if !view.token.trim().is_empty() {
1493 set(&mut h, "authorization", &format!("Bearer {}", view.token));
1494 }
1495 for name in [
1496 "x-codex-beta-features",
1497 "version",
1498 "x-codex-turn-metadata",
1499 "x-codex-turn-state",
1500 "x-client-request-id",
1501 "x-codex-window-id",
1502 "thread-id",
1503 "session-id",
1504 LITE_HEADER,
1505 ] {
1506 ensure_from_client(&mut h, client, name);
1507 }
1508 let default_ua = if view.api_key { "" } else { &settings.default_user_agent };
1509 ensure_config_first(&mut h, client, "user-agent", default_ua, USER_AGENT);
1510 set(
1511 &mut h,
1512 "accept",
1513 if stream {
1514 "text/event-stream"
1515 } else {
1516 "application/json"
1517 },
1518 );
1519 set(&mut h, "connection", "Keep-Alive");
1520 apply_identity(&mut h, view, settings, client);
1521 h
1522}
1523
1524fn siwc_http_headers(
1528 view: &View<'_>,
1529 settings: &Settings,
1530 client: &HeaderMap,
1531 cache_id: Option<&str>,
1532 stream: bool,
1533) -> HeaderMap {
1534 let mut h = HeaderMap::new();
1535 set(&mut h, "content-type", "application/json");
1536 if !view.token.trim().is_empty() {
1537 set(&mut h, "authorization", &format!("Bearer {}", view.token));
1538 }
1539 if let Some(id) = cache_id.map(str::trim).filter(|id| !id.is_empty()) {
1540 set(&mut h, "session_id", id);
1541 set(&mut h, "x-client-request-id", id);
1542 }
1543 set(&mut h, "user-agent", &settings.siwc_user_agent);
1544 set(
1545 &mut h,
1546 "accept",
1547 if stream {
1548 "text/event-stream"
1549 } else {
1550 "application/json"
1551 },
1552 );
1553 set(&mut h, "connection", "Keep-Alive");
1554 for (name, value) in custom_headers(view, client) {
1555 set(&mut h, &name, &value);
1556 }
1557 h
1558}
1559
1560fn apply_identity(h: &mut HeaderMap, view: &View<'_>, settings: &Settings, client: &HeaderMap) {
1562 let originator = header(client, "originator").trim();
1563 if !originator.is_empty() {
1564 set(h, "originator", originator);
1565 } else if !view.api_key {
1566 set(h, "originator", ORIGINATOR);
1567 }
1568 if !view.api_key
1569 && let Some(account) = view.credential.str("account_id")
1570 {
1571 set(h, "chatgpt-account-id", account.trim());
1572 }
1573 for (name, value) in custom_headers(view, client) {
1574 set(h, &name, &value);
1575 }
1576 if !view.cloaking_disabled(settings) {
1577 set(h, "user-agent", USER_AGENT);
1578 set(h, "originator", ORIGINATOR);
1579 }
1580}
1581
1582fn routing_hint(h: &mut HeaderMap, view: &View<'_>, client: &HeaderMap, body: &str, model: &str) {
1584 if view.api_key || view.siwc {
1585 return;
1586 }
1587 h.remove(ROUTING_HINT);
1588 let operator = custom_headers(view, client)
1589 .into_iter()
1590 .find(|(n, _)| n.eq_ignore_ascii_case(ROUTING_HINT))
1591 .map(|(_, v)| v);
1592 if let Some(value) = operator.filter(|v| !v.trim().is_empty()) {
1593 set(h, ROUTING_HINT, value.trim());
1594 return;
1595 }
1596 let model = model.trim();
1597 if model.is_empty() {
1598 return;
1599 }
1600 let mut hint = format!("model={model}");
1601 let tier = gjson::get(body, "service_tier");
1602 if tier.kind() == Kind::String && !tier.str().trim().is_empty() {
1603 hint.push_str(";tier=");
1604 hint.push_str(tier.str().trim());
1605 }
1606 set(h, ROUTING_HINT, &hint);
1607}
1608
1609fn model_header_overrides(h: &mut HeaderMap, model: &str) {
1610 let overrides = model_overrides(model);
1611 if overrides.is_empty() {
1612 return;
1613 }
1614 for (k, v) in overrides {
1615 set(h, &k, &v);
1616 }
1617 let has_session = ["session-id", "session_id"]
1618 .iter()
1619 .any(|n| !header(h, n).trim().is_empty());
1620 if header(h, "user-agent").contains("Mac OS") && !has_session {
1621 set(h, "session_id", &random_uuid());
1622 }
1623}
1624
1625pub(crate) fn ws_headers(
1628 view: &View<'_>,
1629 settings: &Settings,
1630 client: &HeaderMap,
1631 body: &str,
1632 model: &str,
1633 cache_id: Option<&str>,
1634 native: bool,
1635) -> HeaderMap {
1636 let mut h = HeaderMap::new();
1637 if let Some(id) = cache_id {
1638 set(&mut h, "session_id", id);
1639 set(&mut h, "conversation_id", id);
1640 }
1641 if !view.token.trim().is_empty() {
1642 set(&mut h, "authorization", &format!("Bearer {}", view.token));
1643 }
1644 if view.siwc {
1645 siwc_ws_headers(&mut h, view, settings, client);
1646 model_header_overrides(&mut h, model);
1647 return h;
1648 }
1649 let (default_ua, default_beta) = if view.api_key {
1650 ("", "")
1651 } else {
1652 (
1653 settings.default_user_agent.as_str(),
1654 settings.default_beta_features.as_str(),
1655 )
1656 };
1657 for value in [header(client, "x-codex-beta-features"), default_beta] {
1659 if !value.trim().is_empty() {
1660 set(&mut h, "x-codex-beta-features", value.trim());
1661 break;
1662 }
1663 }
1664 for name in [
1665 "x-codex-turn-state",
1666 "x-codex-turn-metadata",
1667 "x-client-request-id",
1668 "x-responsesapi-include-timing-metrics",
1669 "version",
1670 ] {
1671 ensure_from_client(&mut h, client, name);
1672 }
1673 if native {
1674 ensure_from_client(&mut h, client, LITE_HEADER);
1675 }
1676 if view.api_key {
1677 let ua = header(client, "user-agent").trim();
1678 if !ua.is_empty() {
1679 set(&mut h, "user-agent", ua);
1680 }
1681 } else {
1682 ensure_config_first(&mut h, client, "user-agent", default_ua, USER_AGENT);
1683 }
1684 let mut beta = header(client, "openai-beta").trim().to_owned();
1685 if !beta.contains("responses_websockets=") {
1686 beta = WS_BETA.to_owned();
1687 }
1688 set(&mut h, "openai-beta", &beta);
1689 let mut session = header(&h, "session_id").trim().to_owned();
1691 if session.is_empty() {
1692 session = ["session-id", "session_id"]
1693 .iter()
1694 .map(|n| header(client, n).trim())
1695 .find(|v| !v.is_empty())
1696 .unwrap_or_default()
1697 .to_owned();
1698 }
1699 if session.is_empty() && header(&h, "user-agent").contains("Mac OS") {
1700 session = random_uuid();
1701 }
1702 if !session.is_empty() {
1703 set(&mut h, "session_id", &session);
1704 }
1705 h.remove("session-id");
1706 if native && view.cloaking_disabled(settings) {
1707 h.remove("session_id");
1708 h.remove("conversation_id");
1709 for name in [
1710 "session-id",
1711 "session_id",
1712 "conversation_id",
1713 "thread-id",
1714 ROUTING_HINT,
1715 "x-codex-window-id",
1716 ] {
1717 for value in client.get_all(name) {
1718 h.append(HeaderName::from_static(name), value.clone());
1719 }
1720 }
1721 }
1722 apply_identity(&mut h, view, settings, client);
1723 routing_hint(&mut h, view, client, body, model);
1724 model_header_overrides(&mut h, model);
1725 h
1726}
1727
1728fn siwc_ws_headers(h: &mut HeaderMap, view: &View<'_>, settings: &Settings, client: &HeaderMap) {
1733 h.remove("conversation_id");
1734 let existing = header(h, "session_id").trim().to_owned();
1735 let session = if existing.is_empty() {
1736 ["session-id", "session_id"]
1737 .iter()
1738 .map(|n| header(client, n).trim())
1739 .find(|v| !v.is_empty())
1740 .unwrap_or_default()
1741 .to_owned()
1742 } else {
1743 existing
1744 };
1745 if session.is_empty() {
1746 ensure_from_client(h, client, "x-client-request-id");
1747 } else {
1748 set(h, "session_id", &session);
1749 set(h, "x-client-request-id", &session);
1750 }
1751 set(h, "user-agent", &settings.siwc_user_agent);
1752 let beta = header(client, "openai-beta").trim();
1753 let beta = if beta.contains("responses_websockets=") {
1754 beta
1755 } else {
1756 WS_BETA
1757 };
1758 set(h, "openai-beta", beta);
1759 for (name, value) in custom_headers(view, client) {
1760 set(h, &name, &value);
1761 }
1762}
1763
1764#[cfg(test)]
1765mod tests {
1766 use super::*;
1767
1768 #[test]
1772 fn tool_schema_passes_match_go() {
1773 let go: serde_json::Value =
1774 serde_json::from_str(include_str!("../tests/fixtures/codex_tool_schema_go.json")).unwrap();
1775 let expected = |case: &serde_json::Value| case.get("out").unwrap_or(&case["in"]).as_str().unwrap().to_owned();
1776 for case in go["schemas"].as_array().unwrap() {
1777 let input = case["in"].as_str().unwrap().to_owned();
1778 assert_eq!(normalize_tool_schemas(input), expected(case), "{}", case["name"]);
1779 }
1780 for case in go["integers"].as_array().unwrap() {
1781 let mut headers = HeaderMap::new();
1782 if let Some(ua) = case["ua"].as_str() {
1783 headers.insert(http::header::USER_AGENT, ua.parse().unwrap());
1784 }
1785 let out = cpa_common::payload::normalize_codex_tool_integer_types(
1786 case["in"].as_str().unwrap().as_bytes(),
1787 &headers,
1788 );
1789 assert_eq!(
1790 String::from_utf8(out.clone()).unwrap(),
1791 expected(case),
1792 "{} {:?}",
1793 case["name"],
1794 case["ua"]
1795 );
1796 let again = cpa_common::payload::normalize_codex_tool_integer_types(&out, &headers);
1798 assert_eq!(again, out, "{} is not idempotent", case["name"]);
1799 }
1800 }
1801
1802 #[test]
1805 fn web_search_history_matches_go() {
1806 let go: serde_json::Value =
1807 serde_json::from_str(include_str!("../tests/fixtures/codex_web_search_history_go.json")).unwrap();
1808 for case in go["cases"].as_array().unwrap() {
1809 let mut headers = HeaderMap::new();
1810 if let Some(value) = case["lite_header"].as_str() {
1811 headers.insert(LITE_HEADER, HeaderValue::from_bytes(value.as_bytes()).unwrap());
1813 }
1814 let input = case["in"].as_str().unwrap();
1815 let want = case.get("out").unwrap_or(&case["in"]).as_str().unwrap();
1816 assert_eq!(
1817 ensure_web_search_for_history(input.to_owned(), &headers),
1818 want,
1819 "{}",
1820 case["name"]
1821 );
1822 }
1823 }
1824
1825 #[test]
1830 fn home_codex_is_compat_reads_the_credential_options() {
1831 let mut credential = Credential {
1832 id: "c1".into(),
1833 provider: "codex".into(),
1834 source: cpa_core::credential::Source::File("c1".into()),
1835 disabled: false,
1836 label: String::new(),
1837 attributes: Default::default(),
1838 metadata: serde_json::json!({"credential_options": {"models": [{"name": "upstream", "alias": "alias", "is-compat": true}]}})
1839 .as_object()
1840 .cloned()
1841 .unwrap(),
1842 revision: 0,
1843 next_refresh_after: None,
1844 };
1845 let settings = |c: &Credential| Settings {
1846 home: c
1847 .attributes
1848 .contains_key(cpa_core::config::credentials::HOME_PROVIDER)
1849 .then(|| c.clone()),
1850 ..Settings::default()
1851 };
1852 let request = |model: &str| ExecRequest {
1853 operation: cpa_core::exec::Operation::Generate,
1854 source_format: Format::Codex,
1855 response_format: Format::Codex,
1856 stream_payloads: false,
1857 requested_model: model.into(),
1858 model: model.into(),
1859 original_body: Default::default(),
1860 body: Default::default(),
1861 stream: false,
1862 alt: None,
1863 session: None,
1864 execution_session: None,
1865 derived_session: None,
1866 request_path: String::new(),
1867 headers: Default::default(),
1868 caller: cpa_core::exec::Caller {
1869 principal: String::new(),
1870 source: "",
1871 provider: String::new(),
1872 },
1873 resolved_model: None,
1874 usage: Default::default(),
1875 };
1876 credential
1877 .attributes
1878 .insert(cpa_core::config::credentials::HOME_PROVIDER.into(), "codex".into());
1879 for model in ["upstream", "alias", "upstream(high)"] {
1880 assert!(settings(&credential).is_compat(&request(model)), "{model}");
1881 }
1882 let mut other = credential.clone();
1883 other.metadata.clear();
1884 assert!(!settings(&other).is_compat(&request("upstream")));
1885 credential.attributes.clear();
1886 assert!(!settings(&credential).is_compat(&request("upstream")), "standalone");
1887
1888 let keyed = |name: &str| Settings {
1891 key_models: vec![serde_json::json!({"name": name, "is-compat": true})],
1892 ..Settings::default()
1893 };
1894 assert!(!keyed("mİ").is_compat(&request("mi")), "dotted İ is not i");
1895 assert!(keyed("ος").is_compat(&request("ΟΣ")), "final sigma folds");
1896 }
1897
1898 #[test]
1899 fn durations_follow_go_parse_duration() {
1900 assert_eq!(go_duration("1m30s"), Some(Duration::from_secs(90)));
1901 assert_eq!(go_duration("1.5s"), Some(Duration::from_millis(1500)));
1902 assert_eq!(go_duration("45"), Some(Duration::from_secs(45)));
1903 assert_eq!(go_duration("off"), None);
1904 assert_eq!(go_duration("soon"), None);
1905 assert_eq!(go_duration("+2s"), Some(Duration::from_secs(2)));
1906 assert_eq!(go_duration("3\u{3bc}s"), Some(Duration::from_micros(3)));
1907 assert_eq!(go_duration("-1s"), None);
1908 assert_eq!(go_duration("+15"), Some(Duration::from_secs(15)));
1909 }
1910
1911 #[test]
1912 fn rationals_compare_like_big_rat() {
1913 assert_eq!(rational("8"), rational("8.0"));
1914 assert_eq!(rational("8"), rational("0.8e1"));
1915 assert_eq!(rational("-0.50"), rational("-5e-1"));
1916 assert_ne!(rational("8"), rational("80"));
1917 assert_eq!(rational("0.000"), "0");
1918 }
1919
1920 #[test]
1924 fn chatgpt_keep_alive_is_off_unless_configured() {
1925 let cases = [
1926 ("", false),
1927 (
1928 "oauth:\n providers:\n codex:\n disable-codex-cloaking: true\n",
1929 false,
1930 ),
1931 (
1932 "oauth:\n providers:\n codex:\n chatgpt-keep-alive: false\n",
1933 false,
1934 ),
1935 (
1936 "oauth:\n providers:\n codex:\n chatgpt-keep-alive: true\n",
1937 true,
1938 ),
1939 (
1940 "oauth:\n providers:\n codex:\n chatgpt-keep-alive: yes\n",
1941 true,
1942 ),
1943 ("codex:\n chatgpt-keep-alive: true\n", true),
1944 ];
1945 for (yaml, want) in cases {
1946 let cfg = Config::parse(yaml).unwrap();
1947 assert_eq!(chatgpt_keep_alive(&cfg), want, "{yaml:?}");
1948 }
1949 }
1950}