Compare commits

...
9 Commits
Author SHA1 Message Date
ZyyandCodex ef45165d8d chore: bump version to 3.55.3
Co-authored-by: Codex <noreply@openai.com>
2026-11-26 13:42:00 +08:00
ZyyandCodex 75c51b9955 fix(antigravity): honor Responses web search tool choices
Preserve function tools on coding requests with optional web search. Route required live searches to the authorized account search model and return grounded citations in JSON and streaming responses.

Co-authored-by: Codex <noreply@openai.com>
2026-11-26 13:40:25 +08:00
ZyyandCodex 319b3be0f8 feat(antigravity): expose scoped model groups in the Codex catalog
Project reasoning variants, descriptions, image support, and context windows from the models available to each client key. Apply output limits to the selected model and account.

Co-authored-by: Codex <noreply@openai.com>
2026-11-26 12:53:37 +08:00
ZyyandCodex 6de36f4b54 fix(genai): keep native SSE streams silent between frames
Let the downstream endpoint select keepalive behavior before the first frame and during delivery. Preserve HTTP error status when native Gemini generation fails before producing output.

Refs #777

Co-authored-by: Codex <noreply@openai.com>
2026-11-26 11:54:26 +08:00
ZyyandCodex 74ac905abf test(openai): borrow quota window attribution in assertions
Co-authored-by: Codex <noreply@openai.com>
2026-11-26 11:54:18 +08:00
ZyyandCodex a6bdeb17f2 fix(accounts): attribute Antigravity window usage by model group
Co-authored-by: Codex <noreply@openai.com>
2026-11-26 11:30:57 +08:00
ZyyandCodex ce966d3d04 fix(antigravity): refresh stale quota after account activity
Co-authored-by: Codex <noreply@openai.com>
2026-11-26 11:30:47 +08:00
ZyyandCodex 20d04ae57a fix(ui): rebalance model and usage table column widths
Co-authored-by: Codex <noreply@openai.com>
2026-11-26 00:57:19 +08:00
github-actions[bot] 3141bb1a9e chore(release): update release channels to 3.55.2 2026-11-25 16:29:03 +00:00
65 changed files with 2100 additions and 333 deletions
@@ -1,6 +1,9 @@
//! 多 Provider 账号目录与连接测试的公共事实
use std::{collections::BTreeMap, pin::Pin};
use std::{
collections::{BTreeMap, BTreeSet},
pin::Pin,
};
use chrono::{DateTime, Utc};
use futures::Stream;
@@ -192,6 +195,8 @@ pub struct AccountUsage {
/// `key` 只用于把聚合结果关联回调用方的窗口,不承载 Provider 私有语义
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountUsageWindowQuery {
/// 指定时只汇总这些上游模型的请求
pub models: Option<BTreeSet<String>>,
pub account_id: String,
pub key: String,
pub range: TimeRange,
@@ -1,6 +1,6 @@
//! Provider 管理能力交换的中立 Command 与 Result
use std::{fmt, pin::Pin};
use std::{collections::BTreeSet, fmt, pin::Pin};
use async_trait::async_trait;
use bytes::Bytes;
@@ -774,11 +774,13 @@ impl fmt::Debug for RotateCredential {
}
/// 通用账号用量能否可靠归属到一个 Provider quota 窗口
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QuotaLocalUsageAttribution {
/// 窗口覆盖账号的全部请求,可按账号与时间范围聚合
AccountWide,
/// 窗口需要 Provider / 模型级归属,通用账号聚合不可用
/// Provider 已确认该窗口覆盖的上游模型 ID
Models(BTreeSet<String>),
/// 缺少可用于归属本地用量的事实
Unavailable,
}
@@ -1186,7 +1188,7 @@ impl ProviderQuota {
fn quota_usage_priority(window: &ProviderQuotaWindow) -> (u8, u8) {
let attribution = match window.local_usage_attribution {
QuotaLocalUsageAttribution::AccountWide => 0,
QuotaLocalUsageAttribution::Unavailable => 1,
QuotaLocalUsageAttribution::Models(_) | QuotaLocalUsageAttribution::Unavailable => 1,
};
let duration = match window.group.as_str() {
"shortTerm" if window.window_seconds.is_some_and(is_week_window) => 1,
@@ -387,12 +387,11 @@ impl DefaultAccountsService {
for (item, quota) in accounts.iter().zip(quotas) {
for window in &mut quota.windows {
if window.local_usage.is_none()
&& window.local_usage_attribution == QuotaLocalUsageAttribution::AccountWide
&& window.local_usage_attribution != QuotaLocalUsageAttribution::Unavailable
{
let key = (item.account.id.clone(), window.key.clone());
if let Some(usage) = usage_by_window.get(&key) {
window.local_usage = Some(usage.clone());
}
window.local_usage = usage_by_window
.get(&(item.account.id.clone(), window.key.clone()))
.cloned();
}
}
}
@@ -426,6 +425,7 @@ impl DefaultAccountsService {
return None;
}
Some(AccountUsageWindowQuery {
models: None,
account_id: item.account.id.clone(),
key: "account-lifetime".to_owned(),
range: TimeRange {
@@ -1397,13 +1397,16 @@ fn quota_usage_window(
account_id: &str,
window: &ProviderQuotaWindow,
) -> Option<AccountUsageWindowQuery> {
if window.local_usage_attribution != QuotaLocalUsageAttribution::AccountWide {
return None;
}
let models = match &window.local_usage_attribution {
QuotaLocalUsageAttribution::AccountWide => None,
QuotaLocalUsageAttribution::Models(ids) => Some(ids.clone()),
QuotaLocalUsageAttribution::Unavailable => return None,
};
let (start, reset_at) = window.observed_bounds()?;
let range = TimeRange::new(start, reset_at).ok()?;
// 上游百分比以该 reset 边界定义;以当前时间回推会让本地 Token 属于另一窗口
Some(AccountUsageWindowQuery {
models,
account_id: account_id.to_owned(),
key: window.key.clone(),
range,
@@ -3281,10 +3281,10 @@ async fn accounts_list_and_quota_refresh_should_select_the_same_weekly_or_monthl
}
#[tokio::test]
async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_windows() {
async fn account_windows_attach_only_the_usage_allowed_by_the_provider() {
let provider = FakeProviderAdmin::new("openai", events());
let reset_at = Utc::now() + TimeDelta::days(7);
provider.set_quota(ProviderQuota {
let mut quota = ProviderQuota {
paused_windows: Vec::new(),
upstream: None,
credits: None,
@@ -3327,7 +3327,13 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
],
limit_reached: false,
provider_data: None,
});
};
let ids = std::collections::BTreeSet::from(["model-in-group".to_owned()]);
let mut grouped = quota.windows[1].clone();
grouped.key = "known-group".to_owned();
grouped.local_usage_attribution = QuotaLocalUsageAttribution::Models(ids.clone());
quota.windows.push(grouped);
provider.set_quota(quota);
let store = FakeAccountStore::new("openai", events());
store.set_quota_window_usage(vec![
AccountUsageWindowResult {
@@ -3340,9 +3346,14 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
key: "codex-bengalfox-primary".to_owned(),
usage: quota_local_usage("acct_test", 127_926),
},
AccountUsageWindowResult {
account_id: "acct_test".to_owned(),
key: "known-group".to_owned(),
usage: quota_local_usage("acct_test", 85),
},
]);
let page = accounts_service(provider, store)
let page = accounts_service(provider, store.clone())
.await
.accounts()
.list(AccountListQuery {
@@ -3376,6 +3387,7 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
[
("core-primary", Some(12_818_806)),
("codex-bengalfox-primary", None),
("known-group", Some(85)),
],
);
assert_eq!(
@@ -3385,6 +3397,10 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
.and_then(|usage| usage.total_tokens),
Some(12_818_806),
);
let queries = store.quota_window_queries();
assert_eq!(queries.len(), 2);
assert_eq!(queries[0].models, None);
assert_eq!(queries[1].models.as_ref(), Some(&ids));
}
#[tokio::test]
@@ -76,6 +76,19 @@ pub(crate) struct HttpResponseAdapter {
pub stream_error: fn(&Value) -> Bytes,
}
impl GenerationEndpoint {
fn expected_http_body(self, stream: bool) -> ExpectedBody {
if stream {
// 原生 GenAI 客户端会将网关插入的 SSE 注释解析为无效帧
ExpectedBody::Sse {
keep_alive: matches!(self, Self::Responses | Self::Messages),
}
} else {
ExpectedBody::SingleJson
}
}
}
pub(crate) async fn execute_prepared_generation(
service: DataPlaneService,
prepared: PreparedRootExecution,
@@ -106,7 +119,11 @@ pub(crate) async fn execute_prepared_generation(
let terminal_entered = Arc::clone(&execution_entered);
let started_request_id = Arc::new(OnceLock::new());
let terminal_request_id = Arc::clone(&started_request_id);
let (admitted, keepalive) = tokio::sync::oneshot::channel();
let expected = protocol.expected_http_body(stream);
let (admitted, keepalive) = expected
.sends_keepalive()
.then(tokio::sync::oneshot::channel)
.unzip();
let mut middleware_headers = headers.clone();
// 中间件正文已经由入口按上限解压;传输编码和旧长度不能与改写后的正文混用
middleware_headers.remove(CONTENT_ENCODING);
@@ -183,7 +200,9 @@ pub(crate) async fn execute_prepared_generation(
.session
.trace()
.capture("client.request.body", &request_body);
let _ = admitted.send(started.session.response_commit());
if let Some(admitted) = admitted {
let _ = admitted.send(started.session.response_commit());
}
execution_middleware_response(
started,
connection_guard,
@@ -203,11 +222,6 @@ pub(crate) async fn execute_prepared_generation(
} else {
middleware.await
};
let expected = if stream {
ExpectedBody::Sse
} else {
ExpectedBody::SingleJson
};
match middleware {
Ok(response) => {
let response = if let Some(authorization) = authorization {
@@ -226,7 +240,7 @@ pub(crate) async fn execute_prepared_generation(
Err(error) => error_response(error),
}
};
let response = if stream {
let response = if let Some(keepalive) = keepalive {
super::keepalive::response_with_encoder(
response,
keepalive,
@@ -507,7 +521,12 @@ pub async fn stream_execution_response(
.await
{
Ok(response) => {
into_http_response(response, ExpectedBody::Sse, OPENAI_PROTOCOL).await
into_http_response(
response,
GenerationEndpoint::Responses.expected_http_body(true),
OPENAI_PROTOCOL,
)
.await
}
Err(error) => error_response(error),
}
@@ -62,10 +62,14 @@ impl MiddlewareBody for BufferedBody {
pub(crate) enum ExpectedBody {
SingleJson,
SinglePayload,
Sse,
Sse { keep_alive: bool },
}
impl ExpectedBody {
pub(crate) fn sends_keepalive(self) -> bool {
matches!(self, Self::Sse { keep_alive: true })
}
fn validate(self, frame: &MiddlewareFrame) -> Result<(), MiddlewareError> {
let valid = match self {
Self::SingleJson => {
@@ -80,7 +84,7 @@ impl ExpectedBody {
|| Self::SingleJson.validate(frame).is_ok())
}
// 原生超大 SSE 帧允许按原字节片段交付;插件写入边界由 Runtime 校验
Self::Sse => frame.framing() == MiddlewareFraming::SseEvent,
Self::Sse { .. } => frame.framing() == MiddlewareFraming::SseEvent,
};
if valid {
Ok(())
@@ -133,14 +137,15 @@ pub(crate) async fn into_http_response(
})
});
}
if matches!(expected, ExpectedBody::Sse) {
let streaming = matches!(expected, ExpectedBody::Sse { .. });
if streaming {
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("no-cache, no-transform"),
);
headers.insert("x-accel-buffering", HeaderValue::from_static("no"));
}
let exhausted = empty || !matches!(expected, ExpectedBody::Sse);
let exhausted = empty || !streaming;
if !empty && exhausted {
match body.next_frame().await {
Ok(None) => {}
@@ -158,20 +163,24 @@ pub(crate) async fn into_http_response(
exhausted,
terminal_seen: empty,
};
let keep_alive = matches!(expected, ExpectedBody::Sse);
let stream = Box::pin(futures::stream::try_unfold(delivery, HttpDelivery::next));
// 固定同一条输出流;心跳不能取消并重建正在等待的 next_frame 或结算 future
let stream = futures::stream::unfold(stream, move |mut stream| async move {
let chunk = tokio::select! {
biased;
chunk = stream.next() => chunk?,
() = tokio::time::sleep(SSE_KEEPALIVE_INTERVAL), if keep_alive => {
Ok(SSE_KEEPALIVE_FRAME)
}
};
Some((chunk, stream))
});
let mut response = Response::new(Body::from_stream(stream));
let stream = futures::stream::try_unfold(delivery, HttpDelivery::next);
let body = if expected.sends_keepalive() {
// 固定同一条输出流,发送心跳时继续等待原有的读帧或结算操作
Body::from_stream(futures::stream::unfold(
Box::pin(stream),
|mut stream| async move {
let chunk = tokio::select! {
biased;
chunk = stream.next() => chunk?,
() = tokio::time::sleep(SSE_KEEPALIVE_INTERVAL) => Ok(SSE_KEEPALIVE_FRAME),
};
Some((chunk, stream))
},
))
} else {
Body::from_stream(stream)
};
let mut response = Response::new(body);
*response.status_mut() = status;
*response.headers_mut() = headers;
response
@@ -477,7 +477,7 @@ async fn finalization_failure_never_leaks_success_finish_or_usage() {
#[tokio::test(start_paused = true)]
async fn error_after_admission_keepalive_uses_chat_error_encoding() {
let mut session = Session::new(Vec::new());
session.delay = Some(Duration::from_secs(31));
session.read_delay = Some(Duration::from_secs(31));
session.finish = Finish::Error;
let fixture = Fixture::new(session).await;
let response = fixture.post(chat_request(true)).await;
@@ -2,6 +2,7 @@
use super::*;
use base64::{Engine as _, engine::general_purpose::STANDARD};
use std::time::Duration;
#[tokio::test]
async fn session_headers_reach_provider_context_except_when_declared_hop_by_hop() {
@@ -183,15 +184,16 @@ async fn committed_stream_delivers_raw_error_once() {
);
}
#[tokio::test]
async fn stream_preserves_finish_and_later_usage_bytes_before_eof() {
#[tokio::test(start_paused = true)]
async fn silent_stream_delivers_only_native_finish_and_late_usage_frames() {
let first = "data: { \"candidates\":[{\"finishReason\":\"STOP\"}], \"error\":null }\r\n\r\n";
let last = "data: {\"usageMetadata\":{\"totalTokenCount\":7}}\r\n\r\n";
let mut events = vec![wire_frame(first), wire_frame(last)];
events.push(ProviderEvent::canonical(GatewayEvent::Completed(
ResponseMeta::new("id", "model-a"),
)));
let session = Session::new(events);
let mut session = Session::new(events);
session.read_delay = Some(Duration::from_secs(45));
let trace = session.trace.clone();
let execution = Arc::new(Execution {
session: Mutex::new(Some(session)),
@@ -211,6 +213,27 @@ async fn stream_preserves_finish_and_later_usage_bytes_before_eof() {
assert!(trace.finalized.load(Ordering::SeqCst));
}
#[tokio::test(start_paused = true)]
async fn error_after_waiting_for_first_frame_preserves_http_status() {
let mut session = Session::new(Vec::new());
session.read_delay = Some(Duration::from_secs(45));
session.finish = Finish::Error;
let execution = Arc::new(Execution {
session: Mutex::new(Some(session)),
..Default::default()
});
let response = api_router(execution)
.await
.oneshot(request(&format!("{SHORT}:streamGenerateContent?alt=sse")))
.await
.unwrap();
let status = response.status();
assert!(status.is_server_error());
let body: Value =
serde_json::from_slice(&to_bytes(response.into_body(), 2048).await.unwrap()).unwrap();
assert_eq!(body["error"]["code"], status.as_u16());
}
#[tokio::test]
async fn metric_validates_bearer_and_invalid_generation_never_starts_inference() {
let execution = Arc::new(Execution::default());
@@ -39,7 +39,7 @@ pub(crate) struct Session {
events: VecDeque<Vec<ProviderEvent>>,
pub trace: Arc<Trace>,
pub finish: Finish,
pub delay: Option<Duration>,
pub read_delay: Option<Duration>,
pub fail_commit: bool,
pub response_headers: Vec<ProviderResponseHeader>,
committed: bool,
@@ -52,7 +52,7 @@ impl Session {
events: events.into_iter().map(|event| vec![event]).collect(),
trace: Arc::default(),
finish: Finish::Success,
delay: None,
read_delay: None,
fail_commit: false,
response_headers: Vec::new(),
committed: false,
@@ -73,7 +73,7 @@ impl ExecutionSession for Session {
fn next_event(&mut self) -> BoxFuture<'_, Result<Option<CoordinatedEvent>, EngineError>> {
Box::pin(async move {
if let Some(delay) = self.delay.take() {
if let Some(delay) = self.read_delay {
tokio::time::sleep(delay).await;
}
if let Some(event) = self.events.pop_front() {
@@ -424,12 +424,17 @@ impl FrozenAccountScope {
#[must_use]
pub fn excluding_account(&self, account: ProviderAccountId) -> Self {
let mut restricted = self.clone();
let mut excluded = self.excluded_account_ids.as_ref().clone();
excluded.insert(account);
restricted.excluded_account_ids = Arc::new(excluded);
restricted.exclude_accounts([account]);
restricted
}
pub(crate) fn exclude_accounts(
&mut self,
accounts: impl IntoIterator<Item = ProviderAccountId>,
) {
Arc::make_mut(&mut self.excluded_account_ids).extend(accounts);
}
#[must_use]
pub fn allows(&self, account_id: &ProviderAccountId) -> bool {
self.allows_with_policy(account_id, |_| true)
@@ -480,6 +485,18 @@ impl FrozenAccountScope {
self.allows_with_policy(account_id, |access| access.allows_optional_model(None))
}
/// 同一个账号和授权该账号的同一个分组须同时允许请求型号和实际执行型号
pub(crate) fn allows_model_pair(
&self,
account: &ProviderAccountId,
requested: &str,
actual: &str,
) -> bool {
self.allows_with_policy(account, |access| {
access.allows(requested) && access.allows(actual)
})
}
/// 只报告所有已启用绑定分组均明确拒绝模型的情况,空池沿用原路由错误
#[must_use]
pub fn groups_deny_model(&self, upstream_model: Option<&str>) -> bool {
@@ -160,6 +160,14 @@ pub trait ProviderAccountStore: Send + Sync {
.collect())
}
/// 批量返回在各自额度快照之后有成功生成请求完成的账号
async fn accounts_used_since_quota(
&self,
_snapshots: &[QuotaObservationVersion],
) -> Result<Vec<ProviderAccountId>, StoreError> {
Err(StoreError::new(crate::error::StoreErrorKind::InvalidData))
}
async fn compare_and_swap_quota(
&self,
observation: QuotaObservation,
@@ -24,6 +24,10 @@ pub(super) fn authentication_gateway_error(error: ClientAuthenticationError) ->
pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError {
match error {
crate::validation::RoutingError::WebSearchUnavailable => GatewayError::new(
GatewayErrorKind::InvalidRequest,
crate::validation::WEB_SEARCH_UNAVAILABLE_MESSAGE,
),
crate::validation::RoutingError::InvalidReasoningVariant => GatewayError::new(
GatewayErrorKind::InvalidRequest,
"A supported reasoning effort is required for this model group.",
@@ -245,7 +245,8 @@ pub trait NativeResponseTranslator: Send + 'static {
}
}
const MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT: usize = 64;
/// 单个原生输入帧允许展开的 wire 事件数
pub const MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT: usize = 64;
/// Metadata、canonical event stream 与 owned lease 的统一返回值
///
+17 -1
View File
@@ -542,6 +542,7 @@ struct ProviderErrorUpstreamValues {
#[derive(Clone, Default)]
struct ProviderErrorFailureObservation {
invalid_request_message: Option<&'static str>,
unreachable_proxy: Option<crate::upstream::ProxyEndpoint>,
continuation_unavailable_reason: Option<&'static str>,
connection: Option<ProviderConnectionObservation>,
@@ -581,6 +582,17 @@ impl ProviderError {
}
}
/// 本地请求校验只向客户端返回固定提示,内部原因仍独立保存
#[must_use]
pub fn invalid_request(message: &'static str) -> Self {
let mut error = Self::new(
ProviderErrorKind::InvalidRequest,
UpstreamSendState::NotSent,
);
error.failure_observation_mut().invalid_request_message = Some(message);
error
}
pub(crate) fn group_feature_denied(feature: DeniedGroupFeature) -> Self {
let mut error = Self::new(
ProviderErrorKind::RequestPolicyDenied,
@@ -1362,7 +1374,11 @@ impl GatewayError {
}
ProviderErrorKind::InvalidRequest => Self::new(
GatewayErrorKind::InvalidRequest,
"Invalid upstream request.",
error
.failure_observation
.as_ref()
.and_then(|details| details.invalid_request_message)
.unwrap_or("Invalid upstream request."),
),
ProviderErrorKind::SessionPolicyRestricted => Self::new(
GatewayErrorKind::InvalidRequest,
@@ -928,6 +928,16 @@ impl Operation {
}
}
/// Responses 要求本轮执行托管搜索时,按账号快照选择搜索目标
#[must_use]
pub fn requires_web_search(&self) -> bool {
matches!(self, Self::Generate(request) if {
let payload = request.protocol_payload();
payload.protocol() == gateway_protocol::openai::OPENAI_PROTOCOL &&
gateway_protocol::openai::web_search::is_required(payload.body())
})
}
/// 仅提取本次正文明确声明的推理档位,路由不继承 Provider 会话默认值
pub(crate) fn requested_reasoning_effort(&self) -> Option<String> {
let observation = match self {
@@ -19,6 +19,48 @@ pub struct ReasoningModelVariant {
pub accounts: BTreeSet<ProviderAccountId>,
}
/// 具体型号在单个账号目录中声明的能力与说明
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AccountModelMetadata {
pub description: Option<String>,
pub context_window_tokens: Option<u64>,
pub max_context_window_tokens: Option<u64>,
pub image_input: bool,
pub max_output_tokens: Option<u64>,
}
impl ModelPresentation {
/// 分组向客户端承诺的能力必须覆盖每个可选档位和账号
pub(super) fn apply_member_metadata<'a>(
&mut self,
mut members: impl Iterator<Item = Option<&'a AccountModelMetadata>>,
) {
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;
}
}
}
/// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContributedModelAlias {
+26 -3
View File
@@ -11,9 +11,9 @@ pub use crate::account::scope::{
};
pub use crate::identity::ProviderKind;
pub use catalog::{
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort,
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent,
ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
AccountModelMetadata, ContributedModel, ContributedModelAlias, ProviderCatalogGeneration,
ProviderCatalogPort, ProviderCatalogUnavailable, ProviderModelCapabilities,
ProviderModelContent, ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
};
pub use snapshot::RuntimeSnapshot;
@@ -160,6 +160,8 @@ pub struct ModelCapabilities {
generation_protocol: Option<&'static str>,
translated_generation_protocols: BTreeSet<&'static str>,
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
account_metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
dedicated_web_search: Option<Arc<BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>>>,
}
/// Provider 为客户端模型目录提供的展示与交互能力
@@ -435,6 +437,8 @@ impl ModelCapabilities {
generation_protocol: None,
translated_generation_protocols: BTreeSet::new(),
reasoning_variants: BTreeMap::new(),
account_metadata: BTreeMap::new(),
dedicated_web_search: None,
}
}
@@ -459,6 +463,25 @@ impl ModelCapabilities {
&self.reasoning_variants
}
#[must_use]
pub fn with_account_metadata(
mut self,
metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
) -> Self {
self.account_metadata = metadata;
self
}
/// 声明托管搜索必须独立选型,空目录表示目前没有搜索目标
#[must_use]
pub fn with_dedicated_web_search(
mut self,
targets: BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>,
) -> Self {
self.dedicated_web_search = Some(Arc::new(targets));
self
}
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
#[must_use]
pub const fn with_upstream_feature_validation(mut self) -> Self {
@@ -958,32 +958,35 @@ impl RuntimeSnapshot {
let mut profiles = BTreeMap::new();
for (model, presentation) in presentations {
if let Ok(public_model) = PublicModelId::new(model.as_str().to_owned()) {
profiles.insert(public_model, presentation.clone());
profiles.insert(public_model, presentation);
}
}
// 映射覆盖同名模型时,只展示目标画像,包括目标没有画像的情况
for alias in self.settings.values.model_mappings.keys() {
let target = self.mapped_model(alias);
let Some(presentation) = presentations.iter().find_map(|(model, presentation)| {
(model.as_str() == target).then_some(presentation)
}) else {
let Ok(public_model) = PublicModelId::new(alias.clone()) else {
continue;
};
if let Ok(public_model) = PublicModelId::new(alias.clone()) {
profiles.insert(public_model, presentation.clone());
let target = self.mapped_model(alias);
if let Some(presentation) = presentations.get(target.as_str()) {
profiles.insert(public_model, presentation);
} else {
profiles.remove(&public_model);
}
}
for alias in self
.model_aliases()
.iter()
.filter(|alias| &alias.provider == provider)
{
if let Some(presentation) = presentations.get(&alias.target) {
profiles.insert(alias.id.clone(), presentation.clone());
for alias in self.model_aliases() {
if &alias.provider == provider
&& let Some(presentation) = presentations.get(&alias.target)
{
profiles.insert(alias.id.clone(), presentation);
} else {
profiles.remove(&alias.id);
}
}
profiles
.into_iter()
.map(|(model, presentation)| super::PublicModelProfile::new(model, presentation))
.map(|(model, presentation)| {
super::PublicModelProfile::new(model, presentation.clone())
})
.collect()
}
@@ -1137,8 +1140,30 @@ impl RuntimeSnapshot {
scope: &FrozenAccountScope,
) -> Vec<super::PublicModelProfile> {
let mut profiles = self.public_model_profiles_for_provider(provider);
profiles.retain(|profile| {
self.native_catalog_model_allowed_for_scope(provider, profile.model(), scope)
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)))
})
.peekable();
if members.peek().is_none() {
return false;
}
profile.presentation.apply_member_metadata(members);
true
});
// Provider 画像按公开 ID 排序,追加的插件画像保留注册顺序,不参与二分查找
let provider_count = profiles.len();
@@ -1150,6 +1175,30 @@ impl RuntimeSnapshot {
Err(_) => profiles.push(model.public_profile()),
}
}
// 别名及适配器画像也按路由选中的分组成员裁剪,默认档位必须能在当前范围执行
profiles.retain_mut(|profile| {
let Some(group) =
self.model_group(provider, &self.mapped_model(profile.model.as_str()))
else {
return true;
};
let presentation = &mut profile.presentation;
presentation.supported_reasoning_efforts.retain(|effort| {
group
.reasoning_variants
.get(effort)
.is_some_and(|variant| self.variant_allowed(provider, variant, scope))
});
let efforts = &presentation.supported_reasoning_efforts;
if !presentation
.default_reasoning_effort
.as_ref()
.is_some_and(|default| efforts.contains(default))
{
presentation.default_reasoning_effort = efforts.first().cloned();
}
!efforts.is_empty()
});
profiles
}
@@ -1286,7 +1335,17 @@ impl RuntimeSnapshot {
variant: &super::ReasoningModelVariant,
scope: &FrozenAccountScope,
) -> bool {
variant.accounts.iter().any(|account| {
Self::variant_accounts(provider, variant, scope)
.next()
.is_some()
}
fn variant_accounts<'a>(
provider: &'a ProviderKind,
variant: &'a super::ReasoningModelVariant,
scope: &'a FrozenAccountScope,
) -> impl Iterator<Item = &'a ProviderAccountId> {
variant.accounts.iter().filter(move |account| {
scope.account_provider(account) == Some(provider)
&& scope.allows_model(account, variant.model.as_str())
})
@@ -1545,6 +1604,7 @@ impl RuntimeSnapshot {
);
let mut invalid_variant = false;
let mut group_model_denied = false;
let mut search_unavailable = false;
for provider in &providers {
if !self.providers.contains(provider) {
continue;
@@ -1685,6 +1745,84 @@ impl RuntimeSnapshot {
}
native.unwrap_or_default()
};
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
if let (Some(requested), Some(model)) =
(requirements.requested_output_tokens(), capabilities)
{
let mut excluded = model
.account_metadata
.iter()
.filter_map(|(id, metadata)| {
(metadata
.max_output_tokens
.is_some_and(|limit| requested > limit)
&& !contributions
.iter()
.any(|adapter| adapter.accounts.contains(id))
&& candidate_scope.allows(id))
.then_some(id)
})
.peekable();
if excluded.peek().is_some() {
let mut narrowed = candidate_scope.as_ref().clone();
narrowed.exclude_accounts(excluded.cloned());
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
continue;
}
candidate_scope = Arc::new(narrowed);
}
}
if operation.requires_web_search()
&& let Some(model) = capabilities
&& let Some(search_models) = &model.dedicated_web_search
{
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
for account in model.account_metadata.keys() {
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
continue;
}
let Some(target) = search_models.get(account) else {
search_unavailable = true;
continue;
};
if !candidate_scope.allows_model_pair(
account,
upstream_model.as_str(),
target.as_str(),
) {
group_model_denied |=
candidate_scope.groups_deny_model(Some(target.as_str()));
continue;
}
let limit = self
.provider_models
.get(provider)
.and_then(|models| models.get(target))
.and_then(|model| model.account_metadata.get(account))
.and_then(|meta| meta.max_output_tokens);
if requirements
.requested_output_tokens()
.zip(limit)
.is_some_and(|(requested, limit)| requested > limit)
{
continue;
}
targets.entry(target).or_default().insert(account.clone());
}
for (target, accounts) in targets {
candidates.push(ProviderCandidate {
requires_direct_authentication: direct_model.is_some(),
provider: provider.clone(),
upstream_model: Some(target.clone()),
emulated_features: emulated_features.clone(),
account_scope: Arc::new(
candidate_scope.restricted_to(&Default::default(), &accounts),
),
});
}
continue;
}
candidates.push(ProviderCandidate {
requires_direct_authentication: direct_model.is_some(),
provider: provider.clone(),
@@ -1705,6 +1843,9 @@ impl RuntimeSnapshot {
if group_model_denied {
return Err(RoutingError::GroupModelDenied);
}
if search_unavailable {
return Err(RoutingError::WebSearchUnavailable);
}
if invalid_variant {
return Err(RoutingError::InvalidReasoningVariant);
}
@@ -60,6 +60,10 @@ pub const GROUP_MODEL_DENIED_CODE: &str = "group_model_denied";
pub const GROUP_MODEL_DENIED_MESSAGE: &str =
"Model is not allowed by the API key's account groups.";
/// 搜索请求在当前授权范围没有对应的账号目录目标
pub const WEB_SEARCH_UNAVAILABLE_MESSAGE: &str =
"No authorized web search model is available for this account scope.";
/// 路由快照或 Route Plan 不满足不变量
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum RoutingError {
@@ -84,6 +88,9 @@ pub enum RoutingError {
/// 已知模型分组没有与本次请求匹配的推理档位
#[error("model group requires a supported reasoning effort")]
InvalidReasoningVariant,
/// 当前授权账号的目录没有专用搜索型号
#[error("{WEB_SEARCH_UNAVAILABLE_MESSAGE}")]
WebSearchUnavailable,
/// 快照中存在重复实体
#[error("duplicate {entity} `{id}`")]
DuplicateEntity {
@@ -34,9 +34,9 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest,
},
routing::{
ClientRoutingScope, FrozenAccountScope, ProviderModel, ReasoningModelVariant,
RoutingContext, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory,
RuntimeSnapshot,
AccountModelMetadata, ClientRoutingScope, FrozenAccountScope, ProviderModel,
ReasoningModelVariant, RoutingContext, RoutingGroupSnapshot, RuntimeAccount,
RuntimeAccountDirectory, RuntimeSnapshot,
},
validation::RoutingError,
};
@@ -44,16 +44,19 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
let provider = ProviderKind::new("alpha").unwrap();
let declared = ProviderAccountId::new("acct_declared").unwrap();
let other = ProviderAccountId::new("acct_other").unwrap();
let high_only = ProviderAccountId::new("acct_high").unwrap();
let group = gateway_core::routing::AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
let scope = Arc::new(FrozenAccountScope::new(
Arc::new(
RuntimeAccountDirectory::new(BTreeMap::from_iter(
[declared.clone(), other.clone()].into_iter().map(|id| {
(
id,
RuntimeAccount::new(provider.clone(), BTreeSet::from([group.clone()])),
)
}),
[declared.clone(), other.clone(), high_only.clone()]
.into_iter()
.map(|id| {
(
id,
RuntimeAccount::new(provider.clone(), BTreeSet::from([group.clone()])),
)
}),
))
.with_group_model_access(BTreeMap::from([(
group.clone(),
@@ -77,6 +80,7 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
None,
)
.with_generation_protocol("genai")
.with_translated_generation_protocols(["openai"])
.with_upstream_feature_validation()
};
let variants = BTreeMap::from_iter(["medium", "high"].map(|level| {
@@ -84,7 +88,11 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
level.into(),
ReasoningModelVariant {
model: UpstreamModelId::new(format!("family-{level}")).unwrap(),
accounts: BTreeSet::from([declared.clone()]),
accounts: if level == "medium" {
BTreeSet::from([declared.clone()])
} else {
BTreeSet::from([declared.clone(), high_only.clone()])
},
},
)
}));
@@ -93,7 +101,10 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
SettingsValues::new(
2,
"smart",
BTreeMap::from([("alias".into(), "family".into())]),
BTreeMap::from([
("alias".into(), "family".into()),
("pinned".into(), "family-medium".into()),
]),
None,
None,
),
@@ -103,21 +114,90 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
provider.clone(),
UpstreamModelId::new("family").unwrap(),
caps().with_reasoning_variants(variants),
)
.with_presentation(
ModelPresentation::default()
.with_reasoning(Some("high".into()), vec!["medium".into(), "high".into()]),
),
ProviderModel::new(
provider.clone(),
UpstreamModelId::new("family-medium").unwrap(),
caps(),
caps()
.with_dedicated_web_search(BTreeMap::from([(
declared.clone(),
UpstreamModelId::new("search").unwrap(),
)]))
.with_account_metadata(BTreeMap::from([
(
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),
},
),
(other.clone(), AccountModelMetadata::default()),
])),
),
ProviderModel::new(
provider.clone(),
UpstreamModelId::new("family-high").unwrap(),
caps(),
caps().with_account_metadata(BTreeMap::from([
(
declared.clone(),
AccountModelMetadata {
max_context_window_tokens: Some(2000),
..Default::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),
},
),
])),
),
ProviderModel::new(
provider.clone(),
UpstreamModelId::new("pinned").unwrap(),
caps(),
)
.with_presentation(ModelPresentation::default()),
],
vec![],
)
.unwrap();
let search_body = serde_json::json!({"input":"query","tools":[{"type":"web_search"}],"tool_choice":"required"});
let search = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", search_body.as_object().unwrap().clone()).unwrap(),
));
assert!(matches!(
snapshot.plan(
&PublicModelId::new("family-medium").unwrap(),
&search,
scope.clone(),
&RoutingContext::default()
),
Err(RoutingError::GroupModelDenied)
));
let old_account =
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
assert!(matches!(
snapshot.plan(
&PublicModelId::new("family-medium").unwrap(),
&search,
old_account,
&RoutingContext::default()
),
Err(RoutingError::WebSearchUnavailable)
));
let operation = |level: &str, count: bool| {
let body = serde_json::json!({"contents":[], "generationConfig":{"thinkingConfig":{"thinkingLevel":level}}});
if count {
@@ -143,6 +223,93 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
}
};
let base = PublicModelId::new("family").unwrap();
let profiles = snapshot.public_model_profiles_for_scope(&scope);
assert_eq!(
profiles
.iter()
.map(|profile| profile.model().as_str())
.collect::<Vec<_>>(),
["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"]
);
assert_eq!(
profile.presentation().default_reasoning_effort(),
Some("medium")
);
}
let all = FrozenAccountScope::new(
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);
for profile in only_high {
assert_eq!(
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| {
let body = serde_json::json!({"contents":[],"generationConfig":{"maxOutputTokens":tokens,"thinkingConfig":{"thinkingLevel":"MEDIUM"}}});
Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone()).unwrap(),
))
};
assert!(
snapshot
.plan(
&base,
&output_request(25),
scope.clone(),
&RoutingContext::default()
)
.is_ok()
);
assert!(
snapshot
.plan(
&base,
&output_request(26),
scope.clone(),
&RoutingContext::default()
)
.is_err()
);
let direct = snapshot
.plan(
&PublicModelId::new("family-medium").unwrap(),
&output_request(26),
scope.clone(),
&RoutingContext::default(),
)
.unwrap();
assert!(!direct.candidates()[0].account_scope().allows(&declared));
assert!(direct.candidates()[0].account_scope().allows(&other));
for count in [false, true] {
for name in ["family", "alias"] {
for level in ["MEDIUM", "medium"] {
@@ -256,6 +423,11 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
.public_models_for_operation(&blocked, &operation("", false))
.contains(&base)
);
assert!(
snapshot
.public_model_profiles_for_scope(&blocked)
.is_empty()
);
assert!(
snapshot
.plan(
@@ -5,6 +5,7 @@ use serde_json::Value;
/// 转换器消费的模型目录事实;None 表示上游未声明
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct MessagesModelCapabilities {
pub hosted_web_search: Option<bool>,
pub thinking: Option<bool>,
pub adaptive_thinking: Option<bool>,
pub manual_thinking: Option<bool>,
@@ -17,6 +18,7 @@ impl MessagesModelCapabilities {
/// 从 Anthropic Models 条目提取转换所需事实,未知扩展不影响解析
pub fn from_model(model: &Value) -> Self {
Self {
hosted_web_search: None,
thinking: model
.pointer("/capabilities/thinking/supported")
.and_then(Value::as_bool),
@@ -386,7 +386,11 @@ pub fn responses_to_messages_request(
"messages".into(),
Value::Array(normalize_tool_pairing(messages)),
);
tools.write_messages_tools(request, &mut result)?;
tools.write_messages_tools(
request,
&mut result,
capabilities.hosted_web_search != Some(false),
)?;
thinking::apply_to_messages(request, &mut result, capabilities, maximum);
if request
.get("tool_choice")
@@ -3,6 +3,7 @@
use std::collections::BTreeMap;
use super::TranslationError;
use crate::openai::web_search::is_search as is_web_search;
use serde_json::{Map, Value, json};
@@ -145,6 +146,7 @@ impl<'a> ToolSet<&'a Value> {
&self,
request: &Map<String, Value>,
target: &mut Map<String, Value>,
hosted_search: bool,
) -> Result<(), TranslationError> {
let choice = request.get("tool_choice").unwrap_or(&Value::Null);
let restricted = choice["type"] == "allowed_tools";
@@ -167,7 +169,7 @@ impl<'a> ToolSet<&'a Value> {
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|t| is_web_search(t))
.filter(|t| hosted_search && is_web_search(t))
{
// Messages 的搜索是实时联网;缓存或索引模式不能升级为实时访问
if tool
@@ -196,7 +198,19 @@ impl<'a> ToolSet<&'a Value> {
definitions.push(search);
}
if definitions.is_empty() {
if restricted {
// 转往仅支持函数的上游时,可选托管搜索可以省略,强制工具仍须可执行
let optional_search = !hosted_search
&& choice["mode"] == "auto"
&& allowed.is_some_and(|tools| tools.iter().all(is_web_search));
if !hosted_search
&& (choice == "required"
|| matches!(choice["type"].as_str(), Some("function" | "custom")))
{
return Err(TranslationError::InvalidRequest(
"No declared function can satisfy the required tool choice.",
));
}
if restricted && !optional_search {
return Err(TranslationError::InvalidRequest(
"No allowed tool can be used with the Messages upstream.",
));
@@ -239,13 +253,6 @@ impl<'a> ToolSet<&'a Value> {
}
}
fn is_web_search(tool: &Value) -> bool {
matches!(
tool["type"].as_str(),
Some("web_search" | "web_search_preview")
)
}
pub(super) fn messages_tools(tools: &[Value]) -> Vec<Value> {
tools.iter().map(|tool| {
let kind = tool.get("type").and_then(Value::as_str).unwrap_or_default();
@@ -0,0 +1,193 @@
//! 将一次完整搜索的 Google 来源与正文区间投影到同一套 Responses 事件
use crate::anthropic::TranslationError;
use serde_json::{Value, json};
pub fn grounded_search_events(
native: &Value,
mut events: Vec<Value>,
include_sources: bool,
event_budget: usize,
) -> Result<Vec<Value>, TranslationError> {
let candidate = &native["candidates"][0];
let metadata = &candidate["groundingMetadata"];
let queries: Vec<_> = array(&metadata["webSearchQueries"])
.iter()
.filter_map(Value::as_str)
.collect();
let chunks = array(&metadata["groundingChunks"]);
if queries.is_empty() && !chunks.iter().any(|c| web_source(c).is_some()) {
if candidate["finishReason"] == "STOP" {
return Err(TranslationError::InvalidEvent(
"Required web search returned no grounding evidence.",
));
}
return Ok(events);
}
let Some(response) = events.last_mut().and_then(|e| e.get_mut("response")) else {
return Err(TranslationError::InvalidEvent(
"Web search translation is missing its terminal response.",
));
};
let id = format!("ws_{}", response["id"].as_str().unwrap_or_default());
let mut action = json!({"type":"search","queries":queries});
if let Some(query) = queries.first() {
action["query"] = json!(query)
}
if include_sources {
action["sources"] = Value::Array(
chunks
.iter()
.filter_map(web_source)
.map(|(url, _)| json!({"type":"url","url":url}))
.collect(),
);
}
let call = json!({"type":"web_search_call","id":id,"status":"completed","action":action});
let Some(output) = response["output"].as_array_mut() else {
return Err(TranslationError::InvalidEvent(
"Web search translation is missing its terminal response.",
));
};
let citations = annotations(candidate, output);
for (item, annotations) in output.iter_mut().zip(&citations) {
if !annotations.is_empty() {
item["content"][0]["annotations"] = json!(annotations)
}
}
output.insert(0, call.clone());
// 单次搜索已经拿到完整正文,来源很多时仍通过 content_part.done 和终态交付全部引用
let incremental_annotations =
events.len() + 5 + citations.iter().map(Vec::len).sum::<usize>() <= event_budget;
let mut result = Vec::with_capacity(events.len() + 5);
for mut event in events {
let kind = event["type"].as_str().unwrap_or_default();
if kind == "response.in_progress" {
result.push(event);
let pending = json!({"type":"web_search_call","id":id,"status":"in_progress"});
result
.push(json!({"type":"response.output_item.added","output_index":0,"item":pending}));
for stage in ["in_progress", "searching", "completed"] {
result.push(json!({"type":format!("response.web_search_call.{stage}"),"output_index":0,"item_id":id}));
}
result.push(json!({"type":"response.output_item.done","output_index":0,"item":call}));
continue;
}
if let Some(index) = index(&event["output_index"]) {
if let Some(annotations) = citations.get(index).filter(|v| !v.is_empty()) {
match kind {
"response.output_text.done" if incremental_annotations => {
for (i, annotation) in annotations.iter().enumerate() {
result.push(json!({"type":"response.output_text.annotation.added","item_id":event["item_id"],"output_index":index+1,"content_index":0,"annotation_index":i,"annotation":annotation}));
}
}
"response.content_part.done" => {
event["part"]["annotations"] = json!(annotations)
}
"response.output_item.done" => {
event["item"]["content"][0]["annotations"] = json!(annotations)
}
_ => {}
}
}
event["output_index"] = json!(index + 1);
}
result.push(event);
}
for (i, event) in result.iter_mut().enumerate() {
event["sequence_number"] = json!(i);
}
Ok(result)
}
fn array(value: &Value) -> &[Value] {
value.as_array().map_or(&[], Vec::as_slice)
}
fn index(value: &Value) -> Option<usize> {
usize::try_from(value.as_u64()?).ok()
}
fn web_source(chunk: &Value) -> Option<(&str, &str)> {
let web = &chunk["web"];
let url = web["uri"].as_str()?;
let uri = url.parse::<http::Uri>().ok()?;
if !matches!(uri.scheme_str(), Some("http" | "https")) || uri.host().is_none_or(str::is_empty) {
return None;
}
Some((url, web["title"].as_str().unwrap_or(url)))
}
fn annotations(candidate: &Value, output: &[Value]) -> Vec<Vec<Value>> {
let mut found = vec![Vec::new(); output.len()];
let mut native_text = String::new();
let mut parts = Vec::new();
for part in array(&candidate["content"]["parts"]) {
parts.push(
part["text"]
.as_str()
.filter(|_| part["thought"] != true)
.map(|text| {
let start = native_text.len();
native_text.push_str(text);
(start, text)
}),
);
}
// Google 的 offset 是单个 Part 的 UTF-8 字节;Responses 需要每个 output_text 内的字符索引
let mut ranges = Vec::new();
let mut end = 0;
for (i, item) in output.iter().enumerate() {
if let Some(text) = item.pointer("/content/0/text").and_then(Value::as_str) {
if !native_text[end..].starts_with(text) {
return found;
}
ranges.push((end, end + text.len(), i));
end += text.len();
}
}
if end != native_text.len() {
return found;
}
let metadata = &candidate["groundingMetadata"];
for support in array(&metadata["groundingSupports"]) {
let segment = &support["segment"];
let proto_index = |field| segment.get(field).map_or(Some(0), index);
let Some(part) = proto_index("partIndex") else {
continue;
};
let Some(&(offset, text)) = parts.get(part).and_then(Option::as_ref) else {
continue;
};
let Some(start) = proto_index("startIndex") else {
continue;
};
let Some(end) = index(&segment["endIndex"]) else {
continue;
};
let Some(span) = text.get(start..end).filter(|s| !s.is_empty()) else {
continue;
};
if segment["text"].as_str().is_some_and(|s| s != span) {
continue;
}
let Some(&(begin, _, item)) = ranges
.iter()
.find(|(begin, limit, _)| offset + start >= *begin && offset + end <= *limit)
else {
continue;
};
let first = native_text[begin..offset + start].chars().count();
let last = first + span.chars().count();
for source in array(&support["groundingChunkIndices"]) {
let Some((url, title)) = index(source)
.and_then(|i| array(&metadata["groundingChunks"]).get(i))
.and_then(web_source)
else {
continue;
};
found[item].push(json!({"type":"url_citation","url":url,"title":title,"start_index":first,"end_index":last}));
}
}
found
}
@@ -18,3 +18,5 @@ mod tokens;
pub use messages::messages_to_genai_request;
pub use stream::GenAiToMessagesStream;
pub use tokens::{count_tokens_request, count_tokens_to_messages};
mod grounding;
pub use grounding::grounded_search_events;
@@ -23,6 +23,7 @@ mod guardian;
mod headers;
/// Server-Sent Events 帧的解析与编码
pub mod sse;
pub mod web_search;
pub use codex::{
CodexResponsesRequestSemantics, WEBSOCKET_FRAME_CONTEXT_KEY, codex_account_session_id,
@@ -0,0 +1,35 @@
//! Responses 内置搜索声明与强制工具选择,共用同一协议判定
use serde_json::{Map, Value};
#[must_use]
pub fn is_search(tool: &Value) -> bool {
matches!(
tool["type"].as_str(),
Some(
"web_search"
| "web_search_preview"
| "web_search_2025_08_26"
| "web_search_preview_2025_03_11"
)
)
}
/// 只有客户端的选择要求本轮执行搜索时才可以派发独立搜索请求
#[must_use]
pub fn is_required(body: &Map<String, Value>) -> bool {
let Some(choice) = body.get("tool_choice") else {
return false;
};
if is_search(choice) {
return true;
}
let tools = if choice["type"] == "allowed_tools" && choice["mode"] == "required" {
choice["tools"].as_array()
} else if choice == "required" {
body.get("tools").and_then(Value::as_array)
} else {
None
};
tools.is_some_and(|tools| !tools.is_empty() && tools.iter().all(is_search))
}
@@ -588,3 +588,37 @@ fn tool_result_continuation_without_thinking_keeps_the_current_mode() {
.push(json!({"role":"user","content":"new question"}));
assert!(!convert(&req).contains_key("thinking"));
}
#[test]
fn function_only_target_preserves_tool_choice_when_search_is_optional() {
use gateway_protocol::anthropic::{MessagesModelCapabilities, responses_to_messages_request};
let caps = MessagesModelCapabilities {
hosted_web_search: Some(false),
..Default::default()
};
let search = serde_json::json!({"type":"web_search","external_web_access":true});
let function = serde_json::json!({"type":"function","name":"pwd"});
for (choice, mode) in [
(serde_json::json!("auto"), "auto"),
(serde_json::json!("required"), "any"),
(function.clone(), "tool"),
(
serde_json::json!({"type":"allowed_tools","mode":"required","tools":[function,search]}),
"any",
),
] {
let original =
serde_json::json!({"input":"hello","tools":[search,function],"tool_choice":choice});
let mapped = responses_to_messages_request(original.as_object().unwrap(), &caps).unwrap();
assert_eq!(mapped["tools"].as_array().unwrap().len(), 1);
assert_eq!(mapped["tools"][0]["name"], "pwd");
assert_eq!(mapped["tool_choice"]["type"], mode);
if mode == "tool" {
assert_eq!(mapped["tool_choice"]["name"], "pwd")
}
}
let original = serde_json::json!({"input":"hello","tools":[{"type":"web_search","external_web_access":false},function],"tool_choice":{"type":"allowed_tools","mode":"auto","tools":[{"type":"web_search"}]}});
let mapped = responses_to_messages_request(original.as_object().unwrap(), &caps).unwrap();
assert!(!mapped.contains_key("tools"));
assert!(!mapped.contains_key("tool_choice"));
}
@@ -586,7 +586,12 @@ pub(crate) async fn account_usage_windows(
let mut total = MetricState::default();
let mut models = Vec::new();
for ((account, model), state) in &states {
if account != &window.account_id {
if account != &window.account_id
|| window
.models
.as_ref()
.is_some_and(|ids| !ids.contains(model))
{
continue;
}
total.merge(state)?;
@@ -401,6 +401,13 @@ impl ProviderAccountStore for PgProviderAccountRepository {
super::quota::versions(self, accounts).await
}
async fn accounts_used_since_quota(
&self,
snapshots: &[gateway_core::account::QuotaObservationVersion],
) -> Result<Vec<CoreProviderAccountId>, CoreStoreError> {
super::quota::accounts_used_since_quota(self, snapshots).await
}
async fn apply_quota_access(
&self,
change: QuotaAccessChange,
@@ -19,6 +19,35 @@ pub(in crate::postgres::provider_accounts) async fn versions(
.map_err(crate::core_store_error)
}
pub(in crate::postgres::provider_accounts) async fn accounts_used_since_quota(
repository: &PgProviderAccountRepository,
snapshots: &[QuotaObservationVersion],
) -> Result<Vec<CoreProviderAccountId>, CoreStoreError> {
let (ids, times): (Vec<_>, Vec<_>) = snapshots
.iter()
.map(|s| (s.account_id.as_str(), DateTime::<Utc>::from(s.observed_at)))
.unzip();
// 按账号与完成时间探测共享索引,跨实例及重启复用已记录的请求事实
let active: Vec<String> = sqlx::query_scalar(
"select s.id from unnest($1::text[], $2::timestamptz[]) as s(id, observed_at)
where exists (select 1 from request_analytics_facts r
where r.provider_account_ref = s.id and r.completed_at > s.observed_at
and r.outcome = 'succeeded' and r.operation = 'generate')",
)
.bind(ids)
.bind(times)
.fetch_all(&repository.pool)
.await
.map_err(database_error)?;
active
.into_iter()
.map(|id| {
CoreProviderAccountId::new(id)
.map_err(|e| CoreStoreError::caused_by(CoreStoreErrorKind::InvalidData, e))
})
.collect()
}
pub(in crate::postgres::provider_accounts) async fn write(
repository: &PgProviderAccountRepository,
observation: QuotaObservation,
@@ -13,6 +13,13 @@ pub(in crate::postgres::provider_accounts) async fn load_history(
.map_err(|error| admin_store_error(ENTITY, error))?;
let range = ObservabilityRange::new(window.range.start, window.range.end)
.map_err(|error| admin_store_error(ENTITY, error))?;
if window.models.is_some() {
return Err(AdminStoreError::new(
AdminStoreErrorKind::Invalid,
ENTITY,
"quota forecast requires an account-wide window",
));
}
if range.end - range.start > TimeDelta::days(32) {
return Err(AdminStoreError::new(
AdminStoreErrorKind::Invalid,
@@ -5,6 +5,6 @@ mod forecast;
mod history;
mod warmup;
pub(super) use document::{versions, write};
pub(super) use document::{accounts_used_since_quota, versions, write};
pub(super) use forecast::load_history;
pub(super) use history::documents;
@@ -2,6 +2,56 @@
use super::*;
#[tokio::test]
async fn quota_activity_uses_successful_generation_completion_after_each_snapshot() {
use gateway_core::account::QuotaObservationVersion;
let Some(database) = TestDatabase::create("quota_generation_activity").await else {
return;
};
let repo = PgProviderAccountRepository::new(database.pool.clone());
let start = Utc::now() - TimeDelta::minutes(10);
let mut snapshots = Vec::new();
for (name, operation, outcome, offset_ms) in [
("acct_active", "generate", "succeeded", 500),
("acct_observed", "generate", "succeeded", 1000),
("acct_count", "count_tokens", "succeeded", 0),
("acct_failed", "generate", "failed", 0),
] {
seed_model_request(
&database.pool,
ModelRequestSeed {
request_id: name,
account_id: name,
provider_kind: "antigravity",
model: "fixture-model",
total_tokens: 5,
cost_amount: "0",
started_at: start,
},
)
.await
.unwrap();
sqlx::query("update model_requests set operation=$2, outcome=$3 where id=$1")
.bind(name)
.bind(operation)
.bind(outcome)
.execute(&database.pool)
.await
.unwrap();
snapshots.push(QuotaObservationVersion {
account_id: ProviderAccountId::new(name).unwrap(),
credential_revision: CredentialRevision::new(1).unwrap(),
observed_at: (start + TimeDelta::milliseconds(offset_ms)).into(),
});
}
super::super::drain_analytics(&database.pool).await;
assert_eq!(
repo.accounts_used_since_quota(&snapshots).await.unwrap(),
vec![ProviderAccountId::new("acct_active").unwrap()]
);
database.close().await;
}
#[tokio::test]
async fn scoped_account_list_empty_scope_does_not_use_database() {
let pool = sqlx::postgres::PgPoolOptions::new()
@@ -1112,36 +1112,57 @@ async fn terminal_admin_quota_window_usage_prefers_provider_total_and_falls_back
.await
.expect("separate provider total from fallback components");
let mut usage = admin_account_store(&database.pool)
.load_account_usage_by_windows(&[
AccountUsageWindowQuery {
account_id: "acct_quota_window".to_owned(),
key: "short".to_owned(),
range: TimeRange {
start: now - TimeDelta::hours(1),
end: now + TimeDelta::minutes(1),
},
},
AccountUsageWindowQuery {
account_id: "acct_quota_window".to_owned(),
key: "long".to_owned(),
range: TimeRange {
start: now - TimeDelta::hours(7),
end: now + TimeDelta::minutes(1),
},
},
])
let short = TimeRange {
start: now - TimeDelta::hours(5),
end: now + TimeDelta::minutes(1),
};
let week = TimeRange {
start: now - TimeDelta::weeks(1),
end: short.end,
};
let query = |key: &str, range: TimeRange, models| AccountUsageWindowQuery {
account_id: "acct_quota_window".to_owned(),
key: key.to_owned(),
range,
models,
};
let older = Some(["gpt-window-older".to_owned()].into());
let windows = [
query("short", short, None),
query("long", week, None),
query("model-short", short, older.clone()),
query("model-week", week, older),
];
let store = admin_account_store(&database.pool);
let usage = store.load_account_usage_by_windows(&windows).await.unwrap();
for (key, requests, tokens) in [("model-short", 0, 0), ("model-week", 1, 20)] {
let result = usage.iter().find(|result| result.key == key).unwrap();
assert_eq!(
(result.usage.request_count, result.usage.total_tokens),
(requests, Some(tokens))
);
}
let error = store
.load_quota_forecast_history(&windows[3])
.await
.expect("load quota window usage");
usage.sort_by(|left, right| left.key.cmp(&right.key));
assert_eq!(usage[0].key, "long");
assert_eq!(usage[0].usage.total_tokens, Some(720));
assert_eq!(usage[0].usage.models.len(), 2);
.unwrap_err();
assert_eq!(
usage[0]
.usage
.models
error.kind(),
gateway_admin::ports::store::AdminStoreErrorKind::Invalid
);
super::drain_analytics(&database.pool).await;
assert_eq!(
store.load_account_usage_by_windows(&windows).await.unwrap(),
usage
);
let account_usage = |key: &str| &usage.iter().find(|result| result.key == key).unwrap().usage;
let long = account_usage("long");
let short = account_usage("short");
assert_eq!(long.total_tokens, Some(720));
assert_eq!(long.models.len(), 2);
assert_eq!(
long.models
.iter()
.map(|model| (model.model.as_str(), model.total_tokens))
.collect::<Vec<_>>(),
@@ -1150,19 +1171,18 @@ async fn terminal_admin_quota_window_usage_prefers_provider_total_and_falls_back
("gpt-window-recent", Some(700)),
],
);
assert_eq!(usage[0].usage.costs.len(), 1);
assert_eq!(usage[0].usage.costs[0].currency, "USD");
assert_eq!(usage[0].usage.costs[0].amount.as_str(), "3.75");
assert_eq!(usage[0].usage.models[0].costs[0].amount.as_str(), "2.5");
assert_eq!(usage[0].usage.models[1].costs[0].amount.as_str(), "1.25");
assert_eq!(usage[1].key, "short");
assert_eq!(usage[1].usage.total_tokens, Some(700));
assert_eq!(usage[1].usage.costs.len(), 1);
assert_eq!(usage[1].usage.costs[0].currency, "USD");
assert_eq!(usage[1].usage.costs[0].amount.as_str(), "1.25");
assert_eq!(usage[1].usage.models.len(), 1);
assert_eq!(usage[1].usage.models[0].model, "gpt-window-recent");
assert_eq!(usage[1].usage.models[0].total_tokens, Some(700));
assert_eq!(long.costs.len(), 1);
assert_eq!(long.costs[0].currency, "USD");
assert_eq!(long.costs[0].amount.as_str(), "3.75");
assert_eq!(long.models[0].costs[0].amount.as_str(), "2.5");
assert_eq!(long.models[1].costs[0].amount.as_str(), "1.25");
assert_eq!(short.total_tokens, Some(700));
assert_eq!(short.costs.len(), 1);
assert_eq!(short.costs[0].currency, "USD");
assert_eq!(short.costs[0].amount.as_str(), "1.25");
assert_eq!(short.models.len(), 1);
assert_eq!(short.models[0].model, "gpt-window-recent");
assert_eq!(short.models[0].total_tokens, Some(700));
database.close().await;
}
@@ -1221,6 +1241,7 @@ async fn terminal_admin_quota_window_usage_should_include_only_statusless_websoc
let usage = admin_account_store(&database.pool)
.load_account_usage_by_windows(&[AccountUsageWindowQuery {
models: None,
account_id: "acct_quota_window_websocket".to_owned(),
key: "statusless".to_owned(),
range: TimeRange {
@@ -49,6 +49,7 @@ async fn quota_forecast_fractional_slots_keep_microsecond_edges_and_as_of_ties()
}
let history = admin_account_store(&database.pool)
.load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_fraction".to_owned(),
key: "fraction".to_owned(),
range: TimeRange { start, end },
@@ -113,10 +114,12 @@ async fn quota_forecast_excludes_openai_prewarm_but_preserves_inference_and_audi
.unwrap();
let store = admin_account_store(&database.pool);
let query = AccountUsageWindowQuery {
models: None,
account_id: "acct_prewarm".to_owned(),
key: "week".to_owned(),
range: TimeRange { start, end },
};
let history = store.load_quota_forecast_history(&query).await.unwrap();
assert_eq!(history.usage.request_count, 2);
assert_eq!(history.usage.tokens, 300);
@@ -223,6 +226,7 @@ async fn quota_forecast_does_not_apply_openai_prewarm_semantics_to_other_provide
.unwrap();
let history = admin_account_store(&database.pool)
.load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_xai_kind".to_owned(),
key: "week".to_owned(),
range: TimeRange {
@@ -320,6 +324,7 @@ async fn quota_forecast_pairs_completed_usage_and_preserves_missing_pending_and_
let store = admin_account_store(&database.pool);
let history = store
.load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast".to_owned(),
key: "week".to_owned(),
range: TimeRange { start, end },
@@ -345,6 +350,7 @@ async fn quota_forecast_pairs_completed_usage_and_preserves_missing_pending_and_
assert!(!format!("{history:?}").contains("never-debug-this"));
let empty = store
.load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast".to_owned(),
key: "empty".to_owned(),
range: TimeRange {
@@ -391,6 +397,7 @@ async fn quota_forecast_bounds_documents_without_sampling_away_token_totals() {
.unwrap();
let history = admin_account_store(&database.pool)
.load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast_bound".to_owned(),
key: "week".to_owned(),
range: TimeRange {
@@ -459,6 +466,7 @@ async fn quota_forecast_carries_unsampled_usage_between_document_points() {
.unwrap();
let history = admin_account_store(&database.pool)
.load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_prefix".to_owned(),
key: "week".to_owned(),
range: TimeRange { start, end },
@@ -545,6 +553,7 @@ async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds
let store = admin_account_store(&database.pool);
let queries = [
AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast_projection".to_owned(),
key: "complete".to_owned(),
range: TimeRange {
@@ -553,6 +562,7 @@ async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds
},
},
AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast_projection".to_owned(),
key: "edges".to_owned(),
range: TimeRange {
@@ -561,6 +571,7 @@ async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds
},
},
AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast_moved".to_owned(),
key: "moved".to_owned(),
range: TimeRange {
@@ -40,6 +40,7 @@ async fn quota_windows_reconcile_moved_requests_and_pending_deletions_without_wa
drain_analytics(&database.pool).await;
let windows = [
AccountUsageWindowQuery {
models: None,
account_id: "acct_usage_before".to_owned(),
key: "old".to_owned(),
range: TimeRange {
@@ -48,6 +49,7 @@ async fn quota_windows_reconcile_moved_requests_and_pending_deletions_without_wa
},
},
AccountUsageWindowQuery {
models: None,
account_id: "acct_usage_after".to_owned(),
key: "new".to_owned(),
range: TimeRange {
@@ -202,6 +204,7 @@ async fn model_success_rates_preserve_usage_across_source_summary_and_pending_re
.execute(&database.pool).await.unwrap();
let windows = [
AccountUsageWindowQuery {
models: None,
account_id: "acct_health".to_owned(),
key: "whole".to_owned(),
range: TimeRange {
@@ -210,6 +213,7 @@ async fn model_success_rates_preserve_usage_across_source_summary_and_pending_re
},
},
AccountUsageWindowQuery {
models: None,
account_id: "acct_health".to_owned(),
key: "boundary".to_owned(),
range: TimeRange {
@@ -288,6 +288,7 @@ async fn aggregate_import_and_signed_correction_survive_native_rebuild_without_s
ports::store::AccountStore,
};
let windows = [AccountUsageWindowQuery {
models: None,
account_id: "account_usage".into(),
key: "window".into(),
range: TimeRange {
@@ -2,7 +2,7 @@
use crate::{
credential::{CredentialService, oauth::error},
transport::{Catalog, CloudCodeClient, unsent},
transport::{Catalog, CloudCodeClient, Model, unsent},
};
use gateway_admin::{
model::provider_credentials::{ProviderModel, ProviderModels},
@@ -13,11 +13,11 @@ use gateway_core::{
error::{ProviderError, ProviderErrorKind as Kind},
operation::OperationKind,
routing::{
ModelCapabilities, ProviderModelCapabilities, ReasoningModelVariant, UpstreamModelId,
AccountModelMetadata, ModelCapabilities, ProviderModelCapabilities, UpstreamModelId,
},
};
use std::{
collections::{BTreeMap, BTreeSet},
collections::BTreeMap,
sync::{
Arc, Mutex,
atomic::{AtomicU64, AtomicUsize, Ordering},
@@ -165,62 +165,74 @@ impl CatalogService {
pub(crate) async fn capabilities(
&self,
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
let mut models: BTreeMap<UpstreamModelId, BTreeSet<ProviderAccountId>> = BTreeMap::new();
let mut groups: BTreeMap<UpstreamModelId, BTreeMap<String, ReasoningModelVariant>> =
BTreeMap::new();
for (accounts, catalog) in self.catalogs().await? {
for (group, level, target) in super::model_groups::variants(&catalog) {
groups
.entry(group)
.or_default()
.entry(level)
.or_insert_with(|| ReasoningModelVariant {
model: target,
accounts: BTreeSet::new(),
})
.accounts
.extend(accounts.iter().map(|a| a.account_id.clone()));
let mut members =
BTreeMap::<UpstreamModelId, BTreeMap<ProviderAccountId, AccountModelMetadata>>::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 {
super::model_groups::collect(&mut groups, &catalog, &accounts);
if let Some(search_model) = catalog
.web_search_models
.first()
.and_then(|id| UpstreamModelId::new(id).ok())
{
search_models.extend(
accounts
.iter()
.map(|a| (a.account_id.clone(), search_model.clone())),
);
}
for key in catalog.models.into_keys() {
for (key, model) in catalog.models {
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
models
.entry(id)
.or_default()
.extend(accounts.iter().map(|a| a.account_id.clone()));
let metadata = account_metadata(model);
members.entry(id).or_default().extend(
accounts
.iter()
.map(|a| (a.account_id.clone(), metadata.clone())),
);
}
}
let capabilities = ModelCapabilities::new(
[OperationKind::Generate, OperationKind::CountTokens].into(),
None,
)
.with_dedicated_web_search(search_models)
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
.with_translated_generation_protocols([
gateway_protocol::openai::OPENAI_PROTOCOL,
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
])
.with_upstream_feature_validation();
let mut models = BTreeMap::new();
for (id, metadata) in members {
let accounts = metadata.keys().cloned().collect();
let model = ProviderModelCapabilities::new(
id.clone(),
capabilities.clone().with_account_metadata(metadata),
);
models.insert(id, model.with_catalog_accounts(accounts));
}
// 上游已有同名实体时保留原生型号,不让其他账号的分组覆盖它
groups.retain(|group, _| !models.contains_key(group));
for (group, variants) in &groups {
models.insert(
group.clone(),
variants
for (id, group) in groups {
models.entry(id.clone()).or_insert_with(|| {
let accounts = group
.variants
.values()
.flat_map(|v| v.accounts.iter().cloned())
.collect(),
);
.collect();
group
.into_model(id, capabilities.clone())
.with_catalog_accounts(accounts)
});
}
Ok(models
.into_iter()
.map(|(model, accounts)| {
let variants = groups.remove(&model).unwrap_or_default();
ProviderModelCapabilities::new(
model,
ModelCapabilities::new(
[OperationKind::Generate, OperationKind::CountTokens].into(),
None,
)
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
.with_translated_generation_protocols([
gateway_protocol::openai::OPENAI_PROTOCOL,
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
])
.with_upstream_feature_validation()
.with_reasoning_variants(variants),
)
.with_catalog_accounts(accounts)
})
.collect())
Ok(models.into_values().collect())
}
pub(crate) async fn account_models(
@@ -301,6 +313,32 @@ 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),
};
// 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,
max_output_tokens: model.max_output_tokens.filter(|n| *n > 0),
image_input: model.supports_images == Some(true),
}
}
fn admin_models(
catalog: Catalog,
observed: SystemTime,
@@ -1,14 +1,50 @@
//! 从上游分组声明提取实际存在的推理档位,不按型号前缀猜测成员
//! 从上游分组声明提取展示名、档位顺序及实际存在的成员
use crate::transport::Catalog;
use gateway_core::routing::UpstreamModelId;
use gateway_core::{
account::AccountCatalogObservation,
routing::{
ModelCapabilities, ModelPresentation, ProviderModelCapabilities, ReasoningModelVariant,
UpstreamModelId,
},
};
use std::collections::BTreeMap;
pub(super) fn variants(catalog: &Catalog) -> Vec<(UpstreamModelId, String, UpstreamModelId)> {
let mut variants = Vec::new();
let Some(groups) = catalog.grouped_models.as_object() else {
return variants;
#[derive(Default)]
pub(super) struct ModelGroup {
display_name: Option<String>,
efforts: Vec<String>,
pub(super) variants: BTreeMap<String, ReasoningModelVariant>,
}
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<UpstreamModelId, ModelGroup>,
catalog: &Catalog,
accounts: &[AccountCatalogObservation],
) {
let Some(declarations) = catalog.grouped_models.as_object() else {
return;
};
for (group, description) in groups {
for (group, description) in declarations {
let Ok(group_id) = UpstreamModelId::new(group) else {
continue;
};
@@ -19,10 +55,9 @@ pub(super) fn variants(catalog: &Catalog) -> Vec<(UpstreamModelId, String, Upstr
let Some(suffix) = level["thinkingSuffix"].as_str() else {
continue;
};
if suffix.is_empty()
|| !suffix
.split('-')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric()))
if !suffix
.split('-')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric()))
{
continue;
}
@@ -31,9 +66,27 @@ pub(super) fn variants(catalog: &Catalog) -> Vec<(UpstreamModelId, String, Upstr
if catalog.models.contains_key(&target)
&& let Ok(target) = UpstreamModelId::new(target)
{
variants.push((group_id.clone(), level, 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(),
}
})
.accounts
.extend(accounts.iter().map(|account| account.account_id.clone()));
}
}
}
variants
}
@@ -1,6 +1,9 @@
//! 套餐、独立额度桶及模型额度的持久事实与公共投影
use crate::transport::account::{ModelQuota, QuotaSummary, Tier};
use crate::transport::{
Catalog,
account::{ModelQuota, QuotaGroup, QuotaSummary, Tier},
};
use chrono::{DateTime, Utc};
use gateway_admin::model::provider_credentials::{
ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution,
@@ -8,7 +11,7 @@ use gateway_admin::model::provider_credentials::{
use gateway_core::account::{AccountQuotaSignals, QuotaEvidence, QuotaState};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
collections::{BTreeMap, BTreeSet},
time::{Duration, SystemTime},
};
@@ -17,6 +20,64 @@ pub(super) struct Document {
pub(super) tier: Option<Tier>,
pub(super) summary: QuotaSummary,
pub(super) models: BTreeMap<String, ModelQuota>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(super) bucket_models: BTreeMap<String, BTreeSet<String>>,
}
// 只剥离与模型 ID 一致的推理档位,Orchestrator (Carbon) 等名称中的括号属于成员名
fn model_member_name<'a>(id: &str, name: &'a str) -> &'a str {
if let Some((member, level)) = name
.strip_suffix(')')
.and_then(|name| name.rsplit_once(" ("))
&& matches!(level, "Low" | "Medium" | "High" | "XHigh")
&& id
.rsplit_once('-')
.is_some_and(|(_, suffix)| suffix.eq_ignore_ascii_case(level))
{
return member;
}
name
}
impl QuotaGroup {
// 上游在描述里逐项列出额度成员,名单不完整时无法给出可信的本地总量
fn usage_models(&self, catalog: &Catalog) -> Option<BTreeSet<String>> {
let members = self
.description
.as_deref()?
.strip_prefix("Models within this group: ")?;
let mut ids = BTreeSet::new();
for member in members.split(',').map(str::trim) {
if member.is_empty() {
return None;
}
let mut matches = catalog
.models
.iter()
.filter(|(id, model)| {
model.name == member || model_member_name(id, &model.name) == member
})
.peekable();
matches.peek()?;
ids.extend(matches.map(|(id, _)| id.clone()));
}
Some(ids)
}
}
pub(super) fn bucket_models(
summary: &QuotaSummary,
catalog: &Catalog,
) -> BTreeMap<String, BTreeSet<String>> {
let mut buckets = BTreeMap::new();
for group in &summary.groups {
if let Some(ids) = group.usage_models(catalog) {
for bucket in &group.buckets {
buckets.insert(bucket.bucket_id.clone(), ids.clone());
}
}
}
buckets
}
impl ModelQuota {
@@ -143,7 +204,12 @@ impl Document {
limit_id: group_id.clone(),
limit_name: Some(group.display_name.clone()),
role: None,
local_usage_attribution: QuotaLocalUsageAttribution::Unavailable,
local_usage_attribution: self
.bucket_models
.get(&bucket.bucket_id)
.map_or(QuotaLocalUsageAttribution::Unavailable, |ids| {
QuotaLocalUsageAttribution::Models(ids.clone())
}),
window_seconds: seconds,
used_percent: used,
reset_at: bucket.quota.reset_time,
@@ -165,6 +165,7 @@ impl QuotaService {
.map_err(upstream)?;
let doc = Document {
tier: info.paid_tier.or(info.current_tier),
bucket_models: super::document::bucket_models(&summary, &catalog),
summary,
models: catalog
.models
@@ -250,13 +251,13 @@ impl QuotaService {
&self,
cancel: &CancellationToken,
) -> Result<(), WorkerTaskError> {
let mut accounts = self
let accounts = self
.accounts
.list_for_provider(&self.kind, false)
.await
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
let ids: Vec<_> = accounts.iter().map(|a| a.id().clone()).collect();
let observations: BTreeMap<_, _> = self
let mut observations: BTreeMap<_, _> = self
.accounts
.get_quota_versions(&ids)
.await
@@ -264,37 +265,67 @@ impl QuotaService {
.into_iter()
.map(|o| (o.account_id.clone(), o))
.collect();
accounts.retain(|a| {
a.enabled()
&& a.authentication_kind() == "oauth"
&& observations.get(a.id()).is_none_or(|o| {
o.credential_revision != a.revision()
|| o.observed_at.elapsed().unwrap_or_default() >= Duration::from_secs(300)
|| (a.quota().is_exhausted()
&& a.quota()
.reset_at()
.is_some_and(|reset| reset <= SystemTime::now()))
})
});
if accounts.is_empty() {
return Ok(());
let now = SystemTime::now();
let interval = Duration::from_secs(300);
let stale_before = now - interval;
let mut due = Vec::new();
let mut stale = Vec::new();
for account in accounts
.iter()
.filter(|a| a.enabled() && a.authentication_kind() == "oauth")
{
let snapshot = observations
.remove(account.id())
.filter(|s| s.credential_revision == account.revision());
match snapshot {
None => due.push(account.id().clone()),
Some(_) if account.quota().exhaustion_refresh_due(now, interval) => {
due.push(account.id().clone())
}
Some(s) if !account.quota().is_exhausted() && s.observed_at <= stale_before => {
stale.push(s)
}
Some(_) => {}
}
}
accounts.sort_by(|a, b| a.id().cmp(b.id()));
let offset = self.cursor.fetch_add(32, Ordering::Relaxed) % accounts.len();
accounts.rotate_left(offset);
accounts.truncate(32);
let mut results = stream::iter(accounts).map(|a| async move { tokio::select! { biased; _ = cancel.cancelled() => Ok(()), result = self.refresh(a.id()) => result } }).buffer_unordered(4);
let mut failure = None;
let mut outcome = Ok(());
if !stale.is_empty() {
// 用量读取失败时,独立执行已选出的首查和耗尽复查
match self.accounts.accounts_used_since_quota(&stale).await {
Ok(active) => due.extend(active),
Err(e) => {
outcome =
Err(WorkerTaskError::safe("读取 Antigravity 账号使用记录失败")
.with_source(e))
}
}
}
if due.is_empty() {
return outcome;
}
due.sort_unstable();
let offset = self.cursor.fetch_add(32, Ordering::Relaxed) % due.len();
due.rotate_left(offset);
due.truncate(32);
let mut results = stream::iter(due)
.map(|id| async move {
tokio::select! {
biased;
_ = cancel.cancelled() => Ok(()),
result = self.refresh(&id) => result,
}
})
.buffer_unordered(4);
while let Some(result) = results.next().await {
if let Err(e) = result
&& !matches!(e.kind(), Kind::Conflict | Kind::CredentialRefreshRequired)
&& outcome.is_ok()
{
failure.get_or_insert(e);
outcome =
Err(WorkerTaskError::safe("部分 Antigravity 额度刷新失败").with_source(e));
}
}
failure.map_or(Ok(()), |e| {
Err(WorkerTaskError::safe("部分 Antigravity 额度刷新失败").with_source(e))
})
outcome
}
}
@@ -30,10 +30,16 @@ impl AntigravityProvider {
&self,
model: &UpstreamModelId,
ctx: &AttemptContext,
search: bool,
) -> Result<CandidatePool, ProviderError> {
let required = ctx.required_account();
let diagnostic = ctx.is_diagnostic_required_account();
let (accounts, projects) = if diagnostic {
if search {
return Err(ProviderError::invalid_request(
"Web search requires an account model catalog.",
));
}
let id = required.ok_or_else(|| unsent(Kind::NoEligibleAccount))?;
let account = self
.accounts
@@ -45,8 +51,13 @@ impl AntigravityProvider {
let projects = BTreeMap::from([(id.clone(), (account.revision(), Project::Discover))]);
(vec![account], projects)
} else {
let projects = self.catalog_projects(model, ctx).await?;
let projects = self.catalog_projects(model, ctx, search).await?;
let ids: Vec<_> = projects.keys().cloned().collect();
if ids.is_empty() && search {
return Err(ProviderError::invalid_request(
gateway_core::validation::WEB_SEARCH_UNAVAILABLE_MESSAGE,
));
}
if ids.is_empty() {
return Err(unsent(Kind::NoEligibleAccount));
}
@@ -165,11 +176,20 @@ impl AntigravityProvider {
&self,
model: &UpstreamModelId,
ctx: &AttemptContext,
search: bool,
) -> Result<BTreeMap<ProviderAccountId, (CredentialRevision, Project)>, ProviderError> {
let required = ctx.required_account();
let mut projects = BTreeMap::new();
for (observations, catalog) in self.catalog.catalogs().await? {
if !catalog.models.contains_key(model.as_str()) {
let supports = if search {
catalog
.web_search_models
.first()
.is_some_and(|id| id == model.as_str())
} else {
catalog.models.contains_key(model.as_str())
};
if !supports {
continue;
}
for observation in observations {
@@ -41,7 +41,10 @@ impl AntigravityProvider {
let started = Instant::now();
let affinity =
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
let selected = self.select_account(&model, &ctx, affinity.as_ref()).await?;
let search = request.operation().requires_web_search();
let selected = self
.select_account(&model, &ctx, affinity.as_ref(), search)
.await?;
let selection = ProviderSelectionObservation::new(
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
selected.capacity,
@@ -87,6 +90,9 @@ impl AntigravityProvider {
Some(model.as_str().to_owned()),
selected.account.id().clone(),
Box::new(move |operation, headers| Box::pin(async move {
if operation.requires_web_search() != search {
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
}
let (operation, translator) = super::translation::prepare(operation)?;
let headers = crate::transport::request_headers(&operation, headers, selected.account_switch);
if operation.protocol() != GENAI_PROTOCOL {
@@ -126,7 +132,8 @@ impl AntigravityProvider {
// 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号
Project::Discover => resource.account_info(token).await?.project,
};
resource.generate(&project, model.as_str(), token, &body, stream, &headers).await
let mode = if search { crate::transport::GenerateMode::WebSearch } else { crate::transport::GenerateMode::from(stream) };
resource.generate(&project, model.as_str(), token, &body, mode, &headers).await
} => response,
};
let response = match response {
@@ -128,3 +128,5 @@ fn unavailable(error: impl Into<ErrorSource>) -> ProviderError {
crate::transport::unsent(ProviderErrorKind::ProviderInfrastructureUnavailable)
.with_source(error)
}
mod web_search;
@@ -48,9 +48,10 @@ impl AntigravityProvider {
model: &UpstreamModelId,
ctx: &AttemptContext,
affinity_key: Option<&ProviderSessionAffinityKey>,
search: bool,
) -> Result<SelectedAccount, ProviderError> {
let policy = ctx.account_selection_policy();
let select = |queue| self.select_with_queue(model, ctx, queue, affinity_key);
let select = |queue| self.select_with_queue(model, ctx, queue, affinity_key, search);
let result = match select(policy.queue_policy()).await {
Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => {
policy
@@ -82,6 +83,7 @@ impl AntigravityProvider {
ctx: &AttemptContext,
queue: ConcurrencyQueuePolicy,
affinity_key: Option<&ProviderSessionAffinityKey>,
search: bool,
) -> Result<SelectedAccount, SelectionError> {
let mut waiting = CapacityWait::new(
&self.waiting,
@@ -101,7 +103,7 @@ impl AntigravityProvider {
accounts,
mut projects,
mut selection,
} = self.load_candidates(model, ctx).await?;
} = self.load_candidates(model, ctx, search).await?;
let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
Some(key) => Some(ProviderSessionAffinityState::new(
key,
@@ -42,49 +42,59 @@ pub(super) fn prepare(
{
return Err(unsent(ProviderErrorKind::InvalidRequest));
}
let responses = if source == OPENAI_PROTOCOL {
Some(MessagesToResponsesStream::new(original))
let search = operation.requires_web_search();
let body = if search {
super::web_search::request(original)?
} else {
None
};
let mut messages = if source == OPENAI_PROTOCOL {
Cow::Owned(
responses_to_messages_request(original, &MessagesModelCapabilities::default())
let mut messages = if source == OPENAI_PROTOCOL {
Cow::Owned(
responses_to_messages_request(
original,
&MessagesModelCapabilities {
hosted_web_search: Some(false),
..Default::default()
},
)
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?,
)
} else {
Cow::Borrowed(original)
)
} else {
Cow::Borrowed(original)
};
// Messages 的必填输出上限不能成为 GenAI 的隐式默认值
if source == OPENAI_PROTOCOL && !original.contains_key("max_output_tokens") {
messages.to_mut().remove("max_tokens");
}
messages_to_genai_request(&messages)
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?
};
// Messages 的必填输出上限不能成为 GenAI 的隐式默认值
if source == OPENAI_PROTOCOL && !original.contains_key("max_output_tokens") {
messages.to_mut().remove("max_tokens");
}
let model = original
.get("model")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let body = messages_to_genai_request(&messages)
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?;
let translator = if search {
Translator::Search(Box::new(super::web_search::SearchResponse::new(original)))
} else {
Translator::Generate(Box::new(GenerationTranslator {
genai: GenAiToMessagesStream::new(model),
responses: (source == OPENAI_PROTOCOL)
.then(|| MessagesToResponsesStream::new(original)),
}))
};
let mut context = payload.context().clone();
// 转换路径统一请求 SSE,JSON 客户端沿已有交付层聚合
context.insert("stream".into(), json!(true));
// Desktop 搜索使用完整 JSON,编码路径保留增量交付
context.insert("stream".into(), json!(!search));
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
let operation = operation
.replace_protocol_wire(None, context)
.and_then(|operation| operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into()))
.map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
Ok((
operation,
Some(Translator::Generate(Box::new(GenerationTranslator {
genai: GenAiToMessagesStream::new(model),
responses,
}))),
))
Ok((operation, Some(translator)))
}
pub(super) enum Translator {
Generate(Box<GenerationTranslator>),
Search(Box<super::web_search::SearchResponse>),
Count(&'static str),
}
@@ -134,6 +144,7 @@ impl NativeResponseTranslator for Translator {
fn target_protocol(&self) -> &str {
match self {
Self::Generate(translator) => translator.target_protocol(),
Self::Search(_) => OPENAI_PROTOCOL,
Self::Count(protocol) => protocol,
}
}
@@ -141,6 +152,9 @@ impl NativeResponseTranslator for Translator {
&mut self,
event: &ProtocolWireEvent,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
if let Self::Search(search) = self {
return search.translate(event);
}
let Self::Generate(translator) = self else {
let value = match event.raw_json_body() {
Some(raw) => Cow::Owned(
@@ -166,9 +180,13 @@ impl NativeResponseTranslator for Translator {
translator.events(events)
}
fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
if let Self::Search(search) = self {
return search.finish();
}
let Self::Generate(translator) = self else {
return Ok(Vec::new());
};
let events = translator
.genai
.finish()
@@ -0,0 +1,205 @@
//! AGY 编码请求保留函数工具;只有强制搜索才构造独立的原生请求
use crate::transport::sent;
use gateway_core::{
engine::provider::MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT,
error::{ProviderError, ProviderErrorKind},
event::ProtocolWireEvent,
};
use gateway_protocol::{
anthropic::MessagesToResponsesStream,
genai::{GenAiToMessagesStream, grounded_search_events},
openai::{OPENAI_PROTOCOL, web_search::is_search},
};
use serde_json::{Map, Value, json};
use std::borrow::Cow;
pub(super) fn request(original: &Map<String, Value>) -> Result<Map<String, Value>, ProviderError> {
let choice = original.get("tool_choice").unwrap_or(&Value::Null);
let mut tools = original
.get("tools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|tool| {
is_search(tool)
&& (!is_search(choice) || choice["type"] == tool["type"])
&& (choice["type"] != "allowed_tools"
|| choice["tools"]
.as_array()
.is_some_and(|allowed| allowed.iter().any(|t| t["type"] == tool["type"])))
});
let tool = tools.next().ok_or_else(|| {
ProviderError::invalid_request("The selected web search tool must be declared.")
})?;
if tools.next().is_some() {
return Err(ProviderError::invalid_request(
"Select one web search declaration.",
));
}
if tool
.get("external_web_access")
.is_some_and(|v| !v.is_null() && v != true && v != "live")
{
return Err(ProviderError::invalid_request(
"Antigravity web search requires live external web access.",
));
}
let options = google_search_options(tool)?;
if original
.get("text")
.and_then(|v| v.pointer("/format/type"))
.is_some_and(|v| v != "text")
{
return Err(ProviderError::invalid_request(
"Antigravity web search supports text output only.",
));
}
// Desktop 的独立搜索只提交当前用户查询,编码历史和函数返回不进入搜索供应方
let input = original.get("input").unwrap_or(&Value::Null);
let query = if let Some(items) = input.as_array() {
let item = items
.last()
.filter(|i| i["role"] == "user")
.ok_or_else(invalid_query)?;
let content = &item["content"];
if let Some(parts) = content.as_array() {
parts
.iter()
.map(|p| {
(p["type"] == "input_text")
.then(|| p["text"].as_str())
.flatten()
.ok_or_else(invalid_query)
})
.collect::<Result<Vec<_>, _>>()?
.join("\n")
} else {
content.as_str().ok_or_else(invalid_query)?.to_owned()
}
} else {
input.as_str().ok_or_else(invalid_query)?.to_owned()
};
if query.trim().is_empty() {
return Err(invalid_query());
}
let mut body = Map::from_iter([
(
"contents".into(),
json!([{"role":"user","parts":[{"text":query}]}]),
),
("tools".into(), json!([{"googleSearch":options}])),
]);
if let Some(limit) = original.get("max_output_tokens").filter(|v| !v.is_null()) {
let limit = limit.as_u64().filter(|n| *n > 0).ok_or_else(|| {
ProviderError::invalid_request("max_output_tokens must be a positive integer.")
})?;
body.insert("generationConfig".into(), json!({"maxOutputTokens":limit}));
}
Ok(body)
}
fn google_search_options(tool: &Value) -> Result<Map<String, Value>, ProviderError> {
let unsupported = || {
ProviderError::invalid_request("Antigravity cannot honor the specified web search options.")
};
let tool = tool.as_object().ok_or_else(unsupported)?;
if tool.iter().any(|(k, v)| {
!v.is_null() && !matches!(k.as_str(), "type" | "external_web_access" | "filters")
}) {
return Err(unsupported());
}
let mut options = Map::new();
if let Some(filters) = tool.get("filters").filter(|v| !v.is_null()) {
for (field, domains) in filters.as_object().ok_or_else(unsupported)? {
let field = match field.as_str() {
"allowed_domains" => "includedDomains",
"blocked_domains" => "excludeDomains",
_ => return Err(unsupported()),
};
let domains = domains
.as_array()
.filter(|values| {
!values.is_empty()
&& values
.iter()
.all(|v| v.as_str().is_some_and(|s| !s.trim().is_empty()))
})
.ok_or_else(unsupported)?;
options.insert(field.into(), json!(domains));
}
}
Ok(options)
}
fn invalid_query() -> ProviderError {
ProviderError::invalid_request(
"Antigravity web search requires a text query in the last user message.",
)
}
pub(super) struct SearchResponse {
responses: MessagesToResponsesStream,
include_sources: bool,
terminal: Option<ProtocolWireEvent>,
}
impl SearchResponse {
pub(super) fn new(original: &Map<String, Value>) -> Self {
Self {
responses: MessagesToResponsesStream::new(original),
include_sources: original
.get("include")
.and_then(Value::as_array)
.is_some_and(|v| v.iter().any(|v| v == "web_search_call.action.sources")),
terminal: None,
}
}
pub(super) fn translate(
&mut self,
event: &ProtocolWireEvent,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
let value = match event.raw_json_body() {
Some(raw) => Cow::Owned(
serde_json::from_slice(raw).map_err(|_| sent(ProviderErrorKind::Protocol))?,
),
None => Cow::Borrowed(event.data()),
};
let error = |e| sent(ProviderErrorKind::Protocol).with_source(e);
let mut genai = GenAiToMessagesStream::new(String::new());
let mut messages = genai.push(&value).map_err(error)?;
messages.extend(genai.finish().map_err(error)?);
let mut responses = Vec::new();
for message in messages {
responses.extend(self.responses.push(&message).map_err(error)?);
}
let mut wire: Vec<_> = grounded_search_events(
&value,
responses,
self.include_sources,
MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT + 1,
)
.map_err(error)?
.into_iter()
.map(|event| {
ProtocolWireEvent::json(
OPENAI_PROTOCOL,
event["type"].as_str().map(str::to_owned),
event,
)
.map_err(|_| sent(ProviderErrorKind::Protocol))
})
.collect::<Result<_, _>>()?;
// 单次 JSON 先交付内容;协议终态必须随 Core 的 Completed 事实交付
self.terminal = wire.pop();
Ok(wire)
}
pub(super) fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
self.terminal
.take()
.map(|v| vec![v])
.ok_or_else(|| sent(ProviderErrorKind::Protocol))
}
}
@@ -36,6 +36,8 @@ pub(crate) struct QuotaSummary {
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct QuotaGroup {
#[serde(skip_serializing)]
pub(crate) description: Option<String>,
pub(crate) display_name: String,
pub(crate) buckets: Vec<QuotaBucket>,
}
@@ -14,11 +14,18 @@ use url::Url;
use super::failure::{network, sent, successful, unsent};
use crate::profile::ClientProfile;
use gateway_core::engine::middleware::MiddlewareHeader;
// Desktop 独立搜索使用固定任务指令,常规生成与计数使用账号画像
static SEARCH_INSTRUCTION: std::sync::LazyLock<&RawValue> = std::sync::LazyLock::new(|| {
serde_json::from_str(r#"{"parts":[{"text":"Search the web for the query and return a concise answer grounded in the sources."}]}"#).expect("valid static search instruction")
});
const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
#[derive(Serialize, Deserialize)]
pub(crate) struct Catalog {
pub(crate) project: String,
#[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,
@@ -30,6 +37,29 @@ pub(crate) struct Model {
pub(crate) name: String,
#[serde(rename = "quotaInfo", default)]
pub(crate) quota: Option<super::account::ModelQuota>,
#[serde(default)]
pub(crate) description: Option<String>,
#[serde(rename = "tagDescription", default)]
pub(crate) tag_description: Option<String>,
#[serde(rename = "maxTokens", default)]
pub(crate) context_window: Option<u64>,
#[serde(rename = "maxOutputTokens", default)]
pub(crate) max_output_tokens: Option<u64>,
#[serde(rename = "supportsImages", default)]
pub(crate) supports_images: Option<bool>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum GenerateMode {
Json,
Stream,
WebSearch,
}
impl From<bool> for GenerateMode {
fn from(stream: bool) -> Self {
if stream { Self::Stream } else { Self::Json }
}
}
pub(crate) struct CloudCodeClient {
@@ -102,6 +132,8 @@ impl CloudCodeClient {
) -> Result<Catalog, ProviderError> {
#[derive(Deserialize)]
struct Models {
#[serde(rename = "webSearchModelIds", default)]
web_search_models: Vec<String>,
models: BTreeMap<String, Model>,
#[serde(rename = "groupedModels", default)]
grouped_models: serde_json::Value,
@@ -123,6 +155,7 @@ impl CloudCodeClient {
project,
models: models.models,
grouped_models: models.grouped_models,
web_search_models: models.web_search_models,
})
}
@@ -132,17 +165,24 @@ impl CloudCodeClient {
model: &str,
token: &str,
body: &[u8],
stream: bool,
mode: GenerateMode,
headers: &[MiddlewareHeader],
) -> Result<Response, ProviderError> {
#[derive(Serialize)]
struct Envelope<'a> {
project: &'a str,
model: &'a str,
#[serde(rename = "requestType", skip_serializing_if = "Option::is_none")]
request_type: Option<&'static str>,
request: BTreeMap<String, &'a RawValue>,
}
let request = self.request_body(body)?;
let (send, media) = if stream {
let instruction = if mode == GenerateMode::WebSearch {
*SEARCH_INSTRUCTION
} else {
&self.system_instruction
};
let request = Self::request_body(body, instruction)?;
let (send, media) = if mode == GenerateMode::Stream {
(
self.post("streamGenerateContent", token)
.query(&[("alt", "sse")]),
@@ -155,6 +195,7 @@ impl CloudCodeClient {
send.json(&Envelope {
project,
model,
request_type: (mode == GenerateMode::WebSearch).then_some("web_search"),
request,
}),
token,
@@ -170,7 +211,7 @@ impl CloudCodeClient {
body: &[u8],
headers: &[MiddlewareHeader],
) -> Result<Response, ProviderError> {
let mut request = self.request_body(body)?;
let mut request = Self::request_body(body, &self.system_instruction)?;
// Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段
for field in [
"model",
@@ -195,14 +236,14 @@ impl CloudCodeClient {
}
fn request_body<'a>(
&'a self,
body: &'a [u8],
instruction: &'a RawValue,
) -> Result<BTreeMap<String, &'a RawValue>, ProviderError> {
let mut request: BTreeMap<String, &RawValue> = serde_json::from_slice(body)
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
// 生成和计数共享同一身份策略,其他字段保留原始 JSON 表达
request.remove("system_instruction");
request.insert("systemInstruction".to_owned(), &self.system_instruction);
request.insert("systemInstruction".to_owned(), instruction);
Ok(request)
}
@@ -6,7 +6,7 @@ mod failure;
mod headers;
mod pool;
mod response;
pub(crate) use client::{Catalog, CloudCodeClient, unwrap_frame};
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
pub(crate) use count::count_events;
pub(crate) use failure::{sent, unsent};
pub(crate) use headers::request_headers;
@@ -15,6 +15,154 @@ async fn upstream(server: &MockServer, remaining: serde_json::Value, delay: Dura
Mock::given(path("/v1internal:retrieveUserQuotaSummary")).respond_with(ResponseTemplate::new(200).set_delay(delay).set_body_json(json!({"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.9,"resetTime":"2099-01-01T00:00:00Z"},{"bucketId":"gemini-5h","displayName":"Five hour","window":"5h","remainingFraction":remaining,"resetTime":"2099-01-01T00:00:00Z"}]},{"displayName":"Claude and GPT models","buckets":[{"bucketId":"3p-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.8,"resetTime":"2099-01-01T00:00:00Z"}]}]}))).mount(server).await;
}
#[tokio::test]
async fn window_usage_requires_every_named_member_to_resolve_in_the_observed_catalog() {
use gateway_admin::model::provider_credentials::QuotaLocalUsageAttribution::{
Models, Unavailable,
};
let server = MockServer::start().await;
Mock::given(path("/v1internal:loadCodeAssist"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!({"cloudaicompanionProject":"p"})),
)
.mount(&server)
.await;
Mock::given(path("/v1internal:fetchAvailableModels"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"models":{
"gemini-4-neon-high":{"displayName":"Gemini 4 Neon (High)"},
"gemini-4-neon-low":{"displayName":"Gemini 4 Neon (Low)"},
"orchestrator-alias":{"displayName":"Orchestrator (Neon)"},
"gemini-lite":{"displayName":"Gemini Lite"},
"gpt-oss-medium":{"displayName":"GPT-OSS (Medium)"}
}})))
.mount(&server)
.await;
let group = |description: Option<&str>, name: &str| {
json!({
"displayName":name, "description":description,
"buckets":(["5h", "weekly"].map(|window| json!({
"bucketId":format!("{name}-{window}"), "displayName":window, "window":window
})))
})
};
Mock::given(path("/v1internal:retrieveUserQuotaSummary"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"groups":[
group(Some("Models within this group: Gemini 4 Neon, Orchestrator (Neon)"), "gemini"),
group(Some("Models within this group: GPT-OSS"), "3p"),
group(Some("Models within this group: Gemini Lite, Missing Model"), "partial"),
group(None, "unknown")
]})))
.mount(&server)
.await;
let f = Fixture::new(&server.uri());
let account = f.store.primary().loaded.lock().unwrap().account.clone();
f.quota.refresh(account.id()).await.unwrap();
let view = f.quota.read(account.id()).await.unwrap();
for (group, attribution) in [
(
"gemini",
Models(
[
"gemini-4-neon-high",
"gemini-4-neon-low",
"orchestrator-alias",
]
.map(str::to_owned)
.into(),
),
),
("3p", Models(["gpt-oss-medium".to_owned()].into())),
("partial", Unavailable),
("unknown", Unavailable),
] {
for window in ["5h", "weekly"] {
let key = format!("{group}-{window}");
let observed = view.windows.iter().find(|w| w.key == key).unwrap();
assert_eq!(observed.local_usage_attribution, attribution);
}
}
}
#[tokio::test]
async fn background_refresh_requires_new_generation_and_an_aged_snapshot() {
let server = MockServer::start().await;
upstream(&server, json!(0.5), Duration::ZERO).await;
let f = Fixture::new(&server.uri());
let account = f.store.primary();
let cancel = CancellationToken::new();
f.quota.reconcile(&cancel).await.unwrap();
let initial = account.quota.lock().unwrap().clone().unwrap();
let queries = || async {
server
.received_requests()
.await
.unwrap()
.into_iter()
.filter(|r| r.url.path() == "/v1internal:retrieveUserQuotaSummary")
.count()
};
assert_eq!(queries().await, 1);
*account.last_generation.lock().unwrap() = Some(SystemTime::now());
f.quota.reconcile(&cancel).await.unwrap();
assert_eq!(queries().await, 1);
let old = initial.observed_at - Duration::from_secs(900);
account.quota.lock().unwrap().as_mut().unwrap().observed_at = old;
*account.last_generation.lock().unwrap() = Some(old - Duration::from_secs(1));
f.quota.read(&initial.account_id).await.unwrap();
f.quota.reconcile(&cancel).await.unwrap();
assert_eq!(queries().await, 1);
*account.last_generation.lock().unwrap() = Some(SystemTime::now());
f.quota.reconcile(&cancel).await.unwrap();
f.quota.reconcile(&cancel).await.unwrap();
assert_eq!(queries().await, 2);
f.quota.refresh(&initial.account_id).await.unwrap();
assert_eq!(queries().await, 3);
}
#[tokio::test]
async fn exhausted_quota_is_rechecked_when_due_even_without_generation() {
use gateway_core::account::QuotaEvidence;
let server = MockServer::start().await;
upstream(&server, json!(0.5), Duration::ZERO).await;
let f = Fixture::new(&server.uri());
let account = f.store.primary();
let cancel = CancellationToken::new();
f.quota.reconcile(&cancel).await.unwrap();
let now = SystemTime::now();
let old = now - Duration::from_secs(600);
for (observed, reset, due) in [
(old, Some(now + Duration::from_secs(300)), false),
(old, Some(now), true),
(now, None, false),
(old, None, true),
] {
{
let mut loaded = account.loaded.lock().unwrap();
loaded.account = loaded.account.clone().with_account_facts(
true,
CredentialState::Ready,
QuotaState::exhausted(QuotaEvidence::UsageLimitReached, observed, reset),
None,
None,
);
}
f.quota.reconcile(&cancel).await.unwrap();
assert_eq!(
account
.loaded
.lock()
.unwrap()
.account
.quota()
.is_exhausted(),
!due
);
}
}
#[tokio::test]
async fn quota_and_catalog_refresh_use_current_global_identity() {
let server = MockServer::start().await;
@@ -191,6 +339,16 @@ async fn failed_or_stale_refresh_preserves_persisted_quota() {
let cancelled = CancellationToken::new();
cancelled.cancel();
f.quota.reconcile(&cancelled).await.unwrap();
f.quota.reconcile(&CancellationToken::new()).await.unwrap();
assert_eq!(
f.quota
.read(account.id())
.await
.unwrap()
.plan_type
.as_deref(),
Some("g1-pro-tier")
);
}
#[tokio::test]
@@ -196,7 +196,7 @@ async fn mock_project(upstream: &MockServer) {
}
#[tokio::test]
async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
async fn model_group_menu_routes_responses_and_native_generation_to_declared_members() {
use gateway_core::{
engine::provider::ProviderRequest,
operation::{GenerateRequest, Operation, ProtocolPayload},
@@ -210,12 +210,12 @@ async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
Mock::given(path("/v1internal:fetchAvailableModels"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"models": {
"gemini-4-hydrogen-medium": {"displayName":"Hydrogen Medium"},
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High"},
"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"}
},
"groupedModels": {
"gemini-4-hydrogen": {"supportedThinkingLevels":[
"gemini-4-hydrogen": {"displayName":"Gemini 4 Hydrogen","supportedThinkingLevels":[
{"thinkingSuffix":"MEDIUM"}, {"thinkingSuffix":"high"},
{"thinkingSuffix":"low"}, {"thinkingSuffix":"../sonar"}
]},
@@ -237,14 +237,16 @@ async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
.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!(
group
.capabilities()
.reasoning_variants()
.keys()
.map(String::as_str)
.collect::<Vec<_>>(),
vec!["high", "medium"]
models
.iter()
.filter(|entry| entry.presentation().is_some())
.count(),
1
);
let snapshot = RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(),
@@ -253,16 +255,29 @@ async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
models
.iter()
.map(|model| {
ProviderModel::new(
let entry = 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));
assert_eq!(
menu.max_context_window_tokens(),
menu.context_window_tokens()
);
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 {
@@ -309,6 +324,43 @@ async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
assert!(events.iter().any(|event| event.has_client_event()));
released(&fixture).await;
}
Mock::given(path("/v1internal:streamGenerateContent"))
.and(body_partial_json(json!({"model":"gemini-4-hydrogen-high","request":{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"AA=="}}]}]}})))
.respond_with(ResponseTemplate::new(200).set_body_raw(
"data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"OK\"}]},\"finishReason\":\"STOP\"}]}}\n\n",
"text/event-stream",
)).expect(1).mount(&upstream).await;
let body = json!({"model":group.upstream_model().as_str(),"input":[{"role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]}],"reasoning":{"effort":"high"}});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let plan = snapshot
.plan(
&PublicModelId::new(group.upstream_model().as_str()).unwrap(),
&operation,
fixture.store.account_scope(),
&RoutingContext::default(),
)
.unwrap();
let events = fixture
.provider
.clone()
.execute(
ProviderRequest::new(operation, plan.candidates()[0].clone()),
context(frozen_profile(), CancellationToken::new()),
)
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
assert!(
events
.iter()
.flat_map(|event| event.canonical_facts())
.any(|fact| matches!(fact, gateway_core::event::GatewayEvent::Completed(_)))
);
released(&fixture).await;
}
#[tokio::test]
@@ -647,3 +699,112 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
released(&fixture).await;
}
}
#[tokio::test]
async fn required_search_uses_catalog_target_and_delivers_grounded_terminal() {
use gateway_core::{
engine::provider::ProviderRequest,
event::GatewayEvent,
operation::{GenerateRequest, Operation, ProtocolPayload},
routing::{ConfigRevision, ProviderModel, PublicModelId, RoutingContext, RuntimeSnapshot},
settings::SettingsValues,
};
let server = MockServer::start().await;
let fixture = Fixture::new(&server.uri());
{
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
let (_, bytes) = catalog.as_mut().unwrap();
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
value["webSearchModelIds"] = json!(["search-only", "not-selected"]);
*bytes = value.to_string().into();
}
let kind = ProviderKind::new("antigravity").unwrap();
let models = fixture.provider.query_model_capabilities().await.unwrap();
assert!(
!models
.iter()
.any(|m| m.upstream_model().as_str() == "search-only")
);
let snapshot = RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(),
SettingsValues::new(1, "smart", Default::default(), None, None),
vec![kind.clone()],
models
.iter()
.map(|m| {
ProviderModel::new(
kind.clone(),
m.upstream_model().clone(),
m.capabilities().clone(),
)
})
.collect(),
vec![],
)
.unwrap();
let search = json!({"type":"web_search","filters":{"allowed_domains":["example.org"]}});
let choice = json!({"type":"allowed_tools","mode":"required","tools":[{"type":"web_search"}]});
let body = json!({"model":"fixture-model","input":"你好","tool_choice":choice,"tools":[search,{"type":"function","name":"pwd"}],"include":["web_search_call.action.sources"]});
let op = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let plan = snapshot
.plan(
&PublicModelId::new("fixture-model").unwrap(),
&op,
fixture.store.account_scope(),
&RoutingContext::default(),
)
.unwrap();
let candidate = &plan.candidates()[0];
assert_eq!(candidate.upstream_model().unwrap().as_str(), "search-only");
Mock::given(path("/v1internal:generateContent")).and(body_partial_json(json!({
"model":"search-only","requestType":"web_search","request":{"tools":[{"googleSearch":{"includedDomains":["example.org"]}}],"contents":[{"role":"user","parts":[{"text":"你好"}]}]}
}))).respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{
"responseId":"r","candidates":[{"content":{"parts":[{"text":"前 "},{"text":"答案"}]},"finishReason":"STOP",
"groundingMetadata":{"webSearchQueries":["你好"],"groundingChunks":[{"web":{"uri":"https://example.org","title":"来源"}}],
"groundingSupports":[{"segment":{"partIndex":1,"endIndex":6},"groundingChunkIndices":[0]}]}}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":2}}}))).expect(1).mount(&server).await;
let mut stream = fixture
.provider
.clone()
.execute(
ProviderRequest::new(op, candidate.clone()),
context(frozen_profile(), CancellationToken::new()),
)
.await
.unwrap();
let mut wire = Vec::new();
while let Some(event) = stream.next().await {
let event = event.unwrap();
let terminal = event
.canonical_facts()
.iter()
.any(|f| matches!(f, GatewayEvent::Completed(_)));
for translated in stream.translate_native_response(event, terminal).unwrap() {
if let Some(frame) = translated.wire_event() {
assert_eq!(frame.data()["type"] == "response.completed", terminal);
wire.push(frame.data().clone());
}
}
}
for (i, event) in wire.iter().enumerate() {
assert_eq!(event["sequence_number"], i)
}
let response = &wire.last().unwrap()["response"];
assert_eq!(response["model"], "fixture-model");
assert_eq!(response["usage"]["total_tokens"], 7);
let output = &response["output"];
assert_eq!(
output[0]["action"]["sources"][0]["url"],
"https://example.org"
);
let citation = &output[1]["content"][0]["annotations"][0];
assert_eq!(citation["start_index"], 2);
assert_eq!(citation["end_index"], 4);
assert_eq!(citation["url"], "https://example.org");
assert!(
wire.iter()
.any(|v| v["type"] == "response.output_text.annotation.added"
&& &v["annotation"] == citation)
);
}
@@ -72,6 +72,7 @@ pub(crate) struct MemoryAccount {
pub(crate) catalog: Mutex<Option<(AccountCatalogObservation, bytes::Bytes)>>,
active_leases: Arc<AtomicUsize>,
pub(crate) quota: Mutex<Option<gateway_core::account::QuotaObservation>>,
pub(crate) last_generation: Mutex<Option<SystemTime>>,
}
impl MemoryPorts {
@@ -182,6 +183,7 @@ impl Fixture {
))),
active_leases: Arc::new(AtomicUsize::new(0)),
quota: Mutex::new(None),
last_generation: Mutex::new(None),
},
)
})
@@ -594,6 +594,22 @@ impl ProviderAccountStore for MemoryPorts {
*quota = Some(observation);
Ok(QuotaWriteOutcome::Updated)
}
async fn accounts_used_since_quota(
&self,
snapshots: &[QuotaObservationVersion],
) -> Result<Vec<ProviderAccountId>, StoreError> {
Ok(snapshots
.iter()
.filter(|s| {
self.accounts[&s.account_id]
.last_generation
.lock()
.unwrap()
.is_some_and(|at| at > s.observed_at)
})
.map(|s| s.account_id.clone())
.collect())
}
async fn touch_quota_observation(
&self,
_touch: QuotaObservationTouch,
@@ -114,7 +114,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
"fixture-model",
&access_token,
body,
stream,
stream.into(),
&[],
)
.await
@@ -192,7 +192,7 @@ async fn streamed_text_is_projected_once_across_native_frames() {
.mount(&server)
.await;
let response = client
.generate("p", "m", "fixture", b"{}", true, &[])
.generate("p", "m", "fixture", b"{}", true.into(), &[])
.await
.unwrap();
let events = transport::events(
@@ -255,7 +255,7 @@ async fn incomplete_native_stream_and_redirect_are_rejected() {
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
Mock::given(path("/v1internal:streamGenerateContent")).respond_with(ResponseTemplate::new(200).set_body_raw("data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}}\n\n","text/event-stream")).mount(&server).await;
let res = client
.generate("p", "m", "fixture", b"{}", true, &[])
.generate("p", "m", "fixture", b"{}", true.into(), &[])
.await
.unwrap();
let result = transport::events(
@@ -283,7 +283,7 @@ async fn incomplete_native_stream_and_redirect_are_rejected() {
.await;
assert!(
client
.generate("p", "m", "fixture", b"{}", false, &[])
.generate("p", "m", "fixture", b"{}", false.into(), &[])
.await
.is_err()
);
@@ -147,7 +147,7 @@ async fn generate(
"fixture-model",
token,
br#"{"contents":[{"parts":[{"text":"ping","thoughtSignature":"fixture-signature"}]}]}"#,
false,
false.into(),
&[],
)
.await
@@ -1564,6 +1564,10 @@ async fn openai_admin_provider_projects_official_codex_quota_and_independent_buc
.collect::<Vec<_>>();
assert_eq!(monthly.len(), 1);
assert_eq!(
monthly[0].local_usage_attribution,
QuotaLocalUsageAttribution::AccountWide
);
assert!(monthly.iter().any(|window| {
window.label == "月额度"
&& window.limit_id.as_deref() == Some("codex")
@@ -1594,22 +1598,18 @@ async fn openai_admin_provider_projects_official_codex_quota_and_independent_buc
assert_eq!(review.label, "周额度");
assert_eq!(review.limit_name.as_deref(), Some("code_review"));
assert_eq!(review.role, Some(ProviderQuotaWindowRole::Primary));
assert_eq!(
review.local_usage_attribution,
QuotaLocalUsageAttribution::Unavailable
);
let spark = quota
.windows
.iter()
.find(|window| window.limit_id.as_deref() == Some("codex_bengalfox"))
.expect("Spark quota");
assert_eq!(
(
monthly[0].local_usage_attribution,
review.local_usage_attribution,
spark.local_usage_attribution,
),
(
QuotaLocalUsageAttribution::AccountWide,
QuotaLocalUsageAttribution::Unavailable,
QuotaLocalUsageAttribution::Unavailable,
),
spark.local_usage_attribution,
QuotaLocalUsageAttribution::Unavailable
);
}
+17 -5
View File
@@ -260,7 +260,7 @@ Messages 与 Responses 的转换边界见 [Messages 请求](#messages-请求),
| GET | `/v1beta/models`、`/v1beta/models/{model}` | Gemini 格式的模型列表与详情,见[模型目录](#模型目录) |
| POST | `/v1beta:{method}`(客户端后台指标) | 验证 Key 后返回 `{}`,不启动模型请求 |
普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 SSE 数据帧。原生正文保留工具参数、结果、思考签名和未知字段。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content)
普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 SSE 数据帧。等待首帧和后续帧时,网关保持静默。首帧前的失败保留 HTTP 错误状态。原生正文保留工具参数、结果、思考签名和未知字段。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content)
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选账号与冻结画像生成。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters)
@@ -272,7 +272,11 @@ CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保
AGY 上游计数与生成响应的 `usageMetadata.promptTokenCount` 口径不完全一致:系统提示、工具定义及工具结果未完整计入计数返回值。原生与 Messages 计数均保留这一上游口径,不能作为完整上下文占用或计费用量的精确值
Antigravity 模型也可通过 `/v1/responses`、`/v1/chat/completions` 和 `/v1/messages` 调用,均支持 JSON 与 SSE。转换入口支持文本、内嵌图片/文档、函数工具及结果、生成参数和 JSON Schema;未知内容块返回请求错误,模型自身不支持的参数由上游校验。原生入口不经过转换器;所有 AGY 入口在出站时使用同一份系统提示词配置,替换客户端系统指令,其余原生字段保持原始表达
Antigravity 模型也可通过 `/v1/responses`、`/v1/chat/completions` 和 `/v1/messages` 调用,均支持 JSON 与 SSE。转换入口支持文本、内嵌图片/文档、函数工具及结果、生成参数和 JSON Schema;未知内容块返回请求错误,模型自身不支持的参数由上游校验。原生入口不经过转换器;常规生成与计数在出站时使用同一份 AGY 系统提示词配置,替换客户端系统指令,其余原生字段保持原始表达
Responses 编码请求可以同时声明函数和可选的 `web_search`。AGY 向编码模型发送可用函数,保留 `tool_choice` 和 `allowed_tools` 的约束。显式选择搜索,或要求必须调用工具且只允许搜索时,网关取最后一条用户文本作为查询,向该账号目录的首个 `webSearchModelIds` 型号发送独立的实时搜索请求。账号及其授权分组须同时允许原型号与搜索型号
搜索支持 `filters.allowed_domains` 和 `filters.blocked_domains`。强制搜索遇到缓存模式、无法满足的搜索选项或缺少可用搜索型号时返回请求错误。JSON 与 SSE 均按上游实际查询与来源返回 `web_search_call` 和正文引用;传入 `include: ["web_search_call.action.sources"]` 可读取搜索来源列表
工具多轮调用须带回完整助手输出。Responses 的 `reasoning.encrypted_content` 和 Messages 的 `thinking.signature` 携带 GenAI 工具与思考签名及其所属内容,客户端应原样回传。Chat 沿用现有合同,只返回可读思考内容;转换器对缺少签名的工具调用使用 Google 官方的 `skip_thought_signature_validator` 兜底值,不增加服务端签名缓存。工具与思考的真实签名优先于兜底;普通可见文本的可选签名不附加到转换输出,以保持 CLI 最终文本完整。省略签名或使用兜底可能影响后续模型表现,见 [Google 签名规则](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures)。Antigravity 转换入口不支持 `previous_response_id` 续接
@@ -763,6 +767,14 @@ 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` 选路,未声明上限的账号交由上游校验
已知模型只路由到明确提供该模型的 Provider,账号不可用时不转发给其他平台的未知模型通道。
未知模型只在当前范围与路由约束下存在唯一 Provider 透传候选时发送;无法确定归属时返回不可用错误,
可通过 Client Key 分组限定目标平台。Provider 在选号时检查账号模型政策与目录资格,
@@ -774,7 +786,7 @@ OpenAI 聚合当前 Key 范围内合格 OAuth 和 API Key 账号的目录。每
后台刷新失败或超时保留该账号最后成功的结果。当前范围没有任何可用的已知目录时返回 `503 model_catalog_unavailable`。
成功读取但全部条目被账号政策过滤时返回空列表。
目录保留完整的原生 Codex 模型对象。对于 OpenAI API Key 普通模型列表和 xAI 目录生成的通用画像,
目录保留完整的原生 Codex 模型对象。对于 Provider 生成的通用画像,
当前 Key 可访问的适配器若声明了同名模型,其画像在原位置替换通用画像。仅由插件提供的可见模型按声明顺序追加到所属 Provider 的条目之后
服务启动时批量恢复账号目录;目录读取只检查本地账号资格和 Client Key 范围,不等待上游查询。
@@ -1867,7 +1879,7 @@ Google 授权后,将浏览器中的完整 `http://localhost:8085/auth/callback
Antigravity 主动额度刷新同时读取套餐与上游模型组额度,优先采用明确的付费套餐。`g1-pro-tier`、`g1-ultra-tier` 分别显示为 `Google AI Pro`、`Google AI Ultra`,缺少套餐不推断为免费账号
`quota.windows` 只保留上游模型组各自的 5 小时与周额度、已用百分比及重置时间,同组窗口共享 `limitId`。这些窗口的 `accountWide` 为 `false`,不能相加为整号余额,也不用于整号周/月容量预测;缺失的上游百分比保持未知。本地 24 小时请求统计通过账号 `usage` 单独返回,不生成上游额度窗口
`quota.windows` 返回上游模型组的 5 小时与周额度、已用百分比及重置时间,同组窗口共享 `limitId`,`accountWide` 为 `false`。缺失的上游百分比保持未知。网关从额度分组的成员名单与同次模型目录确定模型 ID,按各窗口重置时间与时长汇总本地请求的 `localUsage`。无匹配请求时总 Token 为 0,成员或窗口边界无法确认时 `localUsage` 为空。账号 `usage` 单独返回近一周的本地用量,分组窗口不参与整号周/月容量预测
OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上游请求总超时为 60 秒
@@ -2296,7 +2308,7 @@ xAI 由本地账号/模型冷却、无可选账号、并发容量不足及选号
默认队列满返回 `429` / `concurrency_queue_full`,排队超时返回 `429` / `concurrency_queue_timeout`;
WebSocket 使用对应错误事件。等待期间不发送上游请求,取消后释放等待位置,排队重查不重复计入 RPM。
SSE 在 Key 准入完成并取得执行会话前不发送保活帧,此阶段保留 HTTP 错误状态;
取得会话后的账号等待受 SSE 保活覆盖,已开始交付的失败沿用流内错误合同
Responses、Chat Completions 和 Messages 在取得会话后为账号等待发送心跳,已开始交付的失败沿用各入口的流内错误合同
任一周期的已落库金额与当前进程已接管的待结算费用合计达到限额后拒绝新请求,已准入请求可完成并使金额超过阈值。
HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly_budget_exceeded`,
+2 -1
View File
@@ -1088,7 +1088,8 @@ OpenAI、xAI、Antigravity 的认证及账号后台操作由各 Provider 通过
- Antigravity 使用 Google OAuth 离线授权,账号文件导出凭据、身份、有效期及已有观测,导入通过 refresh token 重新验证权限与主体,不采信文件中的历史观测。
OAuth 每轮操作从运行策略读取全局 AGY 选择,由 `profile` 统一解析并冻结出站身份,换码、刷新和身份查询使用同一画像,不读取 Key 覆盖。
`loadCodeAssist` 的付费套餐优先于基础套餐;分组额度和模型额度保存到同一带凭据版本的快照,独立模型耗尽不升级为整个账号耗尽。
原生额度窗口只投影上游模型分组,不归属整号 Token;Admin 按 Provider 声明独立读取部署时区今天及前 6 天的本地用量,展示为“近一周”,不向额度列表补入本地窗口。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
Provider 在额度观测中保存与同次模型目录核对的分组成员 ID。Admin 按模型和窗口边界汇总本地 Token,账号用量另按部署时区今天及前 6 天统计,展示为“近一周”。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
账号列表和展开的额度面板读取已保存的快照,点击“刷新额度”时立即查询上游。后台补齐启用账号缺失或凭据版本失效的快照。健康账号仅在距上次观测已满 5 分钟、且有生成请求在该次观测后成功完成时补查。整号耗尽按重置时间复查,缺少重置时间时在耗尽观测满 5 分钟后复查
正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试
- 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后,
由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。
@@ -246,8 +246,12 @@ export function quotaWindowDetails(window: AccountQuotaWindow) {
const localUsage = accountLocalUsage(window.localUsage)
const tokenDisplay = localTokenDisplay(localUsage) || null
const amountDisplay = window.amount?.usedDisplay ?? null
const hasConsumption = Boolean(tokenDisplay || amountDisplay)
|| (!window.amount && localUsage?.totalTokens == null)
const showZeroTokens = !window.amount && localUsage?.totalTokens === 0
const consumptionTokens = showZeroTokens ? '0' : tokenDisplay
const consumption = [
amountDisplay,
consumptionTokens && `${consumptionTokens} ${t('common.units.tokens')}`,
].filter(Boolean).join(' · ')
return {
stale: window.stale,
observationDisplay: [
@@ -263,14 +267,7 @@ export function quotaWindowDetails(window: AccountQuotaWindow) {
quotaValueDisplay: window.amount && window.usedPercent === null
? window.amount.totalDisplay
: window.usedPercentDisplay,
consumptionDisplay: hasConsumption
? [
amountDisplay,
tokenDisplay || (!window.amount && localUsage?.totalTokens == null
? '—'
: null),
].filter(Boolean).join(' · ')
: null,
consumptionDisplay: consumption || (window.amount ? null : '—'),
resetAtDisplay: window.amount && window.resetAtDisplay === '—'
? t('accounts.upstream.startsOnNextUse')
: window.resetAtDisplay,
@@ -10,7 +10,7 @@ export const usageDataColumns = computed(() => ([
key: 'model',
label: t('usage.fields.model'),
kind: 'custom',
size: 'xl',
size: '2xl',
},
{
key: 'reasoningEffort',
@@ -22,7 +22,7 @@ export const usageDataColumns = computed(() => ([
key: 'route',
label: t('usage.fields.endpoint'),
kind: 'mono',
minWidth: 224,
width: 208,
},
{
key: 'transport',
@@ -26,7 +26,7 @@ const modelUsageColumns = computed(() => (defineTableColumns<AccountModelUsage>(
key: 'model',
label: t('accounts.concurrency.model'),
kind: 'text',
size: 'md',
size: 'xl',
},
{
key: 'requestCountDisplay',
@@ -74,7 +74,8 @@ const modelUsageColumns = computed(() => (defineTableColumns<AccountModelUsage>(
key: 'lastUsedAt',
label: t('accounts.fields.lastUsed'),
kind: 'datetime',
size: 'md',
size: 'sm',
fixedWidth: true,
align: 'right',
},
])))
+9 -6
View File
@@ -1,18 +1,21 @@
# v3.55.2
# v3.55.3
## 新增功能
- Antigravity 账号支持近一周用量统计,按部署时区汇总当天及前六天
- Codex 模型选择器按基础模型展示 Antigravity 模型,可选择当前密钥有权使用的思考档位,并读取模型说明与上下文大小
- Responses 显式选择联网搜索时,使用账号授权的搜索模型;JSON 和流式响应均可返回来源链接与正文引用
## 优化改进
- 加宽隐私规则的处理方式列,便于查看多个独立步骤
- 展开账号额度面板直接读取已保存的数据;健康账号在成功生成后按需刷新,距上次刷新至少 5 分钟
- 加宽用量明细中的模型列,方便查看完整型号
## 问题修复
- 修复 AGY 原生请求使用基础模型名时提示模型不可用的问题,按思考档位匹配上游已声明的型号,并按实际型号校验账号权限
- 修复 Codex 开启可选网页搜索后,Gemini 编码请求因同时携带函数工具而返回 400 的问题
- Antigravity 按模型分组显示 5 小时和周额度窗口内的本地 Token 消耗,已知窗口内无用量时显示 0
- Gemini 原生流式响应在等待数据时保持静默,首帧前失败时保留 HTTP 错误状态
## 升级须知
- AGY 模型分组能力在升级并刷新账号模型目录后生效
- 旧 `anonymize_workspace` 组合动作已移除,相关隐私规则需在升级前改为项目名、用户名、Git 远端及提交信息的独立处理步骤
- 已有账号刷新模型目录后可使用专用联网搜索;下次刷新额度时会补齐上游可识别的窗口成员
+5 -5
View File
@@ -1,7 +1,7 @@
version: 3.55.2
version: 3.55.3
published:
'3':
stable: 3.55.1
rc: 3.55.1
beta: 3.55.1
alpha: 3.55.1
stable: 3.55.2
rc: 3.55.2
beta: 3.55.2
alpha: 3.55.2