mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 00:00:49 +00:00
refactor(api): separate platform-specific data plane concerns
Move Codex client extensions and OpenAI-only endpoints into dedicated modules. Share HTTP transport rules and keep OpenAI identity filtering explicit. Remove redundant request metadata and test generation through actual routes. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -23,7 +23,7 @@ use crate::data_plane::{
|
||||
ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest,
|
||||
GenerationRequestMetadata, execute_prepared_generation,
|
||||
},
|
||||
responses::OpenAiRequestHeaders,
|
||||
headers::session_context,
|
||||
};
|
||||
|
||||
pub(in crate::data_plane) async fn chat_completions(
|
||||
@@ -92,13 +92,12 @@ pub(in crate::data_plane) fn decode_request(
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
field: "chat request".to_owned(),
|
||||
})?
|
||||
.with_context(OpenAiRequestHeaders::from_headers(headers).session_context());
|
||||
.with_context(session_context(headers));
|
||||
Ok(DecodedGenerationRequest {
|
||||
operation: Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model,
|
||||
stream,
|
||||
store: false,
|
||||
continuation: ContinuationIntent::None,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
//! Codex 模型目录的原生对象保留、通用画像投影与客户端权限裁剪
|
||||
|
||||
use crate::data_plane::{error::openai_error_response, service::DataPlaneService};
|
||||
use axum::{
|
||||
Json,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
routing::{PublicModelDescriptor, PublicModelProfile},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const CODEX_BASE_INSTRUCTIONS: &str = "You are Codex, a coding agent. Follow the user's instructions and use the available tools to complete software engineering tasks. Inspect relevant files before editing, preserve unrelated changes, and verify the result.";
|
||||
|
||||
pub(crate) async fn model_catalog(
|
||||
service: &DataPlaneService,
|
||||
client: &AuthenticatedClient,
|
||||
version: &str,
|
||||
) -> Response {
|
||||
let context = crate::middleware::current();
|
||||
if version.len() > 64
|
||||
|| !version
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b".-+".contains(&byte))
|
||||
{
|
||||
return openai_error_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid client_version.",
|
||||
"invalid_request_error",
|
||||
"invalid_client_version",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let catalog = match service
|
||||
.execution()
|
||||
.client_model_catalog(
|
||||
client,
|
||||
"codex",
|
||||
version,
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(catalog) => catalog,
|
||||
Err(_) => return catalog_unavailable_response(),
|
||||
};
|
||||
let models = catalog
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, entry)| match entry {
|
||||
PublicModelDescriptor::Adapted(profile) => Ok(adapted_codex_model_json(profile, index)),
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != "codex" {
|
||||
return Err(());
|
||||
}
|
||||
let mut value: Value = serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
let object = value.as_object_mut().ok_or(())?;
|
||||
// 别名只改变请求标识,能力、提示词、顺序等仍由上游目录决定
|
||||
object.insert("slug".to_owned(), Value::String(model.as_str().to_owned()));
|
||||
Ok(value)
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, ()>>();
|
||||
let Ok(mut models) = models else {
|
||||
return catalog_unavailable_response();
|
||||
};
|
||||
if !client.policy().account_scope().allows_subagents() {
|
||||
for model in &mut models {
|
||||
model["multi_agent_version"] = json!("disabled");
|
||||
}
|
||||
}
|
||||
(
|
||||
StatusCode::OK,
|
||||
// 目录经过账号选择/别名/多 Provider 聚合,不能借用上游 ETag 表示改写后的正文
|
||||
[("cache-control", "private, no-store")],
|
||||
Json(json!({
|
||||
"models": models,
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn catalog_unavailable_response() -> Response {
|
||||
openai_error_response(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Model catalog is temporarily unavailable.",
|
||||
"server_error",
|
||||
"model_catalog_unavailable",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn adapted_codex_model_json(profile: &PublicModelProfile, index: usize) -> Value {
|
||||
let id = profile.model().as_str();
|
||||
let presentation = profile.presentation();
|
||||
let reasoning_levels = presentation
|
||||
.supported_reasoning_efforts()
|
||||
.iter()
|
||||
.map(|effort| {
|
||||
json!({
|
||||
"effort": effort,
|
||||
"description": reasoning_effort_description(effort),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let reasoning_summary = presentation.reasoning_summary();
|
||||
let context_window = presentation.context_window_tokens();
|
||||
let max_context_window = presentation.max_context_window_tokens();
|
||||
let input_modalities = if presentation.image_input() {
|
||||
vec!["text", "image"]
|
||||
} else {
|
||||
vec!["text"]
|
||||
};
|
||||
let additional_speed_tiers = presentation
|
||||
.service_tiers()
|
||||
.iter()
|
||||
.filter_map(|tier| tier.speed_tier())
|
||||
.collect::<Vec<_>>();
|
||||
let service_tiers = presentation
|
||||
.service_tiers()
|
||||
.iter()
|
||||
.map(|tier| {
|
||||
json!({
|
||||
"id": tier.id(),
|
||||
"name": tier.name(),
|
||||
"description": tier.description(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
json!({
|
||||
"slug": id,
|
||||
"display_name": presentation.display_name().unwrap_or(id),
|
||||
"description": presentation.description(),
|
||||
"default_reasoning_level": presentation.default_reasoning_effort(),
|
||||
"supported_reasoning_levels": reasoning_levels,
|
||||
"shell_type": "shell_command",
|
||||
"visibility": if presentation.hidden() { "hide" } else { "list" },
|
||||
"supported_in_api": true,
|
||||
"priority": index.saturating_add(1),
|
||||
"additional_speed_tiers": additional_speed_tiers,
|
||||
"service_tiers": service_tiers,
|
||||
"availability_nux": Value::Null,
|
||||
"upgrade": Value::Null,
|
||||
"base_instructions": CODEX_BASE_INSTRUCTIONS,
|
||||
"model_messages": Value::Null,
|
||||
"include_skills_usage_instructions": false,
|
||||
"supports_reasoning_summary_parameter": reasoning_summary,
|
||||
"default_reasoning_summary": if reasoning_summary { "auto" } else { "none" },
|
||||
"support_verbosity": presentation.verbosity(),
|
||||
"default_verbosity": Value::Null,
|
||||
"apply_patch_tool_type": presentation.agent_tools().then_some("freeform"),
|
||||
"web_search_tool_type": "text",
|
||||
"truncation_policy": { "mode": "tokens", "limit": 10_000 },
|
||||
"supports_parallel_tool_calls": presentation.parallel_tool_calls(),
|
||||
"supports_image_detail_original": presentation.image_detail_original(),
|
||||
"context_window": context_window,
|
||||
"max_context_window": max_context_window,
|
||||
"effective_context_window_percent": 95,
|
||||
"experimental_supported_tools": [],
|
||||
"input_modalities": input_modalities,
|
||||
"supports_search_tool": presentation.search_tool(),
|
||||
// 通用画像没有 Responses Lite 支持依据,避免客户端启用未经声明的协议行为
|
||||
// 原生目录由 Native 分支保留上游字段,不经过此处
|
||||
"use_responses_lite": false,
|
||||
})
|
||||
}
|
||||
|
||||
fn reasoning_effort_description(effort: &str) -> &'static str {
|
||||
match effort {
|
||||
"none" => "No reasoning",
|
||||
"minimal" => "Minimal reasoning",
|
||||
"low" => "Fast responses with lighter reasoning",
|
||||
"medium" => "Balances speed and reasoning depth for everyday tasks",
|
||||
"high" => "Greater reasoning depth for complex problems",
|
||||
"xhigh" => "Extra high reasoning depth for complex problems",
|
||||
"max" => "Maximum reasoning depth for the hardest problems",
|
||||
_ => "Provider-supported reasoning level",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//! Codex 客户端的目录投影与请求身份扩展
|
||||
|
||||
mod catalog;
|
||||
mod request;
|
||||
|
||||
pub(crate) use catalog::model_catalog;
|
||||
pub(crate) use request::CodexRequestHeaders;
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Codex 请求身份、Guardian 与子代理元数据的客户端边界
|
||||
|
||||
use crate::data_plane::headers::header_string;
|
||||
use axum::http::HeaderMap;
|
||||
use gateway_core::operation::ClientTurn;
|
||||
use gateway_protocol::openai::{
|
||||
X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER, X_OPENAI_MEMGEN_REQUEST_HEADER,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
const OPENAI_SUBAGENT_KEY: &str = "x-openai-subagent";
|
||||
const PASSTHROUGH_HEADERS_CONTEXT_KEY: &str = "opaque_request_headers";
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct CodexRequestHeaders {
|
||||
guardian: Option<String>,
|
||||
ambiguous_guardian_headers: bool,
|
||||
turn_state: Option<String>,
|
||||
turn_metadata: Option<String>,
|
||||
version: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
turn_id: Option<String>,
|
||||
responses_lite: Option<String>,
|
||||
memgen_request: Option<String>,
|
||||
subagent: Option<String>,
|
||||
}
|
||||
|
||||
impl CodexRequestHeaders {
|
||||
pub(crate) fn from_headers(headers: &HeaderMap) -> Self {
|
||||
Self {
|
||||
guardian: header_string(headers, "x-codex-guardian"),
|
||||
ambiguous_guardian_headers: [
|
||||
"x-codex-guardian",
|
||||
OPENAI_SUBAGENT_KEY,
|
||||
"x-codex-turn-metadata",
|
||||
]
|
||||
.into_iter()
|
||||
.any(|name| {
|
||||
let mut values = headers.get_all(name).iter();
|
||||
values.next().is_some_and(|v| v.to_str().is_err()) || values.next().is_some()
|
||||
}),
|
||||
turn_state: header_string(headers, "x-codex-turn-state"),
|
||||
turn_metadata: header_string(headers, "x-codex-turn-metadata"),
|
||||
version: header_string(headers, "version"),
|
||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||
turn_id: header_string(headers, "x-codex-turn-id"),
|
||||
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn append_context(&self, context: &mut Map<String, Value>) {
|
||||
for (key, value) in [
|
||||
("turn_state", self.turn_state.as_ref()),
|
||||
("turn_metadata", self.turn_metadata.as_ref()),
|
||||
("subagent", self.subagent.as_ref()),
|
||||
("version", self.version.as_ref()),
|
||||
("codex_window_id", self.codex_window_id.as_ref()),
|
||||
("parent_thread_id", self.parent_thread_id.as_ref()),
|
||||
("turn_id", self.turn_id.as_ref()),
|
||||
("responses_lite", self.responses_lite.as_ref()),
|
||||
("memgen_request", self.memgen_request.as_ref()),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
context.insert(key.into(), Value::String(value.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply(
|
||||
&self,
|
||||
body: &mut Map<String, Value>,
|
||||
context: &mut Map<String, Value>,
|
||||
websocket_frame: bool,
|
||||
) -> Option<ClientTurn> {
|
||||
gateway_protocol::openai::capture_codex_guardian_identity(
|
||||
body,
|
||||
context,
|
||||
self.guardian.as_deref(),
|
||||
self.ambiguous_guardian_headers,
|
||||
);
|
||||
self.apply_subagent(body, context, websocket_frame);
|
||||
|
||||
let semantics = gateway_protocol::openai::codex_responses_request_semantics(body, context);
|
||||
if body.get("generate").and_then(Value::as_bool) != Some(false)
|
||||
&& semantics.request_kind.as_deref() == Some("turn")
|
||||
&& !semantics.compact
|
||||
{
|
||||
gateway_protocol::openai::codex_account_thread_id(body, context)
|
||||
.zip(gateway_protocol::openai::codex_turn_id(body, context))
|
||||
.and_then(|(thread, turn)| ClientTurn::new(thread, turn))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_subagent(
|
||||
&self,
|
||||
body: &mut Map<String, Value>,
|
||||
context: &mut Map<String, Value>,
|
||||
websocket_frame: bool,
|
||||
) {
|
||||
if websocket_frame
|
||||
&& let Some(frame_agent) = body
|
||||
.get("client_metadata")
|
||||
.and_then(|m| m.get(OPENAI_SUBAGENT_KEY))
|
||||
.and_then(Value::as_str)
|
||||
&& (frame_agent == "guardian"
|
||||
|| self.subagent.as_deref() == Some("guardian")
|
||||
|| self.guardian.is_some())
|
||||
{
|
||||
// 帧内声明优先;旧 opening 的不透明副本也不能在 Provider 再度覆盖
|
||||
let stale_subagent = self
|
||||
.subagent
|
||||
.as_deref()
|
||||
.is_some_and(|opening| opening != frame_agent);
|
||||
let stale_guardian = self.guardian.as_deref().is_some_and(|opening| {
|
||||
frame_agent != "guardian"
|
||||
|| gateway_protocol::openai::codex_guardian_role(body, context)
|
||||
.is_some_and(|role| role.header() != Some(opening))
|
||||
});
|
||||
if stale_subagent {
|
||||
context.insert("subagent".into(), Value::from(frame_agent));
|
||||
}
|
||||
if (stale_subagent || stale_guardian)
|
||||
&& let Some(Value::Array(headers)) =
|
||||
context.get_mut(PASSTHROUGH_HEADERS_CONTEXT_KEY)
|
||||
{
|
||||
headers.retain(|pair| match pair.get(0).and_then(Value::as_str) {
|
||||
Some(OPENAI_SUBAGENT_KEY) => !stale_subagent,
|
||||
Some("x-codex-guardian") => !stale_guardian,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(subagent) = self.subagent.as_deref() {
|
||||
inject_subagent_metadata(body, subagent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn inject_subagent_metadata(body: &mut Map<String, Value>, subagent: &str) {
|
||||
let metadata = body
|
||||
.entry("client_metadata".to_owned())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
let Some(metadata) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
metadata.insert(
|
||||
OPENAI_SUBAGENT_KEY.to_owned(),
|
||||
Value::String(subagent.to_owned()),
|
||||
);
|
||||
}
|
||||
@@ -113,7 +113,7 @@ pub(super) fn decode(
|
||||
}
|
||||
}
|
||||
context.insert("headers".into(), Value::Object(attribution));
|
||||
let passthrough = crate::data_plane::responses::request::passthrough_headers(headers);
|
||||
let passthrough = crate::data_plane::headers::passthrough_headers(headers);
|
||||
if !passthrough.is_empty() {
|
||||
context.insert("opaque_request_headers".into(), Value::Array(passthrough));
|
||||
}
|
||||
@@ -149,7 +149,6 @@ pub(super) fn decode(
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model.to_owned(),
|
||||
stream,
|
||||
store: false,
|
||||
continuation: ContinuationIntent::None,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
|
||||
@@ -32,7 +32,6 @@ use gateway_core::engine::{
|
||||
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
||||
use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
||||
use gateway_core::lifecycle::{CancellationToken, ConnectionGuard};
|
||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
use gateway_protocol::openai::sse::response_failed_sse_event_with_id;
|
||||
use tokio::time::Instant;
|
||||
|
||||
@@ -223,7 +222,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
}
|
||||
};
|
||||
let response = if let Some(keepalive) = keepalive {
|
||||
super::keepalive::response_with_encoder(
|
||||
super::keepalive::response(
|
||||
response,
|
||||
keepalive,
|
||||
stream_error,
|
||||
@@ -472,55 +471,6 @@ async fn streaming_execution_middleware_response(
|
||||
))
|
||||
}
|
||||
|
||||
/// 直接驱动测试 session 的非流式交付;生产入口通过同一 MiddlewareResponse 路径
|
||||
pub async fn collect_execution_response(session: Box<dyn ExecutionSession>) -> Response {
|
||||
match buffered_execution_middleware_response(
|
||||
session,
|
||||
GenerationValidationFacts::new(GenerationEndpoint::Responses),
|
||||
GenerationEndpoint::Responses,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
into_http_response(response, ExpectedBody::SingleJson, OPENAI_PROTOCOL).await
|
||||
}
|
||||
Err(error) => error_response(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// 直接驱动测试 session 的 SSE 交付;生产入口通过同一 MiddlewareResponse 路径
|
||||
pub async fn stream_execution_response(
|
||||
session: Box<dyn ExecutionSession>,
|
||||
connection_guard: Option<Box<dyn ConnectionGuard>>,
|
||||
) -> Response {
|
||||
let (admitted, keepalive) = tokio::sync::oneshot::channel();
|
||||
let _ = admitted.send(session.response_commit());
|
||||
super::keepalive::response(
|
||||
async move {
|
||||
match streaming_execution_middleware_response(
|
||||
session,
|
||||
connection_guard,
|
||||
GenerationValidationFacts::new(GenerationEndpoint::Responses),
|
||||
GenerationEndpoint::Responses,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
into_http_response(
|
||||
response,
|
||||
GenerationEndpoint::Responses.expected_http_body(true),
|
||||
OPENAI_PROTOCOL,
|
||||
)
|
||||
.await
|
||||
}
|
||||
Err(error) => error_response(error),
|
||||
}
|
||||
},
|
||||
keepalive,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn validated_middleware_response(
|
||||
response: MiddlewareResponse,
|
||||
facts: GenerationValidationFacts,
|
||||
@@ -733,9 +683,9 @@ fn apply_provider_response_headers(
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> Response {
|
||||
let connection_options =
|
||||
crate::data_plane::responses::response_connection_options(response_headers);
|
||||
crate::data_plane::headers::response_connection_options(response_headers);
|
||||
for header in response_headers {
|
||||
if !crate::data_plane::responses::response_header_is_forwardable(
|
||||
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
) {
|
||||
@@ -757,7 +707,7 @@ fn response_headers(
|
||||
streaming: bool,
|
||||
) -> Vec<MiddlewareHeader> {
|
||||
let connection_options =
|
||||
crate::data_plane::responses::response_connection_options(provider_headers);
|
||||
crate::data_plane::headers::response_connection_options(provider_headers);
|
||||
let mut headers = Vec::new();
|
||||
headers.push(MiddlewareHeader::new(
|
||||
CONTENT_TYPE.as_str(),
|
||||
@@ -768,7 +718,7 @@ fn response_headers(
|
||||
}),
|
||||
));
|
||||
for header in provider_headers {
|
||||
if !crate::data_plane::responses::response_header_is_forwardable(
|
||||
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
) || header.name().eq_ignore_ascii_case(CONTENT_TYPE.as_str())
|
||||
|
||||
@@ -21,13 +21,6 @@ use crate::data_plane::middleware::{SSE_KEEPALIVE_FRAME, SSE_KEEPALIVE_INTERVAL}
|
||||
pub(in crate::data_plane) async fn response(
|
||||
response: impl Future<Output = Response> + Send + 'static,
|
||||
admitted: oneshot::Receiver<ResponseCommit>,
|
||||
) -> Response {
|
||||
response_with_encoder(response, admitted, None, true).await
|
||||
}
|
||||
|
||||
pub(in crate::data_plane) async fn response_with_encoder(
|
||||
response: impl Future<Output = Response> + Send + 'static,
|
||||
admitted: oneshot::Receiver<ResponseCommit>,
|
||||
error_encoder: Option<fn(&Value) -> Bytes>,
|
||||
append_done: bool,
|
||||
) -> Response {
|
||||
|
||||
@@ -32,12 +32,11 @@ impl fmt::Debug for ContinuationIntent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Handler、Router 和 history owner 使用的请求元数据
|
||||
/// 生成入口的路由、续接与客户端观测事实
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct GenerationRequestMetadata {
|
||||
pub(in crate::data_plane) requested_model: String,
|
||||
pub(in crate::data_plane) stream: bool,
|
||||
pub(in crate::data_plane) store: bool,
|
||||
pub(in crate::data_plane) continuation: ContinuationIntent,
|
||||
pub(in crate::data_plane) client_ip: Option<IpAddr>,
|
||||
pub(in crate::data_plane) user_agent: Option<String>,
|
||||
@@ -56,12 +55,6 @@ impl GenerationRequestMetadata {
|
||||
self.stream
|
||||
}
|
||||
|
||||
/// 返回客户端 storage intent
|
||||
#[must_use]
|
||||
pub const fn store(&self) -> bool {
|
||||
self.store
|
||||
}
|
||||
|
||||
/// 返回 continuation intent
|
||||
#[must_use]
|
||||
pub const fn continuation(&self) -> &ContinuationIntent {
|
||||
@@ -87,7 +80,6 @@ impl fmt::Debug for GenerationRequestMetadata {
|
||||
.debug_struct("GenerationRequestMetadata")
|
||||
.field("requested_model", &self.requested_model)
|
||||
.field("stream", &self.stream)
|
||||
.field("store", &self.store)
|
||||
.field("continuation", &self.continuation)
|
||||
.field("client_ip", &self.client_ip)
|
||||
.field("has_user_agent", &self.user_agent.is_some())
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! 数据面入站业务头与上游响应头的公共传输边界
|
||||
|
||||
use axum::http::{HeaderMap, HeaderName, HeaderValue};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::event::ProviderResponseHeader;
|
||||
use gateway_protocol::http::is_transport_managed_request_header;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// 出口统一剥离已知账号身份,过滤范围不随客户端选择的协议变化
|
||||
pub(crate) fn response_header_is_forwardable(name: &str, connection_options: &[String]) -> bool {
|
||||
gateway_protocol::http::response_header_is_forwardable(name, connection_options)
|
||||
&& !gateway_protocol::openai::is_private_response_header(name)
|
||||
}
|
||||
|
||||
pub(crate) fn response_connection_options(headers: &[ProviderResponseHeader]) -> Vec<String> {
|
||||
headers
|
||||
.iter()
|
||||
.filter(|header| header.name().trim().eq_ignore_ascii_case("connection"))
|
||||
.filter_map(|header| std::str::from_utf8(header.value()).ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn passthrough_headers(headers: &HeaderMap) -> Vec<Value> {
|
||||
passthrough_request_headers(headers)
|
||||
.map(|(name, value)| {
|
||||
Value::Array(vec![
|
||||
Value::String(name.as_str().to_owned()),
|
||||
Value::String(STANDARD.encode(value.as_bytes())),
|
||||
])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// HTTP 与 Live 入站共用的身份、传输边界;保留业务头原始多值字节
|
||||
pub(crate) fn passthrough_request_headers(
|
||||
headers: &HeaderMap,
|
||||
) -> impl Iterator<Item = (&HeaderName, &HeaderValue)> {
|
||||
let connection_headers = headers
|
||||
.get_all("connection")
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
headers
|
||||
.iter()
|
||||
.filter(move |(name, _)| passthrough_header_name(name.as_str(), &connection_headers))
|
||||
}
|
||||
|
||||
fn passthrough_header_name(name: &str, connection_headers: &[String]) -> bool {
|
||||
if connection_headers
|
||||
.iter()
|
||||
.any(|connection_header| connection_header.eq_ignore_ascii_case(name))
|
||||
|| is_transport_managed_request_header(name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
!matches!(
|
||||
name,
|
||||
// 下游鉴权和账号 cookie 绝不能成为上游账号身份
|
||||
"authorization"
|
||||
| "x-api-key"
|
||||
| "x-goog-api-key"
|
||||
// Codex 的服务端托管认证标记只用于客户端能力判断,不代表上游身份
|
||||
| "x-openai-actor-authorization"
|
||||
| "cookie"
|
||||
| "cookie2"
|
||||
| "chatgpt-account-id"
|
||||
| "chatgpt-project-id"
|
||||
| "openai-organization"
|
||||
| "openai-project"
|
||||
// 上游指纹必须由运行时画像统一生成,客户端 originator/User-Agent/version
|
||||
// 不能作为不透明头透传覆盖,避免不同下游客户端暴露不一致的设备指纹
|
||||
| "originator"
|
||||
| "user-agent"
|
||||
| "version"
|
||||
// 设备 attestation/integrity 头只能由官方客户端或网关自身生成,
|
||||
// 客户端注入的 x-oai-attestation / X-OAI-IS 不得透传上游
|
||||
| "x-oai-attestation"
|
||||
| "x-oai-is"
|
||||
| "x-oai-is-update"
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
/// 共享会话头与不透明业务头,不继承 Responses 的续接和连接状态
|
||||
pub(crate) fn session_context(headers: &HeaderMap) -> Map<String, Value> {
|
||||
let mut context = Map::new();
|
||||
for (key, value) in [
|
||||
(
|
||||
"session_id",
|
||||
header_string(headers, "session-id").or_else(|| header_string(headers, "session_id")),
|
||||
),
|
||||
("thread_id", header_string(headers, "thread-id")),
|
||||
(
|
||||
"turn_metadata",
|
||||
header_string(headers, "x-codex-turn-metadata"),
|
||||
),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
context.insert(key.into(), Value::String(value));
|
||||
}
|
||||
}
|
||||
let passthrough = passthrough_headers(headers);
|
||||
if !passthrough.is_empty() {
|
||||
context.insert("opaque_request_headers".into(), Value::Array(passthrough));
|
||||
}
|
||||
context
|
||||
}
|
||||
@@ -23,7 +23,7 @@ use super::{
|
||||
ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest,
|
||||
GenerationRequestMetadata, execute_prepared_generation,
|
||||
},
|
||||
responses::OpenAiRequestHeaders,
|
||||
headers::session_context,
|
||||
};
|
||||
use crate::ApiState;
|
||||
|
||||
@@ -147,7 +147,7 @@ pub(super) fn decode_request(
|
||||
.get("stream")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let context = OpenAiRequestHeaders::from_headers(headers).session_context();
|
||||
let context = session_context(headers);
|
||||
let operation = if counted {
|
||||
let payload = RawJsonPayload::new(protocol.wire(), Bytes::copy_from_slice(&body))
|
||||
.map_err(|_| invalid("Request protocol is invalid."))?
|
||||
@@ -164,7 +164,6 @@ pub(super) fn decode_request(
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model,
|
||||
stream,
|
||||
store: false,
|
||||
continuation: ContinuationIntent::None,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
|
||||
@@ -3,20 +3,19 @@
|
||||
pub mod auth;
|
||||
pub mod body;
|
||||
mod chat_completions;
|
||||
mod codex;
|
||||
pub mod error;
|
||||
pub(crate) mod genai;
|
||||
pub mod generation;
|
||||
pub mod images;
|
||||
pub(crate) mod live;
|
||||
mod headers;
|
||||
mod messages;
|
||||
pub(crate) mod middleware;
|
||||
pub mod models;
|
||||
mod openai_endpoints;
|
||||
mod models;
|
||||
mod openai;
|
||||
mod peer_link;
|
||||
mod provider_endpoints;
|
||||
pub mod responses;
|
||||
pub mod router;
|
||||
pub mod search;
|
||||
pub(crate) mod router;
|
||||
pub(crate) mod service;
|
||||
mod usage;
|
||||
|
||||
|
||||
@@ -6,10 +6,7 @@ use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
routing::{PublicModelDescriptor, PublicModelId, PublicModelProfile},
|
||||
};
|
||||
use gateway_core::{engine::execution::AuthenticatedClient, routing::PublicModelId};
|
||||
use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
@@ -25,7 +22,6 @@ use super::{
|
||||
};
|
||||
|
||||
const MODEL_CREATED_TIMESTAMP: i64 = 1_700_000_000;
|
||||
const CODEX_BASE_INSTRUCTIONS: &str = "You are Codex, a coding agent. Follow the user's instructions and use the available tools to complete software engineering tasks. Inspect relevant files before editing, preserve unrelated changes, and verify the result.";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub(crate) struct ModelsQuery {
|
||||
@@ -78,60 +74,7 @@ async fn models_response(
|
||||
.as_deref()
|
||||
.filter(|version| !version.trim().is_empty())
|
||||
{
|
||||
if version.len() > 64
|
||||
|| !version
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b".-+".contains(&byte))
|
||||
{
|
||||
return openai_error_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Invalid client_version.",
|
||||
"invalid_request_error",
|
||||
"invalid_client_version",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let catalog = match service.client_model_catalog(&client, version).await {
|
||||
Ok(catalog) => catalog,
|
||||
Err(_) => return catalog_unavailable_response(),
|
||||
};
|
||||
let models = catalog
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, entry)| match entry {
|
||||
PublicModelDescriptor::Adapted(profile) => {
|
||||
Ok(adapted_codex_model_json(profile, index))
|
||||
}
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != "codex" {
|
||||
return Err(());
|
||||
}
|
||||
let mut value: Value =
|
||||
serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
let object = value.as_object_mut().ok_or(())?;
|
||||
// 别名只改变请求标识,能力、提示词、顺序等仍由上游目录决定
|
||||
object.insert("slug".to_owned(), Value::String(model.as_str().to_owned()));
|
||||
Ok(value)
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, ()>>();
|
||||
let Ok(mut models) = models else {
|
||||
return catalog_unavailable_response();
|
||||
};
|
||||
if !client.policy().account_scope().allows_subagents() {
|
||||
for model in &mut models {
|
||||
model["multi_agent_version"] = json!("disabled");
|
||||
}
|
||||
}
|
||||
return (
|
||||
StatusCode::OK,
|
||||
// 目录经过账号选择/别名/多 Provider 聚合,不能借用上游 ETag 表示改写后的正文
|
||||
[("cache-control", "private, no-store")],
|
||||
Json(json!({
|
||||
"models": models,
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
return super::codex::model_catalog(service, &client, version).await;
|
||||
}
|
||||
|
||||
let data = service
|
||||
@@ -149,16 +92,6 @@ async fn models_response(
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn catalog_unavailable_response() -> Response {
|
||||
openai_error_response(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Model catalog is temporarily unavailable.",
|
||||
"server_error",
|
||||
"model_catalog_unavailable",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// `GET /v1/models/{model_id}`
|
||||
pub(crate) async fn model_detail(
|
||||
State(state): State<ApiState>,
|
||||
@@ -285,92 +218,3 @@ fn openai_model_json(id: &str) -> Value {
|
||||
"owned_by": "gateway",
|
||||
})
|
||||
}
|
||||
|
||||
fn adapted_codex_model_json(profile: &PublicModelProfile, index: usize) -> Value {
|
||||
let id = profile.model().as_str();
|
||||
let presentation = profile.presentation();
|
||||
let reasoning_levels = presentation
|
||||
.supported_reasoning_efforts()
|
||||
.iter()
|
||||
.map(|effort| {
|
||||
json!({
|
||||
"effort": effort,
|
||||
"description": reasoning_effort_description(effort),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let reasoning_summary = presentation.reasoning_summary();
|
||||
let context_window = presentation.context_window_tokens();
|
||||
let max_context_window = presentation.max_context_window_tokens();
|
||||
let input_modalities = if presentation.image_input() {
|
||||
vec!["text", "image"]
|
||||
} else {
|
||||
vec!["text"]
|
||||
};
|
||||
let additional_speed_tiers = presentation
|
||||
.service_tiers()
|
||||
.iter()
|
||||
.filter_map(|tier| tier.speed_tier())
|
||||
.collect::<Vec<_>>();
|
||||
let service_tiers = presentation
|
||||
.service_tiers()
|
||||
.iter()
|
||||
.map(|tier| {
|
||||
json!({
|
||||
"id": tier.id(),
|
||||
"name": tier.name(),
|
||||
"description": tier.description(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
json!({
|
||||
"slug": id,
|
||||
"display_name": presentation.display_name().unwrap_or(id),
|
||||
"description": presentation.description(),
|
||||
"default_reasoning_level": presentation.default_reasoning_effort(),
|
||||
"supported_reasoning_levels": reasoning_levels,
|
||||
"shell_type": "shell_command",
|
||||
"visibility": if presentation.hidden() { "hide" } else { "list" },
|
||||
"supported_in_api": true,
|
||||
"priority": index.saturating_add(1),
|
||||
"additional_speed_tiers": additional_speed_tiers,
|
||||
"service_tiers": service_tiers,
|
||||
"availability_nux": Value::Null,
|
||||
"upgrade": Value::Null,
|
||||
"base_instructions": CODEX_BASE_INSTRUCTIONS,
|
||||
"model_messages": Value::Null,
|
||||
"include_skills_usage_instructions": false,
|
||||
"supports_reasoning_summary_parameter": reasoning_summary,
|
||||
"default_reasoning_summary": if reasoning_summary { "auto" } else { "none" },
|
||||
"support_verbosity": presentation.verbosity(),
|
||||
"default_verbosity": Value::Null,
|
||||
"apply_patch_tool_type": presentation.agent_tools().then_some("freeform"),
|
||||
"web_search_tool_type": "text",
|
||||
"truncation_policy": { "mode": "tokens", "limit": 10_000 },
|
||||
"supports_parallel_tool_calls": presentation.parallel_tool_calls(),
|
||||
"supports_image_detail_original": presentation.image_detail_original(),
|
||||
"context_window": context_window,
|
||||
"max_context_window": max_context_window,
|
||||
"effective_context_window_percent": 95,
|
||||
"experimental_supported_tools": [],
|
||||
"input_modalities": input_modalities,
|
||||
"supports_search_tool": presentation.search_tool(),
|
||||
// 通用画像没有 Responses Lite 支持依据,避免客户端启用未经声明的协议行为
|
||||
// 原生目录由 Native 分支保留上游字段,不经过此处
|
||||
"use_responses_lite": false,
|
||||
})
|
||||
}
|
||||
|
||||
fn reasoning_effort_description(effort: &str) -> &'static str {
|
||||
match effort {
|
||||
"none" => "No reasoning",
|
||||
"minimal" => "Minimal reasoning",
|
||||
"low" => "Fast responses with lighter reasoning",
|
||||
"medium" => "Balances speed and reasoning depth for everyday tasks",
|
||||
"high" => "Greater reasoning depth for complex problems",
|
||||
"xhigh" => "Extra high reasoning depth for complex problems",
|
||||
"max" => "Maximum reasoning depth for the hardest problems",
|
||||
_ => "Provider-supported reasoning level",
|
||||
}
|
||||
}
|
||||
|
||||
+9
-5
@@ -36,7 +36,7 @@ use crate::data_plane::middleware::{
|
||||
use crate::middleware::headers::encode_headers;
|
||||
use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
||||
|
||||
use super::{
|
||||
use crate::data_plane::{
|
||||
error::{engine_error_response, gateway_error_response, protocol_error_response},
|
||||
service::DataPlaneService,
|
||||
};
|
||||
@@ -142,7 +142,7 @@ where
|
||||
let mut response = if response.headers().contains_key("x-gateway-request-id") {
|
||||
response
|
||||
} else {
|
||||
super::with_model_request_id(response, &request_id)
|
||||
crate::data_plane::with_model_request_id(response, &request_id)
|
||||
};
|
||||
response
|
||||
.extensions_mut()
|
||||
@@ -176,7 +176,7 @@ async fn collect_raw_json_response(
|
||||
},
|
||||
Err(error) => engine_error_response(&error),
|
||||
};
|
||||
let response = super::with_model_request_id(response, &started.request_id);
|
||||
let response = crate::data_plane::with_model_request_id(response, &started.request_id);
|
||||
let (parts, body) = response.into_parts();
|
||||
let framing = if parts.status.is_success() {
|
||||
MiddlewareFraming::JsonDocument
|
||||
@@ -229,9 +229,13 @@ fn apply_response_headers(
|
||||
mut response: Response,
|
||||
response_headers: &[ProviderResponseHeader],
|
||||
) -> Response {
|
||||
let connection_options = super::responses::response_connection_options(response_headers);
|
||||
let connection_options =
|
||||
crate::data_plane::headers::response_connection_options(response_headers);
|
||||
for header in response_headers {
|
||||
if !super::responses::response_header_is_forwardable(header.name(), &connection_options) {
|
||||
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||
+4
-4
@@ -21,9 +21,9 @@ use crate::ApiState;
|
||||
use crate::data_plane::middleware::RequestInput;
|
||||
use crate::data_plane::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
openai_endpoints::provider_endpoint_response,
|
||||
responses::OpenAiRequestHeaders,
|
||||
router::{IMAGE_EDITS_PATH, IMAGE_GENERATIONS_PATH},
|
||||
headers::session_context,
|
||||
openai::endpoints::provider_endpoint_response,
|
||||
openai::{IMAGE_EDITS_PATH, IMAGE_GENERATIONS_PATH},
|
||||
};
|
||||
use crate::middleware::headers::encode_headers;
|
||||
|
||||
@@ -111,7 +111,7 @@ async fn image_operation(
|
||||
} else {
|
||||
body
|
||||
};
|
||||
let mut context = OpenAiRequestHeaders::from_headers(&headers).session_context();
|
||||
let mut context = session_context(&headers);
|
||||
if let Some(turn_id) = headers
|
||||
.get("x-codex-image-turn-id")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
+3
-3
@@ -131,7 +131,7 @@ pub(crate) fn realtime_unsupported_response(capability: &str) -> Response {
|
||||
|
||||
/// 共用 OpenAI 入站头边界;Content-Type 由正文适配结果单独提供
|
||||
pub(crate) fn filter_protocol_headers(headers: &HeaderMap) -> Vec<ProviderHttpHeader> {
|
||||
super::responses::passthrough_request_headers(headers)
|
||||
crate::data_plane::headers::passthrough_request_headers(headers)
|
||||
.filter(|(name, _)| *name != header::CONTENT_TYPE)
|
||||
.map(|(name, value)| {
|
||||
ProviderHttpHeader::new(name.as_str(), Bytes::copy_from_slice(value.as_bytes()))
|
||||
@@ -268,12 +268,12 @@ pub(crate) fn encode_call_request(
|
||||
pub(crate) fn live_forwarded_response_headers(
|
||||
headers: &[ProviderResponseHeader],
|
||||
) -> Vec<(HeaderName, HeaderValue)> {
|
||||
let connection_options = super::responses::response_connection_options(headers);
|
||||
let connection_options = crate::data_plane::headers::response_connection_options(headers);
|
||||
headers
|
||||
.iter()
|
||||
.filter(|header| {
|
||||
header.name().eq_ignore_ascii_case("content-type")
|
||||
|| super::responses::response_header_is_forwardable(
|
||||
|| crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
)
|
||||
+1
-1
@@ -24,7 +24,7 @@ use crate::{
|
||||
data_plane::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
error::runtime_unavailable_response,
|
||||
live::{
|
||||
openai::live::{
|
||||
filter_protocol_headers, live_error_response, offered_subprotocols,
|
||||
realtime_unsupported_response,
|
||||
},
|
||||
@@ -0,0 +1,20 @@
|
||||
//! 绑定 OpenAI Provider 的 Images、独立搜索与 Live 客户端入口
|
||||
|
||||
mod endpoints;
|
||||
mod images;
|
||||
mod live;
|
||||
mod search;
|
||||
|
||||
use axum::{Router, routing::post};
|
||||
|
||||
pub(crate) const IMAGE_GENERATIONS_PATH: &str = "/v1/images/generations";
|
||||
pub(crate) const IMAGE_EDITS_PATH: &str = "/v1/images/edits";
|
||||
pub(crate) const SEARCH_PATH: &str = "/v1/alpha/search";
|
||||
|
||||
pub(crate) fn router() -> Router<crate::ApiState> {
|
||||
Router::new()
|
||||
.route(IMAGE_GENERATIONS_PATH, post(images::image_generations))
|
||||
.route(IMAGE_EDITS_PATH, post(images::image_edits))
|
||||
.route(SEARCH_PATH, post(search::standalone_search))
|
||||
.merge(live::router())
|
||||
}
|
||||
+4
-4
@@ -18,9 +18,9 @@ use crate::ApiState;
|
||||
use crate::data_plane::middleware::RequestInput;
|
||||
use crate::data_plane::{
|
||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||
openai_endpoints::provider_endpoint_response,
|
||||
responses::OpenAiRequestHeaders,
|
||||
router::SEARCH_PATH,
|
||||
headers::session_context,
|
||||
openai::SEARCH_PATH,
|
||||
openai::endpoints::provider_endpoint_response,
|
||||
};
|
||||
use crate::middleware::headers::encode_headers;
|
||||
|
||||
@@ -60,7 +60,7 @@ pub(crate) async fn standalone_search(
|
||||
}
|
||||
|
||||
fn search_operation(body: Bytes, headers: &HeaderMap) -> Result<Operation, GatewayError> {
|
||||
let context = OpenAiRequestHeaders::from_headers(headers).session_context();
|
||||
let context = session_context(headers);
|
||||
let payload = RawJsonPayload::new(OPENAI_PROTOCOL, body)
|
||||
.map_err(|_| {
|
||||
GatewayError::new(
|
||||
@@ -8,28 +8,10 @@ pub(in crate::data_plane) mod validation;
|
||||
pub mod websocket;
|
||||
|
||||
pub use crate::client_error::{ProtocolError, ProtocolErrorBody};
|
||||
pub use crate::data_plane::generation::http::{
|
||||
collect_execution_response, stream_execution_response,
|
||||
};
|
||||
pub use error::ResponseEncodeError;
|
||||
pub(crate) use http::responses;
|
||||
pub(crate) use request::decode_request_with_body;
|
||||
pub use request::{OpenAiRequestHeaders, decode_request_with_headers};
|
||||
pub(crate) use request::{decode_request_with_body, passthrough_request_headers};
|
||||
pub use response::OpenAiResponsesEncoder;
|
||||
pub(crate) use websocket::responses_websocket;
|
||||
pub use websocket::{ResponseCreateFrameError, decode_response_create_with_context};
|
||||
|
||||
use gateway_core::event::ProviderResponseHeader;
|
||||
pub(super) use gateway_protocol::openai::response_header_is_forwardable;
|
||||
|
||||
pub(super) fn response_connection_options(headers: &[ProviderResponseHeader]) -> Vec<String> {
|
||||
headers
|
||||
.iter()
|
||||
.filter(|header| header.name().trim().eq_ignore_ascii_case("connection"))
|
||||
.filter_map(|header| std::str::from_utf8(header.value()).ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
//! OpenAI Responses JSON 到 Core 路由事实与不透明 wire payload 的单一解码边界
|
||||
|
||||
use crate::data_plane::body::decompress_request_body;
|
||||
use crate::data_plane::codex::CodexRequestHeaders;
|
||||
use crate::data_plane::headers::{header_string, passthrough_headers};
|
||||
|
||||
use axum::http::{HeaderMap, HeaderName, HeaderValue};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use axum::http::HeaderMap;
|
||||
use bytes::Bytes;
|
||||
use gateway_core::operation::{ClientTurn, GenerateRequest, Operation, ProtocolPayload};
|
||||
use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload};
|
||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||
use gateway_protocol::openai::{
|
||||
X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER, X_OPENAI_MEMGEN_REQUEST_HEADER,
|
||||
is_transport_managed_request_header,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::data_plane::body::RequestDecodeError;
|
||||
@@ -18,7 +15,6 @@ use crate::data_plane::generation::{
|
||||
ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata,
|
||||
};
|
||||
|
||||
const OPENAI_SUBAGENT_KEY: &str = "x-openai-subagent";
|
||||
const PASSTHROUGH_HEADERS_CONTEXT_KEY: &str = "opaque_request_headers";
|
||||
const DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY: &str = "downstream_websocket_connection_id";
|
||||
|
||||
@@ -33,24 +29,14 @@ pub(super) enum RequestDecodeSource {
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct OpenAiRequestHeaders {
|
||||
guardian: Option<String>,
|
||||
ambiguous_guardian_headers: bool,
|
||||
turn_state: Option<String>,
|
||||
turn_metadata: Option<String>,
|
||||
version: Option<String>,
|
||||
codex_window_id: Option<String>,
|
||||
parent_thread_id: Option<String>,
|
||||
codex: CodexRequestHeaders,
|
||||
downstream_websocket_connection_id: Option<String>,
|
||||
|
||||
conversation_id: Option<String>,
|
||||
session_id: Option<String>,
|
||||
thread_id: Option<String>,
|
||||
client_request_id: Option<String>,
|
||||
turn_id: Option<String>,
|
||||
|
||||
responses_lite: Option<String>,
|
||||
memgen_request: Option<String>,
|
||||
subagent: Option<String>,
|
||||
passthrough_headers: Vec<Value>,
|
||||
}
|
||||
|
||||
@@ -59,22 +45,7 @@ impl OpenAiRequestHeaders {
|
||||
#[must_use]
|
||||
pub fn from_headers(headers: &HeaderMap) -> Self {
|
||||
Self {
|
||||
guardian: header_string(headers, "x-codex-guardian"),
|
||||
ambiguous_guardian_headers: [
|
||||
"x-codex-guardian",
|
||||
OPENAI_SUBAGENT_KEY,
|
||||
"x-codex-turn-metadata",
|
||||
]
|
||||
.into_iter()
|
||||
.any(|name| {
|
||||
let mut values = headers.get_all(name).iter();
|
||||
values.next().is_some_and(|v| v.to_str().is_err()) || values.next().is_some()
|
||||
}),
|
||||
turn_state: header_string(headers, "x-codex-turn-state"),
|
||||
turn_metadata: header_string(headers, "x-codex-turn-metadata"),
|
||||
version: header_string(headers, "version"),
|
||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||
codex: CodexRequestHeaders::from_headers(headers),
|
||||
downstream_websocket_connection_id: None,
|
||||
conversation_id: header_string(headers, "conversation-id")
|
||||
.or_else(|| header_string(headers, "conversation_id")),
|
||||
@@ -82,10 +53,6 @@ impl OpenAiRequestHeaders {
|
||||
.or_else(|| header_string(headers, "session_id")),
|
||||
thread_id: header_string(headers, "thread-id"),
|
||||
client_request_id: header_string(headers, "x-client-request-id"),
|
||||
turn_id: header_string(headers, "x-codex-turn-id"),
|
||||
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||
passthrough_headers: passthrough_headers(headers),
|
||||
}
|
||||
}
|
||||
@@ -100,61 +67,6 @@ impl OpenAiRequestHeaders {
|
||||
self
|
||||
}
|
||||
|
||||
fn apply_subagent(
|
||||
&self,
|
||||
body: &mut Map<String, Value>,
|
||||
context: &mut Map<String, Value>,
|
||||
source: RequestDecodeSource,
|
||||
) {
|
||||
if matches!(source, RequestDecodeSource::WebSocketFrame)
|
||||
&& let Some(frame_agent) = body
|
||||
.get("client_metadata")
|
||||
.and_then(|m| m.get(OPENAI_SUBAGENT_KEY))
|
||||
.and_then(Value::as_str)
|
||||
&& (frame_agent == "guardian"
|
||||
|| self.subagent.as_deref() == Some("guardian")
|
||||
|| self.guardian.is_some())
|
||||
{
|
||||
// 帧内声明优先;旧 opening 的不透明副本也不能在 Provider 再度覆盖
|
||||
let stale_subagent = self
|
||||
.subagent
|
||||
.as_deref()
|
||||
.is_some_and(|opening| opening != frame_agent);
|
||||
let stale_guardian = self.guardian.as_deref().is_some_and(|opening| {
|
||||
frame_agent != "guardian"
|
||||
|| gateway_protocol::openai::codex_guardian_role(body, context)
|
||||
.is_some_and(|role| role.header() != Some(opening))
|
||||
});
|
||||
if stale_subagent {
|
||||
context.insert("subagent".into(), Value::from(frame_agent));
|
||||
}
|
||||
if (stale_subagent || stale_guardian)
|
||||
&& let Some(Value::Array(headers)) =
|
||||
context.get_mut(PASSTHROUGH_HEADERS_CONTEXT_KEY)
|
||||
{
|
||||
headers.retain(|pair| match pair.get(0).and_then(Value::as_str) {
|
||||
Some(OPENAI_SUBAGENT_KEY) => !stale_subagent,
|
||||
Some("x-codex-guardian") => !stale_guardian,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(subagent) = self.subagent.as_deref() {
|
||||
inject_subagent_metadata(body, subagent);
|
||||
}
|
||||
}
|
||||
|
||||
/// 独立端点保留业务扩展头与会话身份,不携带 Responses 的连接状态
|
||||
pub(crate) fn session_context(&self) -> Map<String, Value> {
|
||||
let mut context = Map::new();
|
||||
insert_protocol_context(&mut context, "session_id", self.session_id.as_ref());
|
||||
insert_protocol_context(&mut context, "thread_id", self.thread_id.as_ref());
|
||||
insert_protocol_context(&mut context, "turn_metadata", self.turn_metadata.as_ref());
|
||||
self.insert_passthrough_headers(&mut context);
|
||||
context
|
||||
}
|
||||
|
||||
fn insert_passthrough_headers(&self, context: &mut Map<String, Value>) {
|
||||
if !self.passthrough_headers.is_empty() {
|
||||
context.insert(
|
||||
@@ -170,26 +82,13 @@ impl OpenAiRequestHeaders {
|
||||
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", self.turn_metadata.as_ref());
|
||||
insert_protocol_context(&mut context, "subagent", self.subagent.as_ref());
|
||||
self.codex.append_context(&mut context);
|
||||
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,
|
||||
"codex_window_id",
|
||||
self.codex_window_id.as_ref(),
|
||||
);
|
||||
insert_protocol_context(
|
||||
&mut context,
|
||||
"parent_thread_id",
|
||||
self.parent_thread_id.as_ref(),
|
||||
);
|
||||
insert_protocol_context(
|
||||
&mut context,
|
||||
DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY,
|
||||
@@ -207,9 +106,6 @@ impl OpenAiRequestHeaders {
|
||||
"client_request_id",
|
||||
self.client_request_id.as_ref(),
|
||||
);
|
||||
insert_protocol_context(&mut context, "turn_id", self.turn_id.as_ref());
|
||||
insert_protocol_context(&mut context, "responses_lite", self.responses_lite.as_ref());
|
||||
insert_protocol_context(&mut context, "memgen_request", self.memgen_request.as_ref());
|
||||
self.insert_passthrough_headers(&mut context);
|
||||
if let Some(use_websocket) = use_websocket {
|
||||
context.insert("use_websocket".to_owned(), Value::Bool(use_websocket));
|
||||
@@ -288,10 +184,6 @@ pub(super) fn decode_request_object(
|
||||
Some(value) => value.as_bool().unwrap_or(true),
|
||||
None => matches!(source, RequestDecodeSource::WebSocketFrame),
|
||||
};
|
||||
let store = object
|
||||
.get("store")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let continuation = object
|
||||
.get("previous_response_id")
|
||||
.and_then(Value::as_str)
|
||||
@@ -299,29 +191,11 @@ pub(super) fn decode_request_object(
|
||||
.unwrap_or(ContinuationIntent::None);
|
||||
|
||||
let mut protocol_context = request_headers.protocol_context(use_websocket, source);
|
||||
gateway_protocol::openai::capture_codex_guardian_identity(
|
||||
&object,
|
||||
let client_turn = request_headers.codex.apply(
|
||||
&mut object,
|
||||
&mut protocol_context,
|
||||
request_headers.guardian.as_deref(),
|
||||
request_headers.ambiguous_guardian_headers,
|
||||
matches!(source, RequestDecodeSource::WebSocketFrame),
|
||||
);
|
||||
request_headers.apply_subagent(&mut object, &mut protocol_context, source);
|
||||
|
||||
let semantics =
|
||||
gateway_protocol::openai::codex_responses_request_semantics(&object, &protocol_context);
|
||||
let client_turn = if object.get("generate").and_then(Value::as_bool) != Some(false)
|
||||
&& semantics.request_kind.as_deref() == Some("turn")
|
||||
&& !semantics.compact
|
||||
{
|
||||
gateway_protocol::openai::codex_account_thread_id(&object, &protocol_context)
|
||||
.zip(gateway_protocol::openai::codex_turn_id(
|
||||
&object,
|
||||
&protocol_context,
|
||||
))
|
||||
.and_then(|(thread, turn)| ClientTurn::new(thread, turn))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let payload = ProtocolPayload::json_object(OPENAI_PROTOCOL, object)
|
||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||
@@ -336,7 +210,6 @@ pub(super) fn decode_request_object(
|
||||
metadata: GenerationRequestMetadata {
|
||||
requested_model: model,
|
||||
stream,
|
||||
store,
|
||||
continuation,
|
||||
client_ip: None,
|
||||
user_agent: None,
|
||||
@@ -344,92 +217,6 @@ pub(super) fn decode_request_object(
|
||||
})
|
||||
}
|
||||
|
||||
fn inject_subagent_metadata(body: &mut Map<String, Value>, subagent: &str) {
|
||||
let metadata = body
|
||||
.entry("client_metadata".to_owned())
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
let Some(metadata) = metadata.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
metadata.insert(
|
||||
OPENAI_SUBAGENT_KEY.to_owned(),
|
||||
Value::String(subagent.to_owned()),
|
||||
);
|
||||
}
|
||||
|
||||
fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub(crate) fn passthrough_headers(headers: &HeaderMap) -> Vec<Value> {
|
||||
passthrough_request_headers(headers)
|
||||
.map(|(name, value)| {
|
||||
Value::Array(vec![
|
||||
Value::String(name.as_str().to_owned()),
|
||||
Value::String(STANDARD.encode(value.as_bytes())),
|
||||
])
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// HTTP 与 Live 入站共用的身份、传输边界;保留业务头原始多值字节
|
||||
pub(crate) fn passthrough_request_headers(
|
||||
headers: &HeaderMap,
|
||||
) -> impl Iterator<Item = (&HeaderName, &HeaderValue)> {
|
||||
let connection_headers = headers
|
||||
.get_all("connection")
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
headers
|
||||
.iter()
|
||||
.filter(move |(name, _)| passthrough_header_name(name.as_str(), &connection_headers))
|
||||
}
|
||||
|
||||
fn passthrough_header_name(name: &str, connection_headers: &[String]) -> bool {
|
||||
if connection_headers
|
||||
.iter()
|
||||
.any(|connection_header| connection_header.eq_ignore_ascii_case(name))
|
||||
|| is_transport_managed_request_header(name)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
!matches!(
|
||||
name,
|
||||
// 下游鉴权和账号 cookie 绝不能成为上游账号身份
|
||||
"authorization"
|
||||
| "x-api-key"
|
||||
| "x-goog-api-key"
|
||||
// Codex 的服务端托管认证标记只用于客户端能力判断,不代表上游身份
|
||||
| "x-openai-actor-authorization"
|
||||
| "cookie"
|
||||
| "cookie2"
|
||||
| "chatgpt-account-id"
|
||||
| "chatgpt-project-id"
|
||||
| "openai-organization"
|
||||
| "openai-project"
|
||||
// 上游指纹必须由运行时画像统一生成,客户端 originator/User-Agent/version
|
||||
// 不能作为不透明头透传覆盖,避免不同下游客户端暴露不一致的设备指纹
|
||||
| "originator"
|
||||
| "user-agent"
|
||||
| "version"
|
||||
// 设备 attestation/integrity 头只能由官方客户端或网关自身生成,
|
||||
// 客户端注入的 x-oai-attestation / X-OAI-IS 不得透传上游
|
||||
| "x-oai-attestation"
|
||||
| "x-oai-is"
|
||||
| "x-oai-is-update"
|
||||
)
|
||||
}
|
||||
|
||||
fn required_non_empty_string<'a>(
|
||||
object: &'a Map<String, Value>,
|
||||
key: &str,
|
||||
|
||||
@@ -288,10 +288,9 @@ fn client_payload(wire: &ProtocolWireEvent) -> Option<Value> {
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(|name| name.trim().to_ascii_lowercase())
|
||||
.collect();
|
||||
if headers
|
||||
.keys()
|
||||
.all(|name| super::response_header_is_forwardable(name, &connection_options))
|
||||
{
|
||||
if headers.keys().all(|name| {
|
||||
crate::data_plane::headers::response_header_is_forwardable(name, &connection_options)
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
// 只剥离既有响应头隔离策略禁止的字段,metadata 业务扩展保持不透明
|
||||
@@ -299,7 +298,9 @@ fn client_payload(wire: &ProtocolWireEvent) -> Option<Value> {
|
||||
projected
|
||||
.get_mut("headers")?
|
||||
.as_object_mut()?
|
||||
.retain(|name, _| super::response_header_is_forwardable(name, &connection_options));
|
||||
.retain(|name, _| {
|
||||
crate::data_plane::headers::response_header_is_forwardable(name, &connection_options)
|
||||
});
|
||||
Some(projected)
|
||||
}
|
||||
|
||||
|
||||
@@ -130,10 +130,14 @@ pub(super) fn response_metadata_event(
|
||||
}
|
||||
|
||||
fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<String, Value> {
|
||||
let connection_options = super::super::response_connection_options(response_headers);
|
||||
let connection_options =
|
||||
crate::data_plane::headers::response_connection_options(response_headers);
|
||||
let mut headers = Map::new();
|
||||
for header in response_headers {
|
||||
if !super::super::response_header_is_forwardable(header.name(), &connection_options) {
|
||||
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||
header.name(),
|
||||
&connection_options,
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||
|
||||
@@ -8,12 +8,9 @@ use axum::{
|
||||
|
||||
use super::{
|
||||
chat_completions::chat_completions,
|
||||
images::{image_edits, image_generations},
|
||||
live,
|
||||
messages::{count_tokens, messages},
|
||||
models::{model_detail, models},
|
||||
responses::{responses, responses_websocket},
|
||||
search::standalone_search,
|
||||
usage,
|
||||
};
|
||||
|
||||
@@ -24,9 +21,6 @@ pub(super) use gateway_protocol::openai::RESPONSES_PATH;
|
||||
pub(super) const MESSAGES_PATH: &str = "/v1/messages";
|
||||
pub(super) const MESSAGE_TOKENS_PATH: &str = "/v1/messages/count_tokens";
|
||||
pub(super) const CHAT_COMPLETIONS_PATH: &str = "/v1/chat/completions";
|
||||
pub(super) const IMAGE_GENERATIONS_PATH: &str = "/v1/images/generations";
|
||||
pub(super) const IMAGE_EDITS_PATH: &str = "/v1/images/edits";
|
||||
pub(super) const SEARCH_PATH: &str = "/v1/alpha/search";
|
||||
pub(super) const MODELS_PATH: &str = "/v1/models";
|
||||
pub(super) const MODEL_DETAIL_PATH: &str = "/v1/models/{model_id}";
|
||||
pub(super) const USAGE_PATH: &str = "/v1/usage";
|
||||
@@ -35,9 +29,6 @@ pub(super) const PEER_LINK_PATH: &str = "/v1/cpr/link";
|
||||
/// 构造模型数据面路由
|
||||
pub(crate) fn router() -> Router<ApiState> {
|
||||
Router::new()
|
||||
.route(IMAGE_GENERATIONS_PATH, post(image_generations))
|
||||
.route(IMAGE_EDITS_PATH, post(image_edits))
|
||||
.route(SEARCH_PATH, post(standalone_search))
|
||||
.route(RESPONSES_PATH, get(responses_websocket).post(responses))
|
||||
.route(CHAT_COMPLETIONS_PATH, post(chat_completions))
|
||||
.route(MESSAGES_PATH, post(messages))
|
||||
@@ -48,7 +39,7 @@ pub(crate) fn router() -> Router<ApiState> {
|
||||
.merge(super::genai::router())
|
||||
.merge(usage::router())
|
||||
.merge(super::peer_link::router())
|
||||
.merge(live::router())
|
||||
.merge(super::openai::router())
|
||||
// 生成请求正文属于客户端/上游协议;代理不能用私有大小上限提前拒绝
|
||||
// 上游本可接受的未来 payload
|
||||
.layer(DefaultBodyLimit::disable())
|
||||
|
||||
@@ -11,7 +11,7 @@ use gateway_core::engine::execution::{
|
||||
};
|
||||
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
||||
use gateway_core::lifecycle::{ConnectionDraining, ConnectionGuard, ConnectionLifecycle};
|
||||
use gateway_core::routing::{ProviderCatalogUnavailable, PublicModelDescriptor, PublicModelId};
|
||||
use gateway_core::routing::PublicModelId;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::auth::ClientApiKeyAuthError;
|
||||
@@ -68,22 +68,6 @@ impl DataPlaneService {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) async fn client_model_catalog(
|
||||
&self,
|
||||
client: &AuthenticatedClient,
|
||||
client_version: &str,
|
||||
) -> Result<Vec<PublicModelDescriptor>, ProviderCatalogUnavailable> {
|
||||
let context = crate::middleware::current();
|
||||
self.execution
|
||||
.client_model_catalog(
|
||||
client,
|
||||
"codex",
|
||||
client_version,
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn contains_public_model(
|
||||
&self,
|
||||
client: &AuthenticatedClient,
|
||||
|
||||
@@ -5,17 +5,14 @@ mod chat_completions;
|
||||
mod error;
|
||||
mod genai;
|
||||
mod group_permissions;
|
||||
mod images;
|
||||
mod live;
|
||||
mod messages;
|
||||
mod middleware;
|
||||
mod models;
|
||||
mod openai_endpoints;
|
||||
mod openai;
|
||||
mod peer_link;
|
||||
mod provider_endpoints;
|
||||
mod responses;
|
||||
mod router;
|
||||
mod search;
|
||||
mod usage;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ use gateway_core::upstream::UpstreamSendState;
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use super::{api_router, authenticated_client};
|
||||
use crate::data_plane::{api_router, authenticated_client};
|
||||
|
||||
const IMAGE_RESPONSE: &[u8] =
|
||||
br#"{ "created": 1787212800, "data": [{"b64_json":"AAEC"}], "future": 9007199254740993 }"#;
|
||||
+3
-3
@@ -22,9 +22,9 @@ use gateway_core::operation::Operation;
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use super::api_router;
|
||||
use super::authenticated_client;
|
||||
use super::models::ModelsExecution;
|
||||
use crate::data_plane::api_router;
|
||||
use crate::data_plane::authenticated_client;
|
||||
use crate::data_plane::models::ModelsExecution;
|
||||
|
||||
const LIVE_KEY: &str = "sk_live_test";
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
//! OpenAI 专属端点的路由、透传与交付测试
|
||||
|
||||
mod endpoints;
|
||||
mod images;
|
||||
mod live;
|
||||
mod search;
|
||||
+2
-2
@@ -26,8 +26,8 @@ use gateway_core::upstream::UpstreamSendState;
|
||||
use serde_json::{Value, json};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use super::openai_endpoints::BufferedJsonSession;
|
||||
use super::{api_router, authenticated_client};
|
||||
use super::endpoints::BufferedJsonSession;
|
||||
use crate::data_plane::{api_router, authenticated_client};
|
||||
|
||||
const SEARCH_RESPONSE: &[u8] = br#"{ "encrypted_output":"ciphertext", "output":"search result", "results":[{"type":"text_result","ref_id":"turn0search0","future":9007199254740993}] }"#;
|
||||
|
||||
@@ -41,7 +41,6 @@ use gateway_core::upstream::{OpaqueUpstreamValue, UpstreamSendState};
|
||||
use gateway_protocol::openai::sse::{encode_sse_event, parse_sse_events};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use gateway_api::data_plane::responses::{collect_execution_response, stream_execution_response};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use crate::data_plane::middleware::{RequestMiddleware, ResponseFrameAction};
|
||||
@@ -49,6 +48,30 @@ use crate::data_plane::{
|
||||
api_router, authenticated_client_for_provider, authenticated_client_with_min_versions,
|
||||
};
|
||||
|
||||
async fn execute_session(
|
||||
session: Box<dyn ExecutionSession>,
|
||||
streaming: bool,
|
||||
) -> axum::response::Response {
|
||||
let execution = Arc::new(SessionExecution {
|
||||
client: authenticated_client_for_provider("sk_delivery_test", "openai"),
|
||||
session: Mutex::new(Some(session)),
|
||||
middleware: None,
|
||||
});
|
||||
api_router(execution)
|
||||
.await
|
||||
.oneshot(
|
||||
Request::post("/v1/responses")
|
||||
.header(AUTHORIZATION, "Bearer sk_delivery_test")
|
||||
.body(Body::from(
|
||||
json!({"model": "model-a", "input": "synthetic", "stream": streaming})
|
||||
.to_string(),
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn responses_middleware() -> RequestMiddleware {
|
||||
RequestMiddleware {
|
||||
expected_operation: Some(OperationKind::Generate),
|
||||
@@ -930,7 +953,7 @@ async fn streaming_encodes_first_frame_before_commit_and_http_delivery() {
|
||||
))],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
|
||||
assert_eq!(response.status(), axum::http::StatusCode::OK);
|
||||
assert_eq!(trace.client_statuses(), vec![200]);
|
||||
@@ -1225,7 +1248,7 @@ async fn streaming_should_keep_alive_during_silent_compaction_without_restarting
|
||||
NextStep::FinalizeSuccess,
|
||||
],
|
||||
);
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let mut body = response.into_body().into_data_stream();
|
||||
let first = body.next().await.expect("first frame").expect("body bytes");
|
||||
assert!(String::from_utf8_lossy(&first).contains("response.created"));
|
||||
@@ -1280,7 +1303,7 @@ async fn dropping_stream_during_keepalive_should_cancel_and_finalize_execution()
|
||||
NextStep::FinalizeCancelled,
|
||||
],
|
||||
);
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let mut body = response.into_body().into_data_stream();
|
||||
let _ = body.next().await.expect("first frame").expect("body bytes");
|
||||
let heartbeat = tokio::time::timeout(Duration::from_secs(20), body.next())
|
||||
@@ -1317,7 +1340,7 @@ async fn streaming_keepalive_should_cover_four_minutes_before_first_event() {
|
||||
let start = tokio::time::Instant::now();
|
||||
let response = tokio::time::timeout(
|
||||
Duration::from_secs(20),
|
||||
stream_execution_response(Box::new(session), None),
|
||||
execute_session(Box::new(session), true),
|
||||
)
|
||||
.await
|
||||
.expect("headers and heartbeat must precede the first upstream event");
|
||||
@@ -1361,7 +1384,7 @@ async fn streaming_error_after_initial_keepalive_should_be_a_terminal_sse_failur
|
||||
)],
|
||||
)
|
||||
.with_response_headers(headers(&[("x-codex-turn-state", "private-attempt-state")]));
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert!(!response.headers().contains_key("x-codex-turn-state"));
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
@@ -1400,7 +1423,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
||||
Arc::new(Trace::default()),
|
||||
vec![NextStep::Error(EngineError::Provider(failure()))],
|
||||
);
|
||||
let response = stream_execution_response(Box::new(immediate), None).await;
|
||||
let response = execute_session(Box::new(immediate), true).await;
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(response.headers()[CONTENT_TYPE], "application/json");
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
@@ -1415,7 +1438,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
||||
EngineError::Provider(failure()),
|
||||
)],
|
||||
);
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let events = parse_sse_events(std::str::from_utf8(&bytes).unwrap()).unwrap();
|
||||
@@ -1502,7 +1525,7 @@ async fn dropping_stream_before_first_event_should_cancel_the_original_wait() {
|
||||
NextStep::FinalizeCancelled,
|
||||
],
|
||||
);
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let mut body = response.into_body().into_data_stream();
|
||||
assert_eq!(
|
||||
body.next().await.unwrap().unwrap(),
|
||||
@@ -1529,7 +1552,7 @@ async fn streaming_response_should_disable_proxy_buffering_and_cache_transformat
|
||||
ProviderResponseHeader::new("cache-control", Bytes::from_static(b"public, max-age=60")),
|
||||
]);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
|
||||
assert_eq!(response.headers()["x-accel-buffering"], "no");
|
||||
assert_eq!(
|
||||
@@ -1581,7 +1604,7 @@ async fn streaming_response_should_append_ordinary_headers_and_skip_unrepresenta
|
||||
)
|
||||
.with_response_headers(headers);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
|
||||
assert_eq!(
|
||||
response
|
||||
@@ -1674,7 +1697,7 @@ async fn streaming_commit_batch_preserves_pre_identity_wire_before_committing()
|
||||
vec![NextStep::Event(batch), NextStep::FinalizeSuccess],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read SSE body");
|
||||
@@ -1706,7 +1729,7 @@ async fn streaming_first_frame_encode_failure_cancels_before_commit() {
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
@@ -1728,7 +1751,7 @@ async fn streaming_rate_limit_before_first_frame_should_persist_the_returned_429
|
||||
))],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||
assert_eq!(trace.client_statuses(), vec![429]);
|
||||
@@ -1755,7 +1778,7 @@ async fn streaming_failure_before_first_frame_should_return_safe_observed_header
|
||||
),
|
||||
]);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
||||
assert_eq!(
|
||||
@@ -1795,7 +1818,7 @@ async fn streaming_upstream_http_failure_before_first_frame_should_preserve_raw_
|
||||
vec![NextStep::Error(EngineError::Provider(error))],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||
assert_eq!(
|
||||
@@ -1867,7 +1890,7 @@ async fn buffered_upstream_http_failure_should_preserve_raw_response() {
|
||||
),
|
||||
]);
|
||||
|
||||
let response = collect_execution_response(Box::new(session)).await;
|
||||
let response = execute_session(Box::new(session), false).await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(
|
||||
@@ -1902,7 +1925,7 @@ async fn streaming_canonical_identity_change_does_not_interrupt_wire_delivery()
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read SSE body");
|
||||
@@ -1943,7 +1966,7 @@ async fn streaming_success_should_emit_terminal_event_and_done_marker() {
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read complete SSE body");
|
||||
@@ -1997,7 +2020,7 @@ async fn streaming_finalized_native_wire_should_end_cleanly() {
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read transparent SSE body");
|
||||
@@ -2023,7 +2046,7 @@ async fn streaming_completed_event_without_finalized_execution_should_fail_close
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read failed SSE body");
|
||||
@@ -2059,7 +2082,7 @@ async fn streaming_empty_terminal_should_emit_failure_done_and_cancel_execution(
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read failed SSE body");
|
||||
@@ -2092,7 +2115,7 @@ async fn streaming_error_should_emit_client_visible_upstream_details() {
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read SSE body");
|
||||
@@ -2166,7 +2189,7 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read SSE body");
|
||||
@@ -2271,7 +2294,7 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
@@ -2342,7 +2365,7 @@ async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
||||
NextStep::Error(EngineError::Provider(error)),
|
||||
],
|
||||
);
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), 16 * 1024)
|
||||
.await
|
||||
@@ -2426,7 +2449,7 @@ async fn atomic_uncommitted_upstream_failure_batch_should_be_forwarded_once() {
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read SSE body");
|
||||
@@ -2456,7 +2479,7 @@ async fn streaming_second_commit_request_should_fail_and_finalize_once() {
|
||||
],
|
||||
);
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read failed SSE body");
|
||||
@@ -2483,7 +2506,7 @@ async fn streaming_commit_failure_should_not_deliver_the_prepared_first_frame()
|
||||
)
|
||||
.with_commit_failure();
|
||||
|
||||
let response = stream_execution_response(Box::new(session), None).await;
|
||||
let response = execute_session(Box::new(session), true).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read error response");
|
||||
@@ -2505,7 +2528,7 @@ async fn buffered_response_commits_only_after_complete_json_is_encoded() {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()]);
|
||||
|
||||
let response = collect_execution_response(Box::new(session)).await;
|
||||
let response = execute_session(Box::new(session), false).await;
|
||||
let body = to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("read JSON body");
|
||||
@@ -2570,7 +2593,7 @@ async fn buffered_response_collects_completed_output_items_without_rewriting_str
|
||||
|
||||
let trace = Arc::new(Trace::default());
|
||||
let session = FakeSession::buffered_provider(Arc::clone(&trace), events);
|
||||
let response = collect_execution_response(Box::new(session)).await;
|
||||
let response = execute_session(Box::new(session), false).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let mut expected = terminal;
|
||||
@@ -2715,7 +2738,7 @@ async fn buffered_response_keeps_authoritative_terminal_and_supports_omitted_out
|
||||
super::openai_wire_event(vec![], event_type, json!({"response": terminal})),
|
||||
],
|
||||
);
|
||||
let response = collect_execution_response(Box::new(session)).await;
|
||||
let response = execute_session(Box::new(session), false).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
let mut expected = terminal;
|
||||
@@ -2752,10 +2775,10 @@ async fn buffered_response_rejects_incomplete_or_conflicting_output_items_before
|
||||
"response.completed",
|
||||
json!({"response": {"id": "resp_test", "output": []}}),
|
||||
));
|
||||
let response = collect_execution_response(Box::new(FakeSession::buffered_provider(
|
||||
Arc::clone(&trace),
|
||||
events,
|
||||
)))
|
||||
let response = execute_session(
|
||||
Box::new(FakeSession::buffered_provider(Arc::clone(&trace), events)),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
@@ -2785,10 +2808,10 @@ async fn buffered_response_never_merges_items_from_a_different_wire_response() {
|
||||
super::openai_wire_event(vec![], "response.output_item.done", conflicting_event),
|
||||
super::openai_wire_event(vec![], "response.completed", json!({"response": terminal})),
|
||||
];
|
||||
let response = collect_execution_response(Box::new(FakeSession::buffered_provider(
|
||||
Arc::clone(&trace),
|
||||
events,
|
||||
)))
|
||||
let response = execute_session(
|
||||
Box::new(FakeSession::buffered_provider(Arc::clone(&trace), events)),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
@@ -2886,7 +2909,7 @@ async fn buffered_response_forwards_long_ordinary_provider_header_values() {
|
||||
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()])
|
||||
.with_response_headers(vec![header]);
|
||||
|
||||
let response = collect_execution_response(Box::new(session)).await;
|
||||
let response = execute_session(Box::new(session), false).await;
|
||||
|
||||
assert_eq!(
|
||||
response
|
||||
@@ -2905,7 +2928,7 @@ async fn buffered_encode_failure_cancels_without_commit() {
|
||||
vec![ProviderEvent::canonical(completed())],
|
||||
);
|
||||
|
||||
let response = collect_execution_response(Box::new(session)).await;
|
||||
let response = execute_session(Box::new(session), false).await;
|
||||
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
@@ -2922,7 +2945,7 @@ async fn buffered_commit_failure_should_cancel_after_encoding_without_returning_
|
||||
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()])
|
||||
.with_commit_failure();
|
||||
|
||||
let response = collect_execution_response(Box::new(session)).await;
|
||||
let response = execute_session(Box::new(session), false).await;
|
||||
let status = response.status();
|
||||
|
||||
assert_eq!(status, axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
@@ -2938,7 +2961,7 @@ async fn buffered_commit_failure_should_cancel_after_encoding_without_returning_
|
||||
async fn dropping_buffered_handler_before_commit_cancels_execution() {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let session = FakeSession::pending_buffered(Arc::clone(&trace));
|
||||
let task = tokio::spawn(async move { collect_execution_response(Box::new(session)).await });
|
||||
let task = tokio::spawn(async move { execute_session(Box::new(session), false).await });
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
task.abort();
|
||||
@@ -2959,7 +2982,7 @@ async fn buffered_rate_limit_should_persist_the_returned_429_status() {
|
||||
),
|
||||
);
|
||||
|
||||
let response = collect_execution_response(Box::new(session)).await;
|
||||
let response = execute_session(Box::new(session), false).await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||
assert_eq!(trace.client_statuses(), vec![429]);
|
||||
|
||||
@@ -371,7 +371,6 @@ fn decoder_should_preserve_the_openai_body_and_only_derive_stable_routing_facts(
|
||||
]))
|
||||
);
|
||||
assert!(!decoded.metadata().stream());
|
||||
assert!(decoded.metadata().store());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -96,10 +96,10 @@ fn response_create_should_default_to_the_websocket_streaming_contract() {
|
||||
.expect("decode response.create");
|
||||
|
||||
assert!(decoded.metadata().stream());
|
||||
assert!(!decoded.metadata().store());
|
||||
let Operation::Generate(request) = decoded.operation() else {
|
||||
panic!("Responses must map to Generate");
|
||||
};
|
||||
assert_eq!(request.protocol_payload().body()["store"], false);
|
||||
assert!(request.protocol_payload().body().get("stream").is_none());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! 跨协议 HTTP 头部传输边界与重试时间解析
|
||||
|
||||
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
|
||||
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
|
||||
let now = std::time::SystemTime::now();
|
||||
let value = value.trim();
|
||||
if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return value.parse().ok();
|
||||
}
|
||||
let remaining = httpdate::parse_http_date(value)
|
||||
.ok()?
|
||||
.duration_since(now)
|
||||
.unwrap_or_default();
|
||||
Some(
|
||||
remaining
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(remaining.subsec_nanos() != 0)),
|
||||
)
|
||||
}
|
||||
|
||||
/// 判断小写请求头是否属于传输层管理的字段,不得作为业务扩展头透传
|
||||
///
|
||||
/// API 入站和 Provider 编码共用此分类;`Connection` 动态声明的逐跳头由入站额外剥离
|
||||
/// 只用于请求方向,不影响上游响应中的代理诊断信息
|
||||
#[must_use]
|
||||
pub fn is_transport_managed_request_header(name: &str) -> bool {
|
||||
name.starts_with("sec-websocket-")
|
||||
|| matches!(
|
||||
name,
|
||||
"connection"
|
||||
| "keep-alive"
|
||||
| "proxy-connection"
|
||||
| "proxy-authenticate"
|
||||
| "proxy-authorization"
|
||||
| "te"
|
||||
| "trailer"
|
||||
| "transfer-encoding"
|
||||
| "upgrade"
|
||||
| "host"
|
||||
| "content-length"
|
||||
// 请求实体与响应压缩能力属于各段 transport,不能继承下游协商
|
||||
| "content-encoding"
|
||||
| "accept-encoding"
|
||||
// 网关中间件也会生成该链路诊断 ID,不作为业务上下文转发
|
||||
| "x-request-id"
|
||||
)
|
||||
}
|
||||
|
||||
/// 判断响应头是否满足 HTTP 传输和通用鉴权材料的转发边界
|
||||
///
|
||||
/// `connection_options` 来自同一响应的 `Connection` 字段,调用方应先按逗号拆分并
|
||||
/// 转成小写
|
||||
/// 此函数拒绝逐跳头、实体 framing 和通用认证材料
|
||||
/// 平台专属账号身份由调用边界组合对应协议规则过滤
|
||||
#[must_use]
|
||||
pub fn response_header_is_forwardable(name: &str, connection_options: &[String]) -> bool {
|
||||
let name = name.trim().to_ascii_lowercase();
|
||||
if connection_options
|
||||
.iter()
|
||||
.any(|option| option.eq_ignore_ascii_case(&name))
|
||||
|| name.starts_with("sec-websocket-")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
!matches!(
|
||||
name.as_str(),
|
||||
"connection"
|
||||
| "keep-alive"
|
||||
| "proxy-connection"
|
||||
| "te"
|
||||
| "trailer"
|
||||
| "transfer-encoding"
|
||||
| "upgrade"
|
||||
| "content-length"
|
||||
| "content-type"
|
||||
| "content-encoding"
|
||||
| "authorization"
|
||||
| "x-api-key"
|
||||
| "www-authenticate"
|
||||
| "authentication-info"
|
||||
| "proxy-authenticate"
|
||||
| "proxy-authorization"
|
||||
| "proxy-authentication-info"
|
||||
| "cookie"
|
||||
| "cookie2"
|
||||
| "set-cookie"
|
||||
| "set-cookie2"
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
mod capabilities;
|
||||
|
||||
/// 跨协议 HTTP 传输头与重试时间
|
||||
pub mod http;
|
||||
|
||||
/// OpenAI wire contract
|
||||
pub mod openai;
|
||||
|
||||
|
||||
@@ -245,7 +245,7 @@ pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
|
||||
Some((value, header))
|
||||
})
|
||||
.next_back()?;
|
||||
let seconds = super::headers::parse_retry_after_seconds(header.to_str().ok()?)?;
|
||||
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
|
||||
Some((value, seconds))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,100 +1,21 @@
|
||||
//! OpenAI 头部的传输边界与重试时间解析
|
||||
//! OpenAI 与 Codex 响应中的账号身份字段分类
|
||||
|
||||
/// 解析 HTTP 和流内错误共用的 Retry-After,保留零延迟并向上取整剩余秒数
|
||||
pub fn parse_retry_after_seconds(value: &str) -> Option<u64> {
|
||||
let now = std::time::SystemTime::now();
|
||||
let value = value.trim();
|
||||
if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return value.parse().ok();
|
||||
}
|
||||
let remaining = httpdate::parse_http_date(value)
|
||||
.ok()?
|
||||
.duration_since(now)
|
||||
.unwrap_or_default();
|
||||
Some(
|
||||
remaining
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(remaining.subsec_nanos() != 0)),
|
||||
)
|
||||
}
|
||||
|
||||
/// 判断小写请求头是否属于传输层管理的字段,不得作为业务扩展头透传
|
||||
///
|
||||
/// API 入站和 Provider 编码共用此分类;`Connection` 动态声明的逐跳头由入站额外剥离
|
||||
/// 只用于请求方向,不影响上游响应中的代理诊断信息
|
||||
/// 账号与安装身份不能随上游响应下发给客户端
|
||||
#[must_use]
|
||||
pub fn is_transport_managed_request_header(name: &str) -> bool {
|
||||
name.starts_with("sec-websocket-")
|
||||
|| matches!(
|
||||
name,
|
||||
"connection"
|
||||
| "keep-alive"
|
||||
| "proxy-connection"
|
||||
| "proxy-authenticate"
|
||||
| "proxy-authorization"
|
||||
| "te"
|
||||
| "trailer"
|
||||
| "transfer-encoding"
|
||||
| "upgrade"
|
||||
| "host"
|
||||
| "content-length"
|
||||
// 请求实体与响应压缩能力属于各段 transport,不能继承下游协商
|
||||
| "content-encoding"
|
||||
| "accept-encoding"
|
||||
// 网关中间件也会生成该链路诊断 ID,不作为业务上下文转发
|
||||
| "x-request-id"
|
||||
)
|
||||
}
|
||||
|
||||
/// 判断上游响应头是否可由客户端 HTTP adapter 或插件读取/改写
|
||||
///
|
||||
/// `connection_options` 来自同一响应的 `Connection` 字段,调用方应先按逗号拆分并
|
||||
/// 转成小写
|
||||
/// 此函数同时拒绝逐跳头、实体 framing、认证材料和账号身份字段;所有
|
||||
/// 响应边界共用这一份分类,避免观测、加工和最终转发出现不同的泄漏面
|
||||
#[must_use]
|
||||
pub fn response_header_is_forwardable(name: &str, connection_options: &[String]) -> bool {
|
||||
let name = name.trim().to_ascii_lowercase();
|
||||
if connection_options
|
||||
.iter()
|
||||
.any(|option| option.eq_ignore_ascii_case(&name))
|
||||
|| name.starts_with("sec-websocket-")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
!matches!(
|
||||
name.as_str(),
|
||||
"connection"
|
||||
| "keep-alive"
|
||||
| "proxy-connection"
|
||||
| "te"
|
||||
| "trailer"
|
||||
| "transfer-encoding"
|
||||
| "upgrade"
|
||||
| "content-length"
|
||||
| "content-type"
|
||||
| "content-encoding"
|
||||
| "authorization"
|
||||
| "x-api-key"
|
||||
| "www-authenticate"
|
||||
| "authentication-info"
|
||||
| "proxy-authenticate"
|
||||
| "proxy-authorization"
|
||||
| "proxy-authentication-info"
|
||||
| "cookie"
|
||||
| "cookie2"
|
||||
| "set-cookie"
|
||||
| "set-cookie2"
|
||||
| "chatgpt-account-id"
|
||||
| "chatgpt-organization-id"
|
||||
| "chatgpt-org-id"
|
||||
| "chatgpt-project-id"
|
||||
| "openai-organization"
|
||||
| "openai-project"
|
||||
| "x-openai-organization"
|
||||
| "x-openai-project"
|
||||
| "x-codex-installation-id"
|
||||
| "x-codex-turn-metadata"
|
||||
)
|
||||
pub fn is_private_response_header(name: &str) -> bool {
|
||||
let name = name.trim();
|
||||
[
|
||||
"chatgpt-account-id",
|
||||
"chatgpt-organization-id",
|
||||
"chatgpt-org-id",
|
||||
"chatgpt-project-id",
|
||||
"openai-organization",
|
||||
"openai-project",
|
||||
"x-openai-organization",
|
||||
"x-openai-project",
|
||||
"x-codex-installation-id",
|
||||
"x-codex-turn-metadata",
|
||||
]
|
||||
.iter()
|
||||
.any(|private| name.eq_ignore_ascii_case(private))
|
||||
}
|
||||
|
||||
@@ -36,6 +36,5 @@ pub use guardian::{
|
||||
CODEX_AUTO_REVIEW_MODEL, CodexGuardianRole, capture_codex_guardian_identity,
|
||||
codex_guardian_role,
|
||||
};
|
||||
pub use headers::{
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable,
|
||||
};
|
||||
|
||||
pub use headers::is_private_response_header;
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! 验证传输头部分类,以及响应中的连接级和身份字段过滤
|
||||
|
||||
use gateway_protocol::http::{
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn retry_after_should_accept_nonnegative_seconds_and_http_dates() {
|
||||
for (header, expected) in [
|
||||
(" 30 ", Some(30)),
|
||||
("0", Some(0)),
|
||||
("Sun, 06 Nov 1994 08:49:37 GMT", Some(0)),
|
||||
("Sunday, 06-Nov-94 08:49:37 GMT", Some(0)),
|
||||
("Sun Nov 6 08:49:37 1994", Some(0)),
|
||||
("+30", None),
|
||||
("-1", None),
|
||||
("1.5", None),
|
||||
("18446744073709551616", None),
|
||||
("", None),
|
||||
("later", None),
|
||||
] {
|
||||
assert_eq!(parse_retry_after_seconds(header), expected, "{header}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_after_http_date_should_not_round_down_the_remaining_delay() {
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||
let retry_at = UNIX_EPOCH + Duration::from_secs(now.as_secs() + 60);
|
||||
let header = httpdate::fmt_http_date(retry_at);
|
||||
let seconds = parse_retry_after_seconds(&header).expect("HTTP date");
|
||||
let remaining = retry_at.duration_since(SystemTime::now()).unwrap();
|
||||
assert!(Duration::from_secs(seconds) >= remaining);
|
||||
assert!(seconds <= 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_headers_should_include_hop_fields_and_compression() {
|
||||
for name in [
|
||||
"accept-encoding",
|
||||
"content-encoding",
|
||||
"content-length",
|
||||
"host",
|
||||
"x-request-id",
|
||||
"connection",
|
||||
"keep-alive",
|
||||
"proxy-connection",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"te",
|
||||
"trailer",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
"sec-websocket-key",
|
||||
"sec-websocket-extensions",
|
||||
] {
|
||||
assert!(is_transport_managed_request_header(name), "missing {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_headers_should_leave_business_extensions_to_the_protocol_owner() {
|
||||
for name in [
|
||||
"cf-visitor",
|
||||
"cf-connecting-ip",
|
||||
"cf-connecting-ipv6",
|
||||
"cf-pseudo-ipv4",
|
||||
"cf-ray",
|
||||
"cf-ipcountry",
|
||||
"cf-warp-tag-id",
|
||||
"cf-worker",
|
||||
"cf-ew-via",
|
||||
"cf-future-proxy-field",
|
||||
"cdn-loop",
|
||||
"via",
|
||||
"forwarded",
|
||||
"x-forwarded-for",
|
||||
"x-forwarded-host",
|
||||
"x-forwarded-proto",
|
||||
"x-forwarded-port",
|
||||
"x-forwarded-prefix",
|
||||
"x-forwarded-future-field",
|
||||
"x-real-ip",
|
||||
"true-client-ip",
|
||||
"x-openai-future-mode",
|
||||
"x-custom-extension",
|
||||
"x-client-request-id",
|
||||
"session-id",
|
||||
"thread-id",
|
||||
"x-codex-turn-state",
|
||||
"x-codex-beta-features",
|
||||
"openai-beta",
|
||||
"accept",
|
||||
"content-type",
|
||||
"x-cf-business-field",
|
||||
] {
|
||||
assert!(
|
||||
!is_transport_managed_request_header(name),
|
||||
"unexpected {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_headers_should_reject_hop_credentials_and_dynamic_connection_fields() {
|
||||
let connection_options = vec!["x-hop".to_owned()];
|
||||
for name in [
|
||||
"connection",
|
||||
"x-hop",
|
||||
"content-length",
|
||||
"authorization",
|
||||
"set-cookie",
|
||||
"sec-websocket-accept",
|
||||
] {
|
||||
assert!(
|
||||
!response_header_is_forwardable(name, &connection_options),
|
||||
"unexpectedly exposed {name}"
|
||||
);
|
||||
}
|
||||
assert!(response_header_is_forwardable(
|
||||
"x-ratelimit-remaining-requests",
|
||||
&connection_options
|
||||
));
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod anthropic;
|
||||
mod genai;
|
||||
mod http;
|
||||
mod openai;
|
||||
mod request;
|
||||
|
||||
|
||||
@@ -1,127 +1,21 @@
|
||||
//! 验证传输头部分类,以及响应中的连接级和身份字段过滤
|
||||
//! OpenAI 响应的私有身份与可公开诊断头分类
|
||||
|
||||
use gateway_protocol::openai::{
|
||||
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable,
|
||||
};
|
||||
use gateway_protocol::openai::is_private_response_header;
|
||||
|
||||
#[test]
|
||||
fn retry_after_should_accept_nonnegative_seconds_and_http_dates() {
|
||||
for (header, expected) in [
|
||||
(" 30 ", Some(30)),
|
||||
("0", Some(0)),
|
||||
("Sun, 06 Nov 1994 08:49:37 GMT", Some(0)),
|
||||
("Sunday, 06-Nov-94 08:49:37 GMT", Some(0)),
|
||||
("Sun Nov 6 08:49:37 1994", Some(0)),
|
||||
("+30", None),
|
||||
("-1", None),
|
||||
("1.5", None),
|
||||
("18446744073709551616", None),
|
||||
("", None),
|
||||
("later", None),
|
||||
] {
|
||||
assert_eq!(parse_retry_after_seconds(header), expected, "{header}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_after_http_date_should_not_round_down_the_remaining_delay() {
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||
let retry_at = UNIX_EPOCH + Duration::from_secs(now.as_secs() + 60);
|
||||
let header = httpdate::fmt_http_date(retry_at);
|
||||
let seconds = parse_retry_after_seconds(&header).expect("HTTP date");
|
||||
let remaining = retry_at.duration_since(SystemTime::now()).unwrap();
|
||||
assert!(Duration::from_secs(seconds) >= remaining);
|
||||
assert!(seconds <= 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_headers_should_include_hop_fields_and_compression() {
|
||||
fn private_account_headers_should_be_case_insensitive_and_keep_public_diagnostics() {
|
||||
for name in [
|
||||
"accept-encoding",
|
||||
"content-encoding",
|
||||
"content-length",
|
||||
"host",
|
||||
"x-request-id",
|
||||
"connection",
|
||||
"keep-alive",
|
||||
"proxy-connection",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"te",
|
||||
"trailer",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
"sec-websocket-key",
|
||||
"sec-websocket-extensions",
|
||||
] {
|
||||
assert!(is_transport_managed_request_header(name), "missing {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_headers_should_leave_business_extensions_to_the_protocol_owner() {
|
||||
for name in [
|
||||
"cf-visitor",
|
||||
"cf-connecting-ip",
|
||||
"cf-connecting-ipv6",
|
||||
"cf-pseudo-ipv4",
|
||||
"cf-ray",
|
||||
"cf-ipcountry",
|
||||
"cf-warp-tag-id",
|
||||
"cf-worker",
|
||||
"cf-ew-via",
|
||||
"cf-future-proxy-field",
|
||||
"cdn-loop",
|
||||
"via",
|
||||
"forwarded",
|
||||
"x-forwarded-for",
|
||||
"x-forwarded-host",
|
||||
"x-forwarded-proto",
|
||||
"x-forwarded-port",
|
||||
"x-forwarded-prefix",
|
||||
"x-forwarded-future-field",
|
||||
"x-real-ip",
|
||||
"true-client-ip",
|
||||
"x-openai-future-mode",
|
||||
"x-custom-extension",
|
||||
"x-client-request-id",
|
||||
"session-id",
|
||||
"thread-id",
|
||||
"x-codex-turn-state",
|
||||
"x-codex-beta-features",
|
||||
"openai-beta",
|
||||
"accept",
|
||||
"content-type",
|
||||
"x-cf-business-field",
|
||||
] {
|
||||
assert!(
|
||||
!is_transport_managed_request_header(name),
|
||||
"unexpected {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_headers_should_reject_hop_identity_and_dynamic_connection_fields() {
|
||||
let connection_options = vec!["x-hop".to_owned()];
|
||||
for name in [
|
||||
"connection",
|
||||
"x-hop",
|
||||
"content-length",
|
||||
"authorization",
|
||||
"set-cookie",
|
||||
"chatgpt-account-id",
|
||||
"x-openai-project",
|
||||
"sec-websocket-accept",
|
||||
" X-OpenAI-Project ",
|
||||
"x-codex-turn-metadata",
|
||||
] {
|
||||
assert!(
|
||||
!response_header_is_forwardable(name, &connection_options),
|
||||
"unexpectedly exposed {name}"
|
||||
);
|
||||
assert!(is_private_response_header(name), "exposed {name}");
|
||||
}
|
||||
assert!(response_header_is_forwardable(
|
||||
for name in [
|
||||
"x-request-id",
|
||||
"x-ratelimit-remaining-requests",
|
||||
&connection_options
|
||||
));
|
||||
"x-provider-extension",
|
||||
] {
|
||||
assert!(!is_private_response_header(name), "hidden {name}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::{engine::middleware::MiddlewareHeader, operation::Operation};
|
||||
use gateway_protocol::openai::is_transport_managed_request_header;
|
||||
use gateway_protocol::http::is_transport_managed_request_header;
|
||||
use serde_json::Value;
|
||||
|
||||
pub(crate) fn request_headers(
|
||||
|
||||
@@ -984,7 +984,7 @@ pub(in crate::transport) fn retry_after_seconds(
|
||||
headers
|
||||
.get(RETRY_AFTER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(gateway_protocol::openai::parse_retry_after_seconds)
|
||||
.and_then(gateway_protocol::http::parse_retry_after_seconds)
|
||||
.or_else(|| body.and_then(retry_after_seconds_from_body))
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::time::Instant;
|
||||
|
||||
use bytes::Bytes;
|
||||
use gateway_core::operation::ProviderHttpHeader;
|
||||
use gateway_protocol::openai::is_transport_managed_request_header;
|
||||
use gateway_protocol::http::is_transport_managed_request_header;
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
|
||||
use crate::compat::is_non_codex_request_header;
|
||||
|
||||
@@ -4,9 +4,9 @@ use std::io;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::{account::OpenAiRequestCountry, operation::GenerateRequest};
|
||||
use gateway_protocol::http::is_transport_managed_request_header;
|
||||
use gateway_protocol::openai::{
|
||||
OPENAI_PROTOCOL, WS_REQUEST_HEADER_RESPONSES_LITE_CLIENT_METADATA_KEY,
|
||||
is_transport_managed_request_header,
|
||||
};
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
use roxmltree::Document;
|
||||
|
||||
@@ -143,6 +143,7 @@ fn filter_client_headers(
|
||||
}
|
||||
|
||||
fn client_response_header_is_forwardable(name: &str, connection_options: &[String]) -> bool {
|
||||
gateway_protocol::openai::response_header_is_forwardable(name, connection_options)
|
||||
gateway_protocol::http::response_header_is_forwardable(name, connection_options)
|
||||
&& !gateway_protocol::openai::is_private_response_header(name)
|
||||
&& !is_codex_quota_header_name(name.trim())
|
||||
}
|
||||
|
||||
@@ -415,7 +415,7 @@ fn websocket_opening_error(
|
||||
.headers()
|
||||
.get("retry-after")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(gateway_protocol::openai::parse_retry_after_seconds)
|
||||
.and_then(gateway_protocol::http::parse_retry_after_seconds)
|
||||
.or_else(|| events::retry_after_seconds_from_body(&body));
|
||||
CodexWebSocketExchangeError::Upstream(Box::new(CodexWebSocketUpstreamError {
|
||||
status_code,
|
||||
|
||||
@@ -581,7 +581,14 @@ Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 ca
|
||||
|
||||
Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号并用其凭据查询项目,停用账号仍可接受探测
|
||||
|
||||
数据面协议入口位于 `gateway-api/src/data_plane`。Responses、Chat Completions、Messages 与 GenAI 共用 `generation` 的执行和交付流程。GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity 将选中的 GenAI 请求封装为 Cloud Code 上游请求
|
||||
数据面入口位于 `gateway-api/src/data_plane`,按协议、客户端扩展和平台专属端点划分职责:
|
||||
|
||||
- `responses`、`chat_completions`、`messages`、`genai` 拥有各自协议入口,生成与计数共用 `generation` 的执行交付、取消传播和连接生命周期
|
||||
- `codex` 拥有客户端模型目录投影、Guardian、子代理与轮次身份解析,Responses 入口组合这些扩展;Responses 同时服务 OpenAI 与 xAI,不绑定某个 Provider
|
||||
- `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有
|
||||
- `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者
|
||||
|
||||
GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity 将选中的 GenAI 请求封装为 Cloud Code 上游请求
|
||||
|
||||
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user