mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 08:00:38 +00:00
fix(antigravity): preserve catalog metadata and image discovery
Preserve upstream model descriptors in the AGY GenAI catalog. Follow upstream chat ordering and keep declared image models discoverable without exposing internal helpers in the model menu. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
//! Antigravity 桌面端与 CLI 的模型选择器识别及菜单投影
|
||||
//! Antigravity 桌面端与 CLI 的模型发现请求识别及目录投影
|
||||
|
||||
use axum::http::{HeaderMap, header::USER_AGENT};
|
||||
use gateway_core::routing::{AgentModelListing, ExecutableModelMetadata, PublicModelId};
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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| {
|
||||
|
||||
+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 与调用事实,
|
||||
|
||||
Reference in New Issue
Block a user