From 0118ec01e9daa5b925189c50dcf777152e6568ea Mon Sep 17 00:00:00 2001 From: Zyy Date: Fri, 27 Nov 2026 10:54:00 +0800 Subject: [PATCH] fix(catalog): scope client model menus to executable protocols Use the upstream agent menu for Antigravity and preserve the union of authorized models for generic clients. Select protocol-specific entries from eligible account catalogs before deduplicating model IDs. Co-authored-by: Codex --- .../gateway-api/src/data_plane/antigravity.rs | 10 ++ .../src/data_plane/codex/catalog.rs | 17 +-- .../gateway-api/src/data_plane/error.rs | 10 ++ .../src/data_plane/genai/models.rs | 26 +++- .../crates/gateway-api/src/data_plane/mod.rs | 1 + .../gateway-api/src/data_plane/models.rs | 74 ++++++++-- .../gateway-api/tests/data_plane/models.rs | 16 ++- .../src/engine/execution/contract.rs | 1 + .../src/engine/execution/service.rs | 13 +- .../gateway-core/src/routing/catalog.rs | 87 +++++++----- .../crates/gateway-core/src/routing/mod.rs | 22 +-- .../gateway-core/src/routing/snapshot.rs | 89 ++++++++---- .../tests/engine/execution/identity.rs | 6 +- .../tests/engine/execution/mod.rs | 14 +- .../gateway-core/tests/routing/snapshot.rs | 65 ++++----- .../runtime/src/adapter/catalog.rs | 1 + .../runtime/src/callback/model.rs | 7 +- .../runtime/tests/generation/snapshot.rs | 4 + .../gateway-plugin/sdk/docs/capabilities.md | 2 +- .../antigravity/src/credential/catalog.rs | 66 ++++----- .../src/credential/model_groups.rs | 59 ++------ .../antigravity/src/transport/client.rs | 40 ++++-- .../antigravity/tests/provider/execution.rs | 46 +++---- .../openai/src/credential/catalog/mod.rs | 48 +++---- .../openai/src/credential/catalog/refresh.rs | 3 +- .../providers/openai/src/provider/mod.rs | 8 +- .../providers/openai/src/transport/catalog.rs | 27 ++-- .../tests/credential/catalog/contract.rs | 128 +++++++++++++++--- .../tests/credential/catalog/refresh.rs | 3 +- .../provider/contract/catalog_startup.rs | 3 +- .../openai/tests/provider/contract/mod.rs | 4 +- .../provider/contract/selection_retry.rs | 1 + docs/api.md | 34 ++--- docs/architecture.md | 6 +- 34 files changed, 580 insertions(+), 361 deletions(-) create mode 100644 backend/crates/gateway-api/src/data_plane/antigravity.rs diff --git a/backend/crates/gateway-api/src/data_plane/antigravity.rs b/backend/crates/gateway-api/src/data_plane/antigravity.rs new file mode 100644 index 000000000..04f1fe173 --- /dev/null +++ b/backend/crates/gateway-api/src/data_plane/antigravity.rs @@ -0,0 +1,10 @@ +//! Antigravity 桌面端与 CLI 的模型选择器识别 + +use axum::http::{HeaderMap, header::USER_AGENT}; + +pub(super) fn uses_agent_menu(headers: &HeaderMap) -> bool { + headers + .get(USER_AGENT) + .and_then(|value| value.to_str().ok()) + .is_some_and(|ua| ua.starts_with("antigravity/hub/") || ua.starts_with("antigravity/cli/")) +} diff --git a/backend/crates/gateway-api/src/data_plane/codex/catalog.rs b/backend/crates/gateway-api/src/data_plane/codex/catalog.rs index beb1273fd..c0ee5ffed 100644 --- a/backend/crates/gateway-api/src/data_plane/codex/catalog.rs +++ b/backend/crates/gateway-api/src/data_plane/codex/catalog.rs @@ -1,6 +1,9 @@ //! Codex 模型目录的原生对象保留、通用画像投影与客户端权限裁剪 -use crate::data_plane::{error::openai_error_response, service::DataPlaneService}; +use crate::data_plane::{ + error::{catalog_unavailable_response, openai_error_response}, + service::DataPlaneService, +}; use axum::{ Json, http::StatusCode, @@ -37,7 +40,7 @@ pub(crate) async fn model_catalog( .execution() .client_model_catalog( client, - "codex", + gateway_protocol::openai::OPENAI_PROTOCOL, version, context.as_ref().and_then(|ctx| ctx.extensions.peer_route()), ) @@ -82,16 +85,6 @@ pub(crate) async fn model_catalog( .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(); diff --git a/backend/crates/gateway-api/src/data_plane/error.rs b/backend/crates/gateway-api/src/data_plane/error.rs index 15c1492ae..1bd6d30a9 100644 --- a/backend/crates/gateway-api/src/data_plane/error.rs +++ b/backend/crates/gateway-api/src/data_plane/error.rs @@ -89,6 +89,16 @@ pub fn client_version_rejection_response( ) } +pub(super) fn catalog_unavailable_response() -> Response { + openai_error_response( + StatusCode::SERVICE_UNAVAILABLE, + "Model catalog is temporarily unavailable.", + "server_error", + "model_catalog_unavailable", + ) + .into_response() +} + /// 对外模型不存在 pub fn model_not_found_response() -> (StatusCode, Json) { openai_error_response( diff --git a/backend/crates/gateway-api/src/data_plane/genai/models.rs b/backend/crates/gateway-api/src/data_plane/genai/models.rs index a1f3eac10..252b554c5 100644 --- a/backend/crates/gateway-api/src/data_plane/genai/models.rs +++ b/backend/crates/gateway-api/src/data_plane/genai/models.rs @@ -82,6 +82,7 @@ async fn query_response( } else { MODELS_PATH }; + 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(); middleware::query_response( @@ -89,7 +90,7 @@ async fn query_response( client, input, move |client| async move { - match catalog(&client) { + match catalog(&client, agent_menu) { Ok(models) => match model { Some(model) => models .into_iter() @@ -110,7 +111,7 @@ async fn query_response( .await } -fn catalog(client: &AuthenticatedClient) -> Result, ()> { +fn catalog(client: &AuthenticatedClient, agent_menu: bool) -> Result, ()> { let generate = Operation::Generate( GenerateRequest::from_protocol_payload( ProtocolPayload::json_object(GENAI_PROTOCOL, Map::new()).map_err(|_| ())?, @@ -127,11 +128,22 @@ fn catalog(client: &AuthenticatedClient) -> Result, ()> { let snapshot = client.snapshot(); let scope = client.policy().account_scope(); let counted = snapshot.public_models_for_operation(scope, &count); - Ok(snapshot - .public_models_for_operation(scope, &generate) + let models = if agent_menu { + snapshot.agent_models_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| { + .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"); @@ -139,7 +151,7 @@ fn catalog(client: &AuthenticatedClient) -> Result, ()> { // 上游尚未提供完整 Gemini 元数据,未知版本与 Token 上限保持缺失 json!({ "name": format!("models/{}", model.as_str()), - "displayName": model.as_str(), + "displayName": name, "supportedGenerationMethods": methods, }) }) diff --git a/backend/crates/gateway-api/src/data_plane/mod.rs b/backend/crates/gateway-api/src/data_plane/mod.rs index 47a2d049e..da519150b 100644 --- a/backend/crates/gateway-api/src/data_plane/mod.rs +++ b/backend/crates/gateway-api/src/data_plane/mod.rs @@ -1,5 +1,6 @@ //! 模型数据面的客户端入口、鉴权与协议交付 +mod antigravity; pub mod auth; pub mod body; mod chat_completions; diff --git a/backend/crates/gateway-api/src/data_plane/models.rs b/backend/crates/gateway-api/src/data_plane/models.rs index f697d53e8..8f1c22b74 100644 --- a/backend/crates/gateway-api/src/data_plane/models.rs +++ b/backend/crates/gateway-api/src/data_plane/models.rs @@ -6,7 +6,10 @@ use axum::{ http::{HeaderMap, StatusCode}, response::{IntoResponse, Response}, }; -use gateway_core::{engine::execution::AuthenticatedClient, routing::PublicModelId}; +use gateway_core::{ + engine::execution::AuthenticatedClient, + routing::{ProviderCatalogUnavailable, PublicModelDescriptor, PublicModelId}, +}; use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL; use serde::Deserialize; use serde_json::{Value, json}; @@ -18,7 +21,7 @@ use crate::{ use super::{ auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, - error::{model_not_found_response, openai_error_response}, + error::{catalog_unavailable_response, model_not_found_response, openai_error_response}, }; const MODEL_CREATED_TIMESTAMP: i64 = 1_700_000_000; @@ -67,7 +70,10 @@ async fn models_response( let service = state.data_plane(); if anthropic { - return anthropic_models_response(service.public_models(&client), &query); + return match messages_models(service, &client).await { + Ok(models) => anthropic_models_response(&models, &query), + Err(_) => catalog_unavailable_response(), + }; } if let Some(version) = query .client_version @@ -114,17 +120,20 @@ pub(crate) async fn model_detail( if anthropic { input.protocol = ANTHROPIC_PROTOCOL.to_owned(); } - let response = middleware::query_response( - service.execution(), - client, - input, - move |client| async move { model_detail_response(&state, &client, model_id, anthropic) }, - ) - .await; + let response = + middleware::query_response( + service.execution(), + client, + input, + move |client| async move { + model_detail_response(&state, &client, model_id, anthropic).await + }, + ) + .await; model_protocol_response(response, anthropic).await } -fn model_detail_response( +async fn model_detail_response( state: &ApiState, client: &AuthenticatedClient, model_id: String, @@ -134,7 +143,15 @@ fn model_detail_response( let Ok(public_model) = PublicModelId::new(model_id) else { return model_not_found_response().into_response(); }; - if !service.contains_public_model(client, &public_model) { + let visible = if anthropic { + match messages_models(service, client).await { + Ok(models) => models.binary_search(&public_model).is_ok(), + Err(_) => return catalog_unavailable_response(), + } + } else { + service.contains_public_model(client, &public_model) + }; + if !visible { return model_not_found_response().into_response(); } @@ -149,6 +166,28 @@ fn model_detail_response( .into_response() } +async fn messages_models( + service: &super::service::DataPlaneService, + client: &AuthenticatedClient, +) -> Result, ProviderCatalogUnavailable> { + let context = crate::middleware::current(); + let entries = service + .execution() + .client_model_catalog( + client, + ANTHROPIC_PROTOCOL, + "", + context.as_ref().and_then(|ctx| ctx.extensions.peer_route()), + ) + .await?; + let mut models: Vec<_> = entries + .into_iter() + .map(PublicModelDescriptor::into_model) + .collect(); + models.sort_unstable(); + Ok(models) +} + async fn model_protocol_response(response: Response, anthropic: bool) -> Response { if anthropic { super::messages::project_error_response(response).await @@ -157,7 +196,7 @@ async fn model_protocol_response(response: Response, anthropic: bool) -> Respons } } -fn anthropic_models_response(models: Vec, query: &ModelsQuery) -> Response { +fn anthropic_models_response(models: &[PublicModelId], query: &ModelsQuery) -> Response { let limit = match query.limit.as_deref().unwrap_or("20").parse::() { Ok(limit @ 1..=1000) => limit, _ => { @@ -173,7 +212,12 @@ fn anthropic_models_response(models: Vec, query: &ModelsQuery) -> Respon let cursor = |value: &Option| -> Result, ()> { value .as_ref() - .map(|id| models.iter().position(|model| model == id).ok_or(())) + .map(|id| { + models + .iter() + .position(|model| model.as_str() == id) + .ok_or(()) + }) .transpose() }; let (Ok(after), Ok(before)) = (cursor(&query.after_id), cursor(&query.before_id)) else { @@ -196,7 +240,7 @@ fn anthropic_models_response(models: Vec, query: &ModelsQuery) -> Respon .get(range.clone()) .unwrap_or_default() .iter() - .map(|model| anthropic_model_json(model)) + .map(|model| anthropic_model_json(model.as_str())) .collect::>(); let has_more = if before.is_some() { range.start > start diff --git a/backend/crates/gateway-api/tests/data_plane/models.rs b/backend/crates/gateway-api/tests/data_plane/models.rs index d352bdf1e..87b3cdbca 100644 --- a/backend/crates/gateway-api/tests/data_plane/models.rs +++ b/backend/crates/gateway-api/tests/data_plane/models.rs @@ -82,6 +82,7 @@ async fn anthropic_model_detail_keeps_public_model_access() { let router = api_router(ModelsExecution::new()).await; for (path, expected) in [ ("/v1/models/model-a", StatusCode::OK), + ("/v1/models/responses-only", StatusCode::NOT_FOUND), ("/v1/models/unknown", StatusCode::NOT_FOUND), ] { let response = router @@ -225,7 +226,18 @@ impl ExecutionService for ModelsExecution { _peer_route: Option<&'a axum::http::HeaderValue>, ) -> BoxFuture<'a, Result, ProviderCatalogUnavailable>> { Box::pin(async move { - assert_eq!(protocol, "codex"); + if protocol == gateway_protocol::anthropic::ANTHROPIC_PROTOCOL { + return Ok(["model-a", "model-b"] + .into_iter() + .map(|id| { + PublicModelDescriptor::Adapted(PublicModelProfile::new( + PublicModelId::new(id).unwrap(), + ModelPresentation::default(), + )) + }) + .collect()); + } + assert_eq!(protocol, gateway_protocol::openai::OPENAI_PROTOCOL); self.requested_versions .lock() .expect("versions") @@ -259,7 +271,7 @@ impl ExecutionService for ModelsExecution { } fn contains_public_model(&self, _: &AuthenticatedClient, model: &PublicModelId) -> bool { - matches!(model.as_str(), "model-a" | "model-b") + matches!(model.as_str(), "model-a" | "model-b" | "responses-only") } fn start(&self, _: StartExecution) -> BoxFuture<'_, Result> { diff --git a/backend/crates/gateway-core/src/engine/execution/contract.rs b/backend/crates/gateway-core/src/engine/execution/contract.rs index e326b1cb1..2655892e8 100644 --- a/backend/crates/gateway-core/src/engine/execution/contract.rs +++ b/backend/crates/gateway-core/src/engine/execution/contract.rs @@ -384,6 +384,7 @@ pub trait ExecutionService: Send + Sync { Box::pin(async { Err(ClientAuthenticationError::InvalidKey) }) } fn public_models(&self, client: &AuthenticatedClient) -> Vec; + /// 按请求的生成协议聚合当前 Key 可用的客户端模型目录 fn client_model_catalog<'a>( &'a self, _client: &'a AuthenticatedClient, diff --git a/backend/crates/gateway-core/src/engine/execution/service.rs b/backend/crates/gateway-core/src/engine/execution/service.rs index 6840bf6f7..7f451f70d 100644 --- a/backend/crates/gateway-core/src/engine/execution/service.rs +++ b/backend/crates/gateway-core/src/engine/execution/service.rs @@ -1670,7 +1670,11 @@ impl ExecutionService for DefaultExecutionService { ) .await? else { - for profile in client.snapshot.profiles_for_provider_scope(kind, scope) { + for profile in + client + .snapshot + .profiles_for_provider_scope(kind, scope, Some(protocol)) + { if seen.insert(profile.model().clone()) { result.push(PublicModelDescriptor::Adapted(profile)); } @@ -1679,7 +1683,7 @@ impl ExecutionService for DefaultExecutionService { }; let contributions: Vec<_> = client .snapshot - .contributed_models_for_scope(kind, scope) + .contributed_models_for_scope(kind, scope, Some(protocol)) .collect(); let mut contributed_by_model = BTreeMap::new(); if !contributions.is_empty() @@ -1903,10 +1907,7 @@ impl NestedModelExecutionPort for DefaultExecutionService { }; Ok(models .into_iter() - .map(|model| match model { - PublicModelDescriptor::Native { model, .. } => model, - PublicModelDescriptor::Adapted(profile) => profile.model().clone(), - }) + .map(PublicModelDescriptor::into_model) .collect()) }) } diff --git a/backend/crates/gateway-core/src/routing/catalog.rs b/backend/crates/gateway-core/src/routing/catalog.rs index c388d92dd..495084336 100644 --- a/backend/crates/gateway-core/src/routing/catalog.rs +++ b/backend/crates/gateway-core/src/routing/catalog.rs @@ -19,45 +19,55 @@ pub struct ReasoningModelVariant { pub accounts: BTreeSet, } -/// 具体型号在单个账号目录中声明的能力与说明 +/// 上游账号的聊天菜单声明,未声明时仍可按模型 ID 发现 +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum AgentModelListing { + #[default] + Unspecified, + Hidden, + Listed { + order: usize, + display_name: String, + }, +} + +/// 具体型号在单个账号目录中声明的展示和输出限制 #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct AccountModelMetadata { - pub description: Option, - pub context_window_tokens: Option, - pub max_context_window_tokens: Option, - pub image_input: bool, + pub agent_listing: AgentModelListing, pub max_output_tokens: Option, } -impl ModelPresentation { - /// 分组向客户端承诺的能力必须覆盖每个可选档位和账号 - pub(super) fn apply_member_metadata<'a>( - &mut self, - mut members: impl Iterator>, - ) { - let Some(first) = members.next() else { - return; - }; - let mut has_metadata = first.is_some(); - let mut description = first.and_then(|m| m.description.as_deref()); - let mut window = first.and_then(|m| m.context_window_tokens); - let mut max_window = first.and_then(|m| m.max_context_window_tokens); - let mut images = first.is_some_and(|m| m.image_input); - for member in members { - has_metadata |= member.is_some(); - if description != member.and_then(|m| m.description.as_deref()) { - description = None; - } - window = window.min(member.and_then(|m| m.context_window_tokens)); - max_window = max_window.min(member.and_then(|m| m.max_context_window_tokens)); - images &= member.is_some_and(|m| m.image_input); - } - if has_metadata { - self.description = description.map(str::to_owned); - self.context_window_tokens = window; - self.max_context_window_tokens = max_window; - self.image_input = images; +impl ModelCapabilities { + pub(super) fn agent_menu_entry<'a>( + &'a self, + scope: &super::FrozenAccountScope, + target: &UpstreamModelId, + model: &'a PublicModelId, + ) -> Option<(usize, &'a str)> { + let fallback = (usize::MAX, model.as_str()); + if self.account_metadata.is_empty() { + return Some(fallback); } + self.account_metadata + .iter() + .filter(|(account, _)| scope.allows_model(account, target.as_str())) + .filter_map(|(_, metadata)| match &metadata.agent_listing { + AgentModelListing::Unspecified => Some(fallback), + AgentModelListing::Hidden => None, + AgentModelListing::Listed { + order, + display_name, + } => { + let name = if model.as_str() == target.as_str() { + display_name.as_str() + } else { + model.as_str() + }; + Some((*order, name)) + } + }) + .min_by_key(|(order, _)| *order) } } @@ -74,6 +84,7 @@ pub struct ContributedModelAlias { #[derive(Debug, Clone, PartialEq, Eq)] pub struct ContributedModel { pub owner: String, + pub protocol: String, pub id: PublicModelId, pub provider: ProviderKind, pub accounts: BTreeSet, @@ -110,6 +121,16 @@ pub enum PublicModelDescriptor { Adapted(PublicModelProfile), } +impl PublicModelDescriptor { + #[must_use] + pub fn into_model(self) -> PublicModelId { + match self { + Self::Native { model, .. } => model, + Self::Adapted(profile) => profile.model, + } + } +} + impl ProviderModelContent { pub(crate) fn for_public_model( &self, diff --git a/backend/crates/gateway-core/src/routing/mod.rs b/backend/crates/gateway-core/src/routing/mod.rs index a653d54cc..8f02ea223 100644 --- a/backend/crates/gateway-core/src/routing/mod.rs +++ b/backend/crates/gateway-core/src/routing/mod.rs @@ -11,9 +11,10 @@ pub use crate::account::scope::{ }; pub use crate::identity::ProviderKind; pub use catalog::{ - AccountModelMetadata, ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, - ProviderCatalogPort, ProviderCatalogUnavailable, ProviderModelCapabilities, - ProviderModelContent, ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant, + AccountModelMetadata, AgentModelListing, ContributedModel, ContributedModelAlias, + ProviderCatalogGeneration, ProviderCatalogPort, ProviderCatalogUnavailable, + ProviderModelCapabilities, ProviderModelContent, ProviderModelDescriptor, + PublicModelDescriptor, ReasoningModelVariant, }; pub use snapshot::RuntimeSnapshot; @@ -516,6 +517,13 @@ impl ModelCapabilities { self } + pub(crate) fn supports_generation_protocol(&self, protocol: &str) -> bool { + self.operations.contains(&OperationKind::Generate) + && (self.native_generation_protocols.is_empty() + || self.native_generation_protocols.contains(protocol) + || self.translated_generation_protocols.contains(protocol)) + } + fn match_operation( &self, operation: &crate::operation::Operation, @@ -529,13 +537,7 @@ impl ModelCapabilities { return None; } if matches!(operation, crate::operation::Operation::Generate(_)) - && !self.native_generation_protocols.is_empty() - && !self - .native_generation_protocols - .contains(operation.protocol()) - && !self - .translated_generation_protocols - .contains(operation.protocol()) + && !self.supports_generation_protocol(operation.protocol()) { return None; } diff --git a/backend/crates/gateway-core/src/routing/snapshot.rs b/backend/crates/gateway-core/src/routing/snapshot.rs index 0c816badc..b24618965 100644 --- a/backend/crates/gateway-core/src/routing/snapshot.rs +++ b/backend/crates/gateway-core/src/routing/snapshot.rs @@ -735,9 +735,11 @@ impl RuntimeSnapshot { &self, provider: &ProviderKind, scope: &FrozenAccountScope, + protocol: Option<&str>, ) -> impl Iterator { self.contributed_models().iter().filter(move |model| { &model.provider == provider + && protocol.is_none_or(|protocol| model.protocol == protocol) && model.accounts.iter().any(|account| { scope.account_provider(account) == Some(provider) && scope.allows_model(account, &self.mapped_model(model.id.as_str())) @@ -1114,6 +1116,47 @@ impl RuntimeSnapshot { .collect() } + /// 聊天客户端用可直接路由的具体型号重建档位菜单,来源必须在当前 Key 的账号范围内 + #[must_use] + pub fn agent_models_for_operation( + &self, + scope: &Arc, + operation: &Operation, + ) -> Vec<(PublicModelId, String)> { + let mut entries = Vec::new(); + for model in self.public_models_for_scope(scope) { + let Ok(plan) = self.plan( + &model, + operation, + Arc::clone(scope), + &RoutingContext::default(), + ) else { + continue; + }; + let entry = plan + .candidates() + .iter() + .filter_map(|candidate| { + let target = candidate.upstream_model()?; + let capabilities = self + .provider_models + .get(candidate.provider())? + .get(target)?; + capabilities.agent_menu_entry(candidate.account_scope(), target, &model) + }) + .min_by_key(|(order, _)| *order); + if let Some((order, name)) = entry { + let name = name.to_owned(); + entries.push((order, model, name)); + } + } + entries.sort_unstable(); + entries + .into_iter() + .map(|(_, id, name)| (id, name)) + .collect() + } + /// 合并冻结账号范围内实际存在 Provider 的公开模型画像 #[must_use] pub fn public_model_profiles_for_scope( @@ -1122,7 +1165,7 @@ impl RuntimeSnapshot { ) -> Vec { let mut profiles = BTreeMap::new(); for provider in scope.provider_kinds() { - for profile in self.profiles_for_provider_scope(provider, scope) { + for profile in self.profiles_for_provider_scope(provider, scope, None) { profiles .entry(profile.model().clone()) .or_insert_with(|| profile.presentation().clone()); @@ -1138,36 +1181,23 @@ impl RuntimeSnapshot { &self, provider: &ProviderKind, scope: &FrozenAccountScope, + protocol: Option<&str>, ) -> Vec { let mut profiles = self.public_model_profiles_for_provider(provider); - profiles.retain_mut(|profile| { - let target = self.mapped_model(profile.model.as_str()); - let Some(group) = self.model_group(provider, &target) else { - return self.native_catalog_model_allowed_for_scope( - provider, - profile.model(), - scope, - ); - }; - let models = &self.provider_models[provider]; - let mut members = group - .reasoning_variants - .values() - .flat_map(|variant| { - let model = models.get(&variant.model); - Self::variant_accounts(provider, variant, scope) - .map(move |id| model.and_then(|m| m.account_metadata.get(id))) + profiles.retain(|profile| { + self.native_catalog_model_allowed_for_scope(provider, profile.model(), scope) + && protocol.is_none_or(|protocol| { + self.provider_models + .get(provider) + .and_then(|models| { + models.get(self.mapped_model(profile.model().as_str()).as_str()) + }) + .is_some_and(|model| model.supports_generation_protocol(protocol)) }) - .peekable(); - if members.peek().is_none() { - return false; - } - profile.presentation.apply_member_metadata(members); - true }); // Provider 画像按公开 ID 排序,追加的插件画像保留注册顺序,不参与二分查找 let provider_count = profiles.len(); - for model in self.contributed_models_for_scope(provider, scope) { + for model in self.contributed_models_for_scope(provider, scope, protocol) { match profiles[..provider_count] .binary_search_by(|profile| profile.model().cmp(&model.id)) { @@ -1713,10 +1743,11 @@ impl RuntimeSnapshot { let capable_accounts: BTreeSet<_> = contributions .iter() .filter(|model| { - model - .capabilities - .match_operation(operation, &requirements) - .is_some() + model.protocol == operation.protocol() + && model + .capabilities + .match_operation(operation, &requirements) + .is_some() }) .flat_map(|model| model.accounts.iter()) .filter(|account| { diff --git a/backend/crates/gateway-core/tests/engine/execution/identity.rs b/backend/crates/gateway-core/tests/engine/execution/identity.rs index 16bb88cc0..034705b5a 100644 --- a/backend/crates/gateway-core/tests/engine/execution/identity.rs +++ b/backend/crates/gateway-core/tests/engine/execution/identity.rs @@ -51,7 +51,7 @@ fn identity_queries_keep_frozen_permissions_without_using_execution_resources() &service, client.clone(), CancellationToken::default(), - "codex".into(), + "openai".into(), "0.154.0".into(), ) .await @@ -70,7 +70,7 @@ fn identity_queries_keep_frozen_permissions_without_using_execution_resources() &service, client, cancellation, - "codex".into(), + "openai".into(), "0.154.0".into(), ) .await; @@ -138,7 +138,7 @@ fn execution_scope_limits_apply_only_when_starting_a_model() { &service, client, CancellationToken::default(), - "codex".into(), + "openai".into(), "0.154.0".into(), ) .await diff --git a/backend/crates/gateway-core/tests/engine/execution/mod.rs b/backend/crates/gateway-core/tests/engine/execution/mod.rs index f567fb3d3..5223317b6 100644 --- a/backend/crates/gateway-core/tests/engine/execution/mod.rs +++ b/backend/crates/gateway-core/tests/engine/execution/mod.rs @@ -3757,7 +3757,7 @@ impl Provider for CatalogProvider { > { assert!(scope.allows(&ProviderAccountId::new("acct_start").expect("account"))); assert!(!scope.allows(&ProviderAccountId::new("acct_other").expect("account"))); - assert_eq!((protocol, version), ("codex", "0.154.0")); + assert_eq!((protocol, version), ("openai", "0.154.0")); match self { Self::Unavailable => return Err(gateway_core::routing::ProviderCatalogUnavailable), Self::Empty => return Ok(Some(Vec::new())), @@ -3835,6 +3835,7 @@ fn client_catalog_forwards_scope_maps_whole_objects_and_omits_unroutable_models( .into_iter() .map(|(id, account)| ContributedModel { owner: "catalog-plugin".into(), + protocol: "openai".into(), id: PublicModelId::new(id).unwrap(), provider: ProviderKind::new("openai").unwrap(), accounts: [ProviderAccountId::new(account).unwrap()].into(), @@ -3878,7 +3879,7 @@ fn client_catalog_forwards_scope_maps_whole_objects_and_omits_unroutable_models( Arc::new(crate::RecordingDiagnostics::default()), ); let client = service.authenticate("sk_start_test").expect("authenticate"); - let result = block_on(service.client_model_catalog(&client, "codex", "0.154.0", None)); + let result = block_on(service.client_model_catalog(&client, "openai", "0.154.0", None)); if matches!(provider, CatalogProvider::Unavailable) { assert!( result.is_err(), @@ -3955,11 +3956,18 @@ fn client_catalog_prefers_scoped_profiles_in_provider_order() { }); let contributions = [ ("extra", "acct_start"), + ("messages-only", "acct_start"), ("z-last", "acct_other"), ("shared-model", "acct_start"), ] .map(|(id, account)| ContributedModel { owner: "catalog-plugin".into(), + protocol: if id == "messages-only" { + "anthropic" + } else { + "openai" + } + .into(), id: PublicModelId::new(id).unwrap(), provider: kind.clone(), accounts: [ProviderAccountId::new(account).unwrap()].into(), @@ -3999,7 +4007,7 @@ fn client_catalog_prefers_scoped_profiles_in_provider_order() { ); let client = service.authenticate("sk_start_test").unwrap(); let models = - block_on(service.client_model_catalog(&client, "codex", "0.154.0", None)).unwrap(); + block_on(service.client_model_catalog(&client, "openai", "0.154.0", None)).unwrap(); let profiles = models .iter() .map(|entry| { diff --git a/backend/crates/gateway-core/tests/routing/snapshot.rs b/backend/crates/gateway-core/tests/routing/snapshot.rs index cc8d58c88..6a6f8558f 100644 --- a/backend/crates/gateway-core/tests/routing/snapshot.rs +++ b/backend/crates/gateway-core/tests/routing/snapshot.rs @@ -34,9 +34,9 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() { GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest, }, routing::{ - AccountModelMetadata, ClientRoutingScope, FrozenAccountScope, ProviderModel, - ReasoningModelVariant, RoutingContext, RoutingGroupSnapshot, RuntimeAccount, - RuntimeAccountDirectory, RuntimeSnapshot, + AccountModelMetadata, AgentModelListing, ClientRoutingScope, FrozenAccountScope, + ProviderModel, ReasoningModelVariant, RoutingContext, RoutingGroupSnapshot, + RuntimeAccount, RuntimeAccountDirectory, RuntimeSnapshot, }, validation::RoutingError, }; @@ -131,35 +131,32 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() { ( declared.clone(), AccountModelMetadata { - context_window_tokens: Some(1000), - max_context_window_tokens: Some(1500), - image_input: true, - description: Some("Medium".into()), max_output_tokens: Some(25), + agent_listing: AgentModelListing::Listed { + order: 0, + display_name: "Family Medium".into(), + }, + }, + ), + ( + other.clone(), + AccountModelMetadata { + agent_listing: AgentModelListing::Hidden, + ..Default::default() }, ), - (other.clone(), AccountModelMetadata::default()), ])), ), ProviderModel::new( provider.clone(), UpstreamModelId::new("family-high").unwrap(), caps().with_account_metadata(BTreeMap::from([ - ( - declared.clone(), - AccountModelMetadata { - max_context_window_tokens: Some(2000), - ..Default::default() - }, - ), + (declared.clone(), AccountModelMetadata::default()), ( high_only.clone(), AccountModelMetadata { - context_window_tokens: Some(800), - max_context_window_tokens: Some(1800), - image_input: true, - description: Some("High".into()), max_output_tokens: Some(100), + ..Default::default() }, ), ])), @@ -232,13 +229,6 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() { ["alias", "family"] ); for profile in &profiles { - assert_eq!(profile.presentation().context_window_tokens(), Some(1000)); - assert_eq!( - profile.presentation().max_context_window_tokens(), - Some(1500) - ); - assert!(profile.presentation().image_input()); - assert_eq!(profile.presentation().description(), Some("Medium")); assert_eq!( profile.presentation().supported_reasoning_efforts(), ["medium"] @@ -252,11 +242,6 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() { Arc::clone(scope.directory()), ClientRoutingScope::all_accounts(), ); - let mixed = snapshot.public_model_profiles_for_scope(&all); - assert!(mixed.iter().all(|p| !p.presentation().image_input() - && p.presentation().context_window_tokens().is_none() - && p.presentation().max_context_window_tokens() == Some(1500) - && p.presentation().description().is_none())); let only_high_scope = all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only])); let only_high = snapshot.public_model_profiles_for_scope(&only_high_scope); assert_eq!(only_high.len(), 2); @@ -265,13 +250,6 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() { profile.presentation().supported_reasoning_efforts(), ["high"] ); - assert_eq!(profile.presentation().context_window_tokens(), Some(800)); - assert_eq!( - profile.presentation().max_context_window_tokens(), - Some(1800) - ); - assert!(profile.presentation().image_input()); - assert_eq!(profile.presentation().description(), Some("High")); } // 显式输出只约束返回已知上限的账号,旧目录仍能由上游校验 let output_request = |tokens| { @@ -355,6 +333,11 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() { assert!(listed.contains(&base)); let other_only = Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()]))); + let menu = snapshot.agent_models_for_operation(&other_only, &operation("", count)); + assert!( + menu.iter() + .all(|(model, _)| !matches!(model.as_str(), "family-medium" | "pinned")) + ); assert!( !snapshot .public_models_for_operation(&other_only, &operation("", count)) @@ -443,6 +426,7 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() { ExtensionSetId::new("group-collision".into()).unwrap(), Arc::new(ModelLease(vec![gateway_core::routing::ContributedModel { owner: "fixture".into(), + protocol: "genai".into(), id: base.clone(), provider, accounts: BTreeSet::from([other.clone()]), @@ -574,6 +558,7 @@ fn same_name_native_and_adapted_sources_keep_account_capabilities_separate() { let b = ProviderAccountId::new("acct_b").unwrap(); let mut contribution = ContributedModel { owner: "fixture".into(), + protocol: "openai".into(), id: id.clone(), provider: ProviderKind::new("alpha").unwrap(), accounts: [b.clone()].into(), @@ -710,6 +695,7 @@ fn native_model_without_presentation_cannot_borrow_an_unauthorized_plugin_profil ExtensionSetId::new("private-profile".into()).unwrap(), Arc::new(ModelLease(vec![gateway_core::routing::ContributedModel { owner: "fixture".into(), + protocol: "openai".into(), id: PublicModelId::new("gpt-5.5").unwrap(), provider: ProviderKind::new("openai").unwrap(), accounts: [gateway_core::account::ProviderAccountId::new("acct_private").unwrap()] @@ -740,6 +726,7 @@ fn adapted_models_limit_visibility_and_routing_to_capable_authorized_accounts() let id = PublicModelId::new("adapted-model").unwrap(); let contribution = ContributedModel { owner: "fixture".into(), + protocol: "openai".into(), id: id.clone(), provider, accounts: [account.clone()].into(), @@ -1293,6 +1280,7 @@ fn group_model_access_requires_a_common_group_for_account_and_mapped_model() { ExtensionSetId::new("group-adapter".into()).unwrap(), Arc::new(ModelLease(vec![gateway_core::routing::ContributedModel { owner: "fixture".into(), + protocol: "openai".into(), id: adapted.clone(), provider: ProviderKind::new("alpha").unwrap(), accounts: [a].into(), @@ -2722,6 +2710,7 @@ fn direct_reviewer_model_freezes_only_authorized_native_catalog_accounts() { ExtensionSetId::new("review-catalog".into()).unwrap(), Arc::new(ModelLease(vec![gateway_core::routing::ContributedModel { owner: "review-plugin".into(), + protocol: "openai".into(), id: PublicModelId::new(TARGET).unwrap(), provider: ProviderKind::new("openai").unwrap(), accounts: ["acct_oauth", "acct_unpublished"] diff --git a/backend/crates/gateway-plugin/runtime/src/adapter/catalog.rs b/backend/crates/gateway-plugin/runtime/src/adapter/catalog.rs index 21e890dbc..2906f45e3 100644 --- a/backend/crates/gateway-plugin/runtime/src/adapter/catalog.rs +++ b/backend/crates/gateway-plugin/runtime/src/adapter/catalog.rs @@ -93,6 +93,7 @@ pub(crate) async fn prepare( let p = model.presentation; Ok(ContributedModel { owner: instance.id.clone(), + protocol: target.protocol.clone(), id: PublicModelId::new(model.id) .map_err(|_| AdminError::invalid("适配模型 ID 无效"))?, provider: ProviderKind::new(target.provider.as_str()) diff --git a/backend/crates/gateway-plugin/runtime/src/callback/model.rs b/backend/crates/gateway-plugin/runtime/src/callback/model.rs index 999321c4e..36ba36209 100644 --- a/backend/crates/gateway-plugin/runtime/src/callback/model.rs +++ b/backend/crates/gateway-plugin/runtime/src/callback/model.rs @@ -108,7 +108,12 @@ impl PluginModels { .models( client, call.cancellation.clone(), - request.protocol, + // 插件合同中的 codex 目录使用 Responses 执行协议 + if request.protocol == "codex" { + gateway_protocol::openai::OPENAI_PROTOCOL.to_owned() + } else { + request.protocol + }, request.client_version, ) .await diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/snapshot.rs b/backend/crates/gateway-plugin/runtime/tests/generation/snapshot.rs index 2972cb8e2..67fa0e400 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/snapshot.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/snapshot.rs @@ -54,6 +54,7 @@ async fn adapted_catalog_freezes_adapter_accounts_and_preserves_the_active_gener .await .unwrap(); assert_eq!(active.models().len(), 1); + assert_eq!(active.models()[0].protocol, "openai"); assert_eq!( active.models()[0].accounts.iter().next().unwrap().as_str(), "acct_b" @@ -139,6 +140,9 @@ async fn adapted_catalog_freezes_adapter_accounts_and_preserves_the_active_gener .push(adapter); let mut model = config["model_catalog"]["models"][0].clone(); model["adapter_id"] = "second".into(); + if conflict.is_none() { + config["upstream_registration"]["adapters"][1]["protocol"] = "anthropic".into(); + } if conflict == Some("presentation") { model["presentation"]["display_name"] = "Other".into(); } diff --git a/backend/crates/gateway-plugin/sdk/docs/capabilities.md b/backend/crates/gateway-plugin/sdk/docs/capabilities.md index 1580c48c8..4b463e9a9 100644 --- a/backend/crates/gateway-plugin/sdk/docs/capabilities.md +++ b/backend/crates/gateway-plugin/sdk/docs/capabilities.md @@ -606,7 +606,7 @@ let plugin = PluginBuilder::from_json(include_bytes!("../plugin.json"))? `models` 的每条 `AdaptedModel { id, adapter_id, features, max_output_tokens, presentation }` 声明一个受管适配器提供的公开模型,不要求内置 Provider 的原生目录存在同名条目 -- `adapter_id` 必须指向同实例已绑定的 `upstream_adapter`,Provider 与非空账号集合取自该适配器声明 +- `adapter_id` 必须指向同实例已绑定的 `upstream_adapter`,Provider、生成协议与非空账号集合取自该适配器声明 - 适配器及 binding 的模型范围必须覆盖 `id`;带 Key/账号组条件的适配器不能贡献静态目录,不能丢弃这些条件扩大可见范围 - `features` 使用 `RequestFeature`,仅为生成操作声明工具、图片输入、推理或 JSON Schema 支持;没有声明的能力不能借用同名原生模型的支持事实 - `presentation` 是独立通用画像,字段见 `call::catalog::ModelPresentation`;省略的布尔能力为 false,未声明推理档位不补猜 diff --git a/backend/crates/providers/antigravity/src/credential/catalog.rs b/backend/crates/providers/antigravity/src/credential/catalog.rs index 524e9502b..100e815a9 100644 --- a/backend/crates/providers/antigravity/src/credential/catalog.rs +++ b/backend/crates/providers/antigravity/src/credential/catalog.rs @@ -13,7 +13,8 @@ use gateway_core::{ error::{ProviderError, ProviderErrorKind as Kind}, operation::OperationKind, routing::{ - AccountModelMetadata, ModelCapabilities, ProviderModelCapabilities, UpstreamModelId, + AccountModelMetadata, AgentModelListing, ModelCapabilities, ProviderModelCapabilities, + UpstreamModelId, }, }; use std::{ @@ -169,14 +170,7 @@ impl CatalogService { BTreeMap::>::new(); let mut groups = BTreeMap::new(); let mut search_models = BTreeMap::new(); - let mut catalogs = self.catalogs().await?; - // 多个账号的目录有交集时,按稳定来源顺序合并展示名和档位顺序 - catalogs.sort_by(|(left, _), (right, _)| { - left.first() - .map(|a| &a.account_id) - .cmp(&right.first().map(|a| &a.account_id)) - }); - for (accounts, catalog) in catalogs { + for (accounts, catalog) in self.catalogs().await? { super::model_groups::collect(&mut groups, &catalog, &accounts); if let Some(search_model) = catalog .web_search_models @@ -191,7 +185,7 @@ impl CatalogService { } for (key, model) in catalog.models { let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?; - let metadata = account_metadata(model); + let metadata = account_metadata(&id, model, catalog.agent_model_order.as_ref()); members.entry(id).or_default().extend( accounts .iter() @@ -217,16 +211,17 @@ impl CatalogService { models.insert(id, model.with_catalog_accounts(accounts)); } // 上游已有同名实体时保留原生型号,不让其他账号的分组覆盖它 - for (id, group) in groups { + for (id, variants) in groups { models.entry(id.clone()).or_insert_with(|| { - let accounts = group - .variants + let accounts = variants .values() .flat_map(|v| v.accounts.iter().cloned()) .collect(); - group - .into_model(id, capabilities.clone()) - .with_catalog_accounts(accounts) + ProviderModelCapabilities::new( + id, + capabilities.clone().with_reasoning_variants(variants), + ) + .with_catalog_accounts(accounts) }); } Ok(models.into_values().collect()) @@ -310,29 +305,28 @@ impl CatalogService { } } -fn account_metadata(model: Model) -> AccountModelMetadata { - let description = model - .description - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()); - let tag = model - .tag_description - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()); - let description = match (description, tag) { - (Some(text), Some(tag)) if text != tag => Some(format!("{text} {tag}")), - _ => description.or(tag).map(str::to_owned), +fn account_metadata( + id: &UpstreamModelId, + model: Model, + agent_order: Option<&BTreeMap>, +) -> AccountModelMetadata { + let agent_listing = match agent_order { + None => AgentModelListing::Unspecified, + Some(order) => match order.get(id.as_str()) { + Some(&order) => AgentModelListing::Listed { + order, + display_name: if model.name.trim().is_empty() { + id.as_str().to_owned() + } else { + model.name + }, + }, + None => AgentModelListing::Hidden, + }, }; - // AGY 只声明一个上下文窗口,默认值与可覆盖上限都取 maxTokens - let context_window = model.context_window.filter(|n| *n > 0); AccountModelMetadata { - description, - context_window_tokens: context_window, - max_context_window_tokens: context_window, + agent_listing, max_output_tokens: model.max_output_tokens.filter(|n| *n > 0), - image_input: model.supports_images == Some(true), } } diff --git a/backend/crates/providers/antigravity/src/credential/model_groups.rs b/backend/crates/providers/antigravity/src/credential/model_groups.rs index b9e5860ea..fa416342f 100644 --- a/backend/crates/providers/antigravity/src/credential/model_groups.rs +++ b/backend/crates/providers/antigravity/src/credential/model_groups.rs @@ -1,43 +1,14 @@ -//! 从上游分组声明提取展示名、档位顺序及实际存在的成员 +//! 从上游分组声明解析思考档位及其来源账号 use crate::transport::Catalog; use gateway_core::{ account::AccountCatalogObservation, - routing::{ - ModelCapabilities, ModelPresentation, ProviderModelCapabilities, ReasoningModelVariant, - UpstreamModelId, - }, + routing::{ReasoningModelVariant, UpstreamModelId}, }; use std::collections::BTreeMap; -#[derive(Default)] -pub(super) struct ModelGroup { - display_name: Option, - efforts: Vec, - pub(super) variants: BTreeMap, -} - -impl ModelGroup { - pub(super) fn into_model( - self, - model: UpstreamModelId, - capabilities: ModelCapabilities, - ) -> ProviderModelCapabilities { - let default = self - .efforts - .iter() - .find(|level| *level == "medium") - .or_else(|| self.efforts.first()) - .cloned(); - let presentation = - ModelPresentation::new(self.display_name, None).with_reasoning(default, self.efforts); - ProviderModelCapabilities::new(model, capabilities.with_reasoning_variants(self.variants)) - .with_presentation(presentation) - } -} - pub(super) fn collect( - groups: &mut BTreeMap, + groups: &mut BTreeMap>, catalog: &Catalog, accounts: &[AccountCatalogObservation], ) { @@ -66,23 +37,13 @@ pub(super) fn collect( if catalog.models.contains_key(&target) && let Ok(target) = UpstreamModelId::new(target) { - let entry = groups.entry(group_id.clone()).or_default(); - if entry.display_name.is_none() { - entry.display_name = description["displayName"] - .as_str() - .map(str::trim) - .filter(|name| !name.is_empty()) - .map(str::to_owned); - } - entry - .variants - .entry(level.clone()) - .or_insert_with(|| { - entry.efforts.push(level); - ReasoningModelVariant { - model: target, - accounts: Default::default(), - } + groups + .entry(group_id.clone()) + .or_default() + .entry(level) + .or_insert_with(|| ReasoningModelVariant { + model: target, + accounts: Default::default(), }) .accounts .extend(accounts.iter().map(|account| account.account_id.clone())); diff --git a/backend/crates/providers/antigravity/src/transport/client.rs b/backend/crates/providers/antigravity/src/transport/client.rs index 8c66a5681..0b75c05fd 100644 --- a/backend/crates/providers/antigravity/src/transport/client.rs +++ b/backend/crates/providers/antigravity/src/transport/client.rs @@ -25,6 +25,12 @@ 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>, #[serde(rename = "webSearchModelIds", default)] pub(crate) web_search_models: Vec, pub(crate) models: BTreeMap, @@ -32,22 +38,37 @@ pub(crate) struct Catalog { pub(crate) grouped_models: serde_json::Value, } +#[derive(Deserialize)] +struct AgentModelSort { + #[serde(default)] + groups: Vec, +} + +#[derive(Deserialize)] +struct AgentModelSortGroup { + #[serde(rename = "modelIds", default)] + model_ids: Vec, +} + +fn agent_model_order(sorts: Vec) -> BTreeMap { + let mut order = BTreeMap::new(); + for group in sorts.into_iter().flat_map(|sort| sort.groups) { + for id in group.model_ids { + let index = order.len(); + order.entry(id).or_insert(index); + } + } + order +} + #[derive(Serialize, Deserialize)] pub(crate) struct Model { #[serde(rename = "displayName", default)] pub(crate) name: String, #[serde(rename = "quotaInfo", default)] pub(crate) quota: Option, - #[serde(default)] - pub(crate) description: Option, - #[serde(rename = "tagDescription", default)] - pub(crate) tag_description: Option, - #[serde(rename = "maxTokens", default)] - pub(crate) context_window: Option, #[serde(rename = "maxOutputTokens", default)] pub(crate) max_output_tokens: Option, - #[serde(rename = "supportsImages", default)] - pub(crate) supports_images: Option, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -138,6 +159,8 @@ impl CloudCodeClient { ) -> Result { #[derive(Deserialize)] struct Models { + #[serde(rename = "agentModelSorts", default)] + agent_model_sorts: Option>, #[serde(rename = "webSearchModelIds", default)] web_search_models: Vec, models: BTreeMap, @@ -160,6 +183,7 @@ 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, diff --git a/backend/crates/providers/antigravity/tests/provider/execution.rs b/backend/crates/providers/antigravity/tests/provider/execution.rs index 2ea78b5e3..cf648666e 100644 --- a/backend/crates/providers/antigravity/tests/provider/execution.rs +++ b/backend/crates/providers/antigravity/tests/provider/execution.rs @@ -214,6 +214,10 @@ async fn model_group_menu_routes_chat_and_native_generation_to_declared_members( "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"} }, + "agentModelSorts": [{"groups": [ + {"modelIds":["gemini-4-hydrogen-medium"]}, + {"modelIds":["gemini-4-hydrogen-high","gemini-4-hydrogen-medium","absent"]} + ]}], "groupedModels": { "gemini-4-hydrogen": {"displayName":"Gemini 4 Hydrogen","supportedThinkingLevels":[ {"thinkingSuffix":"MEDIUM"}, {"thinkingSuffix":"high"}, @@ -237,17 +241,7 @@ async fn model_group_menu_routes_chat_and_native_generation_to_declared_members( .iter() .find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen") .unwrap(); - let menu = group.presentation().unwrap(); - assert_eq!(menu.display_name(), Some("Gemini 4 Hydrogen")); - assert_eq!(menu.supported_reasoning_efforts(), ["medium", "high"]); - assert_eq!(menu.default_reasoning_effort(), Some("medium")); - assert_eq!( - models - .iter() - .filter(|entry| entry.presentation().is_some()) - .count(), - 1 - ); + assert!(models.iter().all(|entry| entry.presentation().is_none())); let snapshot = RuntimeSnapshot::new( ConfigRevision::new(1).unwrap(), SettingsValues::new(2, "smart", Default::default(), None, None), @@ -255,29 +249,33 @@ async fn model_group_menu_routes_chat_and_native_generation_to_declared_members( models .iter() .map(|model| { - let entry = ProviderModel::new( + ProviderModel::new( kind.clone(), model.upstream_model().clone(), model.capabilities().clone(), - ); - match model.presentation() { - Some(presentation) => entry.with_presentation(presentation.clone()), - None => entry, - } + ) }) .collect(), vec![], ) .unwrap(); - let profiles = snapshot.public_model_profiles_for_scope(&fixture.store.account_scope()); - let menu = profiles[0].presentation(); - assert!(menu.image_input()); - assert_eq!(menu.context_window_tokens(), Some(900000)); + let discovery = Operation::Generate( + GenerateRequest::from_protocol_payload( + ProtocolPayload::json_object("genai", Default::default()).unwrap(), + ) + .requiring_native_protocol(), + ); + let entries = snapshot.agent_models_for_operation(&fixture.store.account_scope(), &discovery); assert_eq!( - menu.max_context_window_tokens(), - menu.context_window_tokens() + entries + .iter() + .map(|(id, name)| (id.as_str(), name.as_str())) + .collect::>(), + [ + ("gemini-4-hydrogen-medium", "Hydrogen Medium"), + ("gemini-4-hydrogen-high", "Hydrogen High") + ] ); - assert_eq!(menu.description(), Some("Leaving on Nov 30.")); for stream in [false, true] { let response = json!({"response":{"candidates":[{"content":{"parts":[{"text":"OK"}]},"finishReason":"STOP"}]}}); let path_name = if stream { diff --git a/backend/crates/providers/openai/src/credential/catalog/mod.rs b/backend/crates/providers/openai/src/credential/catalog/mod.rs index 343b3bf6f..971bb032e 100644 --- a/backend/crates/providers/openai/src/credential/catalog/mod.rs +++ b/backend/crates/providers/openai/src/credential/catalog/mod.rs @@ -29,7 +29,9 @@ use uuid::Uuid; use super::repository::{CodexCredentialRepository, CredentialRepositoryError}; use crate::profile::CodexWireProfileState; -use crate::transport::{CodexBackendClient, CodexCatalogModel, CodexRequestContext}; +use crate::transport::{ + CodexBackendClient, CodexCatalogModel, CodexModelCatalogSnapshot, CodexRequestContext, +}; const MAX_RESPONSE_ETAG_BYTES: usize = 256; const ACCOUNT_CATALOG_CACHE_TTL: Duration = Duration::from_secs(5 * 60); @@ -121,18 +123,20 @@ impl CodexAccountCatalog { } struct CatalogContent { + generation_protocol: &'static str, models: Vec, ids: Vec, digest: [u8; 32], } impl CatalogContent { - fn new(models: Vec, document: &[u8]) -> Self { + fn new(snapshot: CodexModelCatalogSnapshot) -> Self { use sha2::Digest; Self { - digest: sha2::Sha256::digest(document).into(), - ids: model_ids(&models), - models, + generation_protocol: snapshot.generation_protocol, + digest: sha2::Sha256::digest(&snapshot.document).into(), + ids: model_ids(&snapshot.models), + models: snapshot.models, } } } @@ -287,12 +291,6 @@ struct CatalogCacheState { pending: BTreeMap, } -struct FetchedAccountModels { - models: Vec, - document: bytes::Bytes, - etag: Option, -} - #[derive(Clone)] pub struct CodexCredentialCatalogService { repository: CodexCredentialRepository, @@ -349,6 +347,7 @@ impl CodexCredentialCatalogService { pub async fn client_model_catalog( &self, scope: &FrozenAccountScope, + protocol: &str, ) -> Result, CodexCredentialCatalogError> { let snapshot = self .cached()? @@ -401,6 +400,10 @@ impl CodexCredentialCatalogService { }; available = true; let api = account.authentication_kind() == super::CODEX_AUTHENTICATION_KIND_API_KEY; + // 一个账号目录来自同一协议,先筛选来源再合并同名条目 + if entry.content.generation_protocol != protocol { + continue; + } for (position, model) in entry.content.models.iter().enumerate() { if !scope.allows_model(account.id(), model.request_model().as_str()) { continue; @@ -430,7 +433,12 @@ impl CodexCredentialCatalogService { let id = model.request_model().as_str(); ProviderModelDescriptor { model: model.request_model().clone(), - content: if model.document().protocol() == "codex" { + content: if protocol == gateway_protocol::anthropic::ANTHROPIC_PROTOCOL { + ProviderModelContent::Adapted(ModelPresentation::new( + Some(model.display_name().to_owned()), + None, + )) + } else if model.document().protocol() == "codex" { ProviderModelContent::Native(model.document().clone()) } else { ProviderModelContent::Adapted( @@ -581,13 +589,13 @@ impl CodexCredentialCatalogService { etag: Option, ) -> Result<(CodexAccountCatalog, AccountEntry), CodexCredentialCatalogError> { let observed_at = SystemTime::now(); - let fetched = self.fetch_account_models(client, account).await?; + let mut fetched = self.fetch_account_models(client, account).await?; let observed = AccountCatalogObservation { account_id: account.id().clone(), revision: account.revision(), plan: account.plan_type().map(str::to_owned), observed_at, - etag: fetched.etag.or_else(|| etag.clone()), + etag: fetched.etag.take().or_else(|| etag.clone()), }; if !self .repository @@ -598,7 +606,7 @@ impl CodexCredentialCatalogService { { return Err(CodexCredentialCatalogError::ConcurrentUpdate); } - let content = Arc::new(CatalogContent::new(fetched.models, &fetched.document)); + let content = Arc::new(CatalogContent::new(fetched)); // Redis 仅为管理端短期缓存,失败不能撤销已持久化的目录 let catalog = CodexAccountCatalog::new( scope.cache_scope()?, @@ -693,7 +701,7 @@ impl CodexCredentialCatalogService { &self, client: &CodexBackendClient, account: &ProviderAccount, - ) -> Result { + ) -> Result { tokio::time::timeout(MODEL_CATALOG_TIMEOUT, async { let credential = self.repository.load_runtime_credential(account).await?; let request_id = format!("catalog_{}", Uuid::now_v7().simple()); @@ -723,14 +731,8 @@ impl CodexCredentialCatalogService { None, ) .await; - let snapshot = result.map_err(|error| CodexCredentialCatalogError::Upstream { + result.map_err(|error| CodexCredentialCatalogError::Upstream { detail: error.to_string(), - })?; - let (models, document, etag) = snapshot.into_parts(); - Ok(FetchedAccountModels { - models, - document, - etag, }) }) .await diff --git a/backend/crates/providers/openai/src/credential/catalog/refresh.rs b/backend/crates/providers/openai/src/credential/catalog/refresh.rs index 27d90e3e9..20c9a9b73 100644 --- a/backend/crates/providers/openai/src/credential/catalog/refresh.rs +++ b/backend/crates/providers/openai/src/credential/catalog/refresh.rs @@ -24,8 +24,7 @@ impl CodexCredentialCatalogService { continue; } }; - let (models, _, _) = decoded.into_parts(); - let content = Arc::new(CatalogContent::new(models, &group.document)); + let content = Arc::new(CatalogContent::new(decoded)); for a in group.accounts { let scope = CodexCatalogScope { account_id: a.account_id, diff --git a/backend/crates/providers/openai/src/provider/mod.rs b/backend/crates/providers/openai/src/provider/mod.rs index fb5b0a903..9513b505b 100644 --- a/backend/crates/providers/openai/src/provider/mod.rs +++ b/backend/crates/providers/openai/src/provider/mod.rs @@ -613,11 +613,15 @@ impl Provider for CodexProvider { Option>, gateway_core::routing::ProviderCatalogUnavailable, > { - if protocol != "codex" { + if !matches!( + protocol, + gateway_protocol::openai::OPENAI_PROTOCOL + | gateway_protocol::anthropic::ANTHROPIC_PROTOCOL + ) { return Ok(None); } self.catalog - .client_model_catalog(scope) + .client_model_catalog(scope, protocol) .await .map(Some) .map_err(|_| gateway_core::routing::ProviderCatalogUnavailable) diff --git a/backend/crates/providers/openai/src/transport/catalog.rs b/backend/crates/providers/openai/src/transport/catalog.rs index 72d044c3b..689c37845 100644 --- a/backend/crates/providers/openai/src/transport/catalog.rs +++ b/backend/crates/providers/openai/src/transport/catalog.rs @@ -6,7 +6,7 @@ use std::num::NonZeroU64; use bytes::Bytes; use gateway_core::operation::RawJsonPayload; use gateway_core::routing::{ModelServiceTier, UpstreamModelId}; -use gateway_protocol::anthropic::MessagesModelCapabilities; +use gateway_protocol::anthropic::{ANTHROPIC_PROTOCOL, MessagesModelCapabilities}; use gateway_protocol::openai::OPENAI_PROTOCOL; use reqwest::header::{ETAG, HeaderMap}; use serde::Deserialize; @@ -240,9 +240,10 @@ impl CodexCatalogModel { /// 一次完整成功的 Codex 远端模型快照 #[derive(Clone, PartialEq, Eq)] pub struct CodexModelCatalogSnapshot { - document: Bytes, - models: Vec, - etag: Option, + pub(crate) document: Bytes, + pub(crate) models: Vec, + pub(crate) etag: Option, + pub(crate) generation_protocol: &'static str, } impl std::fmt::Debug for CodexModelCatalogSnapshot { @@ -254,10 +255,6 @@ impl std::fmt::Debug for CodexModelCatalogSnapshot { } impl CodexModelCatalogSnapshot { - pub(crate) fn into_parts(self) -> (Vec, Bytes, Option) { - (self.models, self.document, self.etag) - } - /// 落库的目录沿用相同的上游校验器;协议标记区分普通 API 与 Messages 能力 pub(crate) fn restore(document: &[u8]) -> Result { match document.split_first() { @@ -410,6 +407,7 @@ fn parse_native_model_catalog( models.push(model); } Ok(CodexModelCatalogSnapshot { + generation_protocol: OPENAI_PROTOCOL, document, models, etag, @@ -653,7 +651,7 @@ pub(super) fn parse_api_model_catalog( let mut value: serde_json::Value = serde_json::from_slice(body).map_err(|_| CodexModelCatalogError::InvalidWire)?; // 部分 Responses 上游按客户端版本返回完整 Codex 目录;不能降格为只有 ID 的画像 - if value.get("models").is_some() { + if protocol == OpenAiUpstreamProtocol::ResponsesApi && value.get("models").is_some() { return parse_native_model_catalog(body, etag, OpenAiUpstreamProtocol::ResponsesApi); } if let Some(top) = value.as_object_mut() { @@ -684,8 +682,14 @@ pub(super) fn parse_api_model_catalog( } let mut seen = BTreeSet::new(); let mut models = Vec::with_capacity(wire.data.len()); + let messages_api = protocol == OpenAiUpstreamProtocol::MessagesApi; + let wire_protocol = if messages_api { + ANTHROPIC_PROTOCOL + } else { + OPENAI_PROTOCOL + }; for item in wire.data { - let messages = (protocol == OpenAiUpstreamProtocol::MessagesApi).then(|| { + let messages = messages_api.then(|| { MessagesModelCapabilities::from_model(&serde_json::Value::Object(item.fields)) }); if item.id.trim() != item.id { @@ -698,7 +702,7 @@ pub(super) fn parse_api_model_catalog( .unwrap_or_else(|| request_model.as_str().to_owned()); validate_public_text(&display_name, MAX_DISPLAY_NAME_BYTES, false)?; let document = RawJsonPayload::new( - OPENAI_PROTOCOL, + wire_protocol, Bytes::from( serde_json::to_vec(&serde_json::json!({"id": request_model.as_str()})) .map_err(|_| CodexModelCatalogError::InvalidWire)?, @@ -719,6 +723,7 @@ pub(super) fn parse_api_model_catalog( }); } Ok(CodexModelCatalogSnapshot { + generation_protocol: wire_protocol, document, models, etag: etag.map(validate_etag).transpose()?, diff --git a/backend/crates/providers/openai/tests/credential/catalog/contract.rs b/backend/crates/providers/openai/tests/credential/catalog/contract.rs index c134bf98a..c7867cbd9 100644 --- a/backend/crates/providers/openai/tests/credential/catalog/contract.rs +++ b/backend/crates/providers/openai/tests/credential/catalog/contract.rs @@ -1,6 +1,7 @@ //! 跨模块行为合同测试 use super::*; +use gateway_protocol::openai::OPENAI_PROTOCOL; #[tokio::test] async fn discovery_refresh_and_export_use_the_current_global_profile() { @@ -126,7 +127,7 @@ async fn restored_catalog_is_account_scoped_and_keeps_original_objects() { ), ] { let models = service - .client_model_catalog(&client_scope(&accounts)) + .client_model_catalog(&client_scope(&accounts), OPENAI_PROTOCOL) .await .expect("catalog"); assert_eq!( @@ -148,7 +149,7 @@ async fn restored_catalog_is_account_scoped_and_keeps_original_objects() { } assert!( service - .client_model_catalog(&client_scope(&[])) + .client_model_catalog(&client_scope(&[]), OPENAI_PROTOCOL) .await .is_err() ); @@ -179,13 +180,21 @@ async fn client_catalog_cache_does_not_survive_credential_rotation() { } let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); service.refresh_catalogs().await.unwrap(); - let first = service.client_model_catalog(&scope).await.expect("old"); + let first = service + .client_model_catalog(&scope, OPENAI_PROTOCOL) + .await + .expect("old"); store .repository() .rotate_refreshed_oauth_secret(&account, secret("rotated-access"), None, None) .await .expect("rotate"); - assert!(service.client_model_catalog(&scope).await.is_err()); + assert!( + service + .client_model_catalog(&scope, OPENAI_PROTOCOL) + .await + .is_err() + ); assert!(matches!( service.account_catalog_documents(&account).await, Err(CodexCredentialCatalogError::Credential( @@ -193,7 +202,10 @@ async fn client_catalog_cache_does_not_survive_credential_rotation() { )) )); service.refresh_catalogs().await.unwrap(); - let second = service.client_model_catalog(&scope).await.expect("new"); + let second = service + .client_model_catalog(&scope, OPENAI_PROTOCOL) + .await + .expect("new"); assert_ne!(first, second); server.verify().await; } @@ -256,7 +268,12 @@ async fn failed_client_catalog_never_falls_back_to_an_out_of_scope_account_or_ca let scope = client_scope(&[allowed]); assert!(service.refresh_catalogs().await.is_err()); for _ in 0..2 { - assert!(service.client_model_catalog(&scope).await.is_err()); + assert!( + service + .client_model_catalog(&scope, OPENAI_PROTOCOL) + .await + .is_err() + ); } assert_eq!(server.received_requests().await.expect("requests").len(), 2); server.verify().await; @@ -473,7 +490,7 @@ async fn failed_oauth_catalog_does_not_hide_healthy_peers_or_borrow_their_models let service = service_with_catalog_cache(&store, server.uri(), catalog_cache()); service.refresh_catalogs().await.unwrap(); let models = service - .client_model_catalog(&client_scope(&[failed.clone(), healthy])) + .client_model_catalog(&client_scope(&[failed.clone(), healthy]), OPENAI_PROTOCOL) .await .unwrap(); assert_eq!(models.len(), 1); @@ -664,7 +681,7 @@ async fn api_key_catalogs_are_isolated_and_join_oauth_without_claiming_native_me ["api-second"] ); let combined = service - .client_model_catalog(&client_scope(&[oauth_account, a.clone()])) + .client_model_catalog(&client_scope(&[oauth_account, a.clone()]), OPENAI_PROTOCOL) .await .unwrap(); assert_eq!( @@ -782,7 +799,10 @@ async fn api_key_client_catalog_distinguishes_filtered_empty_from_fetch_failure( let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache()); assert_eq!(service.refresh_catalogs().await.is_ok(), status == 200); let result = service - .client_model_catalog(&client_scope(&[store.account("acct_api").unwrap()])) + .client_model_catalog( + &client_scope(&[store.account("acct_api").unwrap()]), + OPENAI_PROTOCOL, + ) .await; if status == 200 { assert!( @@ -848,7 +868,7 @@ async fn api_key_client_catalog_keeps_native_sources_stable_and_account_scoped() (&accounts[2..], "Second native"), ] { let models = service - .client_model_catalog(&client_scope(scope_accounts)) + .client_model_catalog(&client_scope(scope_accounts), OPENAI_PROTOCOL) .await .unwrap(); assert_eq!(models.len(), 1); @@ -886,9 +906,17 @@ async fn api_key_client_catalog_cache_is_invalidated_by_credential_revision() { .expect(1) .mount(&upstream) .await; - assert!(service.client_model_catalog(&scope).await.is_err()); + assert!( + service + .client_model_catalog(&scope, OPENAI_PROTOCOL) + .await + .is_err() + ); service.refresh_catalogs().await.unwrap(); - let models = service.client_model_catalog(&scope).await.unwrap(); + let models = service + .client_model_catalog(&scope, OPENAI_PROTOCOL) + .await + .unwrap(); assert_eq!(models[0].model.as_str(), model); upstream.verify().await; if model == "before-rotation" { @@ -916,6 +944,65 @@ async fn api_key_client_catalog_cache_is_invalidated_by_credential_revision() { } } +#[tokio::test] +async fn client_catalog_chooses_same_named_models_within_protocol_and_account_scope() { + use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL; + use provider_openai::credential::{ApiKeyProtocol, ResponsesTransport}; + let store = Arc::new(MemoryAccountStore::default()); + let responses = MockServer::start().await; + let messages = MockServer::start().await; + for (server, id, protocol) in [ + (&responses, "responses-only", ApiKeyProtocol::Responses), + (&messages, "messages-only", ApiKeyProtocol::Messages), + ] { + store + .seed_api_key_for_protocol( + &format!("acct_{id}"), + server.uri(), + ResponsesTransport::Http, + protocol, + ) + .await; + Mock::given(method("GET")) + .and(path("/models")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "data":[{"id":id},{"id":"shared"}], "has_more":false + }))) + .mount(server) + .await; + } + let service = service_with_catalog_cache(&store, responses.uri(), catalog_cache()); + service.refresh_catalogs().await.unwrap(); + let accounts = [ + store.account("acct_responses-only").unwrap(), + store.account("acct_messages-only").unwrap(), + ]; + for (protocol, matching) in [(OPENAI_PROTOCOL, 0), (ANTHROPIC_PROTOCOL, 1)] { + for scope in [ + &accounts[..], + &accounts[matching..=matching], + &accounts[1 - matching..=1 - matching], + ] { + let models = service + .client_model_catalog(&client_scope(scope), protocol) + .await + .unwrap(); + let ids: Vec<_> = models.iter().map(|entry| entry.model.as_str()).collect(); + if scope + .iter() + .any(|account| account.id() == accounts[matching].id()) + { + assert_eq!( + ids, + [["responses-only", "messages-only"][matching], "shared"] + ); + } else { + assert!(ids.is_empty()); + } + } + } +} + #[tokio::test] async fn api_key_catalog_hides_only_known_specialized_models_in_codex_picker() { use provider_openai::credential::ResponsesTransport; @@ -964,7 +1051,7 @@ async fn api_key_catalog_hides_only_known_specialized_models_in_codex_picker() { } let account = store.account("acct_api").expect("API account"); let models = service - .client_model_catalog(&client_scope(&[account])) + .client_model_catalog(&client_scope(&[account]), OPENAI_PROTOCOL) .await .expect("client catalog"); let actual_visibility = models.iter().map(|model| { @@ -1058,7 +1145,10 @@ async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() { service.cached_account_models(&oauth_account).unwrap() ); let mixed = service - .client_model_catalog(&client_scope(&[oauth_account, api_account.clone()])) + .client_model_catalog( + &client_scope(&[oauth_account, api_account.clone()]), + OPENAI_PROTOCOL, + ) .await .expect("mixed client catalog"); assert_eq!(mixed.len(), 1); @@ -1067,7 +1157,10 @@ async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() { }; assert_eq!(payload, before.models()[0].document()); let api_only = service - .client_model_catalog(&client_scope(std::slice::from_ref(&api_account))) + .client_model_catalog( + &client_scope(std::slice::from_ref(&api_account)), + OPENAI_PROTOCOL, + ) .await .expect("API client catalog"); assert!(matches!( @@ -1274,7 +1367,10 @@ async fn ten_thousand_restored_accounts_serve_concurrent_native_reads_while_upst let scope = scope.clone(); tokio::spawn(async move { let started = Instant::now(); - let models = catalog.client_model_catalog(&scope).await.unwrap(); + let models = catalog + .client_model_catalog(&scope, OPENAI_PROTOCOL) + .await + .unwrap(); assert!(!models.is_empty()); started.elapsed() }) diff --git a/backend/crates/providers/openai/tests/credential/catalog/refresh.rs b/backend/crates/providers/openai/tests/credential/catalog/refresh.rs index 8381df631..906cf6c0e 100644 --- a/backend/crates/providers/openai/tests/credential/catalog/refresh.rs +++ b/backend/crates/providers/openai/tests/credential/catalog/refresh.rs @@ -1,6 +1,7 @@ //! 对应生产职责的行为测试 use super::*; +use gateway_protocol::openai::OPENAI_PROTOCOL; #[tokio::test] async fn invalidation_queues_background_refresh_without_an_upstream_etag() { @@ -212,7 +213,7 @@ async fn api_key_background_catalog_preserves_negotiated_reasoning_levels_and_en ["z-unknown-reasoning", "vendor/model"] ); let models = service - .client_model_catalog(&client_scope(&[account])) + .client_model_catalog(&client_scope(&[account]), OPENAI_PROTOCOL) .await .unwrap(); assert_eq!( diff --git a/backend/crates/providers/openai/tests/provider/contract/catalog_startup.rs b/backend/crates/providers/openai/tests/provider/contract/catalog_startup.rs index 02e3674a6..ffdfcb86f 100644 --- a/backend/crates/providers/openai/tests/provider/contract/catalog_startup.rs +++ b/backend/crates/providers/openai/tests/provider/contract/catalog_startup.rs @@ -6,6 +6,7 @@ use gateway_core::routing::snapshot::{ RuntimeSnapshotCompiler, SnapshotFacts, SnapshotProviderAccountFacts, SnapshotStoreError, SnapshotStorePort, }; +use gateway_protocol::openai::OPENAI_PROTOCOL; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::Notify; use wiremock::{Request, Respond}; @@ -198,7 +199,7 @@ async fn issue_666_same_plan_special_model_remains_visible_and_routes_only_to_it catalog.refresh_catalogs().await.unwrap(); assert!( catalog - .client_model_catalog(&contract_account_scope()) + .client_model_catalog(&contract_account_scope(), OPENAI_PROTOCOL) .await .unwrap() .iter() diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index b71d13f8f..0f985753e 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -11061,7 +11061,7 @@ async fn provider_compiles_catalog_presentation_for_codex_models() { .query_client_model_catalog( &ClientApiKeyId::new("key_catalog").unwrap(), &scope, - "codex", + "openai", "0.154.0", None, ) @@ -11979,7 +11979,7 @@ async fn api_key_default_http_uses_own_prefix_plain_json_and_only_own_authentica .query_client_model_catalog( &ClientApiKeyId::new("key_catalog").unwrap(), &contract_account_scope(), - "codex", + "openai", "1.0.0", None, ) diff --git a/backend/crates/providers/openai/tests/provider/contract/selection_retry.rs b/backend/crates/providers/openai/tests/provider/contract/selection_retry.rs index f7d5dc377..39f6ce8cb 100644 --- a/backend/crates/providers/openai/tests/provider/contract/selection_retry.rs +++ b/backend/crates/providers/openai/tests/provider/contract/selection_retry.rs @@ -158,6 +158,7 @@ async fn contributed_model_scope_survives_affinity_and_account_rotation() { ExtensionSetId::new("scope-test".into()).unwrap(), Arc::new(Catalog(vec![ContributedModel { owner: "scope-test".into(), + protocol: "openai".into(), id: PublicModelId::new("gpt-5.4").unwrap(), provider: kind, accounts: contributed_accounts diff --git a/docs/api.md b/docs/api.md index b2375f6e6..e390654fb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -653,7 +653,7 @@ Responses WebSocket 接受文本消息,`response.create` 在同一连接串行 | --- | --- | | SSE → SSE | 结束本次响应流,底层 HTTP 连接由 HTTP 连接池管理 | | SSE → WS | 结束 SSE,上游 WS 归池,按无客户端绑定的空闲期限回收 | -| WS → SSE | 通常保留下游 WS。Antigravity 生成和需要完整重放的 OpenAI 大包回退按下述规则重连 | +| WS → SSE | 通常保留下游 WS。需要完整重放的 OpenAI 大包回退按下述规则重连 | | WS → WS | 保留当前绑定的上游 WS,支持下一轮续接 | 活跃客户端 WS 的绑定不受普通空闲回收期限约束;上游 Close(不限关闭码)、EOF、传输读写失败、总寿命到期或连接被回收仍可能使连接内续接失效, @@ -691,11 +691,7 @@ OpenAI 的协议预热、依赖 WS 的非持久化新链和连接内续接要求 客户端配置的 `supports_websockets` 只控制第一段连接,不是服务端传输策略开关。 上游在响应终态前发送 Close 1000 仍属于失败,不能按“正常关闭”计为成功 -Antigravity 在 Responses WS 上收到新链的 `generate=false` 后,本地依次返回 -`response.created` 和 `response.completed`,输出为空,Token 为零。即使带有历史和工具定义,也不选号或调用 Google。 -预热 ID 仅标识这次应答。后续生成按下文的完整输入重放规则处理。 -Antigravity 的 HTTP 新链预热和内建 xAI 的预热返回 `400 unsupported_prewarm`。 -`generate=true` 或省略该字段时正常生成,外部插件按各自的协议能力处理 +内建 xAI 对非生成预热返回 `400 unsupported_prewarm` OpenAI Responses 上游 WS 按握手响应头 `x-codex-websocket-max-message-bytes` 声明的上限, 检查最终 `response.create` 文本的 UTF-8 字节数。允许发送的文本超过 1 MiB 时,每 1 MiB 分一帧,接收方仍收到一条消息。 @@ -715,7 +711,7 @@ OpenAI Responses 上游 WS 按握手响应头 `x-codex-websocket-max-message-byt 切到 HTTP;其他客户端需要自行实现此合同。代理不缓存 transcript,不把增量输入当作独立新链, 连接内续接失去原连接时仍需客户端恢复 -Antigravity 的 Responses 请求,以及 OpenAI 因大小走 HTTP/SSE 且需要完整重放的请求,在 +OpenAI 因大小走 HTTP/SSE 且需要完整重放的请求,在 `response.completed` 成功写出并完成结算后,以关闭码 1000 正常关闭空闲的下游 WS。 客户端在新连接上发送完整输入(含工具调用和结果),省略 `previous_response_id`。 已接收的后续请求按序处理,若增量先到,仍按 `400 previous_response_not_found` 恢复。启用 WS 帧中间件时保留连接 @@ -733,13 +729,13 @@ WebSocket 在交付业务事件前合成的错误保留已确认的失败状态 携带 `anthropic-version` 或 `x-api-key` 请求头时,`GET /v1/models` 返回 Messages 模型目录: `{ data, first_id, last_id, has_more }`,单条模型使用 `type: "model"`、`id`、`display_name` 和 `created_at` -模型范围仍由 Client Key 权限、分组与别名决定,未知发布日期使用 Unix epoch,未知能力和 Token 上限为 null +列表与详情只展示当前 Key 的账号能通过 Messages 调用的模型及其别名。未知发布日期使用 Unix epoch,未知能力和 Token 上限为 null 该格式支持 `after_id`、`before_id` 游标和 `limit`,默认每页 20 条,范围 1–1000;未知游标或无效限制返回 400 `GET /v1/models/{model_id}` 使用同一显式协议头选择格式和错误合同,不根据 User-Agent 猜测协议 -未携带上述协议头时,`GET /v1/models` 默认返回 OpenAI 兼容列表 `{"object": "list", "data": [...]}`;请求携带非空 -`client_version` query 参数(Codex 客户端)时改为返回 Codex 专用目录合同 `{"models": [...]}` +使用 Bearer Key 并省略上述协议头时,`GET /v1/models` 返回 OpenAI 兼容列表 `{"object": "list", "data": [...]}`。混合分组得到当前 Key 可见的各平台模型并集,同名 ID 只出现一次。 +携带非空 `client_version` 查询参数时,返回 Codex 专用目录 `{"models": [...]}` OpenAI Provider 使用后台按账号发现的目录,客户端版本只选择输出格式。目录完整保留每个原生模型 JSON 对象,包括 `base_instructions`、`model_messages`、`service_tiers`、工具与能力字段,以及未知嵌套字段、显式 `null` @@ -752,13 +748,7 @@ API Key 上游返回完整 Codex `models` 目录时沿用该合同;仅返回 xAI 没有 Codex 原生目录,使用官方 CLI proxy 当前目录生成通用画像。推理菜单读取 `reasoning_efforts` 对象列表,默认值只取菜单中的显式标记;缺失时保持未知 -Antigravity 在 Codex 目录中按上游声明的分组展示基础模型。思考菜单只列出当前 Key 可调用的成员档位, -默认选中 `medium`,不可用时选首个可用档位。例如对 `gemini-4-hydrogen` 发送 `reasoning.effort: "high"`, -会路由到 `gemini-4-hydrogen-high`。普通模型列表仍提供可直接调用的完整型号 - -分组中的可用档位和账号都支持图片时,Codex 可发送图片。网关取可用成员中最小的 `maxTokens` 作为该组的默认上下文窗口和可覆盖上限, -有成员未声明时保持未知。成员说明一致时,选模列表显示上游用途说明或下线提示。 -显式请求的输出 Token 数按实际型号和账号的 `maxOutputTokens` 选路,未声明上限的账号交由上游校验 +Codex 目录按 Responses 执行能力筛选。仅具有内置 Antigravity 或 Messages 账号的 Key 会收到空目录。插件适配模型沿用适配器声明的协议与账号范围 已知模型只路由到明确提供该模型的 Provider,账号不可用时不转发给其他平台的未知模型通道。 未知模型只在当前范围与路由约束下存在唯一 Provider 透传候选时发送;无法确定归属时返回不可用错误, @@ -779,7 +769,9 @@ OpenAI 聚合当前 Key 范围内合格 OAuth 和 API Key 账号的目录。每 Gemini 客户端使用 `GET /v1beta/models` 和 `GET /v1beta/models/{model}`。目录只包含当前 Key 可通过原生 GenAI 入口路由的已知模型,沿用账号范围、模型限制和别名;不会将其他协议的同名模型作为原生候选。条目提供 `name: "models/{id}"`、`displayName` 与 `supportedGenerationMethods`,未知的版本、上下文和输出上限不补默认值 -Gemini 列表按模型 ID 排序,支持 `pageSize`(默认 50,上限 1000,0 使用默认值)和 `pageToken`;后续页保持相同的 `pageSize`,末页省略 `nextPageToken`。详情查不到模型返回 Google RPC 格式的 404;分页及详情均重新检查当前 Key 的可见范围,不发起上游模型请求 +普通 Gemini 列表按模型 ID 排序,支持 `pageSize`(默认 50,上限 1000,0 使用默认值)和 `pageToken`;后续页保持相同的 `pageSize`,末页省略 `nextPageToken`。详情查不到模型返回 Google RPC 格式的 404;分页及详情均重新检查当前 Key 的可见范围,不发起上游模型请求 + +Antigravity 桌面端和 CLI 的 GenAI 模型列表按上游 `agentModelSorts` 顺序返回当前 Key 可用的具体聊天型号和展示名。客户端用这些型号合并基础模型并选择思考强度。旧账号目录缺少聊天菜单声明时,刷新前仍可按具体型号发现。完整型号的详情与直接调用沿用账号模型权限。对基础模型显式指定分组档位时,网关按上游声明选择具体型号,并按该型号和账号的 `maxOutputTokens` 检查请求的输出上限 `service_tiers` 中的 `name` 用于生成 `/fast` 等命令,`id` 用作请求的 `service_tier` 值。 上游未声明档位或返回空数组时,网关不补充档位。档位更新后,客户端需重新加载模型目录 @@ -822,11 +814,7 @@ Images 与 Search 保留通过现有过滤规则的普通业务请求头及多 xAI Provider 使用上游原生 Responses wire,只有 Chat 请求装配直接转换。上游结构化错误的 message/code/type 可透出,内嵌的账号指纹 UUID 脱敏。 模型名完整保留,不剥离前缀;别名使用显式模型映射。目录读取失败返回错误,不用硬编码型号补全能力 -xAI 的 `reasoning.effort` 接受 `none / minimal / low / medium / high / xhigh / max`,去除两端 -空白并转为小写后保留档位,不按模型名称降档或删除;模型是否支持该选择由上游判断。 -未知值或错误类型返回字段错误,其他 reasoning 字段保留。`web_search.filters` 支持 -`allowed_domains` 与 `excluded_domains`,两者不能同时为非空;客户端函数与托管搜索工具 -同名时使用内部别名,并在返回工具调用时还原客户端名称。搜索工具顶层的 `allowed_domains` 不受支持,返回请求错误 +原生 Responses 请求的 `reasoning.effort`、工具声明和搜索过滤条件随正文交给 xAI 校验 #### 容量拒绝与重试 diff --git a/docs/architecture.md b/docs/architecture.md index d3e750539..2504d6c4f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -145,7 +145,7 @@ flowchart LR - **模型目录与路由共用事实**:`model_catalog` 的目录贡献保存在发布代次引用中,直接别名由插件负责条目正确性,条目冲突或目标不存在不阻止宿主快照发布。 请求按顺序取首个匹配别名并直接使用其目标,不递归解析插件别名;Provider、账号权限与目标能力沿原选路流程处理。 - 适配模型从同实例受管适配器继承静态账号范围,Core 按冻结权限与请求能力收窄候选账号,不改变调度评分、亲和或租约。 + 适配模型从同实例受管适配器继承生成协议和静态账号范围,Core 按冻结权限与请求能力收窄候选账号,不改变调度评分、亲和或租约。 公开列表、详情、客户端目录和受管模型查询复用同一组目录贡献与账号访问范围。Core 保留 Provider 的完整原生对象,在投影通用画像时应用当前账号范围的插件声明。合并顺序见 SDK [模型目录](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型目录) - **重试由 Core 裁决**:`retry_policy` 只能停止或继续 Core 已允许的恢复路径;绑定按确定顺序委托,故障回退宿主。 发送、交付、续接、外部副作用、预算和取消限制不进入插件控制面,策略返回后继续复核 @@ -585,6 +585,7 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模 - `responses`、`chat_completions`、`messages`、`genai` 拥有各自协议入口,生成与计数共用 `generation` 的执行交付、取消传播和连接生命周期 - `codex` 拥有客户端模型目录投影、Guardian、子代理与轮次身份解析,Responses 入口组合这些扩展;Responses 同时服务 OpenAI 与 xAI,不绑定某个 Provider +- `antigravity` 识别桌面端和 CLI 对聊天选模目录的请求,GenAI 入口按账号声明的展示名和顺序返回可执行型号 - `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有 - `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者 @@ -715,8 +716,7 @@ xAI 的 Chat 路径将 custom 工具包装为 function 输入,并在直接返 客户端到代理与代理到上游的传输选择相互独立。客户端的 `supports_websockets = false` 不禁止 Provider 使用上游 WebSocket。OpenAI Provider 按线程维护 WS 失败预算,消息大小上限随上游 -物理连接保存。OpenAI 的超限回退与 Antigravity 的 Responses 桥接按各自的续接能力,在终态事件上提示下游重连。 -该提示只属于当前交付,与 Provider 的私有会话状态独立。Antigravity 可在路由和客户端准入后本地应答新链 WS 预热,Core 按零次上游尝试结算。 +物理连接保存。超限回退需要完整重放时,OpenAI 在终态事件上提示下游重连。 API 确认成功写出、完成结算且入站队列空闲后关闭连接。响应终态前的 Close 1000 仍视为失败, 后续恢复请求成功也不改写原失败请求的结果