mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-18 16:06:47 +00:00
fix(openai): keep frame metadata separate from forwarded headers
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -19,7 +19,6 @@ use crate::openai::generation::{
|
||||
};
|
||||
|
||||
const OPENAI_SUBAGENT_KEY: &str = "x-openai-subagent";
|
||||
const CODEX_TURN_METADATA_KEY: &str = "x-codex-turn-metadata";
|
||||
const PASSTHROUGH_HEADERS_CONTEXT_KEY: &str = "opaque_request_headers";
|
||||
const DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY: &str = "downstream_websocket_connection_id";
|
||||
|
||||
@@ -36,9 +35,7 @@ pub(super) enum RequestDecodeSource {
|
||||
pub struct OpenAiRequestHeaders {
|
||||
turn_state: Option<String>,
|
||||
turn_metadata: Option<String>,
|
||||
beta_features: Option<String>,
|
||||
version: Option<String>,
|
||||
include_timing_metrics: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
downstream_websocket_connection_id: Option<String>,
|
||||
@@ -62,9 +59,7 @@ impl OpenAiRequestHeaders {
|
||||
Self {
|
||||
turn_state: header_string(headers, "x-codex-turn-state"),
|
||||
turn_metadata: header_string(headers, "x-codex-turn-metadata"),
|
||||
beta_features: header_string(headers, "x-codex-beta-features"),
|
||||
version: header_string(headers, "version"),
|
||||
include_timing_metrics: header_string(headers, "x-responsesapi-include-timing-metrics"),
|
||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||
downstream_websocket_connection_id: None,
|
||||
@@ -120,22 +115,18 @@ impl OpenAiRequestHeaders {
|
||||
fn protocol_context(
|
||||
&self,
|
||||
use_websocket: Option<bool>,
|
||||
frame_turn_metadata: Option<&String>,
|
||||
source: RequestDecodeSource,
|
||||
) -> Map<String, Value> {
|
||||
let mut context = Map::new();
|
||||
insert_protocol_context(&mut context, "turn_state", self.turn_state.as_ref());
|
||||
insert_protocol_context(
|
||||
&mut context,
|
||||
"turn_metadata",
|
||||
frame_turn_metadata.or(self.turn_metadata.as_ref()),
|
||||
);
|
||||
insert_protocol_context(&mut context, "beta_features", self.beta_features.as_ref());
|
||||
insert_protocol_context(&mut context, "turn_metadata", self.turn_metadata.as_ref());
|
||||
if matches!(source, RequestDecodeSource::WebSocketFrame) {
|
||||
context.insert(
|
||||
gateway_protocol::openai::WEBSOCKET_FRAME_CONTEXT_KEY.to_owned(),
|
||||
Value::Bool(true),
|
||||
);
|
||||
}
|
||||
insert_protocol_context(&mut context, "version", self.version.as_ref());
|
||||
insert_protocol_context(
|
||||
&mut context,
|
||||
"include_timing_metrics",
|
||||
self.include_timing_metrics.as_ref(),
|
||||
);
|
||||
insert_protocol_context(
|
||||
&mut context,
|
||||
"codex_window_id",
|
||||
@@ -338,11 +329,7 @@ pub(super) fn decode_request_object(
|
||||
.unwrap_or(ContinuationIntent::None);
|
||||
|
||||
request_headers.apply_subagent(&mut object);
|
||||
let frame_turn_metadata = match source {
|
||||
RequestDecodeSource::Http => None,
|
||||
RequestDecodeSource::WebSocketFrame => frame_turn_metadata(&object),
|
||||
};
|
||||
let protocol_context = request_headers.protocol_context(use_websocket, frame_turn_metadata);
|
||||
let protocol_context = request_headers.protocol_context(use_websocket, source);
|
||||
|
||||
let semantics =
|
||||
gateway_protocol::openai::codex_responses_request_semantics(&object, &protocol_context);
|
||||
@@ -381,16 +368,6 @@ pub(super) fn decode_request_object(
|
||||
})
|
||||
}
|
||||
|
||||
fn frame_turn_metadata(body: &Map<String, Value>) -> Option<&String> {
|
||||
body.get("client_metadata")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|metadata| metadata.get(CODEX_TURN_METADATA_KEY))
|
||||
.and_then(|value| match value {
|
||||
Value::String(value) if !value.trim().is_empty() => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn inject_subagent_metadata(body: &mut Map<String, Value>, subagent: &str) {
|
||||
let metadata = body
|
||||
.entry("client_metadata".to_owned())
|
||||
|
||||
@@ -74,13 +74,11 @@ pub(crate) async fn responses_websocket(
|
||||
&headers,
|
||||
connect_info.map(|Extension(ConnectInfo(address))| address),
|
||||
);
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers);
|
||||
ResponsesWebSocketAdapter::new(service).upgrade_with_client_context(
|
||||
websocket,
|
||||
client,
|
||||
client_ip,
|
||||
user_agent,
|
||||
request_headers,
|
||||
headers,
|
||||
middleware.map(|Extension(plan)| plan),
|
||||
lifetime.map(|Extension(lifetime)| lifetime),
|
||||
@@ -107,7 +105,6 @@ impl ResponsesWebSocketAdapter {
|
||||
client: AuthenticatedClient,
|
||||
client_ip: Option<IpAddr>,
|
||||
user_agent: Option<String>,
|
||||
request_headers: OpenAiRequestHeaders,
|
||||
raw_headers: HeaderMap,
|
||||
middleware: Option<FrozenMiddlewarePlan>,
|
||||
lifetime: Option<Arc<crate::middleware::CallLifetime>>,
|
||||
@@ -130,7 +127,6 @@ impl ResponsesWebSocketAdapter {
|
||||
connection_id,
|
||||
client_ip,
|
||||
user_agent,
|
||||
request_headers,
|
||||
raw_headers,
|
||||
lifecycle: self.service.lifecycle(),
|
||||
connection_guard,
|
||||
@@ -150,7 +146,6 @@ struct ResponsesWebSocketSession {
|
||||
connection_id: String,
|
||||
client_ip: Option<IpAddr>,
|
||||
user_agent: Option<String>,
|
||||
request_headers: OpenAiRequestHeaders,
|
||||
raw_headers: HeaderMap,
|
||||
lifecycle: Arc<dyn ConnectionLifecycle>,
|
||||
connection_guard: Box<dyn ConnectionGuard>,
|
||||
@@ -164,7 +159,6 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
connection_id,
|
||||
client_ip,
|
||||
user_agent,
|
||||
request_headers,
|
||||
mut raw_headers,
|
||||
lifecycle,
|
||||
connection_guard,
|
||||
@@ -178,8 +172,6 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
let cancellation = lifecycle.cancellation().child_token();
|
||||
let _connection_cancellation =
|
||||
crate::middleware::websocket::CancelOnDrop(Some(cancellation.clone()));
|
||||
let request_headers =
|
||||
request_headers.with_downstream_websocket_connection_id(connection_id.clone());
|
||||
// 帧中间件可能改写终态,此时不能据原始响应关闭下游连接
|
||||
let reconnect_for_replay = !middleware
|
||||
.as_ref()
|
||||
@@ -241,31 +233,32 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
continue;
|
||||
}
|
||||
request_count = request_count.saturating_add(1);
|
||||
// 初步解码只保留路由事实,避免整份正文跨越准入等待和响应交付
|
||||
let model_hint = match decode_response_create_with_context(&payload, &request_headers) {
|
||||
Ok(decoded) => Some(decoded.metadata().requested_model().to_owned()),
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
// 初步解码只取帧中的模型,实际执行使用该帧当前生效的请求头
|
||||
let model_hint =
|
||||
match decode_response_create_with_context(&payload, &OpenAiRequestHeaders::default()) {
|
||||
Ok(decoded) => Some(decoded.metadata().requested_model().to_owned()),
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
};
|
||||
// deadline 与 Text 可能同时就绪;在任何上游执行开始前再次封住该竞争窗口
|
||||
if connection.is_expired() {
|
||||
trace_rejected_request(
|
||||
@@ -336,8 +329,9 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
headers: encode_headers(&raw_headers),
|
||||
body: Bytes::from(payload),
|
||||
};
|
||||
// 握手的轮次状态仅属于首次执行,复用连接时由各 response.create 自行携带
|
||||
// 握手的轮次头只属于首次执行,复用连接时由各 response.create 携带本轮数据
|
||||
raw_headers.remove("x-codex-turn-state");
|
||||
raw_headers.remove("x-codex-turn-metadata");
|
||||
let service_for_terminal = service.clone();
|
||||
let replay_for_terminal = replay.clone();
|
||||
let connection_id_for_terminal = connection.id().to_owned();
|
||||
|
||||
@@ -532,6 +532,10 @@ async fn errors_on_a_reused_connection_keep_their_own_upstream_ids() {
|
||||
"x-codex-turn-state",
|
||||
axum::http::HeaderValue::from_static("opening"),
|
||||
);
|
||||
opening.insert(
|
||||
"x-codex-turn-metadata",
|
||||
axum::http::HeaderValue::from_static(r#"{"request_kind":"turn"}"#),
|
||||
);
|
||||
let (mut socket, _server) = connect_with_headers(Arc::clone(&trace), Vec::new(), opening).await;
|
||||
for request_id in ["req_first", "req_second"] {
|
||||
send_request(&mut socket).await;
|
||||
@@ -540,8 +544,14 @@ async fn errors_on_a_reused_connection_keep_their_own_upstream_ids() {
|
||||
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
|
||||
}
|
||||
assert_eq!(
|
||||
*trace.request_turn_states.lock().unwrap(),
|
||||
[Some("opening".to_owned()), None]
|
||||
*trace.request_turn_headers.lock().unwrap(),
|
||||
[
|
||||
[
|
||||
Some("opening".to_owned()),
|
||||
Some(r#"{"request_kind":"turn"}"#.to_owned())
|
||||
],
|
||||
[None, None]
|
||||
]
|
||||
);
|
||||
assert_no_duplicate_failure(&mut socket).await;
|
||||
socket.close(None).await.unwrap();
|
||||
|
||||
@@ -168,21 +168,31 @@ fn response_create_should_preserve_compaction_trigger_for_openai() {
|
||||
|
||||
#[test]
|
||||
fn response_create_should_prefer_frame_turn_metadata_over_opening_headers() {
|
||||
let frame = r#"{"request_kind":"turn","tool_namespaces_info":{"workspace":{}}}"#;
|
||||
let opening = r#"{"request_kind":"compaction"}"#;
|
||||
let decoded = decode_response_create_with_turn_header(
|
||||
json!({
|
||||
"type": "response.create",
|
||||
"model": "smart-code",
|
||||
"input": "hello",
|
||||
"client_metadata": {
|
||||
"x-codex-turn-metadata": r#"{"request_kind":"turn"}"#
|
||||
"x-codex-turn-metadata": frame
|
||||
}
|
||||
}),
|
||||
r#"{"request_kind":"compaction"}"#,
|
||||
opening,
|
||||
);
|
||||
let Operation::Generate(request) = decoded.operation() else {
|
||||
panic!("Responses must map to Generate");
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
request.protocol_payload().context()["turn_metadata"],
|
||||
opening
|
||||
);
|
||||
assert_eq!(
|
||||
request.protocol_payload().body()["client_metadata"]["x-codex-turn-metadata"],
|
||||
frame
|
||||
);
|
||||
let semantics = codex_responses_request_semantics(
|
||||
request.protocol_payload().body(),
|
||||
request.protocol_payload().context(),
|
||||
@@ -308,7 +318,7 @@ struct AtomicFailureTrace {
|
||||
committed: AtomicBool,
|
||||
finalized: AtomicBool,
|
||||
downstream_websocket_connection_ids: Mutex<Vec<String>>,
|
||||
request_turn_states: Mutex<Vec<Option<String>>>,
|
||||
request_turn_headers: Mutex<Vec<[Option<String>; 2]>>,
|
||||
initial_errors: Mutex<std::collections::VecDeque<EngineError>>,
|
||||
first_batch: Mutex<Option<CoordinatedEvent>>,
|
||||
session_drops: Arc<AtomicUsize>,
|
||||
@@ -438,13 +448,10 @@ impl ExecutionService for AtomicFailureExecution {
|
||||
.get("downstream_websocket_connection_id")
|
||||
.and_then(Value::as_str)
|
||||
{
|
||||
self.trace.request_turn_states.lock().unwrap().push(
|
||||
generate
|
||||
.protocol_payload()
|
||||
.context()
|
||||
.get("turn_state")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned),
|
||||
let context = generate.protocol_payload().context();
|
||||
self.trace.request_turn_headers.lock().unwrap().push(
|
||||
["turn_state", "turn_metadata"]
|
||||
.map(|key| context.get(key).and_then(Value::as_str).map(str::to_owned)),
|
||||
);
|
||||
self.trace
|
||||
.downstream_websocket_connection_ids
|
||||
|
||||
@@ -6,6 +6,38 @@ const MULTI_AGENT_MODE_OPEN_TAG: &str = "<multi_agent_mode>";
|
||||
const MULTI_AGENT_MODE_CLOSE_TAG: &str = "</multi_agent_mode>";
|
||||
const PROACTIVE_MULTI_AGENT_MODE_PREFIX: &str = "Proactive multi-agent delegation is active.";
|
||||
|
||||
/// 标记实际入站的 Responses WS 帧,独立于出站传输偏好
|
||||
pub const WEBSOCKET_FRAME_CONTEXT_KEY: &str = "websocket_frame";
|
||||
|
||||
/// 当前帧携带的完整元数据仅用于解释正文,握手或 HTTP 头保留各自的出站值
|
||||
#[must_use]
|
||||
pub fn observed_turn_metadata<'a>(
|
||||
body: &'a Map<String, Value>,
|
||||
header: Option<&'a str>,
|
||||
websocket_frame: bool,
|
||||
) -> Option<&'a str> {
|
||||
if websocket_frame && let Some(frame) = client_metadata_string(body, "x-codex-turn-metadata") {
|
||||
return Some(frame);
|
||||
}
|
||||
header
|
||||
}
|
||||
|
||||
/// HTTP 请求使用本次请求头,WS 帧使用本次正文或首次握手头
|
||||
#[must_use]
|
||||
pub fn context_turn_metadata<'a>(
|
||||
body: &'a Map<String, Value>,
|
||||
context: &'a Map<String, Value>,
|
||||
) -> Option<&'a str> {
|
||||
observed_turn_metadata(
|
||||
body,
|
||||
context.get("turn_metadata").and_then(Value::as_str),
|
||||
context
|
||||
.get(WEBSOCKET_FRAME_CONTEXT_KEY)
|
||||
.and_then(Value::as_bool)
|
||||
== Some(true),
|
||||
)
|
||||
}
|
||||
|
||||
/// 各 Codex 端点共用的显式根会话身份
|
||||
/// 连接边界的 session_id 优先,
|
||||
/// 正文及官方 metadata 只做回退;不从 turn、window 或请求内容猜测归属
|
||||
@@ -24,9 +56,7 @@ pub fn codex_account_session_id(
|
||||
client_metadata_string(body, "session_id")
|
||||
.map(str::to_owned)
|
||||
.or_else(|| request_turn_metadata(body).and_then(turn_metadata_session_id))
|
||||
.or_else(|| {
|
||||
non_empty_string(context.get("turn_metadata")).and_then(turn_metadata_session_id)
|
||||
})
|
||||
.or_else(|| context_turn_metadata(body, context).and_then(turn_metadata_session_id))
|
||||
.or_else(|| non_empty_string(body.get("session_id")).map(str::to_owned))
|
||||
.or_else(|| codex_session_id(body, context))
|
||||
}
|
||||
@@ -40,9 +70,7 @@ pub fn codex_account_thread_id(
|
||||
client_metadata_string(body, "thread_id")
|
||||
.map(str::to_owned)
|
||||
.or_else(|| request_turn_metadata(body).and_then(turn_metadata_thread_id))
|
||||
.or_else(|| {
|
||||
non_empty_string(context.get("turn_metadata")).and_then(turn_metadata_thread_id)
|
||||
})
|
||||
.or_else(|| context_turn_metadata(body, context).and_then(turn_metadata_thread_id))
|
||||
.or_else(|| codex_thread_id(body, context))
|
||||
}
|
||||
|
||||
@@ -64,7 +92,7 @@ pub fn codex_turn_id(body: &Map<String, Value>, context: &Map<String, Value>) ->
|
||||
client_metadata_string(body, "turn_id")
|
||||
.map(str::to_owned)
|
||||
.or_else(|| request_turn_metadata(body).and_then(turn_metadata_turn_id))
|
||||
.or_else(|| non_empty_string(context.get("turn_metadata")).and_then(turn_metadata_turn_id))
|
||||
.or_else(|| context_turn_metadata(body, context).and_then(turn_metadata_turn_id))
|
||||
.or_else(|| codex_identity_field(body, context, "turn_id"))
|
||||
}
|
||||
|
||||
@@ -90,7 +118,8 @@ fn codex_identity_field(
|
||||
.or_else(|| client_metadata_string(body, field))
|
||||
.map(str::to_owned)
|
||||
.or_else(|| {
|
||||
let metadata = non_empty_string(context.get("turn_metadata"))
|
||||
let metadata = context_turn_metadata(body, context)
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| request_turn_metadata(body))?;
|
||||
let metadata: Value = serde_json::from_str(metadata).ok()?;
|
||||
non_empty_string(metadata.get(field)).map(str::to_owned)
|
||||
@@ -127,7 +156,7 @@ pub fn codex_responses_request_semantics(
|
||||
) -> CodexResponsesRequestSemantics {
|
||||
codex_responses_request_semantics_with_turn_metadata(
|
||||
body,
|
||||
context.get("turn_metadata").and_then(Value::as_str),
|
||||
context_turn_metadata(body, context),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -21,9 +21,10 @@ mod headers;
|
||||
pub mod sse;
|
||||
|
||||
pub use codex::{
|
||||
CodexResponsesRequestSemantics, codex_account_session_id, codex_account_thread_id,
|
||||
codex_responses_request_semantics, codex_responses_request_semantics_with_turn_metadata,
|
||||
codex_session_id, codex_thread_id, codex_turn_id, turn_metadata_session_id,
|
||||
CodexResponsesRequestSemantics, WEBSOCKET_FRAME_CONTEXT_KEY, codex_account_session_id,
|
||||
codex_account_thread_id, codex_responses_request_semantics,
|
||||
codex_responses_request_semantics_with_turn_metadata, codex_session_id, codex_thread_id,
|
||||
codex_turn_id, context_turn_metadata, observed_turn_metadata, turn_metadata_session_id,
|
||||
turn_metadata_thread_id, turn_metadata_turn_id,
|
||||
};
|
||||
pub use headers::{
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn request_observation(
|
||||
OPENAI_PROTOCOL => {
|
||||
let semantics = codex_responses_request_semantics_with_turn_metadata(
|
||||
body,
|
||||
context.get("turn_metadata").and_then(Value::as_str),
|
||||
crate::openai::context_turn_metadata(body, context),
|
||||
previous_reasoning_effort_override,
|
||||
);
|
||||
RequestObservation {
|
||||
|
||||
@@ -701,8 +701,6 @@ pub(super) fn codex_request_context<'a>(
|
||||
request_id,
|
||||
turn_state: request.turn_state.as_deref(),
|
||||
turn_metadata: request.turn_metadata.as_deref(),
|
||||
beta_features: request.beta_features.as_deref(),
|
||||
include_timing_metrics: request.include_timing_metrics.as_deref(),
|
||||
version: request.version.as_deref(),
|
||||
codex_window_id: request.codex_window_id.as_deref(),
|
||||
parent_thread_id: request.parent_thread_id.as_deref(),
|
||||
|
||||
@@ -22,7 +22,7 @@ pub(crate) fn follows_session_with_headers(
|
||||
}
|
||||
gateway_protocol::openai::codex_responses_request_semantics_with_turn_metadata(
|
||||
body,
|
||||
metadata.or_else(|| context.get("turn_metadata").and_then(Value::as_str)),
|
||||
metadata.or_else(|| gateway_protocol::openai::context_turn_metadata(body, context)),
|
||||
None,
|
||||
)
|
||||
.subagent_kind
|
||||
|
||||
@@ -472,10 +472,6 @@ pub struct CodexRequestContext<'a> {
|
||||
pub turn_state: Option<&'a str>,
|
||||
/// 客户端 turn metadata;其中 installation ID 已按当前账号处理
|
||||
pub turn_metadata: Option<&'a str>,
|
||||
/// x-codex-beta-features 头值
|
||||
pub beta_features: Option<&'a str>,
|
||||
/// x-responsesapi-include-timing-metrics 头值
|
||||
pub include_timing_metrics: Option<&'a str>,
|
||||
/// 下游 `version` 扩展头;存在时上游值由 Desktop 版本画像统一生成
|
||||
pub version: Option<&'a str>,
|
||||
/// 客户端 window ID
|
||||
@@ -512,8 +508,6 @@ impl<'a> CodexRequestContext<'a> {
|
||||
request_id,
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
|
||||
@@ -211,11 +211,6 @@ impl CodexBackendClient {
|
||||
("x-codex-window-id", context.codex_window_id),
|
||||
("x-codex-turn-state", context.turn_state),
|
||||
("x-codex-turn-metadata", context.turn_metadata),
|
||||
("x-codex-beta-features", context.beta_features),
|
||||
(
|
||||
"x-responsesapi-include-timing-metrics",
|
||||
context.include_timing_metrics,
|
||||
),
|
||||
("x-codex-parent-thread-id", context.parent_thread_id),
|
||||
(
|
||||
X_OPENAI_MEMGEN_REQUEST_HEADER,
|
||||
|
||||
@@ -68,12 +68,10 @@ pub struct CodexResponsesRequest {
|
||||
pub turn_state: Option<String>,
|
||||
/// turn metadata 透传头
|
||||
pub turn_metadata: Option<String>,
|
||||
/// beta features 透传头
|
||||
pub beta_features: Option<String>,
|
||||
/// 实际入站为 WS 帧时,观测优先使用本帧的轮次元数据
|
||||
pub(crate) websocket_frame: bool,
|
||||
/// 下游 `version` 扩展头;存在时上游值由 Desktop 版本画像统一生成
|
||||
pub version: Option<String>,
|
||||
/// timing metrics 透传头
|
||||
pub include_timing_metrics: Option<String>,
|
||||
/// Responses Lite 请求语义;HTTP 使用 header,WebSocket 使用 client metadata 投影
|
||||
pub responses_lite: Option<String>,
|
||||
/// Memory consolidation 请求语义;HTTP 与 WebSocket opening 均使用 header
|
||||
@@ -612,9 +610,8 @@ impl CodexResponsesRequest {
|
||||
force_http_sse: false,
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
websocket_frame: false,
|
||||
version: None,
|
||||
include_timing_metrics: None,
|
||||
responses_lite: None,
|
||||
memgen_request: None,
|
||||
codex_window_id: None,
|
||||
@@ -771,7 +768,11 @@ impl CodexResponsesRequest {
|
||||
) -> CodexRequestSemantics {
|
||||
codex_responses_request_semantics_with_turn_metadata(
|
||||
self.body(),
|
||||
self.turn_metadata.as_deref(),
|
||||
gateway_protocol::openai::observed_turn_metadata(
|
||||
self.body(),
|
||||
self.turn_metadata.as_deref(),
|
||||
self.websocket_frame,
|
||||
),
|
||||
previous_reasoning_effort_override,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -255,9 +255,7 @@ fn extract_request_context(request: &mut CodexResponsesRequest) {
|
||||
let context = ExtractedRequestContext::from_body(request.body());
|
||||
request.turn_state = context.turn_state;
|
||||
request.turn_metadata = context.turn_metadata;
|
||||
request.beta_features = context.beta_features;
|
||||
request.version = context.version;
|
||||
request.include_timing_metrics = context.include_timing_metrics;
|
||||
request.codex_window_id = context.codex_window_id;
|
||||
request.parent_thread_id = context.parent_thread_id;
|
||||
request.client_conversation_id = context.conversation_id;
|
||||
@@ -269,9 +267,7 @@ fn extract_request_context(request: &mut CodexResponsesRequest) {
|
||||
struct ExtractedRequestContext {
|
||||
turn_state: Option<String>,
|
||||
turn_metadata: Option<String>,
|
||||
beta_features: Option<String>,
|
||||
version: Option<String>,
|
||||
include_timing_metrics: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
conversation_id: Option<String>,
|
||||
@@ -291,9 +287,7 @@ impl ExtractedRequestContext {
|
||||
})
|
||||
}),
|
||||
turn_metadata: body_string(body, "turnMetadata"),
|
||||
beta_features: body_string(body, "betaFeatures"),
|
||||
version: body_string(body, "version"),
|
||||
include_timing_metrics: body_string(body, "includeTimingMetrics"),
|
||||
codex_window_id: body_string(body, "codexWindowId"),
|
||||
parent_thread_id: body_string(body, "parentThreadId"),
|
||||
conversation_id: body_string(body, "conversation_id"),
|
||||
@@ -736,13 +730,13 @@ fn replace_metadata_field(metadata: &mut Map<String, Value>, key: &str, value: O
|
||||
// 请求头的场景)
|
||||
fn apply_protocol_context(request: &mut CodexResponsesRequest, context: &Map<String, Value>) {
|
||||
request.passthrough_headers = decode_passthrough_headers(context);
|
||||
request.websocket_frame = context
|
||||
.get(gateway_protocol::openai::WEBSOCKET_FRAME_CONTEXT_KEY)
|
||||
.and_then(Value::as_bool)
|
||||
== Some(true);
|
||||
request.turn_metadata =
|
||||
context_string(context, "turn_metadata").or_else(|| request.turn_metadata.take());
|
||||
request.beta_features =
|
||||
context_string(context, "beta_features").or_else(|| request.beta_features.take());
|
||||
request.version = context_string(context, "version").or_else(|| request.version.take());
|
||||
request.include_timing_metrics = context_string(context, "include_timing_metrics")
|
||||
.or_else(|| request.include_timing_metrics.take());
|
||||
request.codex_window_id =
|
||||
context_string(context, "codex_window_id").or_else(|| request.codex_window_id.take());
|
||||
request.downstream_websocket_connection_id =
|
||||
|
||||
@@ -48,13 +48,15 @@ fn isolation_payload() -> ProtocolPayload {
|
||||
turn_metadata.insert("parent_response_id".to_owned(), json!("client-correlation"));
|
||||
turn_metadata.insert("workspace".to_owned(), json!("/工作区"));
|
||||
turn_metadata.insert("future".to_owned(), json!({"traceparent":"business-value"}));
|
||||
let mut frame_metadata = turn_metadata.clone();
|
||||
frame_metadata.insert("tool_namespaces_info".into(), json!({"workspace":{}}));
|
||||
let mut body = json!({
|
||||
"model": "gpt-5.4",
|
||||
"input": isolation_history(),
|
||||
"client_metadata": {
|
||||
"parent_response_id": "resp_parent_old",
|
||||
"guardian_credits_requested": "true",
|
||||
"x-codex-turn-metadata": Value::Object(turn_metadata.clone()).to_string(),
|
||||
"x-codex-turn-metadata": Value::Object(frame_metadata).to_string(),
|
||||
"turnMetadata": turn_metadata,
|
||||
"mcp_attribution": r#"{"status":"complete","sources":[]}"#
|
||||
}
|
||||
@@ -86,6 +88,10 @@ fn isolation_payload() -> ProtocolPayload {
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone())
|
||||
.unwrap()
|
||||
.with_context(Map::from_iter([
|
||||
(
|
||||
gateway_protocol::openai::WEBSOCKET_FRAME_CONTEXT_KEY.into(),
|
||||
json!(true),
|
||||
),
|
||||
("opaque_request_headers".to_owned(), json!(headers)),
|
||||
(
|
||||
"turn_metadata".to_owned(),
|
||||
@@ -155,7 +161,6 @@ fn assert_isolated_request(
|
||||
&body["turnMetadata"],
|
||||
&body["turn_metadata"],
|
||||
&body["client_metadata"]["turnMetadata"],
|
||||
&body["client_metadata"]["x-codex-turn-metadata"],
|
||||
] {
|
||||
let actual = match metadata {
|
||||
Value::String(raw) => serde_json::from_str(raw).unwrap(),
|
||||
@@ -163,6 +168,15 @@ fn assert_isolated_request(
|
||||
};
|
||||
assert_eq!(actual, Value::Object(expected_turn_metadata.clone()));
|
||||
}
|
||||
let mut expected_frame_metadata = expected_turn_metadata.clone();
|
||||
expected_frame_metadata.insert("tool_namespaces_info".into(), json!({"workspace":{}}));
|
||||
let frame = body["client_metadata"]["x-codex-turn-metadata"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(frame).unwrap(),
|
||||
Value::Object(expected_frame_metadata)
|
||||
);
|
||||
let header = headers["x-codex-turn-metadata"].to_str().unwrap();
|
||||
assert!(header.is_ascii());
|
||||
assert_eq!(
|
||||
|
||||
@@ -2,6 +2,45 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_body_fields_stay_in_the_body_when_using_http_upstream() {
|
||||
let frame = r#"{"request_kind":"turn","tool_namespaces_info":{"workspace":{}}}"#;
|
||||
let body = json!({
|
||||
"model": "gpt-5.4", "input": "hello",
|
||||
"client_metadata": {"x-codex-turn-metadata": frame},
|
||||
"betaFeatures": "only-in-body", "includeTimingMetrics": "true"
|
||||
});
|
||||
let sent = capture_scoped_http_request(
|
||||
"req_frame_only",
|
||||
"acct_scope_same",
|
||||
"acct_scope_same",
|
||||
body.as_object().unwrap().clone(),
|
||||
Map::from_iter([(
|
||||
gateway_protocol::openai::WEBSOCKET_FRAME_CONTEXT_KEY.into(),
|
||||
json!(true),
|
||||
)]),
|
||||
)
|
||||
.await;
|
||||
for header in [
|
||||
"x-codex-turn-metadata",
|
||||
"x-codex-beta-features",
|
||||
"x-responsesapi-include-timing-metrics",
|
||||
] {
|
||||
assert!(!sent.headers.contains_key(header), "{header}");
|
||||
}
|
||||
let sent_body = captured_request_body(&sent);
|
||||
let sent_frame = sent_body["client_metadata"]["x-codex-turn-metadata"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(sent_frame).unwrap(),
|
||||
serde_json::from_str::<Value>(frame).unwrap()
|
||||
);
|
||||
for key in ["betaFeatures", "includeTimingMetrics"] {
|
||||
assert_eq!(sent_body[key], body[key]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn responses_options_follow_the_selected_upstream_on_both_transports() {
|
||||
let oauth_omissions = json!({
|
||||
|
||||
@@ -431,8 +431,6 @@ fn context() -> CodexRequestContext<'static> {
|
||||
request_id: "req_catalog",
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
|
||||
@@ -34,8 +34,6 @@ fn request_context_debug_should_redact_all_identity_material() {
|
||||
request_id: "req_safe",
|
||||
turn_state: Some("turn-secret-marker"),
|
||||
turn_metadata: Some("metadata-secret-marker"),
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
|
||||
@@ -148,8 +148,15 @@ async fn backend_websocket_should_forward_context_headers_and_preserve_payload_f
|
||||
.expect("send terminal event");
|
||||
payload
|
||||
});
|
||||
let mut request =
|
||||
codex_request_with_prompt_cache_key("gpt-test", "be brief", Vec::new(), "client-thread");
|
||||
let mut body = codex_request_body("gpt-test", "be brief", Vec::new());
|
||||
body.insert("prompt_cache_key".into(), json!("client-thread"));
|
||||
let mut request = encode_request_with_headers(
|
||||
body,
|
||||
&[
|
||||
("x-codex-beta-features", "feature-a"),
|
||||
("x-responsesapi-include-timing-metrics", "true"),
|
||||
],
|
||||
);
|
||||
request.use_websocket = true;
|
||||
request.responses_lite = Some("true".to_owned());
|
||||
request.memgen_request = Some("true".to_owned());
|
||||
@@ -179,8 +186,6 @@ async fn backend_websocket_should_forward_context_headers_and_preserve_payload_f
|
||||
request_id: "req_ws_security",
|
||||
turn_state: Some("turn-state"),
|
||||
turn_metadata: Some("{\"thread_source\":\"subagent\"}"),
|
||||
beta_features: Some("feature-a"),
|
||||
include_timing_metrics: Some("true"),
|
||||
version: Some("26.318.11754"),
|
||||
codex_window_id: Some("cw_derived"),
|
||||
parent_thread_id: Some("parent-456"),
|
||||
@@ -264,11 +269,18 @@ async fn backend_http_should_send_codex_context_without_browser_headers() {
|
||||
write_completed_sse_response(&mut stream).await;
|
||||
request
|
||||
});
|
||||
let mut request = codex_request("gpt-test", "", Vec::new());
|
||||
let mut body = codex_request_body("gpt-test", "", Vec::new());
|
||||
body.insert("betaFeatures".into(), json!("body-beta"));
|
||||
body.insert("includeTimingMetrics".into(), json!("body-timing"));
|
||||
let mut request = encode_request_with_headers(
|
||||
body,
|
||||
&[
|
||||
("x-codex-beta-features", "beta-a"),
|
||||
("x-responsesapi-include-timing-metrics", "true"),
|
||||
],
|
||||
);
|
||||
request.force_http_sse = true;
|
||||
request.turn_metadata = Some("turn-meta".to_owned());
|
||||
request.beta_features = Some("beta-a".to_owned());
|
||||
request.include_timing_metrics = Some("true".to_owned());
|
||||
request.version = Some("26.707.51957".to_owned());
|
||||
request.codex_window_id = Some("cw_1".to_owned());
|
||||
request.parent_thread_id = Some("parent-1".to_owned());
|
||||
@@ -296,8 +308,6 @@ async fn backend_http_should_send_codex_context_without_browser_headers() {
|
||||
request_id: "req_order",
|
||||
turn_state: Some("turn-state"),
|
||||
turn_metadata: request.turn_metadata.as_deref(),
|
||||
beta_features: request.beta_features.as_deref(),
|
||||
include_timing_metrics: request.include_timing_metrics.as_deref(),
|
||||
version: request.version.as_deref(),
|
||||
codex_window_id: request.codex_window_id.as_deref(),
|
||||
parent_thread_id: request.parent_thread_id.as_deref(),
|
||||
@@ -429,8 +439,6 @@ async fn backend_http_should_ignore_unrepresentable_protocol_headers_without_blo
|
||||
thread_id: Some("opaque\nthread"),
|
||||
codex_window_id: Some("opaque\nwindow"),
|
||||
parent_thread_id: Some("opaque\nparent"),
|
||||
beta_features: Some("opaque\nbeta"),
|
||||
include_timing_metrics: Some("opaque\ntiming"),
|
||||
version: Some("opaque\nversion"),
|
||||
turn_state: request.turn_state.as_deref(),
|
||||
turn_metadata: request.turn_metadata.as_deref(),
|
||||
|
||||
@@ -130,8 +130,6 @@ async fn codex_backend_client_should_preserve_oversized_error_response() {
|
||||
request_id: "req_large_error",
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
@@ -230,8 +228,6 @@ async fn codex_backend_client_should_parse_retry_after_from_rate_limit_error_bod
|
||||
request_id: "req_http_retry_after_body",
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
@@ -415,8 +411,6 @@ async fn codex_backend_client_should_capture_forwardable_response_metadata() {
|
||||
request_id: "req_response_metadata",
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
|
||||
@@ -157,8 +157,6 @@ pub(crate) fn request_context<'a>(
|
||||
request_id,
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
@@ -356,6 +354,33 @@ fn codex_request_with_prompt_cache_key(
|
||||
CodexResponsesRequest::from_body(body)
|
||||
}
|
||||
|
||||
fn encode_request_with_headers(
|
||||
body: Map<String, Value>,
|
||||
headers: &[(&str, &str)],
|
||||
) -> CodexResponsesRequest {
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::operation::{GenerateRequest, ProtocolPayload};
|
||||
use provider_openai::transport::request::encode_generate_request;
|
||||
|
||||
let headers: Vec<_> = headers
|
||||
.iter()
|
||||
.map(|(name, value)| json!([name, STANDARD.encode(value)]))
|
||||
.collect();
|
||||
let model = body["model"].as_str().unwrap().to_owned();
|
||||
let payload = ProtocolPayload::json_object("openai", body)
|
||||
.unwrap()
|
||||
.with_context(Map::from_iter([(
|
||||
"opaque_request_headers".to_owned(),
|
||||
json!(headers),
|
||||
)]));
|
||||
encode_generate_request(
|
||||
&GenerateRequest::from_protocol_payload(payload),
|
||||
&model,
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn codex_request_body(
|
||||
model: impl Into<String>,
|
||||
instructions: impl Into<String>,
|
||||
|
||||
@@ -542,8 +542,6 @@ async fn fetch_should_use_wham_usage_headers_only() {
|
||||
request_id: "req_usage_headers",
|
||||
turn_state: Some("turn-state"),
|
||||
turn_metadata: Some("turn-meta"),
|
||||
beta_features: Some("feature-a"),
|
||||
include_timing_metrics: Some("true"),
|
||||
version: Some("26.318.11754"),
|
||||
codex_window_id: Some("cw_1"),
|
||||
parent_thread_id: Some("parent-1"),
|
||||
@@ -942,8 +940,6 @@ fn context() -> CodexRequestContext<'static> {
|
||||
request_id: "req_usage_limit",
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
|
||||
@@ -51,7 +51,7 @@ async fn official_websocket_wire_fingerprint_should_remain_aligned() {
|
||||
(opening, websocket_key, frame)
|
||||
});
|
||||
|
||||
let mut request = CodexResponsesRequest::from_body(
|
||||
let mut request = encode_request_with_headers(
|
||||
json!({
|
||||
"model": "gpt-5.5",
|
||||
"instructions": "be brief",
|
||||
@@ -70,11 +70,11 @@ async fn official_websocket_wire_fingerprint_should_remain_aligned() {
|
||||
.as_object()
|
||||
.expect("request object")
|
||||
.clone(),
|
||||
&[("x-codex-beta-features", "feature-a")],
|
||||
);
|
||||
request.use_websocket = true;
|
||||
request.local_conversation_id = Some("conversation-fingerprint".to_owned());
|
||||
request.turn_metadata = Some(r#"{"kind":"fingerprint"}"#.to_owned());
|
||||
request.beta_features = Some("feature-a".to_owned());
|
||||
request.version = Some("26.908.40834".to_owned());
|
||||
request.codex_window_id = Some("window-fingerprint".to_owned());
|
||||
let client = CodexBackendClient::new(
|
||||
@@ -94,7 +94,6 @@ async fn official_websocket_wire_fingerprint_should_remain_aligned() {
|
||||
response_control: None,
|
||||
trace: None,
|
||||
turn_metadata: request.turn_metadata.as_deref(),
|
||||
beta_features: request.beta_features.as_deref(),
|
||||
version: request.version.as_deref(),
|
||||
codex_window_id: request.codex_window_id.as_deref(),
|
||||
session_id: Some("session-fingerprint"),
|
||||
|
||||
@@ -2288,8 +2288,6 @@ async fn codex_backend_client_should_use_websocket_when_previous_response_id_is_
|
||||
request_id: "req_ws_client",
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
|
||||
@@ -542,6 +542,10 @@ Images 的 `x-codex-image-turn-id` 和 Desktop 自动 Git 上下文的 `clientUs
|
||||
续接 response ID、历史 item/call ID、业务正文和未知扩展不参与映射,
|
||||
该处理减少显式追踪标识的跨账号复用,不保证会话内容或业务 metadata 无法关联
|
||||
|
||||
`x-codex-turn-metadata` 请求头与 `client_metadata` 内的同名字段分别按账号处理并转发。
|
||||
WS 握手的轮次元数据头只随首次请求转发,后续帧在正文中携带本轮元数据。网关优先按当前帧识别普通对话和压缩请求。
|
||||
`x-codex-beta-features` 和 `x-responsesapi-include-timing-metrics` 按原始请求头透传
|
||||
|
||||
`x-codex-turn-state` 是上游签发的轮次路由 token。客户端在同一轮原样回传,新轮次省略。
|
||||
网关转发当前请求提供的值,明确换账号时清除。WS 握手携带的值只用于首次请求,当前帧提供的值优先。
|
||||
续接 response ID 及其他账号状态的归属独立校验
|
||||
|
||||
Reference in New Issue
Block a user