mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 08:00:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
533a415a99 | ||
|
|
7b04e08d81 | ||
|
|
8acf376091 | ||
|
|
62e9cd03c5 | ||
|
|
81dacf603f | ||
|
|
5173314136 | ||
|
|
a51395bbc5 |
@@ -5,7 +5,7 @@
|
||||
|
||||
# Codex Proxy RS
|
||||
|
||||
面向 Codex 的自托管多账号 AI 网关
|
||||
多平台自托管多账号 AI 网关
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Antigravity 桌面端与 CLI 的模型选择器识别及菜单投影
|
||||
//! Antigravity 桌面端与 CLI 的模型发现请求识别及目录投影
|
||||
|
||||
use axum::http::{HeaderMap, header::USER_AGENT};
|
||||
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
||||
|
||||
@@ -20,7 +20,6 @@ pub(crate) struct CodexRequestHeaders {
|
||||
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>,
|
||||
@@ -45,7 +44,6 @@ impl CodexRequestHeaders {
|
||||
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),
|
||||
@@ -60,7 +58,6 @@ impl CodexRequestHeaders {
|
||||
("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()),
|
||||
] {
|
||||
|
||||
@@ -83,6 +83,7 @@ fn parse_route(resource: &str, query: Option<&str>) -> Result<GenerationInput, G
|
||||
endpoint,
|
||||
model: model.to_owned(),
|
||||
stream,
|
||||
decoded: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Gemini 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
//! GenAI 模型目录复用冻结范围与原生协议能力,分页不扩大可见模型集合
|
||||
|
||||
use axum::{
|
||||
Json,
|
||||
@@ -10,6 +10,7 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use gateway_core::{
|
||||
engine::execution::AuthenticatedClient,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest},
|
||||
routing::PublicModelDescriptor,
|
||||
};
|
||||
use gateway_protocol::genai::GENAI_PROTOCOL;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -85,12 +86,13 @@ async fn query_response(
|
||||
let agent_menu = model.is_none() && crate::data_plane::antigravity::uses_agent_menu(&headers);
|
||||
let mut input = RequestInput::query(endpoint.to_owned(), model.clone(), &headers);
|
||||
input.protocol = GENAI_PROTOCOL.to_owned();
|
||||
let response_state = state.clone();
|
||||
middleware::query_response(
|
||||
service.execution(),
|
||||
client,
|
||||
input,
|
||||
move |client| async move {
|
||||
match catalog(&client, agent_menu) {
|
||||
match catalog(response_state.data_plane(), &client, agent_menu).await {
|
||||
Ok(models) => match model {
|
||||
Some(model) => models
|
||||
.into_iter()
|
||||
@@ -111,7 +113,22 @@ async fn query_response(
|
||||
.await
|
||||
}
|
||||
|
||||
fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>, ()> {
|
||||
async fn catalog(
|
||||
service: &crate::data_plane::service::DataPlaneService,
|
||||
client: &AuthenticatedClient,
|
||||
agent_menu: bool,
|
||||
) -> Result<Vec<Value>, ()> {
|
||||
let context = crate::middleware::current();
|
||||
let entries = service
|
||||
.execution()
|
||||
.client_model_catalog(
|
||||
client,
|
||||
GENAI_PROTOCOL,
|
||||
"",
|
||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
let generate = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?,
|
||||
@@ -128,36 +145,62 @@ fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result<Vec<Value>,
|
||||
let snapshot = client.snapshot();
|
||||
let scope = client.policy().account_scope();
|
||||
let counted = snapshot.public_models_for_operation(scope, &count);
|
||||
let models = if agent_menu {
|
||||
let generated = snapshot.public_models_for_operation(scope, &generate);
|
||||
let menu = agent_menu.then(|| {
|
||||
crate::data_plane::antigravity::model_menu(
|
||||
snapshot.model_metadata_for_operation(scope, &generate),
|
||||
)
|
||||
} else {
|
||||
snapshot
|
||||
.public_models_for_operation(scope, &generate)
|
||||
.into_iter()
|
||||
.map(|model| {
|
||||
let name = model.as_str().to_owned();
|
||||
(model, name)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
Ok(models
|
||||
.into_iter()
|
||||
.filter(|(model, _)| super::valid_segment(model.as_str()))
|
||||
.map(|(model, name)| {
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
.enumerate()
|
||||
.map(|(order, (model, name))| (model, (order, name)))
|
||||
.collect::<std::collections::BTreeMap<_, _>>()
|
||||
});
|
||||
let mut models = Vec::new();
|
||||
for entry in entries {
|
||||
let (model, mut object) = match entry {
|
||||
PublicModelDescriptor::Native { model, payload } => {
|
||||
if payload.protocol() != GENAI_PROTOCOL {
|
||||
return Err(());
|
||||
}
|
||||
let object: Map<String, Value> =
|
||||
serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||
(model, object)
|
||||
}
|
||||
// 上游尚未提供完整 Gemini 元数据,未知版本与 Token 上限保持缺失
|
||||
json!({
|
||||
"name": format!("models/{}", model.as_str()),
|
||||
"displayName": name,
|
||||
"supportedGenerationMethods": methods,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
PublicModelDescriptor::Adapted(profile) => {
|
||||
let name = menu
|
||||
.as_ref()
|
||||
.and_then(|menu| menu.get(profile.model()))
|
||||
.map(|(_, name)| name.as_str())
|
||||
.or_else(|| profile.presentation().display_name())
|
||||
.unwrap_or(profile.model().as_str());
|
||||
(
|
||||
profile.model().clone(),
|
||||
Map::from_iter([("displayName".into(), json!(name))]),
|
||||
)
|
||||
}
|
||||
};
|
||||
if generated.binary_search(&model).is_err() || !super::valid_segment(model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let order = if let Some(menu) = &menu {
|
||||
let Some((order, _)) = menu.get(&model) else {
|
||||
continue;
|
||||
};
|
||||
*order
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut methods = vec!["generateContent", "streamGenerateContent"];
|
||||
if counted.binary_search(&model).is_ok() {
|
||||
methods.push("countTokens");
|
||||
}
|
||||
// Cloud Code 模型对象完整保留,只适配 AGY Gateway 发现端点的资源名与调用方法
|
||||
object.insert("name".into(), json!(format!("models/{}", model.as_str())));
|
||||
object.insert("supportedGenerationMethods".into(), json!(methods));
|
||||
models.push((order, model, Value::Object(object)));
|
||||
}
|
||||
models.sort_unstable_by(|(a, ma, _), (b, mb, _)| (a, ma).cmp(&(b, mb)));
|
||||
Ok(models.into_iter().map(|(_, _, object)| object).collect())
|
||||
}
|
||||
|
||||
fn paginate(models: Vec<Value>, query: ModelsQuery) -> Response {
|
||||
|
||||
@@ -90,7 +90,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
peer_address,
|
||||
ingress_id,
|
||||
headers,
|
||||
input: generation,
|
||||
input: mut generation,
|
||||
middleware_body,
|
||||
} = request;
|
||||
let (client_ip, user_agent) = request_client_context(&headers, peer_address);
|
||||
@@ -120,6 +120,7 @@ pub(crate) async fn execute_prepared_generation(
|
||||
middleware_headers.remove(CONTENT_LENGTH);
|
||||
let endpoint = protocol.path();
|
||||
let stream_error = protocol.stream_error_encoder();
|
||||
let original_body = middleware_body.clone();
|
||||
let input = RequestInput {
|
||||
endpoint: endpoint.to_owned(),
|
||||
protocol: protocol.wire().to_owned(),
|
||||
@@ -143,17 +144,24 @@ pub(crate) async fn execute_prepared_generation(
|
||||
if wire_protocol != protocol.wire() {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let decoded = generation
|
||||
.decode(
|
||||
// 只复用当前请求中未被改写的解码事实;设置和能力声明仍按最终请求应用
|
||||
let decoded = generation.decoded.take().filter(|_| {
|
||||
request_body == original_body && request_headers == middleware_headers
|
||||
});
|
||||
drop(original_body);
|
||||
let decoded = match decoded {
|
||||
Some(decoded) => decoded,
|
||||
None => generation.decode(
|
||||
&request_body,
|
||||
&request_headers,
|
||||
prepared
|
||||
.client()
|
||||
.snapshot()
|
||||
.responses_max_decompressed_body_bytes(),
|
||||
)?
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
)?,
|
||||
}
|
||||
.with_client_context(client_ip, user_agent)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
if decoded.metadata().stream() != stream {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
|
||||
@@ -28,8 +28,9 @@ impl GenerationEndpoint {
|
||||
pub(crate) fn input(self, request: DecodedGenerationRequest) -> GenerationInput {
|
||||
GenerationInput {
|
||||
endpoint: self,
|
||||
model: request.metadata.requested_model,
|
||||
model: request.metadata.requested_model.clone(),
|
||||
stream: request.metadata.stream,
|
||||
decoded: Some(request),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +65,8 @@ pub(crate) struct GenerationInput {
|
||||
pub(super) endpoint: GenerationEndpoint,
|
||||
pub(super) model: String,
|
||||
pub(super) stream: bool,
|
||||
// GenAI 从 URL 取路由事实,直到 terminal 才首次解码正文
|
||||
pub(super) decoded: Option<DecodedGenerationRequest>,
|
||||
}
|
||||
|
||||
impl GenerationInput {
|
||||
|
||||
@@ -136,7 +136,7 @@ pub fn decode_request_with_headers(
|
||||
|
||||
/// 解码请求并返回已经解除 HTTP content encoding 的中间件正文
|
||||
///
|
||||
/// 外层中间件只接收有界的协议正文;terminal 会用中间件返回的正文重新解码,
|
||||
/// 外层中间件只接收有界的协议正文;terminal 在正文或请求头改写后重新解码,
|
||||
/// 因而不能把压缩字节与已经移除的传输编码语义混用
|
||||
pub(crate) fn decode_request_with_body(
|
||||
body: &[u8],
|
||||
|
||||
@@ -230,32 +230,33 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
continue;
|
||||
}
|
||||
request_count = request_count.saturating_add(1);
|
||||
// 初步解码只取帧中的模型,实际执行使用该帧当前生效的请求头
|
||||
let model_hint =
|
||||
match decode_response_create_with_context(&payload, &OpenAiRequestHeaders::default()) {
|
||||
Ok(decoded) => Some(decoded.metadata().requested_model().to_owned()),
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
let original_headers = raw_headers.clone();
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&original_headers)
|
||||
.with_downstream_websocket_connection_id(connection.id().to_owned());
|
||||
let decoded = match decode_response_create_with_context(&payload, &request_headers) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
trace_rejected_request(
|
||||
&correlation_id,
|
||||
connection.id(),
|
||||
&payload,
|
||||
"decode",
|
||||
&error.to_string(),
|
||||
);
|
||||
if send_protocol_error(
|
||||
&mut connection,
|
||||
StatusCode::BAD_REQUEST,
|
||||
error.protocol_body(),
|
||||
&correlation_id,
|
||||
)
|
||||
.await
|
||||
== ForwardOutcome::Disconnect
|
||||
{
|
||||
break;
|
||||
}
|
||||
};
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// deadline 与 Text 可能同时就绪;在任何上游执行开始前再次封住该竞争窗口
|
||||
if connection.is_expired() {
|
||||
trace_rejected_request(
|
||||
@@ -317,14 +318,15 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
response_control = prepared.response_control();
|
||||
let capture = new_replay_capture();
|
||||
let validation = ResponseValidationFacts::default();
|
||||
let original_body = Bytes::from(payload);
|
||||
let input = RequestInput {
|
||||
endpoint: crate::data_plane::router::RESPONSES_PATH.to_owned(),
|
||||
protocol: OPENAI_PROTOCOL.to_owned(),
|
||||
operation: Some(OperationKind::Generate),
|
||||
transport: ClientTransport::WebSocket,
|
||||
model_hint,
|
||||
model_hint: Some(decoded.metadata().requested_model().to_owned()),
|
||||
headers: encode_headers(&raw_headers),
|
||||
body: Bytes::from(payload),
|
||||
body: original_body.clone(),
|
||||
};
|
||||
// 握手的轮次头只属于首次执行,复用连接时由各 response.create 携带本轮数据
|
||||
raw_headers.remove("x-codex-turn-state");
|
||||
@@ -353,15 +355,22 @@ async fn serve_responses_websocket(socket: Socket, session: ResponsesWebSocketSe
|
||||
if protocol != OPENAI_PROTOCOL {
|
||||
return Err(MiddlewareError::Rejected);
|
||||
}
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
let decoded = decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
// 帧正文或本轮请求头变化时重新解释,不能复用改写前的路由与续接事实
|
||||
let decoded = if body == original_body && headers == original_headers {
|
||||
decoded
|
||||
} else {
|
||||
drop(decoded);
|
||||
let payload =
|
||||
std::str::from_utf8(&body).map_err(|_| MiddlewareError::Rejected)?;
|
||||
let request_headers = OpenAiRequestHeaders::from_headers(&headers)
|
||||
.with_downstream_websocket_connection_id(
|
||||
connection_id_for_terminal.clone(),
|
||||
);
|
||||
decode_response_create_with_context(payload, &request_headers)
|
||||
.map_err(|_| MiddlewareError::Rejected)?
|
||||
}
|
||||
.with_client_context(client_ip, user_agent_for_terminal);
|
||||
drop(original_body);
|
||||
let decoded = replay_for_terminal
|
||||
.prepare(decoded)
|
||||
.with_middleware_capabilities(&request)?;
|
||||
|
||||
@@ -276,6 +276,33 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_middleware_updates_the_decoded_session_context() {
|
||||
let middleware = Arc::new(RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, mut headers, body) = request.clone().into_parts();
|
||||
headers.push(gateway_core::engine::middleware::MiddlewareHeader::new(
|
||||
"session-id",
|
||||
Bytes::from_static(b"rewritten-session"),
|
||||
));
|
||||
request
|
||||
.replace_parts(protocol, headers, body, None)
|
||||
.unwrap()
|
||||
}),
|
||||
..RequestMiddleware::default()
|
||||
});
|
||||
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||
execution.middleware = Some(middleware.frozen());
|
||||
let fixture = Fixture::with_execution(execution).await;
|
||||
let response = fixture.post(chat_request(false)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
fixture.captured().context["session_id"],
|
||||
"rewritten-session"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
||||
let mut session = Session::new(vec![created()]);
|
||||
|
||||
@@ -37,6 +37,7 @@ const BODY: &str = r#"{ "contents":[{"role":"user","parts":[{"text":"Read record
|
||||
#[derive(Default)]
|
||||
struct Execution {
|
||||
client: Option<AuthenticatedClient>,
|
||||
catalog: Option<Vec<gateway_core::routing::PublicModelDescriptor>>,
|
||||
session: Mutex<Option<Session>>,
|
||||
seen: Mutex<Option<PreparedExecutionRequest>>,
|
||||
}
|
||||
@@ -61,6 +62,37 @@ impl ExecutionService for Execution {
|
||||
fn public_models(&self, _: &AuthenticatedClient) -> Vec<PublicModelId> {
|
||||
vec![]
|
||||
}
|
||||
fn client_model_catalog<'a>(
|
||||
&'a self,
|
||||
client: &'a AuthenticatedClient,
|
||||
protocol: &'a str,
|
||||
_: &'a str,
|
||||
_: Option<&'a axum::http::HeaderValue>,
|
||||
) -> BoxFuture<
|
||||
'a,
|
||||
Result<
|
||||
Vec<gateway_core::routing::PublicModelDescriptor>,
|
||||
gateway_core::routing::ProviderCatalogUnavailable,
|
||||
>,
|
||||
> {
|
||||
use gateway_core::routing::{ModelPresentation, PublicModelDescriptor, PublicModelProfile};
|
||||
assert_eq!(protocol, GENAI_PROTOCOL);
|
||||
Box::pin(async {
|
||||
Ok(self.catalog.clone().unwrap_or_else(|| {
|
||||
client
|
||||
.snapshot()
|
||||
.public_models_for_scope(client.policy().account_scope())
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
PublicModelDescriptor::Adapted(PublicModelProfile::new(
|
||||
id,
|
||||
ModelPresentation::default(),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}))
|
||||
})
|
||||
}
|
||||
fn contains_public_model(&self, _: &AuthenticatedClient, _: &PublicModelId) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
@@ -176,6 +176,10 @@ fn agent_menu_client() -> AuthenticatedClient {
|
||||
"model-b",
|
||||
BTreeMap::from([(account.clone(), listed(1, "Bee"))]),
|
||||
),
|
||||
(
|
||||
"gemini-3.1-flash-image",
|
||||
BTreeMap::from([(account.clone(), listed(2, "Image"))]),
|
||||
),
|
||||
(
|
||||
"model-hidden",
|
||||
BTreeMap::from([
|
||||
@@ -220,6 +224,23 @@ fn agent_menu_client() -> AuthenticatedClient {
|
||||
super::super::authenticated_client_from_snapshot(KEY, snapshot)
|
||||
}
|
||||
|
||||
fn catalog_client() -> AuthenticatedClient {
|
||||
let source = client();
|
||||
let settings =
|
||||
source
|
||||
.snapshot()
|
||||
.settings()
|
||||
.clone()
|
||||
.with_model_mappings(std::collections::BTreeMap::from([(
|
||||
"alias-a".into(),
|
||||
"model-a".into(),
|
||||
)]));
|
||||
super::super::authenticated_client_from_snapshot(
|
||||
KEY,
|
||||
source.snapshot().with_settings(&settings).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Value {
|
||||
let response = router
|
||||
.clone()
|
||||
@@ -236,6 +257,86 @@ async fn agent_query(router: &axum::Router, path: &str, user_agent: &str) -> Val
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_preserves_metadata_and_aliases_for_every_client() {
|
||||
use gateway_core::{operation::RawJsonPayload, routing::PublicModelDescriptor};
|
||||
let document = json!({
|
||||
"displayName":"Upstream Model", "tagTitle":"New", "tagDescription":"Leaving on Nov 30.",
|
||||
"maxTokens":1048576, "maxOutputTokens":65536,
|
||||
"future":{"capability":true},
|
||||
});
|
||||
let payload = RawJsonPayload::new(
|
||||
GENAI_PROTOCOL,
|
||||
serde_json::to_vec(&document).unwrap().into(),
|
||||
)
|
||||
.unwrap();
|
||||
let router = api_router(Arc::new(Execution {
|
||||
client: Some(catalog_client()),
|
||||
catalog: Some(
|
||||
["model-a", "model-b", "model-c", "alias-a"]
|
||||
.into_iter()
|
||||
.map(|id| PublicModelDescriptor::Native {
|
||||
model: PublicModelId::new(id).unwrap(),
|
||||
payload: payload.clone(),
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
for agent in [
|
||||
"ordinary",
|
||||
"antigravity/hub/2.34.0",
|
||||
"antigravity/cli/1.5.18",
|
||||
] {
|
||||
let first = agent_query(&router, "/v1beta/models?pageSize=2", agent).await;
|
||||
let second = agent_query(
|
||||
&router,
|
||||
&format!(
|
||||
"/v1beta/models?pageSize=2&pageToken={}",
|
||||
first["nextPageToken"].as_str().unwrap()
|
||||
),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert!(second.get("nextPageToken").is_none());
|
||||
let entries = first["models"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.chain(second["models"].as_array().unwrap());
|
||||
assert_eq!(
|
||||
entries
|
||||
.clone()
|
||||
.map(|v| v["name"].as_str().unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"models/alias-a",
|
||||
"models/model-a",
|
||||
"models/model-b",
|
||||
"models/model-c"
|
||||
]
|
||||
);
|
||||
for entry in entries {
|
||||
let detail = agent_query(
|
||||
&router,
|
||||
&format!("/v1beta/{}", entry["name"].as_str().unwrap()),
|
||||
agent,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(entry, &detail);
|
||||
for (key, expected) in document.as_object().unwrap() {
|
||||
assert_eq!(&entry[key], expected, "{key}");
|
||||
}
|
||||
assert_eq!(
|
||||
entry["supportedGenerationMethods"],
|
||||
json!(["generateContent", "streamGenerateContent", "countTokens"])
|
||||
);
|
||||
assert!(entry.get("inputTokenLimit").is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination() {
|
||||
let router = api_router(Arc::new(Execution {
|
||||
@@ -273,7 +374,7 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
||||
names(&second),
|
||||
vec![
|
||||
(json!("models/model-b"), json!("Bee")),
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
(json!("models/gemini-3.1-flash-image"), json!("Image")),
|
||||
]
|
||||
);
|
||||
let third = agent_query(
|
||||
@@ -287,7 +388,10 @@ async fn agent_menus_apply_scoped_visibility_names_and_order_before_pagination()
|
||||
.await;
|
||||
assert_eq!(
|
||||
names(&third),
|
||||
vec![(json!("models/model-plain"), json!("model-plain"))]
|
||||
vec![
|
||||
(json!("models/model-fallback"), json!("model-fallback")),
|
||||
(json!("models/model-plain"), json!("model-plain")),
|
||||
]
|
||||
);
|
||||
assert!(third.get("nextPageToken").is_none());
|
||||
let detail = agent_query(&router, "/v1beta/models/model-hidden", agent).await;
|
||||
|
||||
@@ -39,6 +39,7 @@ pub(in crate::data_plane) struct RequestMiddleware {
|
||||
pub(in crate::data_plane) short_circuit_json: Option<Bytes>,
|
||||
pub(in crate::data_plane) settings:
|
||||
Option<fn(&mut gateway_core::routing::request_settings::ExecutionSettings)>,
|
||||
pub(in crate::data_plane) request_update: Option<fn(MiddlewareRequest) -> MiddlewareRequest>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -136,6 +137,9 @@ impl MiddlewarePlan for RequestMiddleware {
|
||||
Err(error) => return Box::pin(async move { Err(error) }),
|
||||
};
|
||||
}
|
||||
if let Some(update) = self.request_update {
|
||||
request = update(request);
|
||||
}
|
||||
Box::pin(async move {
|
||||
if let Some(body) = short_circuit_json {
|
||||
return Ok(MiddlewareResponse::new(
|
||||
|
||||
@@ -548,6 +548,64 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn header_only_request_middleware_updates_websocket_turn_context() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, mut headers, body) = request.clone().into_parts();
|
||||
headers.push(gateway_core::engine::middleware::MiddlewareHeader::new(
|
||||
"x-codex-turn-state",
|
||||
Bytes::from_static(b"rewritten-turn"),
|
||||
));
|
||||
request
|
||||
.replace_parts(protocol, headers, body, None)
|
||||
.unwrap()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
middleware: Some(middleware.frozen()),
|
||||
initial_errors: Mutex::new(VecDeque::from([EngineError::Provider(upstream_failure(
|
||||
502,
|
||||
b"",
|
||||
Vec::new(),
|
||||
))])),
|
||||
..Default::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(Arc::clone(&trace), Vec::new()).await;
|
||||
send_request(&mut socket).await;
|
||||
next_error(&mut socket).await;
|
||||
assert_eq!(
|
||||
trace.request_turn_headers.lock().unwrap().as_slice(),
|
||||
[[Some("rewritten-turn".to_owned()), None, None, None]]
|
||||
);
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_middleware_cannot_reuse_decoded_facts_after_replacing_a_websocket_frame() {
|
||||
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
|
||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||
request_update: Some(|request| {
|
||||
let (protocol, headers, _) = request.clone().into_parts();
|
||||
request
|
||||
.replace_parts(protocol, headers, Bytes::from_static(b"{}"), None)
|
||||
.unwrap()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let trace = Arc::new(AtomicFailureTrace {
|
||||
middleware: Some(middleware.frozen()),
|
||||
..Default::default()
|
||||
});
|
||||
let (mut socket, _server) = connect(Arc::clone(&trace), Vec::new()).await;
|
||||
send_request(&mut socket).await;
|
||||
next_error(&mut socket).await;
|
||||
assert_eq!(trace.starts.load(Ordering::Acquire), 0);
|
||||
socket.close(None).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn errors_on_a_reused_connection_keep_their_own_upstream_ids() {
|
||||
let errors = ["req_first", "req_second"].map(|request_id| {
|
||||
|
||||
@@ -19,7 +19,7 @@ pub struct ReasoningModelVariant {
|
||||
pub accounts: BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 上游账号的聊天菜单声明,未声明时仍可按模型 ID 发现
|
||||
/// 上游账号的客户端发现声明,未声明时仍可按模型 ID 发现
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub enum AgentModelListing {
|
||||
#[default]
|
||||
|
||||
@@ -173,8 +173,7 @@ impl CatalogService {
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||
if let Some(search_model) = catalog
|
||||
.web_search_models
|
||||
.first()
|
||||
.web_search_model()
|
||||
.and_then(|id| UpstreamModelId::new(id).ok())
|
||||
{
|
||||
search_models.extend(
|
||||
@@ -183,9 +182,10 @@ impl CatalogService {
|
||||
.map(|a| (a.account_id.clone(), search_model.clone())),
|
||||
);
|
||||
}
|
||||
let discovery_order = catalog.discovery_order();
|
||||
for (key, model) in catalog.models {
|
||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||
let metadata = account_metadata(&id, model, catalog.agent_model_order.as_ref());
|
||||
let metadata = account_metadata(&id, model, discovery_order.as_ref());
|
||||
members.entry(id).or_default().extend(
|
||||
accounts
|
||||
.iter()
|
||||
@@ -227,6 +227,50 @@ impl CatalogService {
|
||||
Ok(models.into_values().collect())
|
||||
}
|
||||
|
||||
pub(crate) async fn client_model_catalog(
|
||||
&self,
|
||||
scope: &gateway_core::account::scope::FrozenAccountScope,
|
||||
) -> Result<Vec<gateway_core::routing::ProviderModelDescriptor>, ProviderError> {
|
||||
use gateway_core::{
|
||||
operation::RawJsonPayload,
|
||||
routing::{ProviderModelContent, ProviderModelDescriptor},
|
||||
};
|
||||
let mut selected = BTreeMap::new();
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
for (id, mut model) in catalog.models {
|
||||
let Some(account) = accounts
|
||||
.iter()
|
||||
.filter(|account| scope.allows_model(&account.account_id, &id))
|
||||
.min_by_key(|account| &account.account_id)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// 同名模型选择一个完整的授权来源,不跨账号拼接字段
|
||||
if selected
|
||||
.get(&id)
|
||||
.is_some_and(|(source, _)| source <= &account.account_id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
model.0.remove("quotaInfo");
|
||||
let body = serde_json::to_vec(&model).map_err(|_| unsent(Kind::Protocol))?;
|
||||
selected.insert(id, (account.account_id.clone(), body));
|
||||
}
|
||||
}
|
||||
selected
|
||||
.into_iter()
|
||||
.map(|(id, (_, body))| {
|
||||
Ok(ProviderModelDescriptor {
|
||||
model: UpstreamModelId::new(id).map_err(|_| unsent(Kind::Protocol))?,
|
||||
content: ProviderModelContent::Native(
|
||||
RawJsonPayload::new(gateway_protocol::genai::GENAI_PROTOCOL, body.into())
|
||||
.map_err(|_| unsent(Kind::Protocol))?,
|
||||
),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) async fn account_models(
|
||||
&self,
|
||||
id: &ProviderAccountId,
|
||||
@@ -282,7 +326,7 @@ impl CatalogService {
|
||||
) -> Result<ProviderModels, ProviderAdminError> {
|
||||
// 模型目录只拥有能力事实,易变的额度由独立快照保存
|
||||
for model in catalog.models.values_mut() {
|
||||
model.quota = None;
|
||||
model.0.remove("quotaInfo");
|
||||
}
|
||||
let observed = AccountCatalogObservation {
|
||||
account_id: account.id().clone(),
|
||||
@@ -315,10 +359,10 @@ fn account_metadata(
|
||||
Some(order) => match order.get(id.as_str()) {
|
||||
Some(&order) => AgentModelListing::Listed {
|
||||
order,
|
||||
display_name: if model.name.trim().is_empty() {
|
||||
display_name: if model.name().trim().is_empty() {
|
||||
id.as_str().to_owned()
|
||||
} else {
|
||||
model.name
|
||||
model.name().to_owned()
|
||||
},
|
||||
},
|
||||
None => AgentModelListing::Hidden,
|
||||
@@ -326,7 +370,7 @@ fn account_metadata(
|
||||
};
|
||||
AccountModelMetadata {
|
||||
agent_listing,
|
||||
max_output_tokens: model.max_output_tokens.filter(|n| *n > 0),
|
||||
max_output_tokens: model.max_output_tokens(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,10 +383,10 @@ fn admin_models(
|
||||
.into_iter()
|
||||
.map(|(id, m)| {
|
||||
Ok(ProviderModel {
|
||||
name: if m.name.is_empty() {
|
||||
name: if m.name().is_empty() {
|
||||
id.clone()
|
||||
} else {
|
||||
m.name
|
||||
m.name().to_owned()
|
||||
},
|
||||
id: UpstreamModelId::new(id).map_err(|_| error(AdminKind::Invalid))?,
|
||||
})
|
||||
|
||||
@@ -12,7 +12,11 @@ pub(super) fn collect(
|
||||
catalog: &Catalog,
|
||||
accounts: &[AccountCatalogObservation],
|
||||
) {
|
||||
let Some(declarations) = catalog.grouped_models.as_object() else {
|
||||
let Some(declarations) = catalog
|
||||
.metadata
|
||||
.get("groupedModels")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
for (group, description) in declarations {
|
||||
|
||||
@@ -57,7 +57,7 @@ impl QuotaGroup {
|
||||
.models
|
||||
.iter()
|
||||
.filter(|(id, model)| {
|
||||
model.name == member || model_member_name(id, &model.name) == member
|
||||
model.name() == member || model_member_name(id, model.name()) == member
|
||||
})
|
||||
.peekable();
|
||||
matches.peek()?;
|
||||
|
||||
@@ -191,18 +191,18 @@ impl QuotaService {
|
||||
.models
|
||||
.iter()
|
||||
.map(|(id, model)| {
|
||||
(
|
||||
Ok((
|
||||
id.clone(),
|
||||
model
|
||||
.quota
|
||||
.clone()
|
||||
.quota()?
|
||||
.unwrap_or(crate::transport::account::ModelQuota {
|
||||
remaining_fraction: None,
|
||||
reset_time: None,
|
||||
}),
|
||||
)
|
||||
))
|
||||
})
|
||||
.collect(),
|
||||
.collect::<Result<_, serde_json::Error>>()
|
||||
.map_err(|e| error(Kind::Unavailable).with_source(e))?,
|
||||
};
|
||||
let plan = doc.plan_type();
|
||||
let quota = serde_json::to_value(&doc).map_err(|e| error(Kind::Internal).with_source(e))?;
|
||||
|
||||
@@ -183,8 +183,7 @@ impl AntigravityProvider {
|
||||
for (observations, catalog) in self.catalog.catalogs().await? {
|
||||
let supports = if search {
|
||||
catalog
|
||||
.web_search_models
|
||||
.first()
|
||||
.web_search_model()
|
||||
.is_some_and(|id| id == model.as_str())
|
||||
} else {
|
||||
catalog.models.contains_key(model.as_str())
|
||||
|
||||
@@ -123,6 +123,27 @@ impl Provider for AntigravityProvider {
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
self.execute_native(request, context).await
|
||||
}
|
||||
|
||||
async fn query_client_model_catalog(
|
||||
&self,
|
||||
_client_api_key_id: &gateway_core::policy::ClientApiKeyId,
|
||||
scope: &gateway_core::account::scope::FrozenAccountScope,
|
||||
protocol: &str,
|
||||
_client_version: &str,
|
||||
_peer_route: Option<&http::HeaderValue>,
|
||||
) -> Result<
|
||||
Option<Vec<gateway_core::routing::ProviderModelDescriptor>>,
|
||||
gateway_core::routing::ProviderCatalogUnavailable,
|
||||
> {
|
||||
if protocol != gateway_protocol::genai::GENAI_PROTOCOL {
|
||||
return Ok(None);
|
||||
}
|
||||
self.catalog
|
||||
.client_model_catalog(scope)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(|_| gateway_core::routing::ProviderCatalogUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
fn unavailable(error: impl Into<ErrorSource>) -> ProviderError {
|
||||
|
||||
@@ -25,50 +25,74 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Catalog {
|
||||
pub(crate) project: String,
|
||||
#[serde(
|
||||
rename = "agentModelOrder",
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub(crate) agent_model_order: Option<BTreeMap<String, usize>>,
|
||||
#[serde(rename = "webSearchModelIds", default)]
|
||||
pub(crate) web_search_models: Vec<String>,
|
||||
pub(crate) models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
pub(crate) grouped_models: serde_json::Value,
|
||||
#[serde(flatten)]
|
||||
pub(crate) metadata: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AgentModelSort {
|
||||
#[serde(default)]
|
||||
groups: Vec<AgentModelSortGroup>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AgentModelSortGroup {
|
||||
#[serde(rename = "modelIds", default)]
|
||||
model_ids: Vec<String>,
|
||||
}
|
||||
|
||||
fn agent_model_order(sorts: Vec<AgentModelSort>) -> BTreeMap<String, usize> {
|
||||
let mut order = BTreeMap::new();
|
||||
for group in sorts.into_iter().flat_map(|sort| sort.groups) {
|
||||
for id in group.model_ids {
|
||||
impl Catalog {
|
||||
pub(crate) fn discovery_order(&self) -> Option<BTreeMap<String, usize>> {
|
||||
let sorts = self.metadata.get("agentModelSorts")?.as_array()?;
|
||||
let mut order = BTreeMap::new();
|
||||
for id in sorts
|
||||
.iter()
|
||||
.filter_map(|sort| sort.get("groups")?.as_array())
|
||||
.flatten()
|
||||
.filter_map(|group| group.get("modelIds")?.as_array())
|
||||
.flatten()
|
||||
.chain(
|
||||
self.metadata
|
||||
.get("imageGenerationModelIds")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.into_iter()
|
||||
.flatten(),
|
||||
)
|
||||
.filter_map(serde_json::Value::as_str)
|
||||
{
|
||||
// AGY 用同一次发现获取聊天和生图模型,不能把生图入口按聊天菜单隐藏
|
||||
let index = order.len();
|
||||
order.entry(id).or_insert(index);
|
||||
order.entry(id.to_owned()).or_insert(index);
|
||||
}
|
||||
Some(order)
|
||||
}
|
||||
|
||||
pub(crate) fn web_search_model(&self) -> Option<&str> {
|
||||
self.metadata
|
||||
.get("webSearchModelIds")?
|
||||
.as_array()?
|
||||
.first()?
|
||||
.as_str()
|
||||
}
|
||||
order
|
||||
}
|
||||
|
||||
/// 模型对象完整保存,业务读取必要事实时不改变目录正文
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct Model {
|
||||
#[serde(rename = "displayName", default)]
|
||||
pub(crate) name: String,
|
||||
#[serde(rename = "quotaInfo", default)]
|
||||
pub(crate) quota: Option<super::account::ModelQuota>,
|
||||
#[serde(rename = "maxOutputTokens", default)]
|
||||
pub(crate) max_output_tokens: Option<u64>,
|
||||
#[serde(transparent)]
|
||||
pub(crate) struct Model(pub(crate) serde_json::Map<String, serde_json::Value>);
|
||||
|
||||
impl Model {
|
||||
pub(crate) fn name(&self) -> &str {
|
||||
self.0
|
||||
.get("displayName")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn max_output_tokens(&self) -> Option<u64> {
|
||||
self.0
|
||||
.get("maxOutputTokens")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.filter(|n| *n > 0)
|
||||
}
|
||||
|
||||
pub(crate) fn quota(&self) -> Result<Option<super::account::ModelQuota>, serde_json::Error> {
|
||||
self.0
|
||||
.get("quotaInfo")
|
||||
.filter(|value| !value.is_null())
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -159,13 +183,9 @@ impl CloudCodeClient {
|
||||
) -> Result<Catalog, ProviderError> {
|
||||
#[derive(Deserialize)]
|
||||
struct Models {
|
||||
#[serde(rename = "agentModelSorts", default)]
|
||||
agent_model_sorts: Option<Vec<AgentModelSort>>,
|
||||
#[serde(rename = "webSearchModelIds", default)]
|
||||
web_search_models: Vec<String>,
|
||||
models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
grouped_models: serde_json::Value,
|
||||
#[serde(flatten)]
|
||||
metadata: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
let models: Models = control(
|
||||
self.post("fetchAvailableModels", token)
|
||||
@@ -183,10 +203,8 @@ impl CloudCodeClient {
|
||||
}
|
||||
Ok(Catalog {
|
||||
project,
|
||||
agent_model_order: models.agent_model_sorts.map(agent_model_order),
|
||||
models: models.models,
|
||||
grouped_models: models.grouped_models,
|
||||
web_search_models: models.web_search_models,
|
||||
metadata: models.metadata,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -176,3 +176,116 @@ async fn renewed_identity_rebinds_catalog_without_waiting_for_another_upstream_q
|
||||
assert!(catalogs[0].1.models.contains_key("fixture-model"));
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_preserves_upstream_objects_without_chat_menu_filtering() {
|
||||
use gateway_core::routing::ProviderModelContent;
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
let document = json!({
|
||||
"models": {
|
||||
"chat-model": {"displayName":"Chat","tagTitle":"New","tagDescription":"Leaving on Nov 30.","quotaInfo":{"remainingFraction":0.5}},
|
||||
"gemini-3.1-flash-image": {"displayName":"Image","unknownImageMetadata":{"future":true}},
|
||||
"gemini-3.5-flash-lite": {"displayName":"Search"},
|
||||
"future-helper": {"unknown":[1,{"newCapability":true}]}
|
||||
},
|
||||
"agentModelSorts":[{"groups":[{"modelIds":["chat-model"],"futureGroupField":"keep"}]}],
|
||||
"imageGenerationModelIds":["gemini-3.1-flash-image"],
|
||||
"webSearchModelIds":["gemini-3.5-flash-lite"],
|
||||
"futureCatalogField":{"values":[1,2,3]}
|
||||
});
|
||||
Mock::given(path("/v1internal:loadCodeAssist"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_json(json!({"cloudaicompanionProject":"fixture-project"})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:fetchAvailableModels"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(&document))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
fixture
|
||||
.catalog
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut expected = document;
|
||||
expected["models"]["chat-model"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("quotaInfo");
|
||||
{
|
||||
let stored = fixture.store.primary().catalog.lock().unwrap();
|
||||
let mut actual: serde_json::Value =
|
||||
serde_json::from_slice(&stored.as_ref().unwrap().1).unwrap();
|
||||
assert_eq!(
|
||||
actual.as_object_mut().unwrap().remove("project"),
|
||||
Some(json!("fixture-project"))
|
||||
);
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
let entries = fixture
|
||||
.catalog
|
||||
.client_model_catalog(&fixture.store.account_scope())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(entries.len(), expected["models"].as_object().unwrap().len());
|
||||
for entry in entries {
|
||||
let ProviderModelContent::Native(payload) = entry.content else {
|
||||
panic!("expected native model");
|
||||
};
|
||||
let actual: serde_json::Value = serde_json::from_slice(payload.body()).unwrap();
|
||||
assert_eq!(actual, expected["models"][entry.model.as_str()]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_catalog_selects_whole_objects_only_from_authorized_sources() {
|
||||
use gateway_core::account::ProviderAccountStore;
|
||||
use gateway_core::routing::ProviderModelContent;
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::with_two_accounts(&upstream.uri());
|
||||
for (accounts, catalog) in fixture.catalog.catalogs().await.unwrap() {
|
||||
let mut document = serde_json::to_value(catalog).unwrap();
|
||||
document["models"]["fixture-model"] = if accounts[0].account_id.as_str() == "acct_fixture" {
|
||||
json!({"displayName":"Primary","primaryOnly":true})
|
||||
} else {
|
||||
json!({"displayName":"Standby","standbyOnly":true})
|
||||
};
|
||||
assert!(
|
||||
fixture
|
||||
.store
|
||||
.save_account_catalog(&accounts[0], &serde_json::to_vec(&document).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
let scope = fixture.store.account_scope();
|
||||
for (scope, expected) in [
|
||||
(
|
||||
scope.as_ref().clone(),
|
||||
json!({"displayName":"Primary","primaryOnly":true}),
|
||||
),
|
||||
(
|
||||
scope.excluding_account(
|
||||
gateway_core::account::ProviderAccountId::new("acct_fixture").unwrap(),
|
||||
),
|
||||
json!({"displayName":"Standby","standbyOnly":true}),
|
||||
),
|
||||
] {
|
||||
let entries = fixture.catalog.client_model_catalog(&scope).await.unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
let ProviderModelContent::Native(payload) = &entries[0].content else {
|
||||
panic!("expected native model");
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(payload.body()).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
@@ -215,8 +215,10 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
"models": {
|
||||
"gemini-4-hydrogen-medium": {"displayName":"Hydrogen Medium","maxTokens":1048576,"maxOutputTokens":65536,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High","maxTokens":900000,"maxOutputTokens":262144,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"}
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"},
|
||||
"gemini-3.1-flash-image": {"displayName":"Image"}
|
||||
},
|
||||
"imageGenerationModelIds": ["gemini-3.1-flash-image"],
|
||||
"agentModelSorts": [{"groups": [
|
||||
{"modelIds":["gemini-4-hydrogen-medium"]},
|
||||
{"modelIds":["gemini-4-hydrogen-high","gemini-4-hydrogen-medium","absent"]}
|
||||
@@ -239,7 +241,7 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
.unwrap();
|
||||
let kind = ProviderKind::new("antigravity").unwrap();
|
||||
let models = fixture.provider.query_model_capabilities().await.unwrap();
|
||||
assert_eq!(models.len(), 4);
|
||||
assert_eq!(models.len(), 5);
|
||||
let group = models
|
||||
.iter()
|
||||
.find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen")
|
||||
@@ -278,6 +280,13 @@ async fn catalog_metadata_and_groups_preserve_declared_members_for_generation()
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
(
|
||||
"gemini-3.1-flash-image",
|
||||
&AgentModelListing::Listed {
|
||||
order: 3,
|
||||
display_name: "Image".into(),
|
||||
}
|
||||
),
|
||||
(
|
||||
"gemini-4-hydrogen-high",
|
||||
&AgentModelListing::Listed {
|
||||
|
||||
@@ -59,7 +59,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
.mount(&server)
|
||||
.await;
|
||||
let catalog = client.catalog(&access_token).await.unwrap();
|
||||
assert_eq!(catalog.models["fixture-model"].name, "Fixture Model");
|
||||
assert_eq!(catalog.models["fixture-model"].name(), "Fixture Model");
|
||||
let body=br#"{ "contents":[{"parts":[{"functionResponse":{"name":"lookup","response":{"x":1}},"thoughtSignature":"opaque"}]}],"unknown":98765432109876543210987654,"systemInstruction":{"parts":[{"text":"You are Claude Code."}]},"system_instruction":{"parts":[{"text":"old"}]} }"#;
|
||||
let reply = r#"{ "responseId":"r","candidates":[{"content":{"parts":[{"text":"hidden","thought":true},{"text":"ok"},{"functionCall":{"name":"lookup","args":{"text":"not output"}}}]},"finishReason":"STOP"},{"index":1,"content":{"parts":[{"text":"other candidate"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":4,"candidatesTokenCount":2},"extra":98765432109876543210987654 }"#;
|
||||
let received_body = move |r: &wiremock::Request| {
|
||||
|
||||
@@ -45,7 +45,7 @@ impl CodexBackendClient {
|
||||
|| is_transport_managed_request_header(name.as_str())
|
||||
|| is_non_codex_request_header(name.as_str())
|
||||
// Live 不继承 Responses 的路由或连接续接状态
|
||||
|| matches!(name.as_str(), "x-codex-routing-hint" | "x-codex-turn-state" | "x-codex-turn-id")
|
||||
|| matches!(name.as_str(), "x-codex-routing-hint" | "x-codex-turn-state")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use gateway_core::diagnostics::{StreamCapture, StreamFormat, TraceContext, diagnostic_json};
|
||||
|
||||
use std::{
|
||||
sync::Arc,
|
||||
sync::{Arc, OnceLock},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
@@ -125,7 +125,8 @@ impl CodexBackendClient {
|
||||
);
|
||||
}
|
||||
let body = if compress {
|
||||
zstd::stream::encode_all(std::io::Cursor::new(body), 3)
|
||||
compress_request_body(body)
|
||||
.await
|
||||
.map_err(CodexClientError::RequestCompression)?
|
||||
} else {
|
||||
body
|
||||
@@ -909,6 +910,23 @@ fn observe_http_sse_rate_limits(
|
||||
))
|
||||
}
|
||||
|
||||
async fn compress_request_body(body: Vec<u8>) -> std::io::Result<Vec<u8>> {
|
||||
// 压缩不能占用 Tokio worker;先限并发再提交,取消后由工作线程持有名额直到结束
|
||||
static WORKERS: OnceLock<tokio::sync::Semaphore> = OnceLock::new();
|
||||
let workers = WORKERS.get_or_init(|| {
|
||||
tokio::sync::Semaphore::new(
|
||||
std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get),
|
||||
)
|
||||
});
|
||||
let permit = workers.acquire().await.map_err(std::io::Error::other)?;
|
||||
tokio_util::task::AbortOnDropHandle::new(tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
zstd::stream::encode_all(std::io::Cursor::new(body), 3)
|
||||
}))
|
||||
.await
|
||||
.map_err(std::io::Error::other)?
|
||||
}
|
||||
|
||||
async fn append_http_sse_rate_limit_updates(
|
||||
frames: Vec<SseFrame>,
|
||||
updates: &CodexRateLimitUpdates,
|
||||
|
||||
@@ -283,7 +283,6 @@ pub(super) fn append_passthrough_headers(headers: &mut HeaderMap, passthrough: &
|
||||
| "content-type"
|
||||
| "content-encoding"
|
||||
| "x-codex-routing-hint"
|
||||
| "x-codex-turn-id"
|
||||
| X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER
|
||||
)
|
||||
{
|
||||
|
||||
@@ -247,7 +247,6 @@ async fn backend_websocket_should_forward_context_headers_and_preserve_payload_f
|
||||
for forbidden in [
|
||||
"x-codex-turn-state",
|
||||
"x-codex-installation-id",
|
||||
"x-codex-turn-id",
|
||||
"x-openai-internal-codex-residency",
|
||||
"accept",
|
||||
"content-type",
|
||||
@@ -383,7 +382,6 @@ async fn backend_http_should_send_codex_context_without_browser_headers() {
|
||||
assert_eq!(header_names, expected_names);
|
||||
for forbidden in [
|
||||
"x-codex-installation-id",
|
||||
"x-codex-turn-id",
|
||||
"x-openai-internal-codex-residency",
|
||||
"sec-ch-ua",
|
||||
"sec-ch-ua-mobile",
|
||||
@@ -459,7 +457,6 @@ async fn backend_http_should_ignore_unrepresentable_protocol_headers_without_blo
|
||||
for omitted in [
|
||||
"session-id",
|
||||
"thread-id",
|
||||
"x-codex-turn-id",
|
||||
"x-codex-window-id",
|
||||
"x-codex-turn-state",
|
||||
"x-codex-turn-metadata",
|
||||
@@ -527,6 +524,73 @@ async fn backend_http_should_zstd_compress_codex_responses_request_body() {
|
||||
assert_eq!(json["instructions"], "compress me");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_compression_yields_to_cancellation_and_releases_capacity() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.max_blocking_threads(1)
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(async {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let request = read_http_request_with_body(&mut stream).await;
|
||||
write_completed_sse_response(&mut stream).await;
|
||||
request
|
||||
});
|
||||
let mut request = codex_request("gpt-test", "compress after cancellation", Vec::new());
|
||||
request.force_http_sse = true;
|
||||
let client = CodexBackendClient::new(
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
format!("http://{address}"),
|
||||
test_wire_profile(),
|
||||
);
|
||||
|
||||
// 占满 blocking pool,只有真正让出 reactor 的压缩任务才能被此定时器取消
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
let (release, wait) = std::sync::mpsc::channel::<()>();
|
||||
let blocker = tokio::task::spawn_blocking(move || {
|
||||
started.send(()).unwrap();
|
||||
let _ = wait.recv();
|
||||
});
|
||||
ready.await.unwrap();
|
||||
assert!(
|
||||
timeout(
|
||||
Duration::from_millis(50),
|
||||
client.create_response(&request, request_context("req_cancel_compression", None)),
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
!server.is_finished(),
|
||||
"cancelled preparation must not send upstream"
|
||||
);
|
||||
drop(release);
|
||||
blocker.await.unwrap();
|
||||
|
||||
timeout(
|
||||
Duration::from_secs(5),
|
||||
client.create_response(
|
||||
&request,
|
||||
request_context("req_after_compression_cancel", None),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let raw = server.await.unwrap();
|
||||
let separator = raw.windows(4).position(|part| part == b"\r\n\r\n").unwrap();
|
||||
let body = zstd::stream::decode_all(&raw[separator + 4..]).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Value>(&body).unwrap()["instructions"],
|
||||
"compress after cancellation"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn backend_http_should_force_upstream_sse_for_non_streaming_client_request() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
|
||||
@@ -69,7 +69,6 @@ async fn each_core_endpoint_uses_the_current_bundled_release() {
|
||||
assert_eq!(headers["chatgpt-account-id"], "audit-account");
|
||||
for forbidden in [
|
||||
"x-codex-installation-id",
|
||||
"x-codex-turn-id",
|
||||
"x-openai-internal-codex-residency",
|
||||
"oai-language",
|
||||
"openai-beta",
|
||||
|
||||
@@ -122,7 +122,6 @@ async fn fetch_should_use_wham_usage_headers_only() {
|
||||
"session_id",
|
||||
"session-id",
|
||||
"thread-id",
|
||||
"x-codex-turn-id",
|
||||
"x-codex-window-id",
|
||||
"x-codex-turn-state",
|
||||
"x-codex-turn-metadata",
|
||||
|
||||
+3
-3
@@ -770,11 +770,11 @@ OpenAI 聚合当前 Key 范围内合格 OAuth 和 API Key 账号的目录。每
|
||||
服务启动时批量恢复账号目录;目录读取只检查本地账号资格和 Client Key 范围,不等待上游查询。
|
||||
成功目录响应带 `Cache-Control: private, no-store`,不借用上游 ETag 标识经过选择/别名/聚合后的正文
|
||||
|
||||
Gemini 客户端使用 `GET /v1beta/models` 和 `GET /v1beta/models/{model}`。目录只包含当前 Key 可通过原生 GenAI 入口路由的已知模型,沿用账号范围、模型限制和别名;不会将其他协议的同名模型作为原生候选。条目提供 `name: "models/{id}"`、`displayName` 与 `supportedGenerationMethods`,未知的版本、上下文和输出上限不补默认值
|
||||
Antigravity 桌面端和 CLI 的 Gateway/GenAI 接入使用 `GET /v1beta/models` 和 `GET /v1beta/models/{model}`。目录只包含当前 Key 可通过原生 GenAI 入口路由的上游目录条目,沿用账号范围、模型限制和别名;不会将其他协议的同名模型作为原生候选。原生模型对象整体保留,包括未知扩展字段;API 仅适配 `name: "models/{id}"` 和 `supportedGenerationMethods`。未知的版本、上下文和输出上限不补默认值
|
||||
|
||||
普通 Gemini 列表按模型 ID 排序,支持 `pageSize`(默认 50,上限 1000,0 使用默认值)和 `pageToken`;后续页保持相同的 `pageSize`,末页省略 `nextPageToken`。详情查不到模型返回 Google RPC 格式的 404;分页及详情均重新检查当前 Key 的可见范围,不发起上游模型请求
|
||||
普通列表按模型 ID 排序,AGY 桌面端和 CLI 列表按上游声明顺序排序;支持 `pageSize`(默认 50,上限 1000,0 使用默认值)和 `pageToken`;后续页保持相同的 `pageSize`,末页省略 `nextPageToken`。详情查不到模型返回 Google RPC 格式的 404;分页及详情均重新检查当前 Key 的可见范围,不发起上游模型请求
|
||||
|
||||
Antigravity 桌面端和 CLI 的 GenAI 模型列表按上游 `agentModelSorts` 顺序返回当前 Key 可用的具体聊天型号和展示名。客户端用这些型号合并基础模型并选择思考强度。旧账号目录缺少聊天菜单声明时,刷新前仍可按具体型号发现。完整型号的详情与直接调用沿用账号模型权限。对基础模型显式指定分组档位时,网关按上游声明选择具体型号,并按该型号和账号的 `maxOutputTokens` 检查请求的输出上限
|
||||
AGY 模型发现按上游 `agentModelSorts` 保留聊天型号,并追加 `imageGenerationModelIds` 声明的生图型号;内部辅助型号不进入选择器,其详情与直接调用仍按账号模型权限处理。模型条目取自当前权限允许的完整账号目录对象,不跨账号拼接字段;账号额度由独立快照管理,不进入公开目录。AGY 网关模式读取 GenAI 列表,不能直接消费 Cloud Code 的目录外层;聊天型号合并、思考强度选择、生图分类和标签展示仍取决于客户端支持。对基础模型显式指定分组档位时,网关按上游声明选择具体型号,并按该型号和账号的 `maxOutputTokens` 检查请求的输出上限
|
||||
|
||||
`service_tiers` 中的 `name` 用于生成 `/fast` 等命令,`id` 用作请求的 `service_tier` 值。
|
||||
上游未声明档位或返回空数组时,网关不补充档位。档位更新后,客户端需重新加载模型目录
|
||||
|
||||
@@ -586,7 +586,7 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模
|
||||
|
||||
- `responses`、`chat_completions`、`messages`、`genai` 拥有各自协议入口,生成与计数共用 `generation` 的执行交付、取消传播和连接生命周期
|
||||
- `codex` 拥有客户端模型目录投影、Guardian、子代理与轮次身份解析,Responses 入口组合这些扩展;Responses 同时服务 OpenAI 与 xAI,不绑定某个 Provider
|
||||
- `antigravity` 识别桌面端和 CLI 的选模请求,负责菜单隐藏、显示名和排序;Core 只按执行计划与账号权限提供目录来源,GenAI 入口负责协议输出与分页
|
||||
- `antigravity` 识别桌面端和 CLI 的模型发现请求,按上游声明筛选聊天和生图模型并排序;Core 提供权限范围内的目录来源,GenAI 入口保留原生模型对象并分页
|
||||
- `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有
|
||||
- `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者
|
||||
|
||||
@@ -594,7 +594,7 @@ GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中
|
||||
|
||||
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。
|
||||
|
||||
GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范围;列表、详情和执行使用同一份能力事实。Antigravity 声明生成与输入计数能力,原生 GenAI 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
|
||||
GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录。Antigravity 声明生成与输入计数能力,原生 GenAI 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
|
||||
|
||||
Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。
|
||||
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
|
||||
|
||||
@@ -389,7 +389,6 @@
|
||||
"quotaResetPrioritySettings": "Quota scheduling settings"
|
||||
},
|
||||
"access": {
|
||||
"accessRestrictions": "Access restrictions",
|
||||
"deleteAdminApiKey": "Delete Admin API key",
|
||||
"deleteKeyDescription": "External systems will lose admin API access through this key",
|
||||
"areYouSureYouWantToDelete": "Are you sure you want to delete the current administrator API key? This operation will take effect immediately"
|
||||
|
||||
@@ -389,7 +389,6 @@
|
||||
"quotaResetPrioritySettings": "额度调度设置"
|
||||
},
|
||||
"access": {
|
||||
"accessRestrictions": "访问限制",
|
||||
"deleteAdminApiKey": "删除管理员 API密钥",
|
||||
"deleteKeyDescription": "删除后外部系统将无法继续使用该 API密钥调用管理接口",
|
||||
"areYouSureYouWantToDelete": "确定要删除当前管理员 API密钥吗?此操作会立即生效"
|
||||
|
||||
@@ -389,7 +389,6 @@
|
||||
"quotaResetPrioritySettings": "額度調度設置"
|
||||
},
|
||||
"access": {
|
||||
"accessRestrictions": "訪問限制",
|
||||
"deleteAdminApiKey": "刪除管理員 API密鑰",
|
||||
"deleteKeyDescription": "刪除後外部系統將無法繼續使用該 API密鑰調用管理接口",
|
||||
"areYouSureYouWantToDelete": "確定要刪除當前管理員 API密鑰嗎?此操作會立即生效"
|
||||
|
||||
@@ -3,23 +3,12 @@ import { ZConfirmDialog } from '@codex-proxy/ui'
|
||||
|
||||
import { onMounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ClientVersionSettings from '../client-version/index.vue'
|
||||
import AdminApiKeyCard from './AdminApiKeyCard.vue'
|
||||
import AdminPasswordCard from './AdminPasswordCard.vue'
|
||||
import ResponseBodyLimitCard from './ResponseBodyLimitCard.vue'
|
||||
import { useAdminApiKey } from './useAdminApiKey'
|
||||
|
||||
defineProps<{
|
||||
disabled: boolean
|
||||
loading: boolean
|
||||
}>()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const minCodexDesktopVersion = defineModel<string>('minCodexDesktopVersion', { required: true })
|
||||
const minCodexCliVersion = defineModel<string>('minCodexCliVersion', { required: true })
|
||||
const responsesMaxDecompressedBodyMiB = defineModel<string>('responsesMaxDecompressedBodyMiB', { required: true })
|
||||
|
||||
const {
|
||||
loading: adminKeyLoading,
|
||||
regenerating,
|
||||
@@ -51,15 +40,6 @@ onMounted(loadStatus)
|
||||
@copy="copyGeneratedKey"
|
||||
/>
|
||||
|
||||
<fieldset :disabled="disabled" class="col-span-full m-0 grid min-w-0 gap-5 border-0 p-0 @6xl/settings:grid-cols-2" :aria-label="t('settings.access.accessRestrictions')">
|
||||
<ClientVersionSettings
|
||||
v-model:min-codex-desktop-version="minCodexDesktopVersion"
|
||||
v-model:min-codex-cli-version="minCodexCliVersion"
|
||||
:loading="loading"
|
||||
/>
|
||||
<ResponseBodyLimitCard v-model="responsesMaxDecompressedBodyMiB" />
|
||||
</fieldset>
|
||||
|
||||
<ZConfirmDialog
|
||||
v-model="showDeleteModal"
|
||||
:title="t('settings.access.deleteAdminApiKey')"
|
||||
|
||||
@@ -14,6 +14,7 @@ import { isBuiltinProvider, PROVIDER_IDS } from '@/providers/catalog'
|
||||
import AccountAffinityCard from './components/AccountAffinityCard.vue'
|
||||
import AccountWarmupCard from './components/AccountWarmupCard.vue'
|
||||
import SettingsBackupSection from './components/backup/index.vue'
|
||||
import ClientVersionSettings from './components/client-version/index.vue'
|
||||
import ConcurrencyPolicyCard from './components/ConcurrencyPolicyCard.vue'
|
||||
import AccountErrorProtectionCard from './components/error-protection/index.vue'
|
||||
import GuardianReviewCard from './components/GuardianReviewCard.vue'
|
||||
@@ -25,6 +26,7 @@ import RequestHistoryCard from './components/RequestHistoryCard.vue'
|
||||
import RequestLocationCard from './components/RequestLocationCard.vue'
|
||||
import RequestProfileCard from './components/RequestProfileCard.vue'
|
||||
import ResetCreditCard from './components/ResetCreditCard.vue'
|
||||
import ResponseBodyLimitCard from './components/ResponseBodyLimitCard.vue'
|
||||
import RetryPolicyCard from './components/RetryPolicyCard.vue'
|
||||
import RotationStrategyCard from './components/RotationStrategyCard.vue'
|
||||
import SettingsAccessSection from './components/settings-access/index.vue'
|
||||
@@ -253,11 +255,13 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) =>
|
||||
<ModelAliasesCard
|
||||
:mappings="mappings"
|
||||
:loading="loading"
|
||||
class="col-span-full"
|
||||
@add-mapping="addMapping"
|
||||
@update-mapping="updateMapping"
|
||||
@remove-mapping="removeMapping"
|
||||
/>
|
||||
<RequestHistoryCard v-model="usageRetentionDaysValue" />
|
||||
<ResponseBodyLimitCard v-model="responsesMaxDecompressedBodyMiBValue" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -309,7 +313,11 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) =>
|
||||
v-model:enabled="form.accountWarmupEnabled"
|
||||
v-model:cron="form.accountWarmupCron"
|
||||
v-model:model="form.accountWarmupModel"
|
||||
class="col-span-full"
|
||||
/>
|
||||
<ClientVersionSettings
|
||||
v-model:min-codex-desktop-version="form.minCodexDesktopVersion"
|
||||
v-model:min-codex-cli-version="form.minCodexCliVersion"
|
||||
:loading="loading"
|
||||
/>
|
||||
<div class="col-span-full min-w-0">
|
||||
<PrivacyPolicyCard v-model="form.codexPrivacyPolicy" :disabled="disabled" />
|
||||
@@ -322,12 +330,7 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) =>
|
||||
<SettingsAccessSection
|
||||
v-if="visited.has('runtime')"
|
||||
v-show="section === 'runtime'"
|
||||
v-model:min-codex-desktop-version="form.minCodexDesktopVersion"
|
||||
v-model:min-codex-cli-version="form.minCodexCliVersion"
|
||||
v-model:responses-max-decompressed-body-mi-b="responsesMaxDecompressedBodyMiBValue"
|
||||
data-settings-section="runtime"
|
||||
:disabled="disabled"
|
||||
:loading="loading"
|
||||
/>
|
||||
</ZForm>
|
||||
|
||||
|
||||
+9
-4
@@ -1,7 +1,12 @@
|
||||
# v3.57.1
|
||||
# v3.57.2
|
||||
|
||||
## 优化改进
|
||||
|
||||
- HTTP 和 WebSocket 请求未被中间件改写时复用解码结果,减少重复解析
|
||||
- OpenAI 请求体的 zstd 压缩移到后台线程,减少对其他请求的阻塞
|
||||
- 系统设置:将 Codex 最低版本和请求体解压上限移至对应的设置分区,模型别名独占一行
|
||||
|
||||
## 问题修复
|
||||
|
||||
- Antigravity CLI 使用分组模型调用 `search_web` 时,无需指定推理档位即可搜索,原有搜索选项随请求透传
|
||||
- OpenAI Responses 通过 WebSocket 复用连接时,按当前请求的设置省略响应字段和流事件字段,避免沿用其他请求的设置
|
||||
- OpenAI 模型目录保留预热连接握手返回的 ETag,复用同一连接时只确认一次目录版本
|
||||
- Antigravity 的 GenAI 模型目录保留上游模型信息和聊天模型顺序,并列出上游声明的生图模型
|
||||
- OpenAI 接入按通用请求头规则处理 `x-codex-turn-id`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.57.1
|
||||
version: 3.57.2
|
||||
published:
|
||||
'3':
|
||||
stable: 3.57.0
|
||||
rc: 3.57.0
|
||||
beta: 3.57.0
|
||||
alpha: 3.57.0
|
||||
stable: 3.57.1
|
||||
rc: 3.57.1
|
||||
beta: 3.57.1
|
||||
alpha: 3.57.1
|
||||
|
||||
Reference in New Issue
Block a user