Compare commits

...
16 Commits
Author SHA1 Message Date
ZyyandCodex 88da31137b fix(protocol): preserve semantics across provider translations
Centralize Responses web search selection across protocol and provider adapters. Map GenAI generation settings directly from Responses while sharing content, tool, and signature conversion.

Preserve translator error sources and cover request parameters, search selection, and failure propagation.

Validation: 292 scoped tests, cargo fmt, and scoped Clippy.

Co-authored-by: Codex <noreply@openai.com>
2026-11-26 14:21:29 +08:00
github-actions[bot] 3da3338908 chore(release): update release channels to 3.55.3 2026-11-26 06:01:30 +00:00
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
ZyyandCodex add1f9f40f chore: bump version to 3.55.2
Co-authored-by: Codex <noreply@openai.com>
2026-11-25 23:42:36 +08:00
ZyyandCodex 080d3867f1 fix(antigravity): resolve native model groups by thinking level
Resolve declared model groups to concrete variants before account and model-policy checks. Preserve explicit model IDs and native request bodies, and expose only accessible groups in the catalog.

Co-authored-by: Codex <noreply@openai.com>
2026-11-25 23:39:26 +08:00
ZyyandCodex 0bf3c8daaf feat(accounts): show recent week usage for Antigravity
Aggregate local usage over today and the previous six days in the deployment timezone. Keep the local usage period independent from grouped quota reset windows and preserve it when usage is empty.

Co-authored-by: Codex <noreply@openai.com>
2026-11-25 23:34:29 +08:00
ZyyandCodex 9d3d7ef223 refactor(privacy): remove combined workspace action
Use independent workspace privacy steps and widen the processing method column.

Co-authored-by: Codex <noreply@openai.com>
2026-11-25 22:43:44 +08:00
github-actions[bot] c843a4d380 chore(release): update release channels to 3.55.1 2026-11-25 14:21:08 +00:00
103 changed files with 3654 additions and 592 deletions
@@ -1,6 +1,9 @@
//! 多 Provider 账号目录与连接测试的公共事实 //! 多 Provider 账号目录与连接测试的公共事实
use std::{collections::BTreeMap, pin::Pin}; use std::{
collections::{BTreeMap, BTreeSet},
pin::Pin,
};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use futures::Stream; use futures::Stream;
@@ -192,6 +195,8 @@ pub struct AccountUsage {
/// `key` 只用于把聚合结果关联回调用方的窗口,不承载 Provider 私有语义 /// `key` 只用于把聚合结果关联回调用方的窗口,不承载 Provider 私有语义
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountUsageWindowQuery { pub struct AccountUsageWindowQuery {
/// 指定时只汇总这些上游模型的请求
pub models: Option<BTreeSet<String>>,
pub account_id: String, pub account_id: String,
pub key: String, pub key: String,
pub range: TimeRange, pub range: TimeRange,
@@ -1,6 +1,6 @@
//! Provider 管理能力交换的中立 Command 与 Result //! Provider 管理能力交换的中立 Command 与 Result
use std::{fmt, pin::Pin}; use std::{collections::BTreeSet, fmt, pin::Pin};
use async_trait::async_trait; use async_trait::async_trait;
use bytes::Bytes; use bytes::Bytes;
@@ -774,11 +774,13 @@ impl fmt::Debug for RotateCredential {
} }
/// 通用账号用量能否可靠归属到一个 Provider quota 窗口 /// 通用账号用量能否可靠归属到一个 Provider quota 窗口
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum QuotaLocalUsageAttribution { pub enum QuotaLocalUsageAttribution {
/// 窗口覆盖账号的全部请求,可按账号与时间范围聚合 /// 窗口覆盖账号的全部请求,可按账号与时间范围聚合
AccountWide, AccountWide,
/// 窗口需要 Provider / 模型级归属,通用账号聚合不可用 /// Provider 已确认该窗口覆盖的上游模型 ID
Models(BTreeSet<String>),
/// 缺少可用于归属本地用量的事实
Unavailable, Unavailable,
} }
@@ -828,12 +830,46 @@ impl ProviderQuotaWindow {
} }
} }
/// 账号用量统计周期,完整周/月额度优先,缺少可归属窗口时使用本地滚动日统计 /// 账号用量统计周期,区分上游额度周期与独立的本地统计范围
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum AccountUsagePeriod { pub enum AccountUsagePeriod {
Weekly, Weekly,
Monthly, Monthly,
Daily, Daily,
RecentWeek,
}
/// 缺少可归属整号的额度窗口时,Provider 选择的本地用量范围
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum AccountUsageLookback {
#[default]
RollingDay,
RecentWeek,
}
impl AccountUsageLookback {
pub(crate) fn range(
self,
now: DateTime<Utc>,
timezone: gateway_core::time::DeploymentTimeZone,
) -> Result<super::observability::TimeRange, super::AdminModelError> {
use super::observability::{CalendarPeriod, TimeRange};
match self {
Self::RollingDay => Ok(TimeRange {
start: now - chrono::Duration::hours(24),
end: now,
}),
Self::RecentWeek => TimeRange::calendar_at(CalendarPeriod::SevenDays, now, timezone),
}
}
pub(crate) fn period(self) -> AccountUsagePeriod {
match self {
Self::RollingDay => AccountUsagePeriod::Daily,
Self::RecentWeek => AccountUsagePeriod::RecentWeek,
}
}
} }
/// Provider 解释 quota 所需的公共请求事实 /// Provider 解释 quota 所需的公共请求事实
@@ -1152,7 +1188,7 @@ impl ProviderQuota {
fn quota_usage_priority(window: &ProviderQuotaWindow) -> (u8, u8) { fn quota_usage_priority(window: &ProviderQuotaWindow) -> (u8, u8) {
let attribution = match window.local_usage_attribution { let attribution = match window.local_usage_attribution {
QuotaLocalUsageAttribution::AccountWide => 0, QuotaLocalUsageAttribution::AccountWide => 0,
QuotaLocalUsageAttribution::Unavailable => 1, QuotaLocalUsageAttribution::Models(_) | QuotaLocalUsageAttribution::Unavailable => 1,
}; };
let duration = match window.group.as_str() { let duration = match window.group.as_str() {
"shortTerm" if window.window_seconds.is_some_and(is_week_window) => 1, "shortTerm" if window.window_seconds.is_some_and(is_week_window) => 1,
@@ -152,6 +152,11 @@ struct ProviderAdminDiagnostic {
/// 运行时资源通知只在事务成功后发生 /// 运行时资源通知只在事务成功后发生
#[async_trait] #[async_trait]
pub trait ProviderAdmin: Send + Sync { pub trait ProviderAdmin: Send + Sync {
/// 独立本地统计不借用模型分组额度的重置时间
fn account_usage_lookback(&self) -> crate::model::provider_credentials::AccountUsageLookback {
Default::default()
}
fn compile_privacy_policy( fn compile_privacy_policy(
&self, &self,
_policy: &gateway_core::settings::privacy::CodexPrivacyPolicy, _policy: &gateway_core::settings::privacy::CodexPrivacyPolicy,
@@ -8,7 +8,7 @@ use std::{
}; };
use async_trait::async_trait; use async_trait::async_trait;
use chrono::{Duration, Utc}; use chrono::Utc;
use futures::StreamExt as _; use futures::StreamExt as _;
use gateway_core::{ use gateway_core::{
account::ProviderAccountId, account::ProviderAccountId,
@@ -30,11 +30,11 @@ use crate::{
observability::TimeRange, observability::TimeRange,
provider_credentials::{ provider_credentials::{
AccountDirectoryItem, AccountDirectoryPage, AccountExportBundle, AccountPersonalInfo, AccountDirectoryItem, AccountDirectoryPage, AccountExportBundle, AccountPersonalInfo,
AccountRefreshResult, AccountUsagePeriod, ConsumeProviderResetCredit, AccountRefreshResult, AccountUsageLookback, AccountUsagePeriod,
PrepareCredentialRefresh, ProviderModelCatalogDocument, ProviderModels, ConsumeProviderResetCredit, PrepareCredentialRefresh, ProviderModelCatalogDocument,
ProviderProfileAvatar, ProviderQuota, ProviderQuotaReadRequest, ProviderQuotaRequest, ProviderModels, ProviderProfileAvatar, ProviderQuota, ProviderQuotaReadRequest,
ProviderQuotaWindow, ProviderResetCreditResult, ProviderResetCredits, ProviderQuotaRequest, ProviderQuotaWindow, ProviderResetCreditResult,
QuotaLocalUsageAttribution, ProviderResetCredits, QuotaLocalUsageAttribution,
}, },
quota_forecast::{ quota_forecast::{
AccountQuotaForecastReport, account_quota_forecasts, quota_forecast_source_window, AccountQuotaForecastReport, account_quota_forecasts, quota_forecast_source_window,
@@ -387,12 +387,11 @@ impl DefaultAccountsService {
for (item, quota) in accounts.iter().zip(quotas) { for (item, quota) in accounts.iter().zip(quotas) {
for window in &mut quota.windows { for window in &mut quota.windows {
if window.local_usage.is_none() 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()); window.local_usage = usage_by_window
if let Some(usage) = usage_by_window.get(&key) { .get(&(item.account.id.clone(), window.key.clone()))
window.local_usage = Some(usage.clone()); .cloned();
}
} }
} }
} }
@@ -426,6 +425,7 @@ impl DefaultAccountsService {
return None; return None;
} }
Some(AccountUsageWindowQuery { Some(AccountUsageWindowQuery {
models: None,
account_id: item.account.id.clone(), account_id: item.account.id.clone(),
key: "account-lifetime".to_owned(), key: "account-lifetime".to_owned(),
range: TimeRange { range: TimeRange {
@@ -457,10 +457,10 @@ impl DefaultAccountsService {
let (stored, provider) = self.provider_for_account(account_id).await?; let (stored, provider) = self.provider_for_account(account_id).await?;
let account = &stored.account; let account = &stored.account;
let now = Utc::now(); let now = Utc::now();
let rolling_range = TimeRange { let lookback = provider.account_usage_lookback();
start: now - Duration::hours(24), let rolling_range = lookback
end: now, .range(now, self.timezone)
}; .map_err(|_| AdminError::internal("时间超出支持范围"))?;
let ids = vec![account.id.clone()]; let ids = vec![account.id.clone()];
let rolling_usage = self let rolling_usage = self
.accounts .accounts
@@ -510,6 +510,7 @@ impl DefaultAccountsService {
&quota, &quota,
rolling_usage, rolling_usage,
api_key_usage, api_key_usage,
lookback,
); );
Ok(AccountDirectoryItem { Ok(AccountDirectoryItem {
protection_rules: stored.protection_rules, protection_rules: stored.protection_rules,
@@ -574,10 +575,6 @@ impl AccountsService for DefaultAccountsService {
.await .await
.map_err(|error| map_store_error(error, "account directory"))?; .map_err(|error| map_store_error(error, "account directory"))?;
let now = Utc::now(); let now = Utc::now();
let rolling_range = TimeRange {
start: now - Duration::hours(24),
end: now,
};
let ids = page let ids = page
.items .items
.iter() .iter()
@@ -595,15 +592,33 @@ impl AccountsService for DefaultAccountsService {
} }
} }
}; };
let rolling_usage = self let mut usage_groups = BTreeMap::<AccountUsageLookback, Vec<String>>::new();
.accounts for item in &page.items {
.load_account_usage(rolling_range, &ids) let lookback = providers
.await .require(&item.account.provider_kind)
.map_err(|error| map_store_error(error, "rolling account usage"))?; .map(|provider| provider.account_usage_lookback())
let mut rolling_usage = rolling_usage .unwrap_or_default();
.into_iter() usage_groups
.map(|usage| (usage.account_id.clone(), usage)) .entry(lookback)
.collect::<BTreeMap<_, _>>(); .or_default()
.push(item.account.id.clone());
}
let mut rolling_usage = BTreeMap::new();
for (lookback, ids) in usage_groups {
let range = lookback
.range(now, self.timezone)
.map_err(|_| AdminError::internal("时间超出支持范围"))?;
let usages = self
.accounts
.load_account_usage(range, &ids)
.await
.map_err(|error| map_store_error(error, "local account usage"))?;
rolling_usage.extend(
usages
.into_iter()
.map(|usage| (usage.account_id.clone(), usage)),
);
}
let mut quotas = self.read_quotas(&page.items, &rolling_usage).await; let mut quotas = self.read_quotas(&page.items, &rolling_usage).await;
self.attach_quota_local_usage(&page.items, &mut quotas) self.attach_quota_local_usage(&page.items, &mut quotas)
.await?; .await?;
@@ -615,10 +630,13 @@ impl AccountsService for DefaultAccountsService {
.map(|(mut item, quota)| { .map(|(mut item, quota)| {
let id = ProviderAccountId::new(item.account.id.clone()) let id = ProviderAccountId::new(item.account.id.clone())
.map_err(|_| AdminError::invalid("服务商账号 ID 不合法"))?; .map_err(|_| AdminError::invalid("服务商账号 ID 不合法"))?;
let capabilities = providers let (capabilities, lookback) = providers
.require(&item.account.provider_kind) .require(&item.account.provider_kind)
.map(|provider| { .map(|provider| {
provider.account_capabilities(&id, &item.account.authentication_kind) (
provider.account_capabilities(&id, &item.account.authentication_kind),
provider.account_usage_lookback(),
)
}) })
.unwrap_or_default(); .unwrap_or_default();
let (usage, usage_period) = resolve_account_usage( let (usage, usage_period) = resolve_account_usage(
@@ -626,6 +644,7 @@ impl AccountsService for DefaultAccountsService {
&quota, &quota,
rolling_usage.remove(&item.account.id), rolling_usage.remove(&item.account.id),
api_key_usage.remove(&item.account.id), api_key_usage.remove(&item.account.id),
lookback,
); );
Ok(AccountDirectoryItem { Ok(AccountDirectoryItem {
protection_rules: item.protection_rules, protection_rules: item.protection_rules,
@@ -1348,6 +1367,7 @@ fn resolve_account_usage(
quota: &ProviderQuota, quota: &ProviderQuota,
rolling_usage: Option<AccountUsage>, rolling_usage: Option<AccountUsage>,
api_key_usage: Option<AccountUsage>, api_key_usage: Option<AccountUsage>,
lookback: AccountUsageLookback,
) -> (Option<AccountUsage>, Option<AccountUsagePeriod>) { ) -> (Option<AccountUsage>, Option<AccountUsagePeriod>) {
if authentication_kind == "api_key" { if authentication_kind == "api_key" {
return (api_key_usage, None); return (api_key_usage, None);
@@ -1356,7 +1376,7 @@ fn resolve_account_usage(
return (window.local_usage.clone(), Some(period)); return (window.local_usage.clone(), Some(period));
} }
// 模型分组额度无法归属整号用量,本地统计独立回退,不能为此合成上游额度桶 // 模型分组额度无法归属整号用量,本地统计独立回退,不能为此合成上游额度桶
(rolling_usage, Some(AccountUsagePeriod::Daily)) (rolling_usage, Some(lookback.period()))
} }
fn map_reset_credits_error_after_refresh( fn map_reset_credits_error_after_refresh(
@@ -1377,13 +1397,16 @@ fn quota_usage_window(
account_id: &str, account_id: &str,
window: &ProviderQuotaWindow, window: &ProviderQuotaWindow,
) -> Option<AccountUsageWindowQuery> { ) -> Option<AccountUsageWindowQuery> {
if window.local_usage_attribution != QuotaLocalUsageAttribution::AccountWide { let models = match &window.local_usage_attribution {
return None; QuotaLocalUsageAttribution::AccountWide => None,
} QuotaLocalUsageAttribution::Models(ids) => Some(ids.clone()),
QuotaLocalUsageAttribution::Unavailable => return None,
};
let (start, reset_at) = window.observed_bounds()?; let (start, reset_at) = window.observed_bounds()?;
let range = TimeRange::new(start, reset_at).ok()?; let range = TimeRange::new(start, reset_at).ok()?;
// 上游百分比以该 reset 边界定义;以当前时间回推会让本地 Token 属于另一窗口 // 上游百分比以该 reset 边界定义;以当前时间回推会让本地 Token 属于另一窗口
Some(AccountUsageWindowQuery { Some(AccountUsageWindowQuery {
models,
account_id: account_id.to_owned(), account_id: account_id.to_owned(),
key: window.key.clone(), key: window.key.clone(),
range, range,
@@ -74,6 +74,7 @@ pub(super) type EventLog = Arc<Mutex<Vec<&'static str>>>;
pub(super) struct FakeProviderAdmin { pub(super) struct FakeProviderAdmin {
kind: ProviderKind, kind: ProviderKind,
usage_lookback: Mutex<gateway_admin::model::provider_credentials::AccountUsageLookback>,
capabilities: Mutex<gateway_admin::model::accounts::ProviderAccountCapabilities>, capabilities: Mutex<gateway_admin::model::accounts::ProviderAccountCapabilities>,
events: EventLog, events: EventLog,
failure: Mutex<Option<ProviderAdminError>>, failure: Mutex<Option<ProviderAdminError>>,
@@ -104,6 +105,7 @@ impl FakeProviderAdmin {
pub(super) fn new(kind: &str, events: EventLog) -> Arc<Self> { pub(super) fn new(kind: &str, events: EventLog) -> Arc<Self> {
Arc::new(Self { Arc::new(Self {
kind: ProviderKind::new(kind).expect("provider kind"), kind: ProviderKind::new(kind).expect("provider kind"),
usage_lookback: Mutex::default(),
capabilities: Mutex::default(), capabilities: Mutex::default(),
events, events,
failure: Mutex::new(None), failure: Mutex::new(None),
@@ -281,6 +283,12 @@ impl FakeProviderAdmin {
#[async_trait] #[async_trait]
impl ProviderAdmin for FakeProviderAdmin { impl ProviderAdmin for FakeProviderAdmin {
fn account_usage_lookback(
&self,
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
*self.usage_lookback.lock().unwrap()
}
fn peer_authentication_kinds(&self) -> &[&str] { fn peer_authentication_kinds(&self) -> &[&str] {
&["api_key"] &["api_key"]
} }
@@ -618,6 +626,7 @@ pub(super) struct FakeAccountStore {
import_settings: Mutex<Vec<Option<gateway_admin::model::accounts::AccountImportSettings>>>, import_settings: Mutex<Vec<Option<gateway_admin::model::accounts::AccountImportSettings>>>,
quota_window_usage: Mutex<Vec<AccountUsageWindowResult>>, quota_window_usage: Mutex<Vec<AccountUsageWindowResult>>,
rolling_usage: Mutex<Vec<AccountUsage>>, rolling_usage: Mutex<Vec<AccountUsage>>,
usage_queries: Mutex<Vec<(TimeRange, Vec<String>)>>,
quota_window_queries: Mutex<Vec<AccountUsageWindowQuery>>, quota_window_queries: Mutex<Vec<AccountUsageWindowQuery>>,
quota_forecast_history: Mutex<QuotaForecastHistory>, quota_forecast_history: Mutex<QuotaForecastHistory>,
update_commands: Mutex<Vec<UpdateAccount>>, update_commands: Mutex<Vec<UpdateAccount>>,
@@ -642,6 +651,7 @@ impl FakeAccountStore {
import_settings: Mutex::new(Vec::new()), import_settings: Mutex::new(Vec::new()),
quota_window_usage: Mutex::new(Vec::new()), quota_window_usage: Mutex::new(Vec::new()),
rolling_usage: Mutex::new(Vec::new()), rolling_usage: Mutex::new(Vec::new()),
usage_queries: Mutex::default(),
quota_window_queries: Mutex::new(Vec::new()), quota_window_queries: Mutex::new(Vec::new()),
quota_forecast_history: Mutex::new(QuotaForecastHistory::default()), quota_forecast_history: Mutex::new(QuotaForecastHistory::default()),
update_commands: Mutex::new(Vec::new()), update_commands: Mutex::new(Vec::new()),
@@ -827,10 +837,21 @@ impl AccountStore for FakeAccountStore {
async fn load_account_usage( async fn load_account_usage(
&self, &self,
_: TimeRange, range: TimeRange,
_: &[String], ids: &[String],
) -> AdminStoreResult<Vec<AccountUsage>> { ) -> AdminStoreResult<Vec<AccountUsage>> {
Ok(self.rolling_usage.lock().unwrap().clone()) self.usage_queries
.lock()
.unwrap()
.push((range, ids.to_vec()));
Ok(self
.rolling_usage
.lock()
.unwrap()
.iter()
.filter(|usage| ids.contains(&usage.account_id))
.cloned()
.collect())
} }
async fn load_account_usage_by_windows( async fn load_account_usage_by_windows(
@@ -3001,14 +3022,25 @@ async fn api_key_list_and_detail_should_accumulate_local_usage_without_subscript
} }
#[tokio::test] #[tokio::test]
async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas() { async fn accounts_list_and_detail_keep_recent_week_usage_separate_from_group_quotas() {
use gateway_admin::model::provider_credentials::AccountUsagePeriod; use gateway_admin::model::provider_credentials::{AccountUsageLookback, AccountUsagePeriod};
let provider = FakeProviderAdmin::new("antigravity", events()); let provider = FakeProviderAdmin::new("antigravity", events());
*provider.usage_lookback.lock().unwrap() = AccountUsageLookback::RecentWeek;
let store = FakeAccountStore::new("antigravity", events()); let store = FakeAccountStore::new("antigravity", events());
let expected_usage = quota_local_usage("acct_test", 139); let expected_usage = quota_local_usage("acct_test", 139);
*store.rolling_usage.lock().unwrap() = vec![expected_usage.clone()]; let mut daily_account = account_record("xai");
let services = accounts_service(provider.clone(), store.clone()).await; daily_account.id = "acct_daily".to_owned();
store.accounts.lock().unwrap().push(daily_account);
let daily_usage = quota_local_usage("acct_daily", 23);
*store.rolling_usage.lock().unwrap() = vec![expected_usage.clone(), daily_usage.clone()];
let services = super::AdminHarness::new()
.accounts(store.clone())
.settings(Arc::new(StaticSettingsStore::default()))
.provider(provider.clone())
.provider(FakeProviderAdmin::new("xai", events()))
.build()
.await;
let grouped_window = ProviderQuotaWindow { let grouped_window = ProviderQuotaWindow {
upstream: None, upstream: None,
key: "gemini-weekly".to_owned(), key: "gemini-weekly".to_owned(),
@@ -3048,12 +3080,38 @@ async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas(
.quota(&ProviderAccountId::new("acct_test").unwrap(), false) .quota(&ProviderAccountId::new("acct_test").unwrap(), false)
.await .await
.unwrap(); .unwrap();
for item in [&page.items[0], &detail] { let refreshed = services
.accounts()
.quota(&ProviderAccountId::new("acct_test").unwrap(), true)
.await
.unwrap();
for item in [&page.items[0], &detail, &refreshed] {
assert_eq!(item.quota.windows, windows); assert_eq!(item.quota.windows, windows);
assert_eq!(item.usage.as_ref(), Some(&expected_usage)); assert_eq!(item.usage.as_ref(), Some(&expected_usage));
assert_eq!(item.usage_period, Some(AccountUsagePeriod::Daily)); assert_eq!(item.usage_period, Some(AccountUsagePeriod::RecentWeek));
} }
assert!(store.quota_window_queries().is_empty()); assert!(store.quota_window_queries().is_empty());
let daily = page
.items
.iter()
.find(|item| item.account.id == "acct_daily")
.unwrap();
assert_eq!(daily.usage.as_ref(), Some(&daily_usage));
assert_eq!(daily.usage_period, Some(AccountUsagePeriod::Daily));
let queries = std::mem::take(&mut *store.usage_queries.lock().unwrap());
assert_eq!(queries.len(), 4);
assert_eq!(queries[0].0.end, queries[1].0.end);
for (range, ids) in queries {
if ids == ["acct_daily"] {
assert_eq!(range.end - range.start, TimeDelta::hours(24));
continue;
}
assert_eq!(ids, ["acct_test"]);
let timezone = gateway_core::time::DeploymentTimeZone::default();
assert_eq!(range.start, timezone.days_before(range.end, 6).unwrap());
assert!(range.end - range.start >= TimeDelta::days(6));
assert!(range.end - range.start < TimeDelta::days(7));
}
} }
} }
@@ -3223,10 +3281,10 @@ async fn accounts_list_and_quota_refresh_should_select_the_same_weekly_or_monthl
} }
#[tokio::test] #[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 provider = FakeProviderAdmin::new("openai", events());
let reset_at = Utc::now() + TimeDelta::days(7); let reset_at = Utc::now() + TimeDelta::days(7);
provider.set_quota(ProviderQuota { let mut quota = ProviderQuota {
paused_windows: Vec::new(), paused_windows: Vec::new(),
upstream: None, upstream: None,
credits: None, credits: None,
@@ -3269,7 +3327,13 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
], ],
limit_reached: false, limit_reached: false,
provider_data: None, 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()); let store = FakeAccountStore::new("openai", events());
store.set_quota_window_usage(vec![ store.set_quota_window_usage(vec![
AccountUsageWindowResult { AccountUsageWindowResult {
@@ -3282,9 +3346,14 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
key: "codex-bengalfox-primary".to_owned(), key: "codex-bengalfox-primary".to_owned(),
usage: quota_local_usage("acct_test", 127_926), 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 .await
.accounts() .accounts()
.list(AccountListQuery { .list(AccountListQuery {
@@ -3318,6 +3387,7 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
[ [
("core-primary", Some(12_818_806)), ("core-primary", Some(12_818_806)),
("codex-bengalfox-primary", None), ("codex-bengalfox-primary", None),
("known-group", Some(85)),
], ],
); );
assert_eq!( assert_eq!(
@@ -3327,6 +3397,10 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
.and_then(|usage| usage.total_tokens), .and_then(|usage| usage.total_tokens),
Some(12_818_806), 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] #[tokio::test]
@@ -191,6 +191,7 @@ fn quota_forecast_view(
AccountUsagePeriod::Weekly => "weekly", AccountUsagePeriod::Weekly => "weekly",
AccountUsagePeriod::Monthly => "monthly", AccountUsagePeriod::Monthly => "monthly",
AccountUsagePeriod::Daily => "daily", AccountUsagePeriod::Daily => "daily",
AccountUsagePeriod::RecentWeek => "recent_week",
}, },
target_days: forecast.target_seconds as f64 / 86_400.0, target_days: forecast.target_seconds as f64 / 86_400.0,
extrapolated: forecast.extrapolated, extrapolated: forecast.extrapolated,
@@ -374,8 +375,18 @@ pub(super) fn account_usage_view(
now: DateTime<Utc>, now: DateTime<Utc>,
time: crate::time::TimePresenter, time: crate::time::TimePresenter,
) -> AccountUsageView { ) -> AccountUsageView {
let window_kind = match period {
Some(AccountUsagePeriod::Daily) => AccountUsageWindowKind::Daily,
Some(AccountUsagePeriod::RecentWeek) => AccountUsageWindowKind::RecentWeek,
Some(AccountUsagePeriod::Weekly) => AccountUsageWindowKind::Weekly,
Some(AccountUsagePeriod::Monthly) => AccountUsageWindowKind::Monthly,
None => AccountUsageWindowKind::Quota,
};
let Some(usage) = usage else { let Some(usage) = usage else {
return empty_account_usage(); return AccountUsageView {
window_kind,
..empty_account_usage()
};
}; };
let known_count = usage let known_count = usage
.cost_coverage .cost_coverage
@@ -389,12 +400,7 @@ pub(super) fn account_usage_view(
"known" "known"
}; };
AccountUsageView { AccountUsageView {
window_kind: match period { window_kind,
Some(AccountUsagePeriod::Daily) => AccountUsageWindowKind::Daily,
Some(AccountUsagePeriod::Weekly) => AccountUsageWindowKind::Weekly,
Some(AccountUsagePeriod::Monthly) => AccountUsageWindowKind::Monthly,
None => AccountUsageWindowKind::Quota,
},
request_count: Some(usage.request_count), request_count: Some(usage.request_count),
request_count_display: format_number(usage.request_count), request_count_display: format_number(usage.request_count),
input_tokens: usage.input_tokens, input_tokens: usage.input_tokens,
@@ -437,6 +437,7 @@ pub struct AccountQuotaWindowView {
pub enum AccountUsageWindowKind { pub enum AccountUsageWindowKind {
General, General,
Daily, Daily,
RecentWeek,
Weekly, Weekly,
Monthly, Monthly,
Quota, Quota,
@@ -76,6 +76,19 @@ pub(crate) struct HttpResponseAdapter {
pub stream_error: fn(&Value) -> Bytes, 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( pub(crate) async fn execute_prepared_generation(
service: DataPlaneService, service: DataPlaneService,
prepared: PreparedRootExecution, prepared: PreparedRootExecution,
@@ -106,7 +119,11 @@ pub(crate) async fn execute_prepared_generation(
let terminal_entered = Arc::clone(&execution_entered); let terminal_entered = Arc::clone(&execution_entered);
let started_request_id = Arc::new(OnceLock::new()); let started_request_id = Arc::new(OnceLock::new());
let terminal_request_id = Arc::clone(&started_request_id); 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(); let mut middleware_headers = headers.clone();
// 中间件正文已经由入口按上限解压;传输编码和旧长度不能与改写后的正文混用 // 中间件正文已经由入口按上限解压;传输编码和旧长度不能与改写后的正文混用
middleware_headers.remove(CONTENT_ENCODING); middleware_headers.remove(CONTENT_ENCODING);
@@ -183,7 +200,9 @@ pub(crate) async fn execute_prepared_generation(
.session .session
.trace() .trace()
.capture("client.request.body", &request_body); .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( execution_middleware_response(
started, started,
connection_guard, connection_guard,
@@ -203,11 +222,6 @@ pub(crate) async fn execute_prepared_generation(
} else { } else {
middleware.await middleware.await
}; };
let expected = if stream {
ExpectedBody::Sse
} else {
ExpectedBody::SingleJson
};
match middleware { match middleware {
Ok(response) => { Ok(response) => {
let response = if let Some(authorization) = authorization { let response = if let Some(authorization) = authorization {
@@ -226,7 +240,7 @@ pub(crate) async fn execute_prepared_generation(
Err(error) => error_response(error), Err(error) => error_response(error),
} }
}; };
let response = if stream { let response = if let Some(keepalive) = keepalive {
super::keepalive::response_with_encoder( super::keepalive::response_with_encoder(
response, response,
keepalive, keepalive,
@@ -507,7 +521,12 @@ pub async fn stream_execution_response(
.await .await
{ {
Ok(response) => { 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), Err(error) => error_response(error),
} }
@@ -62,10 +62,14 @@ impl MiddlewareBody for BufferedBody {
pub(crate) enum ExpectedBody { pub(crate) enum ExpectedBody {
SingleJson, SingleJson,
SinglePayload, SinglePayload,
Sse, Sse { keep_alive: bool },
} }
impl ExpectedBody { impl ExpectedBody {
pub(crate) fn sends_keepalive(self) -> bool {
matches!(self, Self::Sse { keep_alive: true })
}
fn validate(self, frame: &MiddlewareFrame) -> Result<(), MiddlewareError> { fn validate(self, frame: &MiddlewareFrame) -> Result<(), MiddlewareError> {
let valid = match self { let valid = match self {
Self::SingleJson => { Self::SingleJson => {
@@ -80,7 +84,7 @@ impl ExpectedBody {
|| Self::SingleJson.validate(frame).is_ok()) || Self::SingleJson.validate(frame).is_ok())
} }
// 原生超大 SSE 帧允许按原字节片段交付;插件写入边界由 Runtime 校验 // 原生超大 SSE 帧允许按原字节片段交付;插件写入边界由 Runtime 校验
Self::Sse => frame.framing() == MiddlewareFraming::SseEvent, Self::Sse { .. } => frame.framing() == MiddlewareFraming::SseEvent,
}; };
if valid { if valid {
Ok(()) 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( headers.insert(
header::CACHE_CONTROL, header::CACHE_CONTROL,
HeaderValue::from_static("no-cache, no-transform"), HeaderValue::from_static("no-cache, no-transform"),
); );
headers.insert("x-accel-buffering", HeaderValue::from_static("no")); headers.insert("x-accel-buffering", HeaderValue::from_static("no"));
} }
let exhausted = empty || !matches!(expected, ExpectedBody::Sse); let exhausted = empty || !streaming;
if !empty && exhausted { if !empty && exhausted {
match body.next_frame().await { match body.next_frame().await {
Ok(None) => {} Ok(None) => {}
@@ -158,20 +163,24 @@ pub(crate) async fn into_http_response(
exhausted, exhausted,
terminal_seen: empty, terminal_seen: empty,
}; };
let keep_alive = matches!(expected, ExpectedBody::Sse); let stream = futures::stream::try_unfold(delivery, HttpDelivery::next);
let stream = Box::pin(futures::stream::try_unfold(delivery, HttpDelivery::next)); let body = if expected.sends_keepalive() {
// 固定同一条输出流;心跳不能取消并重建正在等待的 next_frame 或结算 future // 固定同一条输出流,发送心跳时继续等待原有的读帧或结算操作
let stream = futures::stream::unfold(stream, move |mut stream| async move { Body::from_stream(futures::stream::unfold(
let chunk = tokio::select! { Box::pin(stream),
biased; |mut stream| async move {
chunk = stream.next() => chunk?, let chunk = tokio::select! {
() = tokio::time::sleep(SSE_KEEPALIVE_INTERVAL), if keep_alive => { biased;
Ok(SSE_KEEPALIVE_FRAME) chunk = stream.next() => chunk?,
} () = tokio::time::sleep(SSE_KEEPALIVE_INTERVAL) => Ok(SSE_KEEPALIVE_FRAME),
}; };
Some((chunk, stream)) Some((chunk, stream))
}); },
let mut response = Response::new(Body::from_stream(stream)); ))
} else {
Body::from_stream(stream)
};
let mut response = Response::new(body);
*response.status_mut() = status; *response.status_mut() = status;
*response.headers_mut() = headers; *response.headers_mut() = headers;
response response
@@ -475,17 +475,17 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
last_error_reason: None, last_error_reason: None,
last_error_message: None, last_error_message: None,
}; };
for (authentication_kind, read, write) in [ for (provider_kind, authentication_kind, window_kind, read, write) in [
("api_key", Some(13), Some(7)), ("openai", "api_key", "general", Some(13), Some(7)),
("api_key", None, None), ("openai", "api_key", "general", None, None),
("oauth", Some(13), Some(7)), ("xai", "oauth", "daily", Some(13), Some(7)),
("oauth", None, None), ("xai", "oauth", "daily", None, None),
("antigravity", "oauth", "recent_week", Some(13), Some(7)),
("antigravity", "oauth", "recent_week", None, None),
] { ] {
let mut account = account_page_item(facts.clone(), now, authentication_kind); let mut account = account_page_item(facts.clone(), now, authentication_kind);
if authentication_kind == "oauth" { account.account.provider_kind =
account.account.provider_kind = gateway_core::routing::ProviderKind::new(provider_kind).unwrap();
gateway_core::routing::ProviderKind::new("xai").unwrap();
}
*fixture.account.lock().unwrap() = Some(account); *fixture.account.lock().unwrap() = Some(account);
let local_usage = AccountUsage { let local_usage = AccountUsage {
account_id: "acct_cooldown".to_owned(), account_id: "acct_cooldown".to_owned(),
@@ -576,14 +576,7 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
let value: serde_json::Value = serde_json::from_slice(&body).unwrap(); let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(status, StatusCode::OK, "{value}"); assert_eq!(status, StatusCode::OK, "{value}");
let usage = &value["data"]["items"][0]["usage"]; let usage = &value["data"]["items"][0]["usage"];
assert_eq!( assert_eq!(usage["windowKind"], window_kind);
usage["windowKind"],
if authentication_kind == "oauth" {
"daily"
} else {
"general"
}
);
assert_eq!(usage["models"][0]["successRateDisplay"], "33.3%"); assert_eq!(usage["models"][0]["successRateDisplay"], "33.3%");
assert!((usage["models"][0]["successRate"].as_f64().unwrap() - 100.0 / 3.0).abs() < 0.001); assert!((usage["models"][0]["successRate"].as_f64().unwrap() - 100.0 / 3.0).abs() < 0.001);
assert_eq!(usage["models"][1]["successRate"], 0.0); assert_eq!(usage["models"][1]["successRate"], 0.0);
@@ -608,6 +601,26 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
usage["cacheWriteInputTokensDisplay"], usage["cacheWriteInputTokensDisplay"],
if write.is_some() { "7" } else { "—" } if write.is_some() { "7" } else { "—" }
); );
fixture.account_usage.lock().unwrap().clear();
let response = admin::accounts::router::<AdminTestState>()
.with_state(fixture.state())
.oneshot(
Request::builder()
.uri("/api/admin/accounts")
.header("x-request-id", "req_empty_account_usage_contract")
.header(header::COOKIE, "cpr_session=valid-session")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), 32768).await.unwrap();
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
let usage = &value["data"]["items"][0]["usage"];
assert_eq!(usage["windowKind"], window_kind);
assert!(usage["totalTokens"].is_null());
assert_eq!(usage["models"], serde_json::json!([]));
} }
} }
@@ -200,6 +200,13 @@ impl AdminTestFixture {
let provider_quota_gate = Arc::new(Mutex::new(None)); let provider_quota_gate = Arc::new(Mutex::new(None));
let provider_models = Arc::new(Mutex::new(None)); let provider_models = Arc::new(Mutex::new(None));
let providers: Vec<Arc<dyn ProviderAdmin>> = vec![ let providers: Vec<Arc<dyn ProviderAdmin>> = vec![
Arc::new(UnusedProvider::new(
"antigravity",
Arc::clone(&provider_error),
Arc::clone(&provider_quota),
Arc::clone(&provider_quota_gate),
Arc::clone(&provider_models),
)),
Arc::new(UnusedProvider::new( Arc::new(UnusedProvider::new(
"openai", "openai",
Arc::clone(&provider_error), Arc::clone(&provider_error),
@@ -1735,6 +1742,16 @@ impl UnusedProvider {
#[async_trait] #[async_trait]
impl ProviderAdmin for UnusedProvider { impl ProviderAdmin for UnusedProvider {
fn account_usage_lookback(
&self,
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
use gateway_admin::model::provider_credentials::AccountUsageLookback;
match self.kind.as_str() {
"antigravity" => AccountUsageLookback::RecentWeek,
_ => AccountUsageLookback::RollingDay,
}
}
fn account_capabilities( fn account_capabilities(
&self, &self,
_: &ProviderAccountId, _: &ProviderAccountId,
@@ -477,7 +477,7 @@ async fn finalization_failure_never_leaks_success_finish_or_usage() {
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
async fn error_after_admission_keepalive_uses_chat_error_encoding() { async fn error_after_admission_keepalive_uses_chat_error_encoding() {
let mut session = Session::new(Vec::new()); 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; session.finish = Finish::Error;
let fixture = Fixture::new(session).await; let fixture = Fixture::new(session).await;
let response = fixture.post(chat_request(true)).await; let response = fixture.post(chat_request(true)).await;
@@ -2,6 +2,7 @@
use super::*; use super::*;
use base64::{Engine as _, engine::general_purpose::STANDARD}; use base64::{Engine as _, engine::general_purpose::STANDARD};
use std::time::Duration;
#[tokio::test] #[tokio::test]
async fn session_headers_reach_provider_context_except_when_declared_hop_by_hop() { 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] #[tokio::test(start_paused = true)]
async fn stream_preserves_finish_and_later_usage_bytes_before_eof() { 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 first = "data: { \"candidates\":[{\"finishReason\":\"STOP\"}], \"error\":null }\r\n\r\n";
let last = "data: {\"usageMetadata\":{\"totalTokenCount\":7}}\r\n\r\n"; let last = "data: {\"usageMetadata\":{\"totalTokenCount\":7}}\r\n\r\n";
let mut events = vec![wire_frame(first), wire_frame(last)]; let mut events = vec![wire_frame(first), wire_frame(last)];
events.push(ProviderEvent::canonical(GatewayEvent::Completed( events.push(ProviderEvent::canonical(GatewayEvent::Completed(
ResponseMeta::new("id", "model-a"), 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 trace = session.trace.clone();
let execution = Arc::new(Execution { let execution = Arc::new(Execution {
session: Mutex::new(Some(session)), 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)); 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] #[tokio::test]
async fn metric_validates_bearer_and_invalid_generation_never_starts_inference() { async fn metric_validates_bearer_and_invalid_generation_never_starts_inference() {
let execution = Arc::new(Execution::default()); let execution = Arc::new(Execution::default());
@@ -39,7 +39,7 @@ pub(crate) struct Session {
events: VecDeque<Vec<ProviderEvent>>, events: VecDeque<Vec<ProviderEvent>>,
pub trace: Arc<Trace>, pub trace: Arc<Trace>,
pub finish: Finish, pub finish: Finish,
pub delay: Option<Duration>, pub read_delay: Option<Duration>,
pub fail_commit: bool, pub fail_commit: bool,
pub response_headers: Vec<ProviderResponseHeader>, pub response_headers: Vec<ProviderResponseHeader>,
committed: bool, committed: bool,
@@ -52,7 +52,7 @@ impl Session {
events: events.into_iter().map(|event| vec![event]).collect(), events: events.into_iter().map(|event| vec![event]).collect(),
trace: Arc::default(), trace: Arc::default(),
finish: Finish::Success, finish: Finish::Success,
delay: None, read_delay: None,
fail_commit: false, fail_commit: false,
response_headers: Vec::new(), response_headers: Vec::new(),
committed: false, committed: false,
@@ -73,7 +73,7 @@ impl ExecutionSession for Session {
fn next_event(&mut self) -> BoxFuture<'_, Result<Option<CoordinatedEvent>, EngineError>> { fn next_event(&mut self) -> BoxFuture<'_, Result<Option<CoordinatedEvent>, EngineError>> {
Box::pin(async move { Box::pin(async move {
if let Some(delay) = self.delay.take() { if let Some(delay) = self.read_delay {
tokio::time::sleep(delay).await; tokio::time::sleep(delay).await;
} }
if let Some(event) = self.events.pop_front() { if let Some(event) = self.events.pop_front() {
@@ -424,12 +424,17 @@ impl FrozenAccountScope {
#[must_use] #[must_use]
pub fn excluding_account(&self, account: ProviderAccountId) -> Self { pub fn excluding_account(&self, account: ProviderAccountId) -> Self {
let mut restricted = self.clone(); let mut restricted = self.clone();
let mut excluded = self.excluded_account_ids.as_ref().clone(); restricted.exclude_accounts([account]);
excluded.insert(account);
restricted.excluded_account_ids = Arc::new(excluded);
restricted 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] #[must_use]
pub fn allows(&self, account_id: &ProviderAccountId) -> bool { pub fn allows(&self, account_id: &ProviderAccountId) -> bool {
self.allows_with_policy(account_id, |_| true) 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)) 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] #[must_use]
pub fn groups_deny_model(&self, upstream_model: Option<&str>) -> bool { pub fn groups_deny_model(&self, upstream_model: Option<&str>) -> bool {
@@ -160,6 +160,14 @@ pub trait ProviderAccountStore: Send + Sync {
.collect()) .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( async fn compare_and_swap_quota(
&self, &self,
observation: QuotaObservation, observation: QuotaObservation,
@@ -24,6 +24,14 @@ pub(super) fn authentication_gateway_error(error: ClientAuthenticationError) ->
pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError { pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError {
match error { 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.",
),
crate::validation::RoutingError::GroupModelDenied => GatewayError::new( crate::validation::RoutingError::GroupModelDenied => GatewayError::new(
GatewayErrorKind::PolicyDenied, GatewayErrorKind::PolicyDenied,
crate::validation::GROUP_MODEL_DENIED_MESSAGE, crate::validation::GROUP_MODEL_DENIED_MESSAGE,
@@ -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 的统一返回值 /// Metadata、canonical event stream 与 owned lease 的统一返回值
/// ///
+17 -1
View File
@@ -542,6 +542,7 @@ struct ProviderErrorUpstreamValues {
#[derive(Clone, Default)] #[derive(Clone, Default)]
struct ProviderErrorFailureObservation { struct ProviderErrorFailureObservation {
invalid_request_message: Option<&'static str>,
unreachable_proxy: Option<crate::upstream::ProxyEndpoint>, unreachable_proxy: Option<crate::upstream::ProxyEndpoint>,
continuation_unavailable_reason: Option<&'static str>, continuation_unavailable_reason: Option<&'static str>,
connection: Option<ProviderConnectionObservation>, 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 { pub(crate) fn group_feature_denied(feature: DeniedGroupFeature) -> Self {
let mut error = Self::new( let mut error = Self::new(
ProviderErrorKind::RequestPolicyDenied, ProviderErrorKind::RequestPolicyDenied,
@@ -1362,7 +1374,11 @@ impl GatewayError {
} }
ProviderErrorKind::InvalidRequest => Self::new( ProviderErrorKind::InvalidRequest => Self::new(
GatewayErrorKind::InvalidRequest, 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( ProviderErrorKind::SessionPolicyRestricted => Self::new(
GatewayErrorKind::InvalidRequest, GatewayErrorKind::InvalidRequest,
@@ -920,6 +920,50 @@ pub enum Operation {
} }
impl Operation { impl Operation {
pub(crate) fn requires_native_protocol(&self) -> bool {
match self {
Self::Generate(request) => request.requires_native_protocol(),
Self::CountTokens(request) => request.requires_native_protocol(),
_ => false,
}
}
/// 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 {
Self::Generate(request) => {
let payload = request.protocol_payload();
gateway_protocol::request::request_observation(
payload.protocol(),
payload.body(),
payload.context(),
None,
)
}
Self::CountTokens(request) => {
let payload = request.payload();
let body = serde_json::from_slice::<Map<String, Value>>(payload.body()).ok()?;
gateway_protocol::request::token_count_observation(
payload.protocol(),
&body,
payload.context(),
)
}
_ => return None,
};
observation.reasoning_effort
}
pub(crate) fn with_inherited_capability_requirements( pub(crate) fn with_inherited_capability_requirements(
self, self,
inherited: CapabilityRequirements, inherited: CapabilityRequirements,
@@ -12,6 +12,55 @@ use super::{
ModelCapabilities, ModelPresentation, PublicModelId, PublicModelProfile, UpstreamModelId, ModelCapabilities, ModelPresentation, PublicModelId, PublicModelProfile, UpstreamModelId,
}; };
/// Provider 声明的推理档位目标及确认该分组成员关系的账号
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReasoningModelVariant {
pub model: UpstreamModelId,
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 /// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContributedModelAlias { pub struct ContributedModelAlias {
+54 -3
View File
@@ -11,9 +11,9 @@ pub use crate::account::scope::{
}; };
pub use crate::identity::ProviderKind; pub use crate::identity::ProviderKind;
pub use catalog::{ pub use catalog::{
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort, AccountModelMetadata, ContributedModel, ContributedModelAlias, ProviderCatalogGeneration,
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent, ProviderCatalogPort, ProviderCatalogUnavailable, ProviderModelCapabilities,
ProviderModelDescriptor, PublicModelDescriptor, ProviderModelContent, ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
}; };
pub use snapshot::RuntimeSnapshot; pub use snapshot::RuntimeSnapshot;
@@ -118,6 +118,12 @@ impl fmt::Display for UpstreamModelId {
} }
} }
impl std::borrow::Borrow<str> for UpstreamModelId {
fn borrow(&self) -> &str {
self.as_str()
}
}
/// `runtime_settings.config_revision` /// `runtime_settings.config_revision`
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ConfigRevision(NonZeroU64); pub struct ConfigRevision(NonZeroU64);
@@ -153,6 +159,9 @@ pub struct ModelCapabilities {
upstream_validates_features: bool, upstream_validates_features: bool,
generation_protocol: Option<&'static str>, generation_protocol: Option<&'static str>,
translated_generation_protocols: BTreeSet<&'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 为客户端模型目录提供的展示与交互能力 /// Provider 为客户端模型目录提供的展示与交互能力
@@ -427,6 +436,9 @@ impl ModelCapabilities {
upstream_validates_features: false, upstream_validates_features: false,
generation_protocol: None, generation_protocol: None,
translated_generation_protocols: BTreeSet::new(), translated_generation_protocols: BTreeSet::new(),
reasoning_variants: BTreeMap::new(),
account_metadata: BTreeMap::new(),
dedicated_web_search: None,
} }
} }
@@ -436,6 +448,40 @@ impl ModelCapabilities {
self self
} }
/// 分组名只按请求明确声明的档位解析,不推测默认型号
#[must_use]
pub fn with_reasoning_variants(
mut self,
variants: BTreeMap<String, ReasoningModelVariant>,
) -> Self {
self.reasoning_variants = variants;
self
}
#[must_use]
pub fn reasoning_variants(&self) -> &BTreeMap<String, ReasoningModelVariant> {
&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 /// 将请求形态 feature 的最终合法性判断交给上游 wire API
#[must_use] #[must_use]
pub const fn with_upstream_feature_validation(mut self) -> Self { pub const fn with_upstream_feature_validation(mut self) -> Self {
@@ -465,6 +511,11 @@ impl ModelCapabilities {
operation: &crate::operation::Operation, operation: &crate::operation::Operation,
requirements: &CapabilityRequirements, requirements: &CapabilityRequirements,
) -> Option<BTreeSet<Feature>> { ) -> Option<BTreeSet<Feature>> {
if operation.requires_native_protocol()
&& self.generation_protocol != Some(operation.protocol())
{
return None;
}
if matches!(operation, crate::operation::Operation::Generate(_)) if matches!(operation, crate::operation::Operation::Generate(_))
&& self.generation_protocol.is_some_and(|protocol| { && self.generation_protocol.is_some_and(|protocol| {
protocol != operation.protocol() protocol != operation.protocol()
@@ -958,32 +958,35 @@ impl RuntimeSnapshot {
let mut profiles = BTreeMap::new(); let mut profiles = BTreeMap::new();
for (model, presentation) in presentations { for (model, presentation) in presentations {
if let Ok(public_model) = PublicModelId::new(model.as_str().to_owned()) { 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() { for alias in self.settings.values.model_mappings.keys() {
let target = self.mapped_model(alias); let Ok(public_model) = PublicModelId::new(alias.clone()) else {
let Some(presentation) = presentations.iter().find_map(|(model, presentation)| {
(model.as_str() == target).then_some(presentation)
}) else {
continue; continue;
}; };
if let Ok(public_model) = PublicModelId::new(alias.clone()) { let target = self.mapped_model(alias);
profiles.insert(public_model, presentation.clone()); if let Some(presentation) = presentations.get(target.as_str()) {
profiles.insert(public_model, presentation);
} else {
profiles.remove(&public_model);
} }
} }
for alias in self for alias in self.model_aliases() {
.model_aliases() if &alias.provider == provider
.iter() && let Some(presentation) = presentations.get(&alias.target)
.filter(|alias| &alias.provider == provider) {
{ profiles.insert(alias.id.clone(), presentation);
if let Some(presentation) = presentations.get(&alias.target) { } else {
profiles.insert(alias.id.clone(), presentation.clone()); profiles.remove(&alias.id);
} }
} }
profiles profiles
.into_iter() .into_iter()
.map(|(model, presentation)| super::PublicModelProfile::new(model, presentation)) .map(|(model, presentation)| {
super::PublicModelProfile::new(model, presentation.clone())
})
.collect() .collect()
} }
@@ -1078,6 +1081,35 @@ impl RuntimeSnapshot {
&RoutingContext::default(), &RoutingContext::default(),
) )
.is_ok() .is_ok()
|| scope.provider_kinds().iter().any(|provider| {
self.contains_public_model_for_provider(model, provider)
&& self
.model_group(provider, &self.mapped_model(model.as_str()))
.is_some_and(|group| {
group
.match_operation(
operation,
&operation.capability_requirements(),
)
.is_some()
&& group.reasoning_variants.values().any(|variant| {
self.variant_allowed(provider, variant, scope)
&& self
.provider_models
.get(provider)
.and_then(|models| models.get(&variant.model))
.is_some_and(|target| {
target
.match_operation(
operation,
&operation
.capability_requirements(),
)
.is_some()
})
})
})
})
}) })
.collect() .collect()
} }
@@ -1108,8 +1140,30 @@ impl RuntimeSnapshot {
scope: &FrozenAccountScope, scope: &FrozenAccountScope,
) -> Vec<super::PublicModelProfile> { ) -> Vec<super::PublicModelProfile> {
let mut profiles = self.public_model_profiles_for_provider(provider); let mut profiles = self.public_model_profiles_for_provider(provider);
profiles.retain(|profile| { profiles.retain_mut(|profile| {
self.native_catalog_model_allowed_for_scope(provider, profile.model(), scope) 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 排序,追加的插件画像保留注册顺序,不参与二分查找 // Provider 画像按公开 ID 排序,追加的插件画像保留注册顺序,不参与二分查找
let provider_count = profiles.len(); let provider_count = profiles.len();
@@ -1121,6 +1175,30 @@ impl RuntimeSnapshot {
Err(_) => profiles.push(model.public_profile()), 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 profiles
} }
@@ -1172,6 +1250,13 @@ impl RuntimeSnapshot {
return false; return false;
}; };
let upstream = self.mapped_model(public_model.as_str()); let upstream = self.mapped_model(public_model.as_str());
if let Some(group) = self.model_group(provider, &upstream) {
return self.contains_public_model_for_provider(public_model, provider)
&& group.reasoning_variants.values().any(|variant| {
variant.accounts.contains(account)
&& scope.allows_model(account, variant.model.as_str())
});
}
if !scope.allows_model(account, &upstream) if !scope.allows_model(account, &upstream)
|| !self.contains_public_model_for_provider(public_model, provider) || !self.contains_public_model_for_provider(public_model, provider)
{ {
@@ -1237,6 +1322,35 @@ impl RuntimeSnapshot {
}) })
} }
fn model_group(&self, provider: &ProviderKind, model: &str) -> Option<&ModelCapabilities> {
self.provider_models
.get(provider)?
.get(model)
.filter(|capabilities| !capabilities.reasoning_variants.is_empty())
}
fn variant_allowed(
&self,
provider: &ProviderKind,
variant: &super::ReasoningModelVariant,
scope: &FrozenAccountScope,
) -> bool {
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())
})
}
fn native_catalog_model_allowed_for_scope( fn native_catalog_model_allowed_for_scope(
&self, &self,
provider: &ProviderKind, provider: &ProviderKind,
@@ -1244,6 +1358,12 @@ impl RuntimeSnapshot {
scope: &FrozenAccountScope, scope: &FrozenAccountScope,
) -> bool { ) -> bool {
let upstream_model = self.mapped_model(public_model.as_str()); let upstream_model = self.mapped_model(public_model.as_str());
if let Some(group) = self.model_group(provider, &upstream_model) {
return group
.reasoning_variants
.values()
.any(|variant| self.variant_allowed(provider, variant, scope));
}
match self match self
.model_catalog_accounts .model_catalog_accounts
.get(provider) .get(provider)
@@ -1461,7 +1581,13 @@ impl RuntimeSnapshot {
} }
.map_err(|_| RoutingError::InvalidIdentifier)? .map_err(|_| RoutingError::InvalidIdentifier)?
}; };
if enforce_routing_policy && account_scope.groups_deny_model(Some(upstream_model.as_str())) let grouped = self.providers.iter().any(|provider| {
self.model_group(provider, upstream_model.as_str())
.is_some()
});
if !grouped
&& enforce_routing_policy
&& account_scope.groups_deny_model(Some(upstream_model.as_str()))
{ {
return Err(RoutingError::GroupModelDenied); return Err(RoutingError::GroupModelDenied);
} }
@@ -1476,6 +1602,9 @@ impl RuntimeSnapshot {
|| account_scope.provider_kinds().clone(), || account_scope.provider_kinds().clone(),
|provider| BTreeSet::from([provider.clone()]), |provider| BTreeSet::from([provider.clone()]),
); );
let mut invalid_variant = false;
let mut group_model_denied = false;
let mut search_unavailable = false;
for provider in &providers { for provider in &providers {
if !self.providers.contains(provider) { if !self.providers.contains(provider) {
continue; continue;
@@ -1495,23 +1624,50 @@ impl RuntimeSnapshot {
{ {
continue; continue;
} }
let mut candidate_scope = Arc::clone(&account_scope);
let upstream_model =
if let Some(group) = self.model_group(provider, upstream_model.as_str()) {
if group.match_operation(operation, &requirements).is_none() {
continue;
}
let effort = operation.requested_reasoning_effort();
let Some(variant) = effort
.as_ref()
.and_then(|effort| group.reasoning_variants.get(effort))
else {
invalid_variant = true;
continue;
};
// 空集合在 restricted_to 中表示不收窄,必须先拒绝没有来源的档位
if variant.accounts.is_empty() {
continue;
}
candidate_scope = Arc::new(
account_scope
.restricted_to(&BTreeSet::from([provider.clone()]), &variant.accounts),
);
&variant.model
} else {
&upstream_model
};
if enforce_routing_policy
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
{
group_model_denied = true;
continue;
}
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定 // 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
if enforce_routing_policy if enforce_routing_policy
&& !account_scope.allows_provider_model(provider, upstream_model.as_str()) && !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
{ {
continue; continue;
} }
let capabilities = self let capabilities = self
.provider_models .provider_models
.get(provider) .get(provider)
.and_then(|models| models.get(&upstream_model)); .and_then(|models| models.get(upstream_model));
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派 // 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
let native_protocol = match operation { if operation.requires_native_protocol()
Operation::Generate(request) => request.requires_native_protocol(),
Operation::CountTokens(request) => request.requires_native_protocol(),
_ => false,
};
if native_protocol
&& capabilities.and_then(|model| model.generation_protocol) && capabilities.and_then(|model| model.generation_protocol)
!= Some(operation.protocol()) != Some(operation.protocol())
{ {
@@ -1530,7 +1686,6 @@ impl RuntimeSnapshot {
&& &model.id == public_model && &model.id == public_model
}) })
.collect(); .collect();
let mut candidate_scope = Arc::clone(&account_scope);
let emulated_features = if contributions.is_empty() { let emulated_features = if contributions.is_empty() {
match capabilities { match capabilities {
Some(capabilities) => { Some(capabilities) => {
@@ -1562,14 +1717,14 @@ impl RuntimeSnapshot {
}) })
.flat_map(|model| model.accounts.iter()) .flat_map(|model| model.accounts.iter())
.filter(|account| { .filter(|account| {
account_scope.account_provider(account) == Some(provider) candidate_scope.account_provider(account) == Some(provider)
&& account_scope.allows_model(account, upstream_model.as_str()) && candidate_scope.allows_model(account, upstream_model.as_str())
}) })
.cloned() .cloned()
.collect(); .collect();
if native.is_some() { if native.is_some() {
// 这些账号实际由适配器执行,不能借用同名原生模型的能力 // 这些账号实际由适配器执行,不能借用同名原生模型的能力
let mut restricted = account_scope.as_ref().clone(); let mut restricted = candidate_scope.as_ref().clone();
for account in contributions.iter().flat_map(|model| &model.accounts) { for account in contributions.iter().flat_map(|model| &model.accounts) {
if !capable_accounts.contains(account) { if !capable_accounts.contains(account) {
restricted = restricted.excluding_account(account.clone()); restricted = restricted.excluding_account(account.clone());
@@ -1582,7 +1737,7 @@ impl RuntimeSnapshot {
continue; continue;
} }
candidate_scope = Arc::new( candidate_scope = Arc::new(
account_scope.restricted_to(&Default::default(), &capable_accounts), candidate_scope.restricted_to(&Default::default(), &capable_accounts),
); );
} }
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) { if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
@@ -1590,6 +1745,84 @@ impl RuntimeSnapshot {
} }
native.unwrap_or_default() 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 { candidates.push(ProviderCandidate {
requires_direct_authentication: direct_model.is_some(), requires_direct_authentication: direct_model.is_some(),
provider: provider.clone(), provider: provider.clone(),
@@ -1607,6 +1840,15 @@ impl RuntimeSnapshot {
} }
if candidates.is_empty() { if candidates.is_empty() {
if group_model_denied {
return Err(RoutingError::GroupModelDenied);
}
if search_unavailable {
return Err(RoutingError::WebSearchUnavailable);
}
if invalid_variant {
return Err(RoutingError::InvalidReasoningVariant);
}
// 模型存在性必须包含被请求路由限制排除的 Provider;目录未知时不能断言模型不存在 // 模型存在性必须包含被请求路由限制排除的 Provider;目录未知时不能断言模型不存在
let mut scoped_providers = providers.intersection(&self.providers).peekable(); let mut scoped_providers = providers.intersection(&self.providers).peekable();
if scoped_providers.peek().is_some() if scoped_providers.peek().is_some()
@@ -49,8 +49,6 @@ pub enum PrivacyAction {
RenameKey, RenameKey,
RemoveField, RemoveField,
AnonymizeProject, AnonymizeProject,
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
AnonymizeWorkspace,
} }
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -60,6 +60,10 @@ pub const GROUP_MODEL_DENIED_CODE: &str = "group_model_denied";
pub const GROUP_MODEL_DENIED_MESSAGE: &str = pub const GROUP_MODEL_DENIED_MESSAGE: &str =
"Model is not allowed by the API key's account groups."; "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 不满足不变量 /// 路由快照或 Route Plan 不满足不变量
#[derive(Debug, Clone, PartialEq, Eq, Error)] #[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum RoutingError { pub enum RoutingError {
@@ -81,6 +85,12 @@ pub enum RoutingError {
/// 已启用的绑定分组均明确禁止请求模型 /// 已启用的绑定分组均明确禁止请求模型
#[error("{GROUP_MODEL_DENIED_MESSAGE}")] #[error("{GROUP_MODEL_DENIED_MESSAGE}")]
GroupModelDenied, GroupModelDenied,
/// 已知模型分组没有与本次请求匹配的推理档位
#[error("model group requires a supported reasoning effort")]
InvalidReasoningVariant,
/// 当前授权账号的目录没有专用搜索型号
#[error("{WEB_SEARCH_UNAVAILABLE_MESSAGE}")]
WebSearchUnavailable,
/// 快照中存在重复实体 /// 快照中存在重复实体
#[error("duplicate {entity} `{id}`")] #[error("duplicate {entity} `{id}`")]
DuplicateEntity { DuplicateEntity {
@@ -26,6 +26,442 @@ use gateway_core::routing::{
}; };
use gateway_core::settings::SettingsValues; use gateway_core::settings::SettingsValues;
#[test]
fn reasoning_groups_resolve_before_account_and_group_model_policies() {
use gateway_core::{
account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId},
operation::{
GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest,
},
routing::{
AccountModelMetadata, ClientRoutingScope, FrozenAccountScope, ProviderModel,
ReasoningModelVariant, RoutingContext, RoutingGroupSnapshot, RuntimeAccount,
RuntimeAccountDirectory, RuntimeSnapshot,
},
validation::RoutingError,
};
use std::collections::BTreeSet;
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(), high_only.clone()]
.into_iter()
.map(|id| {
(
id,
RuntimeAccount::new(provider.clone(), BTreeSet::from([group.clone()])),
)
}),
))
.with_group_model_access(BTreeMap::from([(
group.clone(),
AccountModelAccess::new(
AccountModelAccessMode::Allowlist,
vec!["family-medium".into()],
)
.unwrap(),
)])),
),
ClientRoutingScope::restricted(
vec![RoutingGroupSnapshot::new(group.clone(), "Group".into())],
BTreeSet::from([group]),
BTreeSet::from([provider.clone()]),
)
.unwrap(),
));
let caps = || {
ModelCapabilities::new(
BTreeSet::from([OperationKind::Generate, OperationKind::CountTokens]),
None,
)
.with_generation_protocol("genai")
.with_translated_generation_protocols(["openai"])
.with_upstream_feature_validation()
};
let variants = BTreeMap::from_iter(["medium", "high"].map(|level| {
(
level.into(),
ReasoningModelVariant {
model: UpstreamModelId::new(format!("family-{level}")).unwrap(),
accounts: if level == "medium" {
BTreeSet::from([declared.clone()])
} else {
BTreeSet::from([declared.clone(), high_only.clone()])
},
},
)
}));
let snapshot = RuntimeSnapshot::new(
revision(1),
SettingsValues::new(
2,
"smart",
BTreeMap::from([
("alias".into(), "family".into()),
("pinned".into(), "family-medium".into()),
]),
None,
None,
),
vec![provider.clone()],
vec![
ProviderModel::new(
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()
.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().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 {
let body = serde_json::json!({"generateContentRequest": body});
Operation::CountTokens(
TokenCountRequest::from_raw_json(
RawJsonPayload::new(
"genai",
bytes::Bytes::from(serde_json::to_vec(&body).unwrap()),
)
.unwrap(),
)
.requiring_native_protocol(),
)
} else {
Operation::Generate(
GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone())
.unwrap(),
)
.requiring_native_protocol(),
)
}
};
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"] {
let request = operation(level, count);
let plan = snapshot
.plan(
&PublicModelId::new(name).unwrap(),
&request,
scope.clone(),
&RoutingContext::default(),
)
.unwrap();
let candidate = &plan.candidates()[0];
assert_eq!(
candidate.upstream_model().unwrap().as_str(),
"family-medium"
);
assert!(candidate.account_scope().allows(&declared));
assert!(!candidate.account_scope().allows(&other));
}
}
assert!(matches!(
snapshot.plan(
&base,
&operation("HIGH", count),
scope.clone(),
&RoutingContext::default()
),
Err(RoutingError::GroupModelDenied)
));
for level in ["", "unsupported"] {
assert!(matches!(
snapshot.plan(
&base,
&operation(level, count),
scope.clone(),
&RoutingContext::default()
),
Err(RoutingError::InvalidReasoningVariant)
));
}
let listed = snapshot.public_models_for_operation(&scope, &operation("", count));
assert!(listed.contains(&base));
let other_only =
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
assert!(
!snapshot
.public_models_for_operation(&other_only, &operation("", count))
.contains(&base)
);
assert!(
snapshot
.plan(
&base,
&operation("MEDIUM", count),
other_only,
&RoutingContext::default()
)
.is_err()
);
}
// 完整型号不受正文中的其他档位重定向
let direct = PublicModelId::new("family-medium").unwrap();
assert_eq!(
snapshot
.plan(
&direct,
&operation("HIGH", false),
scope.clone(),
&RoutingContext::default()
)
.unwrap()
.candidates()[0]
.upstream_model()
.unwrap()
.as_str(),
"family-medium"
);
let incompatible = Operation::Generate(
GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("other-wire", Default::default()).unwrap(),
)
.requiring_native_protocol(),
);
assert!(
!snapshot
.public_models_for_operation(&scope, &incompatible)
.contains(&base)
);
let blocked = Arc::new(FrozenAccountScope::new(
Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([
(
declared.clone(),
RuntimeAccount::new(provider.clone(), BTreeSet::new()).with_model_access(
AccountModelAccess::new(
AccountModelAccessMode::Allowlist,
vec!["unrelated".into()],
)
.unwrap(),
),
),
(
other.clone(),
RuntimeAccount::new(provider.clone(), BTreeSet::new()),
),
]))),
ClientRoutingScope::all_accounts(),
));
assert!(
!snapshot
.public_models_for_operation(&blocked, &operation("", false))
.contains(&base)
);
assert!(
snapshot
.public_model_profiles_for_scope(&blocked)
.is_empty()
);
assert!(
snapshot
.plan(
&base,
&operation("MEDIUM", false),
blocked,
&RoutingContext::default()
)
.is_err()
);
// 同名插件模型也不能把分组候选重新扩大到未声明成员关系的账号
let snapshot = snapshot.with_extensions(Some(ExtensionSetReference::new(
ExtensionSetId::new("group-collision".into()).unwrap(),
Arc::new(ModelLease(vec![gateway_core::routing::ContributedModel {
owner: "fixture".into(),
id: base.clone(),
provider,
accounts: BTreeSet::from([other.clone()]),
capabilities: caps(),
presentation: ModelPresentation::new(None, None),
}])),
)));
let plan = snapshot
.plan(
&base,
&operation("MEDIUM", false),
scope,
&RoutingContext::default(),
)
.unwrap();
assert!(plan.candidates()[0].account_scope().allows(&declared));
assert!(!plan.candidates()[0].account_scope().allows(&other));
}
#[derive(Clone)] #[derive(Clone)]
struct TestSnapshotStore { struct TestSnapshotStore {
facts: Arc<Mutex<Result<SnapshotFacts, SnapshotStoreError>>>, facts: Arc<Mutex<Result<SnapshotFacts, SnapshotStoreError>>>,
@@ -87,8 +87,6 @@ pub enum PrivacyAction {
RenameKey, RenameKey,
RemoveField, RemoveField,
AnonymizeProject, AnonymizeProject,
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
AnonymizeWorkspace,
} }
#[derive(Clone, Serialize, Deserialize)] #[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
@@ -5,6 +5,7 @@ use serde_json::Value;
/// 转换器消费的模型目录事实;None 表示上游未声明 /// 转换器消费的模型目录事实;None 表示上游未声明
#[derive(Debug, Default, Clone, PartialEq, Eq)] #[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct MessagesModelCapabilities { pub struct MessagesModelCapabilities {
pub hosted_web_search: Option<bool>,
pub thinking: Option<bool>, pub thinking: Option<bool>,
pub adaptive_thinking: Option<bool>, pub adaptive_thinking: Option<bool>,
pub manual_thinking: Option<bool>, pub manual_thinking: Option<bool>,
@@ -17,6 +18,7 @@ impl MessagesModelCapabilities {
/// 从 Anthropic Models 条目提取转换所需事实,未知扩展不影响解析 /// 从 Anthropic Models 条目提取转换所需事实,未知扩展不影响解析
pub fn from_model(model: &Value) -> Self { pub fn from_model(model: &Value) -> Self {
Self { Self {
hosted_web_search: None,
thinking: model thinking: model
.pointer("/capabilities/thinking/supported") .pointer("/capabilities/thinking/supported")
.and_then(Value::as_bool), .and_then(Value::as_bool),
@@ -12,6 +12,7 @@ mod tools;
mod usage; mod usage;
pub(crate) use content::GENAI_CARRIER; pub(crate) use content::GENAI_CARRIER;
pub(crate) use request::responses_to_messages_content;
pub use capabilities::MessagesModelCapabilities; pub use capabilities::MessagesModelCapabilities;
pub use error::TranslationError; pub use error::TranslationError;
@@ -259,7 +259,6 @@ pub fn responses_to_messages_request(
request: &Map<String, Value>, request: &Map<String, Value>,
capabilities: &MessagesModelCapabilities, capabilities: &MessagesModelCapabilities,
) -> Result<Map<String, Value>, TranslationError> { ) -> Result<Map<String, Value>, TranslationError> {
let tools = ToolSet::from_responses(request);
let mut result = Map::new(); let mut result = Map::new();
copy_fields( copy_fields(
request, request,
@@ -291,6 +290,47 @@ pub fn responses_to_messages_request(
} }
_ => {} _ => {}
} }
result.extend(responses_to_messages_content(
request,
capabilities.hosted_web_search != Some(false),
)?);
thinking::apply_to_messages(request, &mut result, capabilities, maximum);
if request
.get("tool_choice")
.is_some_and(|c| c["type"] == "allowed_tools" && c["mode"] == "required")
&& result["tool_choice"]["type"] != "any"
{
return Err(TranslationError::InvalidRequest(
"The Messages upstream cannot require an allowed tool with this thinking mode.",
));
}
if matches!(
result
.get("thinking")
.and_then(|value| value.get("type"))
.and_then(Value::as_str),
Some("enabled" | "adaptive")
) {
// CPA 在生成推理配置后移除不相容的采样参数;原生 Messages 不经过此转换
result.shift_remove("temperature");
result.shift_remove("top_p");
}
if let Some(format) = request.get("text").and_then(|v| v.get("format"))
&& format.get("type").and_then(Value::as_str) == Some("json_schema")
{
let config = result.entry("output_config").or_insert_with(|| json!({}));
config["format"] = json!({"type":"json_schema","schema":format.get("schema").cloned().unwrap_or_else(||json!({}))});
}
Ok(result)
}
/// 共享对话、签名与工具映射,生成参数由最终目标协议独立处理
pub(crate) fn responses_to_messages_content(
request: &Map<String, Value>,
hosted_search: bool,
) -> Result<Map<String, Value>, TranslationError> {
let tools = ToolSet::from_responses(request);
let mut result = Map::new();
let mut system = Vec::new(); let mut system = Vec::new();
if let Some(instructions) = request.get("instructions").and_then(Value::as_str) if let Some(instructions) = request.get("instructions").and_then(Value::as_str)
&& !instructions.is_empty() && !instructions.is_empty()
@@ -386,34 +426,7 @@ pub fn responses_to_messages_request(
"messages".into(), "messages".into(),
Value::Array(normalize_tool_pairing(messages)), Value::Array(normalize_tool_pairing(messages)),
); );
tools.write_messages_tools(request, &mut result)?; tools.write_messages_tools(request, &mut result, hosted_search)?;
thinking::apply_to_messages(request, &mut result, capabilities, maximum);
if request
.get("tool_choice")
.is_some_and(|c| c["type"] == "allowed_tools" && c["mode"] == "required")
&& result["tool_choice"]["type"] != "any"
{
return Err(TranslationError::InvalidRequest(
"The Messages upstream cannot require an allowed tool with this thinking mode.",
));
}
if matches!(
result
.get("thinking")
.and_then(|value| value.get("type"))
.and_then(Value::as_str),
Some("enabled" | "adaptive")
) {
// CPA 在生成推理配置后移除不相容的采样参数;原生 Messages 不经过此转换
result.shift_remove("temperature");
result.shift_remove("top_p");
}
if let Some(format) = request.get("text").and_then(|v| v.get("format"))
&& format.get("type").and_then(Value::as_str) == Some("json_schema")
{
let config = result.entry("output_config").or_insert_with(|| json!({}));
config["format"] = json!({"type":"json_schema","schema":format.get("schema").cloned().unwrap_or_else(||json!({}))});
}
Ok(result) Ok(result)
} }
@@ -3,6 +3,7 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use super::TranslationError; use super::TranslationError;
use crate::openai::web_search;
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
@@ -40,7 +41,7 @@ impl<D> ToolSet<D> {
{ {
result.insert(child, Some(namespace), definition(child)); result.insert(child, Some(namespace), definition(child));
} }
} else if !is_web_search(tool) { } else if !web_search::is_search(tool) {
result.insert(tool, None, definition(tool)); result.insert(tool, None, definition(tool));
} }
} }
@@ -145,6 +146,7 @@ impl<'a> ToolSet<&'a Value> {
&self, &self,
request: &Map<String, Value>, request: &Map<String, Value>,
target: &mut Map<String, Value>, target: &mut Map<String, Value>,
hosted_search: bool,
) -> Result<(), TranslationError> { ) -> Result<(), TranslationError> {
let choice = request.get("tool_choice").unwrap_or(&Value::Null); let choice = request.get("tool_choice").unwrap_or(&Value::Null);
let restricted = choice["type"] == "allowed_tools"; let restricted = choice["type"] == "allowed_tools";
@@ -162,21 +164,9 @@ impl<'a> ToolSet<&'a Value> {
None None
}; };
let mut definitions = self.definitions(allowed); let mut definitions = self.definitions(allowed);
for tool in request for tool in web_search::allowed_declarations(request)
.get("tools") .filter(|tool| hosted_search && web_search::allows_live_access(tool))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(|t| is_web_search(t))
{ {
// Messages 的搜索是实时联网;缓存或索引模式不能升级为实时访问
if tool
.get("external_web_access")
.is_some_and(|v| !v.is_null() && v != true && v != "live")
|| allowed.is_some_and(|choices| !choices.iter().any(|c| c["type"] == tool["type"]))
{
continue;
}
let mut search = json!({"type":"web_search_20250305","name":"web_search"}); let mut search = json!({"type":"web_search_20250305","name":"web_search"});
if let Some(filters) = tool.get("filters").filter(|v| !v.is_null()) { if let Some(filters) = tool.get("filters").filter(|v| !v.is_null()) {
let filters = filters.as_object().ok_or(TranslationError::InvalidRequest( let filters = filters.as_object().ok_or(TranslationError::InvalidRequest(
@@ -196,7 +186,19 @@ impl<'a> ToolSet<&'a Value> {
definitions.push(search); definitions.push(search);
} }
if definitions.is_empty() { if definitions.is_empty() {
if restricted { // 转往仅支持函数的上游时,可选托管搜索可以省略,强制工具仍须可执行
let optional_search = !hosted_search
&& choice["mode"] == "auto"
&& allowed.is_some_and(|tools| tools.iter().all(web_search::is_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( return Err(TranslationError::InvalidRequest(
"No allowed tool can be used with the Messages upstream.", "No allowed tool can be used with the Messages upstream.",
)); ));
@@ -239,13 +241,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> { pub(super) fn messages_tools(tools: &[Value]) -> Vec<Value> {
tools.iter().map(|tool| { tools.iter().map(|tool| {
let kind = tool.get("type").and_then(Value::as_str).unwrap_or_default(); 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
}
@@ -13,6 +13,53 @@ fn invalid() -> TranslationError {
/// 转换 Messages 请求;不支持的内容返回错误,避免静默丢失客户端输入 /// 转换 Messages 请求;不支持的内容返回错误,避免静默丢失客户端输入
pub fn messages_to_genai_request( pub fn messages_to_genai_request(
request: &Map<String, Value>, request: &Map<String, Value>,
) -> Result<Map<String, Value>, TranslationError> {
let mut result = content_to_genai(request)?;
let mut generation = Map::new();
for (from, to) in [
("max_tokens", "maxOutputTokens"),
("temperature", "temperature"),
("top_p", "topP"),
("top_k", "topK"),
("stop_sequences", "stopSequences"),
] {
if let Some(value) = request.get(from) {
generation.insert(to.into(), value.clone());
}
}
if let Some(thinking) = request.get("thinking") {
match thinking["type"].as_str() {
Some("disabled") => {
generation.insert("thinkingConfig".into(), json!({"thinkingBudget":0}));
}
Some("enabled") => {
generation.insert(
"thinkingConfig".into(),
json!({"thinkingBudget":thinking["budget_tokens"],"includeThoughts":true}),
);
}
Some("adaptive" | "auto") => {
generation.insert(
"thinkingConfig".into(),
json!({"thinkingBudget":-1,"includeThoughts":true}),
);
}
_ => return Err(invalid()),
}
}
if let Some(format) = request.get("output_config").and_then(|c| c.get("format")) {
if format["type"] != "json_schema" {
return Err(invalid());
}
generation.insert("responseMimeType".into(), json!("application/json"));
generation.insert("responseSchema".into(), format["schema"].clone());
}
result.insert("generationConfig".into(), Value::Object(generation));
Ok(result)
}
pub(super) fn content_to_genai(
request: &Map<String, Value>,
) -> Result<Map<String, Value>, TranslationError> { ) -> Result<Map<String, Value>, TranslationError> {
let mut result = Map::new(); let mut result = Map::new();
if let Some(system) = request.get("system") { if let Some(system) = request.get("system") {
@@ -125,46 +172,6 @@ pub fn messages_to_genai_request(
} }
} }
result.insert("contents".into(), json!(contents)); result.insert("contents".into(), json!(contents));
let mut generation = Map::new();
for (from, to) in [
("max_tokens", "maxOutputTokens"),
("temperature", "temperature"),
("top_p", "topP"),
("top_k", "topK"),
("stop_sequences", "stopSequences"),
] {
if let Some(value) = request.get(from) {
generation.insert(to.into(), value.clone());
}
}
if let Some(thinking) = request.get("thinking") {
match thinking["type"].as_str() {
Some("disabled") => {
generation.insert("thinkingConfig".into(), json!({"thinkingBudget":0}));
}
Some("enabled") => {
generation.insert(
"thinkingConfig".into(),
json!({"thinkingBudget":thinking["budget_tokens"],"includeThoughts":true}),
);
}
Some("adaptive" | "auto") => {
generation.insert(
"thinkingConfig".into(),
json!({"thinkingBudget":-1,"includeThoughts":true}),
);
}
_ => return Err(invalid()),
}
}
if let Some(format) = request.get("output_config").and_then(|c| c.get("format")) {
if format["type"] != "json_schema" {
return Err(invalid());
}
generation.insert("responseMimeType".into(), json!("application/json"));
generation.insert("responseSchema".into(), format["schema"].clone());
}
result.insert("generationConfig".into(), Value::Object(generation));
if let Some(tools) = request.get("tools").and_then(Value::as_array) { if let Some(tools) = request.get("tools").and_then(Value::as_array) {
let declarations = tools let declarations = tools
.iter() .iter()
@@ -13,8 +13,12 @@ pub use response::{
pub const GENAI_PROTOCOL: &str = "genai"; pub const GENAI_PROTOCOL: &str = "genai";
mod messages; mod messages;
mod responses;
mod stream; mod stream;
mod tokens; mod tokens;
pub use messages::messages_to_genai_request; pub use messages::messages_to_genai_request;
pub use responses::responses_to_genai_request;
pub use stream::GenAiToMessagesStream; pub use stream::GenAiToMessagesStream;
pub use tokens::{count_tokens_request, count_tokens_to_messages}; pub use tokens::{count_tokens_request, count_tokens_to_messages};
mod grounding;
pub use grounding::grounded_search_events;
@@ -0,0 +1,65 @@
//! Responses 复用内容映射,生成参数直接转入 GenAI,避免继承 Messages 的默认值与限制
use crate::anthropic::{TranslationError, responses_to_messages_content};
use serde_json::{Map, Value, json};
/// 普通生成只映射函数工具,独立搜索由 Provider 按账号能力编排
pub fn responses_to_genai_request(
request: &Map<String, Value>,
) -> Result<Map<String, Value>, TranslationError> {
let mut generation = Map::new();
if let Some(value) = request
.get("max_output_tokens")
.filter(|value| !value.is_null())
{
let maximum =
value
.as_u64()
.filter(|value| *value > 0)
.ok_or(TranslationError::InvalidRequest(
"The max_output_tokens field must be a positive integer.",
))?;
generation.insert("maxOutputTokens".into(), json!(maximum));
}
for (from, to) in [("temperature", "temperature"), ("top_p", "topP")] {
if let Some(value) = request.get(from) {
generation.insert(to.into(), value.clone());
}
}
if let Some(thinking) = request
.get("reasoning")
.and_then(|value| value.get("effort"))
.and_then(Value::as_str)
.and_then(thinking_config)
{
generation.insert("thinkingConfig".into(), thinking);
}
if let Some(format) = request.get("text").and_then(|value| value.get("format"))
&& format["type"] == "json_schema"
{
generation.insert("responseMimeType".into(), json!("application/json"));
generation.insert(
"responseSchema".into(),
format.get("schema").cloned().unwrap_or_else(|| json!({})),
);
}
let content = responses_to_messages_content(request, false)?;
let mut result = super::messages::content_to_genai(&content)?;
result.insert("generationConfig".into(), Value::Object(generation));
Ok(result)
}
fn thinking_config(effort: &str) -> Option<Value> {
// 档位预算不受 Messages 的必填输出上限、强制工具或无思考续轮规则影响
let budget = match effort.trim().to_ascii_lowercase().as_str() {
"none" => return Some(json!({"thinkingBudget":0})),
"minimal" | "low" => 1024,
"medium" => 8192,
"high" => 24576,
"xhigh" => 32768,
"max" => 128000,
"auto" => -1,
_ => return None,
};
Some(json!({"thinkingBudget":budget,"includeThoughts":true}))
}
@@ -23,6 +23,7 @@ mod guardian;
mod headers; mod headers;
/// Server-Sent Events 帧的解析与编码 /// Server-Sent Events 帧的解析与编码
pub mod sse; pub mod sse;
pub mod web_search;
pub use codex::{ pub use codex::{
CodexResponsesRequestSemantics, WEBSOCKET_FRAME_CONTEXT_KEY, codex_account_session_id, CodexResponsesRequestSemantics, WEBSOCKET_FRAME_CONTEXT_KEY, codex_account_session_id,
@@ -0,0 +1,103 @@
//! Responses 内置搜索声明与强制工具选择,共用同一协议判定
use serde_json::{Map, Value};
/// 强制搜索无法对应唯一声明,不替调用方猜测搜索参数
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchSelectionError {
MissingDeclaration,
MultipleDeclarations,
}
impl SearchSelectionError {
/// 只包含静态协议诊断,可交给请求边界展示
#[must_use]
pub const fn message(self) -> &'static str {
match self {
Self::MissingDeclaration => "The selected web search tool must be declared.",
Self::MultipleDeclarations => "Select one web search declaration.",
}
}
}
impl std::fmt::Display for SearchSelectionError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(self.message())
}
}
impl std::error::Error for SearchSelectionError {}
#[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))
}
/// 只收窄搜索声明的允许范围,不把工具选择中的引用当成完整声明
pub fn allowed_declarations(body: &Map<String, Value>) -> impl Iterator<Item = &Value> {
let choice = body.get("tool_choice").unwrap_or(&Value::Null);
body.get("tools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter(move |tool| {
is_search(tool)
&& (choice["type"] != "allowed_tools"
|| choice["tools"].as_array().is_some_and(|allowed| {
allowed
.iter()
.any(|reference| reference["type"] == tool["type"])
}))
})
}
/// 可选搜索返回 None;强制搜索必须选出唯一声明,缺失或歧义不能退回普通生成
pub fn required_tool(body: &Map<String, Value>) -> Result<Option<&Value>, SearchSelectionError> {
if !is_required(body) {
return Ok(None);
}
let choice = body.get("tool_choice").unwrap_or(&Value::Null);
let mut tools = allowed_declarations(body)
.filter(|tool| !is_search(choice) || choice["type"] == tool["type"]);
let tool = tools
.next()
.ok_or(SearchSelectionError::MissingDeclaration)?;
if tools.next().is_some() {
return Err(SearchSelectionError::MultipleDeclarations);
}
Ok(Some(tool))
}
/// 未限制联网或明确选择 live 时允许实时访问;目标上游决定能否兑现其他模式
#[must_use]
pub fn allows_live_access(tool: &Value) -> bool {
tool.get("external_web_access")
.is_none_or(|value| value.is_null() || value == true || value == "live")
}
@@ -23,6 +23,23 @@ pub struct RequestObservation {
pub compact: bool, pub compact: bool,
} }
/// 计数入口的生成封套优先于顶层内容,沿用生成请求的协议观测
#[must_use]
pub fn token_count_observation(
protocol: &str,
body: &Map<String, Value>,
context: &Map<String, Value>,
) -> RequestObservation {
let body = if protocol == GENAI_PROTOCOL {
body.get("generateContentRequest")
.and_then(Value::as_object)
.unwrap_or(body)
} else {
body
};
request_observation(protocol, body, context, None)
}
/// 旧配置只由状态所属 Provider 提供,是否继承仍由当前协议的续接语义决定 /// 旧配置只由状态所属 Provider 提供,是否继承仍由当前协议的续接语义决定
#[must_use] #[must_use]
pub fn request_observation( pub fn request_observation(
@@ -588,3 +588,37 @@ fn tool_result_continuation_without_thinking_keeps_the_current_mode() {
.push(json!({"role":"user","content":"new question"})); .push(json!({"role":"user","content":"new question"}));
assert!(!convert(&req).contains_key("thinking")); 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"));
}
@@ -1,11 +1,8 @@
//! 验证转换路径的工具往返、多模态输入和签名来源 //! 验证转换路径的工具往返、多模态输入和签名来源
use gateway_protocol::{ use gateway_protocol::{
anthropic::{ anthropic::{MessagesAccumulator, MessagesToResponsesStream},
MessagesAccumulator, MessagesModelCapabilities, MessagesToResponsesStream, genai::{GenAiToMessagesStream, messages_to_genai_request, responses_to_genai_request},
responses_to_messages_request,
},
genai::{GenAiToMessagesStream, messages_to_genai_request},
}; };
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -36,12 +33,7 @@ fn signed_tool_roundtrip_preserves_custom_identity_and_final_usage() {
let call_id = call["call_id"].clone(); let call_id = call["call_id"].clone();
input.push(json!({"type":"custom_tool_call_output","call_id":call_id,"output":"done"})); input.push(json!({"type":"custom_tool_call_output","call_id":call_id,"output":"done"}));
let next = json!({"model":"fixture","input":input,"tools":original["tools"]}); let next = json!({"model":"fixture","input":input,"tools":original["tools"]});
let messages = responses_to_messages_request( let request = responses_to_genai_request(next.as_object().unwrap()).unwrap();
next.as_object().unwrap(),
&MessagesModelCapabilities::default(),
)
.unwrap();
let request = messages_to_genai_request(&messages).unwrap();
let call = &request["contents"][0]["parts"][0]; let call = &request["contents"][0]["parts"][0];
assert_eq!(call["thoughtSignature"], "opaque-signature"); assert_eq!(call["thoughtSignature"], "opaque-signature");
assert_eq!(call["functionCall"]["name"], "patch"); assert_eq!(call["functionCall"]["name"], "patch");
@@ -4,3 +4,4 @@ mod response;
mod tokens; mod tokens;
mod messages; mod messages;
mod responses;
@@ -0,0 +1,112 @@
//! Responses 生成参数不继承 Messages 的默认值、推理约束和采样裁剪
use gateway_protocol::genai::responses_to_genai_request;
use serde_json::{Value, json};
#[test]
fn unspecified_generation_settings_remain_unspecified_on_tool_continuations() {
let function = json!({"type":"function","name":"lookup","parameters":{"type":"object"}});
for choice in [json!("auto"), json!("required"), function.clone()] {
let mut request = json!({"tools":[function],"tool_choice":choice,"input":[
{"type":"function_call","call_id":"c","name":"lookup","arguments":"{}"},
{"type":"function_call_output","call_id":"c","output":"value"}
]});
for maximum in [None, Some(Value::Null)] {
if let Some(maximum) = maximum {
request["max_output_tokens"] = maximum;
}
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
assert_eq!(body["generationConfig"], json!({}));
assert_eq!(
body["contents"][1]["parts"][0]["functionResponse"]["name"],
"lookup"
);
}
}
}
#[test]
fn explicit_reasoning_and_sampling_survive_required_tools_and_small_output_limits() {
let function = json!({"type":"function","name":"lookup","parameters":{"type":"object"}});
for choice in [
json!("required"),
function.clone(),
json!({"type":"allowed_tools","mode":"required","tools":[{"type":"function","name":"lookup"}]}),
] {
let request = json!({"input":"hello","tools":[function],"tool_choice":choice,
"max_output_tokens":128,"reasoning":{"effort":"high"},"temperature":0.3,"top_p":0.8});
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
assert_eq!(
body["generationConfig"],
json!({"maxOutputTokens":128,"thinkingConfig":{"thinkingBudget":24576,"includeThoughts":true},"temperature":0.3,"topP":0.8})
);
assert_eq!(body["toolConfig"]["functionCallingConfig"]["mode"], "ANY");
if choice["type"] == "function" {
assert_eq!(
body["toolConfig"]["functionCallingConfig"]["allowedFunctionNames"],
json!(["lookup"])
);
}
}
}
#[test]
fn reasoning_budgets_do_not_inherit_messages_limits() {
for (effort, budget) in [
("none", 0),
("minimal", 1024),
("low", 1024),
("medium", 8192),
("high", 24576),
("xhigh", 32768),
("max", 128000),
("auto", -1),
] {
let request = json!({"input":"hello","reasoning":{"effort":effort}});
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
let thinking = &body["generationConfig"]["thinkingConfig"];
assert_eq!(thinking["thinkingBudget"], budget, "{effort}");
assert_eq!(
thinking.get("includeThoughts"),
(budget != 0).then_some(&json!(true))
);
assert!(body["generationConfig"].get("maxOutputTokens").is_none());
}
}
#[test]
fn explicit_output_limits_must_be_positive_integers() {
for maximum in [json!(0), json!(-1), json!(1.5), json!("128"), json!(true)] {
let request = json!({"input":"hello","max_output_tokens":maximum});
assert!(
responses_to_genai_request(request.as_object().unwrap()).is_err(),
"{maximum}"
);
}
for maximum in [1, 128, 100000] {
let request = json!({"input":"hello","max_output_tokens":maximum});
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
assert_eq!(body["generationConfig"]["maxOutputTokens"], maximum);
}
}
#[test]
fn content_and_json_schema_preserve_their_target_representation() {
let request = json!({"instructions":"system","input":[{"role":"user","content":[
{"type":"input_text","text":"hello"},
{"type":"input_image","image_url":"data:image/png;base64,AA=="}
]}],"text":{"format":{"type":"json_schema","name":"answer","schema":{"type":"object","properties":{"answer":{"type":"string"}}}}}});
let body = responses_to_genai_request(request.as_object().unwrap()).unwrap();
assert_eq!(
body["systemInstruction"]["parts"],
json!([{"text":"system"}])
);
assert_eq!(
body["contents"][0]["parts"],
json!([{"text":"hello"},{"inlineData":{"mimeType":"image/png","data":"AA=="}}])
);
assert_eq!(
body["generationConfig"],
json!({"responseMimeType":"application/json","responseSchema":request["text"]["format"]["schema"]})
);
}
@@ -4,3 +4,4 @@ mod codex;
mod events; mod events;
mod headers; mod headers;
mod sse; mod sse;
mod web_search;
@@ -0,0 +1,90 @@
//! 搜索路由与声明解析共用 Responses 工具选择语义
use gateway_protocol::openai::web_search::{SearchSelectionError, is_required, required_tool};
use serde_json::{Value, json};
#[test]
fn optional_or_mixed_tool_choices_do_not_require_search() {
let search = json!({"type":"web_search"});
let function = json!({"type":"function","name":"pwd"});
for choice in [
Value::Null,
json!("auto"),
json!("none"),
json!("required"),
function.clone(),
json!({"type":"allowed_tools","mode":"auto","tools":[search]}),
json!({"type":"allowed_tools","mode":"required","tools":[search,function]}),
json!({"type":"allowed_tools","mode":"required","tools":[]}),
] {
let body = json!({"tools":[search,function],"tool_choice":choice});
let body = body.as_object().unwrap();
assert!(!is_required(body), "{choice}");
assert_eq!(required_tool(body), Ok(None), "{choice}");
}
assert!(!is_required(
json!({"tool_choice":"required"}).as_object().unwrap()
));
}
#[test]
fn required_search_uses_the_original_selected_declaration() {
for kind in [
"web_search",
"web_search_preview",
"web_search_2025_08_26",
"web_search_preview_2025_03_11",
] {
let search = json!({"type":kind,"filters":{"allowed_domains":["example.org"]},"external_web_access":false});
for choice in [
json!("required"),
json!({"type":kind}),
json!({"type":"allowed_tools","mode":"required","tools":[{"type":kind}]}),
] {
let mut tools = vec![search.clone()];
if choice != "required" {
tools.push(json!({"type":"function","name":"pwd"}));
tools.push(json!({"type":if kind == "web_search" {"web_search_preview"} else {"web_search"}}));
}
let body = json!({"tools":tools,"tool_choice":choice});
let body = body.as_object().unwrap();
assert!(is_required(body));
assert_eq!(required_tool(body), Ok(Some(&search)));
}
}
}
#[test]
fn missing_or_ambiguous_required_search_cannot_fall_back_to_generation() {
let search = json!({"type":"web_search"});
for (body, expected) in [
(
json!({"tool_choice":search}),
SearchSelectionError::MissingDeclaration,
),
(
json!({"tools":[search],"tool_choice":{"type":"web_search_preview"}}),
SearchSelectionError::MissingDeclaration,
),
(
json!({"tools":[search],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[{"type":"web_search_preview"}]}}),
SearchSelectionError::MissingDeclaration,
),
(
json!({"tools":[search,search],"tool_choice":search}),
SearchSelectionError::MultipleDeclarations,
),
(
json!({"tools":[search,{"type":"web_search_preview"}],"tool_choice":"required"}),
SearchSelectionError::MultipleDeclarations,
),
(
json!({"tools":[search,search],"tool_choice":{"type":"allowed_tools","mode":"required","tools":[search]}}),
SearchSelectionError::MultipleDeclarations,
),
] {
let body = body.as_object().unwrap();
assert!(is_required(body));
assert_eq!(required_tool(body), Err(expected));
}
}
@@ -1,6 +1,35 @@
//! 验证不同协议的共享请求事实 //! 验证不同协议的共享请求事实
use gateway_protocol::request::{request_facts, request_observation}; use gateway_protocol::request::{request_facts, request_observation};
#[test]
fn token_count_observation_uses_the_nested_generation_request() {
for (body, expected) in [
(
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"MEDIUM"}}}),
Some("medium"),
),
(
serde_json::json!({"generation_config":{"thinking_config":{"thinking_level":"HIGH"}}}),
Some("high"),
),
(
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"generationConfig":{"thinkingConfig":{"thinkingLevel":"MEDIUM"}}}}),
Some("medium"),
),
(
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"contents":[]}}),
None,
),
] {
let observation = gateway_protocol::request::token_count_observation(
"genai",
body.as_object().unwrap(),
&Default::default(),
);
assert_eq!(observation.reasoning_effort.as_deref(), expected);
}
}
use serde_json::{Map, json}; use serde_json::{Map, json};
#[test] #[test]
@@ -586,7 +586,12 @@ pub(crate) async fn account_usage_windows(
let mut total = MetricState::default(); let mut total = MetricState::default();
let mut models = Vec::new(); let mut models = Vec::new();
for ((account, model), state) in &states { 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; continue;
} }
total.merge(state)?; total.merge(state)?;
@@ -401,6 +401,13 @@ impl ProviderAccountStore for PgProviderAccountRepository {
super::quota::versions(self, accounts).await 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( async fn apply_quota_access(
&self, &self,
change: QuotaAccessChange, change: QuotaAccessChange,
@@ -19,6 +19,35 @@ pub(in crate::postgres::provider_accounts) async fn versions(
.map_err(crate::core_store_error) .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( pub(in crate::postgres::provider_accounts) async fn write(
repository: &PgProviderAccountRepository, repository: &PgProviderAccountRepository,
observation: QuotaObservation, observation: QuotaObservation,
@@ -13,6 +13,13 @@ pub(in crate::postgres::provider_accounts) async fn load_history(
.map_err(|error| admin_store_error(ENTITY, error))?; .map_err(|error| admin_store_error(ENTITY, error))?;
let range = ObservabilityRange::new(window.range.start, window.range.end) let range = ObservabilityRange::new(window.range.start, window.range.end)
.map_err(|error| admin_store_error(ENTITY, error))?; .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) { if range.end - range.start > TimeDelta::days(32) {
return Err(AdminStoreError::new( return Err(AdminStoreError::new(
AdminStoreErrorKind::Invalid, AdminStoreErrorKind::Invalid,
@@ -5,6 +5,6 @@ mod forecast;
mod history; mod history;
mod warmup; 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 forecast::load_history;
pub(super) use history::documents; pub(super) use history::documents;
@@ -2,6 +2,56 @@
use super::*; 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] #[tokio::test]
async fn scoped_account_list_empty_scope_does_not_use_database() { async fn scoped_account_list_empty_scope_does_not_use_database() {
let pool = sqlx::postgres::PgPoolOptions::new() let pool = sqlx::postgres::PgPoolOptions::new()
@@ -1112,36 +1112,57 @@ async fn terminal_admin_quota_window_usage_prefers_provider_total_and_falls_back
.await .await
.expect("separate provider total from fallback components"); .expect("separate provider total from fallback components");
let mut usage = admin_account_store(&database.pool) let short = TimeRange {
.load_account_usage_by_windows(&[ start: now - TimeDelta::hours(5),
AccountUsageWindowQuery { end: now + TimeDelta::minutes(1),
account_id: "acct_quota_window".to_owned(), };
key: "short".to_owned(), let week = TimeRange {
range: TimeRange { start: now - TimeDelta::weeks(1),
start: now - TimeDelta::hours(1), end: short.end,
end: now + TimeDelta::minutes(1), };
}, let query = |key: &str, range: TimeRange, models| AccountUsageWindowQuery {
}, account_id: "acct_quota_window".to_owned(),
AccountUsageWindowQuery { key: key.to_owned(),
account_id: "acct_quota_window".to_owned(), range,
key: "long".to_owned(), models,
range: TimeRange { };
start: now - TimeDelta::hours(7), let older = Some(["gpt-window-older".to_owned()].into());
end: now + TimeDelta::minutes(1), 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 .await
.expect("load quota window usage"); .unwrap_err();
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);
assert_eq!( assert_eq!(
usage[0] error.kind(),
.usage gateway_admin::ports::store::AdminStoreErrorKind::Invalid
.models );
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() .iter()
.map(|model| (model.model.as_str(), model.total_tokens)) .map(|model| (model.model.as_str(), model.total_tokens))
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
@@ -1150,19 +1171,18 @@ async fn terminal_admin_quota_window_usage_prefers_provider_total_and_falls_back
("gpt-window-recent", Some(700)), ("gpt-window-recent", Some(700)),
], ],
); );
assert_eq!(usage[0].usage.costs.len(), 1); assert_eq!(long.costs.len(), 1);
assert_eq!(usage[0].usage.costs[0].currency, "USD"); assert_eq!(long.costs[0].currency, "USD");
assert_eq!(usage[0].usage.costs[0].amount.as_str(), "3.75"); assert_eq!(long.costs[0].amount.as_str(), "3.75");
assert_eq!(usage[0].usage.models[0].costs[0].amount.as_str(), "2.5"); assert_eq!(long.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!(long.models[1].costs[0].amount.as_str(), "1.25");
assert_eq!(usage[1].key, "short"); assert_eq!(short.total_tokens, Some(700));
assert_eq!(usage[1].usage.total_tokens, Some(700)); assert_eq!(short.costs.len(), 1);
assert_eq!(usage[1].usage.costs.len(), 1); assert_eq!(short.costs[0].currency, "USD");
assert_eq!(usage[1].usage.costs[0].currency, "USD"); assert_eq!(short.costs[0].amount.as_str(), "1.25");
assert_eq!(usage[1].usage.costs[0].amount.as_str(), "1.25"); assert_eq!(short.models.len(), 1);
assert_eq!(usage[1].usage.models.len(), 1); assert_eq!(short.models[0].model, "gpt-window-recent");
assert_eq!(usage[1].usage.models[0].model, "gpt-window-recent"); assert_eq!(short.models[0].total_tokens, Some(700));
assert_eq!(usage[1].usage.models[0].total_tokens, Some(700));
database.close().await; 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) let usage = admin_account_store(&database.pool)
.load_account_usage_by_windows(&[AccountUsageWindowQuery { .load_account_usage_by_windows(&[AccountUsageWindowQuery {
models: None,
account_id: "acct_quota_window_websocket".to_owned(), account_id: "acct_quota_window_websocket".to_owned(),
key: "statusless".to_owned(), key: "statusless".to_owned(),
range: TimeRange { 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) let history = admin_account_store(&database.pool)
.load_quota_forecast_history(&AccountUsageWindowQuery { .load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_fraction".to_owned(), account_id: "acct_fraction".to_owned(),
key: "fraction".to_owned(), key: "fraction".to_owned(),
range: TimeRange { start, end }, range: TimeRange { start, end },
@@ -113,10 +114,12 @@ async fn quota_forecast_excludes_openai_prewarm_but_preserves_inference_and_audi
.unwrap(); .unwrap();
let store = admin_account_store(&database.pool); let store = admin_account_store(&database.pool);
let query = AccountUsageWindowQuery { let query = AccountUsageWindowQuery {
models: None,
account_id: "acct_prewarm".to_owned(), account_id: "acct_prewarm".to_owned(),
key: "week".to_owned(), key: "week".to_owned(),
range: TimeRange { start, end }, range: TimeRange { start, end },
}; };
let history = store.load_quota_forecast_history(&query).await.unwrap(); let history = store.load_quota_forecast_history(&query).await.unwrap();
assert_eq!(history.usage.request_count, 2); assert_eq!(history.usage.request_count, 2);
assert_eq!(history.usage.tokens, 300); assert_eq!(history.usage.tokens, 300);
@@ -223,6 +226,7 @@ async fn quota_forecast_does_not_apply_openai_prewarm_semantics_to_other_provide
.unwrap(); .unwrap();
let history = admin_account_store(&database.pool) let history = admin_account_store(&database.pool)
.load_quota_forecast_history(&AccountUsageWindowQuery { .load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_xai_kind".to_owned(), account_id: "acct_xai_kind".to_owned(),
key: "week".to_owned(), key: "week".to_owned(),
range: TimeRange { 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 store = admin_account_store(&database.pool);
let history = store let history = store
.load_quota_forecast_history(&AccountUsageWindowQuery { .load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast".to_owned(), account_id: "acct_forecast".to_owned(),
key: "week".to_owned(), key: "week".to_owned(),
range: TimeRange { start, end }, 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")); assert!(!format!("{history:?}").contains("never-debug-this"));
let empty = store let empty = store
.load_quota_forecast_history(&AccountUsageWindowQuery { .load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast".to_owned(), account_id: "acct_forecast".to_owned(),
key: "empty".to_owned(), key: "empty".to_owned(),
range: TimeRange { range: TimeRange {
@@ -391,6 +397,7 @@ async fn quota_forecast_bounds_documents_without_sampling_away_token_totals() {
.unwrap(); .unwrap();
let history = admin_account_store(&database.pool) let history = admin_account_store(&database.pool)
.load_quota_forecast_history(&AccountUsageWindowQuery { .load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast_bound".to_owned(), account_id: "acct_forecast_bound".to_owned(),
key: "week".to_owned(), key: "week".to_owned(),
range: TimeRange { range: TimeRange {
@@ -459,6 +466,7 @@ async fn quota_forecast_carries_unsampled_usage_between_document_points() {
.unwrap(); .unwrap();
let history = admin_account_store(&database.pool) let history = admin_account_store(&database.pool)
.load_quota_forecast_history(&AccountUsageWindowQuery { .load_quota_forecast_history(&AccountUsageWindowQuery {
models: None,
account_id: "acct_prefix".to_owned(), account_id: "acct_prefix".to_owned(),
key: "week".to_owned(), key: "week".to_owned(),
range: TimeRange { start, end }, 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 store = admin_account_store(&database.pool);
let queries = [ let queries = [
AccountUsageWindowQuery { AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast_projection".to_owned(), account_id: "acct_forecast_projection".to_owned(),
key: "complete".to_owned(), key: "complete".to_owned(),
range: TimeRange { range: TimeRange {
@@ -553,6 +562,7 @@ async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds
}, },
}, },
AccountUsageWindowQuery { AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast_projection".to_owned(), account_id: "acct_forecast_projection".to_owned(),
key: "edges".to_owned(), key: "edges".to_owned(),
range: TimeRange { range: TimeRange {
@@ -561,6 +571,7 @@ async fn quota_forecast_summaries_match_source_during_moves_deletes_and_rebuilds
}, },
}, },
AccountUsageWindowQuery { AccountUsageWindowQuery {
models: None,
account_id: "acct_forecast_moved".to_owned(), account_id: "acct_forecast_moved".to_owned(),
key: "moved".to_owned(), key: "moved".to_owned(),
range: TimeRange { range: TimeRange {
@@ -40,6 +40,7 @@ async fn quota_windows_reconcile_moved_requests_and_pending_deletions_without_wa
drain_analytics(&database.pool).await; drain_analytics(&database.pool).await;
let windows = [ let windows = [
AccountUsageWindowQuery { AccountUsageWindowQuery {
models: None,
account_id: "acct_usage_before".to_owned(), account_id: "acct_usage_before".to_owned(),
key: "old".to_owned(), key: "old".to_owned(),
range: TimeRange { range: TimeRange {
@@ -48,6 +49,7 @@ async fn quota_windows_reconcile_moved_requests_and_pending_deletions_without_wa
}, },
}, },
AccountUsageWindowQuery { AccountUsageWindowQuery {
models: None,
account_id: "acct_usage_after".to_owned(), account_id: "acct_usage_after".to_owned(),
key: "new".to_owned(), key: "new".to_owned(),
range: TimeRange { range: TimeRange {
@@ -202,6 +204,7 @@ async fn model_success_rates_preserve_usage_across_source_summary_and_pending_re
.execute(&database.pool).await.unwrap(); .execute(&database.pool).await.unwrap();
let windows = [ let windows = [
AccountUsageWindowQuery { AccountUsageWindowQuery {
models: None,
account_id: "acct_health".to_owned(), account_id: "acct_health".to_owned(),
key: "whole".to_owned(), key: "whole".to_owned(),
range: TimeRange { range: TimeRange {
@@ -210,6 +213,7 @@ async fn model_success_rates_preserve_usage_across_source_summary_and_pending_re
}, },
}, },
AccountUsageWindowQuery { AccountUsageWindowQuery {
models: None,
account_id: "acct_health".to_owned(), account_id: "acct_health".to_owned(),
key: "boundary".to_owned(), key: "boundary".to_owned(),
range: TimeRange { range: TimeRange {
@@ -288,6 +288,7 @@ async fn aggregate_import_and_signed_correction_survive_native_rebuild_without_s
ports::store::AccountStore, ports::store::AccountStore,
}; };
let windows = [AccountUsageWindowQuery { let windows = [AccountUsageWindowQuery {
models: None,
account_id: "account_usage".into(), account_id: "account_usage".into(),
key: "window".into(), key: "window".into(),
range: TimeRange { range: TimeRange {
@@ -37,6 +37,12 @@ pub(crate) struct AntigravityAdmin {
#[async_trait] #[async_trait]
impl ProviderAdmin for AntigravityAdmin { impl ProviderAdmin for AntigravityAdmin {
fn account_usage_lookback(
&self,
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
gateway_admin::model::provider_credentials::AccountUsageLookback::RecentWeek
}
fn is_direct_account(&self, authentication_kind: &str) -> bool { fn is_direct_account(&self, authentication_kind: &str) -> bool {
authentication_kind == "oauth" authentication_kind == "oauth"
} }
@@ -2,7 +2,7 @@
use crate::{ use crate::{
credential::{CredentialService, oauth::error}, credential::{CredentialService, oauth::error},
transport::{Catalog, CloudCodeClient, unsent}, transport::{Catalog, CloudCodeClient, Model, unsent},
}; };
use gateway_admin::{ use gateway_admin::{
model::provider_credentials::{ProviderModel, ProviderModels}, model::provider_credentials::{ProviderModel, ProviderModels},
@@ -12,10 +12,12 @@ use gateway_core::{
account::{AccountCatalogObservation, ProviderAccountId, StoredAccountCatalog}, account::{AccountCatalogObservation, ProviderAccountId, StoredAccountCatalog},
error::{ProviderError, ProviderErrorKind as Kind}, error::{ProviderError, ProviderErrorKind as Kind},
operation::OperationKind, operation::OperationKind,
routing::{ModelCapabilities, ProviderModelCapabilities, UpstreamModelId}, routing::{
AccountModelMetadata, ModelCapabilities, ProviderModelCapabilities, UpstreamModelId,
},
}; };
use std::{ use std::{
collections::{BTreeMap, BTreeSet}, collections::BTreeMap,
sync::{ sync::{
Arc, Mutex, Arc, Mutex,
atomic::{AtomicU64, AtomicUsize, Ordering}, atomic::{AtomicU64, AtomicUsize, Ordering},
@@ -163,35 +165,74 @@ impl CatalogService {
pub(crate) async fn capabilities( pub(crate) async fn capabilities(
&self, &self,
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> { ) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
let mut models: BTreeMap<UpstreamModelId, BTreeSet<ProviderAccountId>> = BTreeMap::new(); let mut members =
for (accounts, catalog) in self.catalogs().await? { BTreeMap::<UpstreamModelId, BTreeMap<ProviderAccountId, AccountModelMetadata>>::new();
for key in catalog.models.into_keys() { 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, model) in catalog.models {
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?; let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
models let metadata = account_metadata(model);
.entry(id) members.entry(id).or_default().extend(
.or_default() accounts
.extend(accounts.iter().map(|a| a.account_id.clone())); .iter()
.map(|a| (a.account_id.clone(), metadata.clone())),
);
} }
} }
Ok(models let capabilities = ModelCapabilities::new(
.into_iter() [OperationKind::Generate, OperationKind::CountTokens].into(),
.map(|(model, accounts)| { None,
ProviderModelCapabilities::new( )
model, .with_dedicated_web_search(search_models)
ModelCapabilities::new( .with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
[OperationKind::Generate, OperationKind::CountTokens].into(), .with_translated_generation_protocols([
None, gateway_protocol::openai::OPENAI_PROTOCOL,
) gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL) ])
.with_translated_generation_protocols([ .with_upstream_feature_validation();
gateway_protocol::openai::OPENAI_PROTOCOL, let mut models = BTreeMap::new();
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL, for (id, metadata) in members {
]) let accounts = metadata.keys().cloned().collect();
.with_upstream_feature_validation(), let model = ProviderModelCapabilities::new(
) id.clone(),
.with_catalog_accounts(accounts) capabilities.clone().with_account_metadata(metadata),
}) );
.collect()) models.insert(id, model.with_catalog_accounts(accounts));
}
// 上游已有同名实体时保留原生型号,不让其他账号的分组覆盖它
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();
group
.into_model(id, capabilities.clone())
.with_catalog_accounts(accounts)
});
}
Ok(models.into_values().collect())
} }
pub(crate) async fn account_models( pub(crate) async fn account_models(
@@ -272,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( fn admin_models(
catalog: Catalog, catalog: Catalog,
observed: SystemTime, observed: SystemTime,
@@ -3,6 +3,7 @@
mod authorization; mod authorization;
pub(crate) mod catalog; pub(crate) mod catalog;
mod documents; mod documents;
mod model_groups;
pub(crate) mod oauth; pub(crate) mod oauth;
pub(crate) mod quota; pub(crate) mod quota;
mod refresh; mod refresh;
@@ -0,0 +1,92 @@
//! 从上游分组声明提取展示名、档位顺序及实际存在的成员
use crate::transport::Catalog;
use gateway_core::{
account::AccountCatalogObservation,
routing::{
ModelCapabilities, ModelPresentation, ProviderModelCapabilities, ReasoningModelVariant,
UpstreamModelId,
},
};
use std::collections::BTreeMap;
#[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 declarations {
let Ok(group_id) = UpstreamModelId::new(group) else {
continue;
};
let Some(levels) = description["supportedThinkingLevels"].as_array() else {
continue;
};
for level in levels {
let Some(suffix) = level["thinkingSuffix"].as_str() else {
continue;
};
if !suffix
.split('-')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric()))
{
continue;
}
let level = suffix.to_ascii_lowercase();
let target = format!("{group}-{level}");
if catalog.models.contains_key(&target)
&& let Ok(target) = UpstreamModelId::new(target)
{
let entry = groups.entry(group_id.clone()).or_default();
if entry.display_name.is_none() {
entry.display_name = description["displayName"]
.as_str()
.map(str::trim)
.filter(|name| !name.is_empty())
.map(str::to_owned);
}
entry
.variants
.entry(level.clone())
.or_insert_with(|| {
entry.efforts.push(level);
ReasoningModelVariant {
model: target,
accounts: Default::default(),
}
})
.accounts
.extend(accounts.iter().map(|account| account.account_id.clone()));
}
}
}
}
@@ -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 chrono::{DateTime, Utc};
use gateway_admin::model::provider_credentials::{ use gateway_admin::model::provider_credentials::{
ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution, ProviderQuota, ProviderQuotaWindow, QuotaLocalUsageAttribution,
@@ -8,7 +11,7 @@ use gateway_admin::model::provider_credentials::{
use gateway_core::account::{AccountQuotaSignals, QuotaEvidence, QuotaState}; use gateway_core::account::{AccountQuotaSignals, QuotaEvidence, QuotaState};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
collections::BTreeMap, collections::{BTreeMap, BTreeSet},
time::{Duration, SystemTime}, time::{Duration, SystemTime},
}; };
@@ -17,6 +20,64 @@ pub(super) struct Document {
pub(super) tier: Option<Tier>, pub(super) tier: Option<Tier>,
pub(super) summary: QuotaSummary, pub(super) summary: QuotaSummary,
pub(super) models: BTreeMap<String, ModelQuota>, 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 { impl ModelQuota {
@@ -143,7 +204,12 @@ impl Document {
limit_id: group_id.clone(), limit_id: group_id.clone(),
limit_name: Some(group.display_name.clone()), limit_name: Some(group.display_name.clone()),
role: None, 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, window_seconds: seconds,
used_percent: used, used_percent: used,
reset_at: bucket.quota.reset_time, reset_at: bucket.quota.reset_time,
@@ -165,6 +165,7 @@ impl QuotaService {
.map_err(upstream)?; .map_err(upstream)?;
let doc = Document { let doc = Document {
tier: info.paid_tier.or(info.current_tier), tier: info.paid_tier.or(info.current_tier),
bucket_models: super::document::bucket_models(&summary, &catalog),
summary, summary,
models: catalog models: catalog
.models .models
@@ -250,13 +251,13 @@ impl QuotaService {
&self, &self,
cancel: &CancellationToken, cancel: &CancellationToken,
) -> Result<(), WorkerTaskError> { ) -> Result<(), WorkerTaskError> {
let mut accounts = self let accounts = self
.accounts .accounts
.list_for_provider(&self.kind, false) .list_for_provider(&self.kind, false)
.await .await
.map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?; .map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?;
let ids: Vec<_> = accounts.iter().map(|a| a.id().clone()).collect(); let ids: Vec<_> = accounts.iter().map(|a| a.id().clone()).collect();
let observations: BTreeMap<_, _> = self let mut observations: BTreeMap<_, _> = self
.accounts .accounts
.get_quota_versions(&ids) .get_quota_versions(&ids)
.await .await
@@ -264,37 +265,67 @@ impl QuotaService {
.into_iter() .into_iter()
.map(|o| (o.account_id.clone(), o)) .map(|o| (o.account_id.clone(), o))
.collect(); .collect();
accounts.retain(|a| { let now = SystemTime::now();
a.enabled() let interval = Duration::from_secs(300);
&& a.authentication_kind() == "oauth" let stale_before = now - interval;
&& observations.get(a.id()).is_none_or(|o| { let mut due = Vec::new();
o.credential_revision != a.revision() let mut stale = Vec::new();
|| o.observed_at.elapsed().unwrap_or_default() >= Duration::from_secs(300) for account in accounts
|| (a.quota().is_exhausted() .iter()
&& a.quota() .filter(|a| a.enabled() && a.authentication_kind() == "oauth")
.reset_at() {
.is_some_and(|reset| reset <= SystemTime::now())) let snapshot = observations
}) .remove(account.id())
}); .filter(|s| s.credential_revision == account.revision());
if accounts.is_empty() { match snapshot {
return Ok(()); 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 mut outcome = Ok(());
let offset = self.cursor.fetch_add(32, Ordering::Relaxed) % accounts.len(); if !stale.is_empty() {
accounts.rotate_left(offset); // 用量读取失败时,独立执行已选出的首查和耗尽复查
accounts.truncate(32); match self.accounts.accounts_used_since_quota(&stale).await {
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); Ok(active) => due.extend(active),
let mut failure = None; 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 { while let Some(result) = results.next().await {
if let Err(e) = result if let Err(e) = result
&& !matches!(e.kind(), Kind::Conflict | Kind::CredentialRefreshRequired) && !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| { outcome
Err(WorkerTaskError::safe("部分 Antigravity 额度刷新失败").with_source(e))
})
} }
} }
@@ -30,10 +30,16 @@ impl AntigravityProvider {
&self, &self,
model: &UpstreamModelId, model: &UpstreamModelId,
ctx: &AttemptContext, ctx: &AttemptContext,
search: bool,
) -> Result<CandidatePool, ProviderError> { ) -> Result<CandidatePool, ProviderError> {
let required = ctx.required_account(); let required = ctx.required_account();
let diagnostic = ctx.is_diagnostic_required_account(); let diagnostic = ctx.is_diagnostic_required_account();
let (accounts, projects) = if diagnostic { 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 id = required.ok_or_else(|| unsent(Kind::NoEligibleAccount))?;
let account = self let account = self
.accounts .accounts
@@ -45,8 +51,13 @@ impl AntigravityProvider {
let projects = BTreeMap::from([(id.clone(), (account.revision(), Project::Discover))]); let projects = BTreeMap::from([(id.clone(), (account.revision(), Project::Discover))]);
(vec![account], projects) (vec![account], projects)
} else { } 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(); 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() { if ids.is_empty() {
return Err(unsent(Kind::NoEligibleAccount)); return Err(unsent(Kind::NoEligibleAccount));
} }
@@ -165,11 +176,20 @@ impl AntigravityProvider {
&self, &self,
model: &UpstreamModelId, model: &UpstreamModelId,
ctx: &AttemptContext, ctx: &AttemptContext,
search: bool,
) -> Result<BTreeMap<ProviderAccountId, (CredentialRevision, Project)>, ProviderError> { ) -> Result<BTreeMap<ProviderAccountId, (CredentialRevision, Project)>, ProviderError> {
let required = ctx.required_account(); let required = ctx.required_account();
let mut projects = BTreeMap::new(); let mut projects = BTreeMap::new();
for (observations, catalog) in self.catalog.catalogs().await? { 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; continue;
} }
for observation in observations { for observation in observations {
@@ -41,7 +41,10 @@ impl AntigravityProvider {
let started = Instant::now(); let started = Instant::now();
let affinity = let affinity =
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model); 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( let selection = ProviderSelectionObservation::new(
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
selected.capacity, selected.capacity,
@@ -87,6 +90,9 @@ impl AntigravityProvider {
Some(model.as_str().to_owned()), Some(model.as_str().to_owned()),
selected.account.id().clone(), selected.account.id().clone(),
Box::new(move |operation, headers| Box::pin(async move { 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 (operation, translator) = super::translation::prepare(operation)?;
let headers = crate::transport::request_headers(&operation, headers, selected.account_switch); let headers = crate::transport::request_headers(&operation, headers, selected.account_switch);
if operation.protocol() != GENAI_PROTOCOL { if operation.protocol() != GENAI_PROTOCOL {
@@ -126,7 +132,8 @@ impl AntigravityProvider {
// 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号 // 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号
Project::Discover => resource.account_info(token).await?.project, 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, } => response,
}; };
let response = match response { let response = match response {
@@ -128,3 +128,5 @@ fn unavailable(error: impl Into<ErrorSource>) -> ProviderError {
crate::transport::unsent(ProviderErrorKind::ProviderInfrastructureUnavailable) crate::transport::unsent(ProviderErrorKind::ProviderInfrastructureUnavailable)
.with_source(error) .with_source(error)
} }
mod web_search;
@@ -48,9 +48,10 @@ impl AntigravityProvider {
model: &UpstreamModelId, model: &UpstreamModelId,
ctx: &AttemptContext, ctx: &AttemptContext,
affinity_key: Option<&ProviderSessionAffinityKey>, affinity_key: Option<&ProviderSessionAffinityKey>,
search: bool,
) -> Result<SelectedAccount, ProviderError> { ) -> Result<SelectedAccount, ProviderError> {
let policy = ctx.account_selection_policy(); 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 { let result = match select(policy.queue_policy()).await {
Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => { Err(SelectionError::Queue(reason)) if ctx.required_account().is_none() => {
policy policy
@@ -82,6 +83,7 @@ impl AntigravityProvider {
ctx: &AttemptContext, ctx: &AttemptContext,
queue: ConcurrencyQueuePolicy, queue: ConcurrencyQueuePolicy,
affinity_key: Option<&ProviderSessionAffinityKey>, affinity_key: Option<&ProviderSessionAffinityKey>,
search: bool,
) -> Result<SelectedAccount, SelectionError> { ) -> Result<SelectedAccount, SelectionError> {
let mut waiting = CapacityWait::new( let mut waiting = CapacityWait::new(
&self.waiting, &self.waiting,
@@ -101,7 +103,7 @@ impl AntigravityProvider {
accounts, accounts,
mut projects, mut projects,
mut selection, 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()) { let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
Some(key) => Some(ProviderSessionAffinityState::new( Some(key) => Some(ProviderSessionAffinityState::new(
key, key,
@@ -8,12 +8,12 @@ use gateway_core::{
operation::Operation, operation::Operation,
}; };
use gateway_protocol::{ use gateway_protocol::{
anthropic::{ anthropic::{ANTHROPIC_PROTOCOL, MessagesToResponsesStream},
ANTHROPIC_PROTOCOL, MessagesModelCapabilities, MessagesToResponsesStream, genai::{
responses_to_messages_request, GENAI_PROTOCOL, GenAiToMessagesStream, messages_to_genai_request,
responses_to_genai_request,
}, },
genai::{GENAI_PROTOCOL, GenAiToMessagesStream, messages_to_genai_request}, openai::{OPENAI_PROTOCOL, web_search},
openai::OPENAI_PROTOCOL,
}; };
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::borrow::Cow; use std::borrow::Cow;
@@ -42,49 +42,50 @@ pub(super) fn prepare(
{ {
return Err(unsent(ProviderErrorKind::InvalidRequest)); return Err(unsent(ProviderErrorKind::InvalidRequest));
} }
let responses = if source == OPENAI_PROTOCOL { let search = if source == OPENAI_PROTOCOL {
Some(MessagesToResponsesStream::new(original)) web_search::required_tool(original)
.map_err(|error| ProviderError::invalid_request(error.message()).with_source(error))?
} else { } else {
None None
}; };
let mut messages = if source == OPENAI_PROTOCOL { let body = if let Some(tool) = search {
Cow::Owned( super::web_search::request(original, tool)?
responses_to_messages_request(original, &MessagesModelCapabilities::default())
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?,
)
} else { } else {
Cow::Borrowed(original) if source == OPENAI_PROTOCOL {
responses_to_genai_request(original)
} else {
messages_to_genai_request(original)
}
.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 let model = original
.get("model") .get("model")
.and_then(Value::as_str) .and_then(Value::as_str)
.unwrap_or_default() .unwrap_or_default()
.to_owned(); .to_owned();
let body = messages_to_genai_request(&messages) let translator = if search.is_some() {
.map_err(|e| unsent(ProviderErrorKind::InvalidRequest).with_source(e))?; 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(); let mut context = payload.context().clone();
// 转换路径统一请求 SSE,JSON 客户端沿已有交付层聚合 // Desktop 搜索使用完整 JSON,编码路径保留增量交付
context.insert("stream".into(), json!(true)); context.insert("stream".into(), json!(search.is_none()));
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
let operation = operation let operation = operation
.replace_protocol_wire(None, context) .replace_protocol_wire(None, context)
.and_then(|operation| operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into())) .and_then(|operation| operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into()))
.map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?; .map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
Ok(( Ok((operation, Some(translator)))
operation,
Some(Translator::Generate(Box::new(GenerationTranslator {
genai: GenAiToMessagesStream::new(model),
responses,
}))),
))
} }
pub(super) enum Translator { pub(super) enum Translator {
Generate(Box<GenerationTranslator>), Generate(Box<GenerationTranslator>),
Search(Box<super::web_search::SearchResponse>),
Count(&'static str), Count(&'static str),
} }
@@ -134,6 +135,7 @@ impl NativeResponseTranslator for Translator {
fn target_protocol(&self) -> &str { fn target_protocol(&self) -> &str {
match self { match self {
Self::Generate(translator) => translator.target_protocol(), Self::Generate(translator) => translator.target_protocol(),
Self::Search(_) => OPENAI_PROTOCOL,
Self::Count(protocol) => protocol, Self::Count(protocol) => protocol,
} }
} }
@@ -141,6 +143,9 @@ impl NativeResponseTranslator for Translator {
&mut self, &mut self,
event: &ProtocolWireEvent, event: &ProtocolWireEvent,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> { ) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
if let Self::Search(search) = self {
return search.translate(event);
}
let Self::Generate(translator) = self else { let Self::Generate(translator) = self else {
let value = match event.raw_json_body() { let value = match event.raw_json_body() {
Some(raw) => Cow::Owned( Some(raw) => Cow::Owned(
@@ -166,9 +171,13 @@ impl NativeResponseTranslator for Translator {
translator.events(events) translator.events(events)
} }
fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> { fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
if let Self::Search(search) = self {
return search.finish();
}
let Self::Generate(translator) = self else { let Self::Generate(translator) = self else {
return Ok(Vec::new()); return Ok(Vec::new());
}; };
let events = translator let events = translator
.genai .genai
.finish() .finish()
@@ -0,0 +1,183 @@
//! 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},
};
use serde_json::{Map, Value, json};
use std::borrow::Cow;
pub(super) fn request(
original: &Map<String, Value>,
tool: &Value,
) -> Result<Map<String, Value>, ProviderError> {
if !web_search::allows_live_access(tool) {
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)] #[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub(crate) struct QuotaGroup { pub(crate) struct QuotaGroup {
#[serde(skip_serializing)]
pub(crate) description: Option<String>,
pub(crate) display_name: String, pub(crate) display_name: String,
pub(crate) buckets: Vec<QuotaBucket>, pub(crate) buckets: Vec<QuotaBucket>,
} }
@@ -14,12 +14,21 @@ use url::Url;
use super::failure::{network, sent, successful, unsent}; use super::failure::{network, sent, successful, unsent};
use crate::profile::ClientProfile; use crate::profile::ClientProfile;
use gateway_core::engine::middleware::MiddlewareHeader; 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; const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub(crate) struct Catalog { pub(crate) struct Catalog {
pub(crate) project: String, pub(crate) project: String,
#[serde(rename = "webSearchModelIds", default)]
pub(crate) web_search_models: Vec<String>,
pub(crate) models: BTreeMap<String, Model>, pub(crate) models: BTreeMap<String, Model>,
#[serde(rename = "groupedModels", default)]
pub(crate) grouped_models: serde_json::Value,
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
@@ -28,6 +37,29 @@ pub(crate) struct Model {
pub(crate) name: String, pub(crate) name: String,
#[serde(rename = "quotaInfo", default)] #[serde(rename = "quotaInfo", default)]
pub(crate) quota: Option<super::account::ModelQuota>, 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 { pub(crate) struct CloudCodeClient {
@@ -100,7 +132,11 @@ impl CloudCodeClient {
) -> Result<Catalog, ProviderError> { ) -> Result<Catalog, ProviderError> {
#[derive(Deserialize)] #[derive(Deserialize)]
struct Models { struct Models {
#[serde(rename = "webSearchModelIds", default)]
web_search_models: Vec<String>,
models: BTreeMap<String, Model>, models: BTreeMap<String, Model>,
#[serde(rename = "groupedModels", default)]
grouped_models: serde_json::Value,
} }
let models: Models = control( let models: Models = control(
self.post("fetchAvailableModels", token) self.post("fetchAvailableModels", token)
@@ -118,6 +154,8 @@ impl CloudCodeClient {
Ok(Catalog { Ok(Catalog {
project, project,
models: models.models, models: models.models,
grouped_models: models.grouped_models,
web_search_models: models.web_search_models,
}) })
} }
@@ -127,17 +165,24 @@ impl CloudCodeClient {
model: &str, model: &str,
token: &str, token: &str,
body: &[u8], body: &[u8],
stream: bool, mode: GenerateMode,
headers: &[MiddlewareHeader], headers: &[MiddlewareHeader],
) -> Result<Response, ProviderError> { ) -> Result<Response, ProviderError> {
#[derive(Serialize)] #[derive(Serialize)]
struct Envelope<'a> { struct Envelope<'a> {
project: &'a str, project: &'a str,
model: &'a str, model: &'a str,
#[serde(rename = "requestType", skip_serializing_if = "Option::is_none")]
request_type: Option<&'static str>,
request: BTreeMap<String, &'a RawValue>, request: BTreeMap<String, &'a RawValue>,
} }
let request = self.request_body(body)?; let instruction = if mode == GenerateMode::WebSearch {
let (send, media) = if stream { *SEARCH_INSTRUCTION
} else {
&self.system_instruction
};
let request = Self::request_body(body, instruction)?;
let (send, media) = if mode == GenerateMode::Stream {
( (
self.post("streamGenerateContent", token) self.post("streamGenerateContent", token)
.query(&[("alt", "sse")]), .query(&[("alt", "sse")]),
@@ -150,6 +195,7 @@ impl CloudCodeClient {
send.json(&Envelope { send.json(&Envelope {
project, project,
model, model,
request_type: (mode == GenerateMode::WebSearch).then_some("web_search"),
request, request,
}), }),
token, token,
@@ -165,7 +211,7 @@ impl CloudCodeClient {
body: &[u8], body: &[u8],
headers: &[MiddlewareHeader], headers: &[MiddlewareHeader],
) -> Result<Response, ProviderError> { ) -> Result<Response, ProviderError> {
let mut request = self.request_body(body)?; let mut request = Self::request_body(body, &self.system_instruction)?;
// Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段 // Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段
for field in [ for field in [
"model", "model",
@@ -190,14 +236,14 @@ impl CloudCodeClient {
} }
fn request_body<'a>( fn request_body<'a>(
&'a self,
body: &'a [u8], body: &'a [u8],
instruction: &'a RawValue,
) -> Result<BTreeMap<String, &'a RawValue>, ProviderError> { ) -> Result<BTreeMap<String, &'a RawValue>, ProviderError> {
let mut request: BTreeMap<String, &RawValue> = serde_json::from_slice(body) let mut request: BTreeMap<String, &RawValue> = serde_json::from_slice(body)
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?; .map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
// 生成和计数共享同一身份策略,其他字段保留原始 JSON 表达 // 生成和计数共享同一身份策略,其他字段保留原始 JSON 表达
request.remove("system_instruction"); request.remove("system_instruction");
request.insert("systemInstruction".to_owned(), &self.system_instruction); request.insert("systemInstruction".to_owned(), instruction);
Ok(request) Ok(request)
} }
@@ -6,7 +6,7 @@ mod failure;
mod headers; mod headers;
mod pool; mod pool;
mod response; 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 count::count_events;
pub(crate) use failure::{sent, unsent}; pub(crate) use failure::{sent, unsent};
pub(crate) use headers::request_headers; pub(crate) use headers::request_headers;
@@ -4,6 +4,8 @@
mod authorization; mod authorization;
#[path = "../../src/credential/documents.rs"] #[path = "../../src/credential/documents.rs"]
mod documents; mod documents;
#[path = "../../src/credential/model_groups.rs"]
mod model_groups;
#[path = "../../src/credential/oauth.rs"] #[path = "../../src/credential/oauth.rs"]
pub(crate) mod oauth; pub(crate) mod oauth;
#[path = "../../src/credential/refresh.rs"] #[path = "../../src/credential/refresh.rs"]
@@ -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; 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] #[tokio::test]
async fn quota_and_catalog_refresh_use_current_global_identity() { async fn quota_and_catalog_refresh_use_current_global_identity() {
let server = MockServer::start().await; let server = MockServer::start().await;
@@ -191,6 +339,16 @@ async fn failed_or_stale_refresh_preserves_persisted_quota() {
let cancelled = CancellationToken::new(); let cancelled = CancellationToken::new();
cancelled.cancel(); cancelled.cancel();
f.quota.reconcile(&cancelled).await.unwrap(); 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] #[tokio::test]
@@ -195,6 +195,174 @@ async fn mock_project(upstream: &MockServer) {
.await; .await;
} }
#[tokio::test]
async fn model_group_menu_routes_responses_and_native_generation_to_declared_members() {
use gateway_core::{
engine::provider::ProviderRequest,
operation::{GenerateRequest, Operation, ProtocolPayload},
routing::{ConfigRevision, ProviderModel, PublicModelId, RoutingContext, RuntimeSnapshot},
settings::SettingsValues,
};
let upstream = MockServer::start().await;
let fixture = Fixture::new(&upstream.uri());
*fixture.store.primary().catalog.lock().unwrap() = None;
mock_project(&upstream).await;
Mock::given(path("/v1internal:fetchAvailableModels"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"models": {
"gemini-4-hydrogen-medium": {"displayName":"Hydrogen Medium","maxTokens":1048576,"maxOutputTokens":65536,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High","maxTokens":900000,"maxOutputTokens":262144,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"}
},
"groupedModels": {
"gemini-4-hydrogen": {"displayName":"Gemini 4 Hydrogen","supportedThinkingLevels":[
{"thinkingSuffix":"MEDIUM"}, {"thinkingSuffix":"high"},
{"thinkingSuffix":"low"}, {"thinkingSuffix":"../sonar"}
]},
"unknown-family": {"supportedThinkingLevels":[{"thinkingSuffix":"medium"}]}
}
})))
.expect(1)
.mount(&upstream)
.await;
fixture
.catalog
.reconcile(&CancellationToken::new())
.await
.unwrap();
let kind = ProviderKind::new("antigravity").unwrap();
let models = fixture.provider.query_model_capabilities().await.unwrap();
assert_eq!(models.len(), 4);
let group = models
.iter()
.find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen")
.unwrap();
let menu = group.presentation().unwrap();
assert_eq!(menu.display_name(), Some("Gemini 4 Hydrogen"));
assert_eq!(menu.supported_reasoning_efforts(), ["medium", "high"]);
assert_eq!(menu.default_reasoning_effort(), Some("medium"));
assert_eq!(
models
.iter()
.filter(|entry| entry.presentation().is_some())
.count(),
1
);
let snapshot = RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(),
SettingsValues::new(2, "smart", Default::default(), None, None),
vec![kind.clone()],
models
.iter()
.map(|model| {
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 {
"/v1internal:streamGenerateContent"
} else {
"/v1internal:generateContent"
};
let template = if stream {
ResponseTemplate::new(200)
.set_body_raw(format!("data: {response}\n\n"), "text/event-stream")
} else {
ResponseTemplate::new(200).set_body_json(response)
};
Mock::given(path(path_name))
.and(body_partial_json(json!({"model":"gemini-4-hydrogen-medium", "project":"probe-project", "request":{"generationConfig":{"maxOutputTokens":65536,"thinkingConfig":{"thinkingLevel":"MEDIUM","includeThoughts":true}}}})))
.respond_with(template).expect(1).mount(&upstream).await;
let body = json!({"contents":[{"role":"user","parts":[{"text":"Reply only OK."}]}],"generationConfig":{"maxOutputTokens":65536,"thinkingConfig":{"thinkingLevel":"MEDIUM","includeThoughts":true}}});
let operation = Operation::Generate(
GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone())
.unwrap()
.with_context(json!({"stream":stream}).as_object().unwrap().clone()),
)
.requiring_native_protocol(),
);
let plan = snapshot
.plan(
&PublicModelId::new("gemini-4-hydrogen").unwrap(),
&operation,
fixture.store.account_scope(),
&RoutingContext::default(),
)
.unwrap();
let request = ProviderRequest::new(operation, plan.candidates()[0].clone());
let events = fixture
.provider
.clone()
.execute(request, context(frozen_profile(), CancellationToken::new()))
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
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] #[tokio::test]
async fn disabled_account_probe_discovers_its_own_project_on_first_poll() { async fn disabled_account_probe_discovers_its_own_project_on_first_poll() {
let upstream = MockServer::start().await; let upstream = MockServer::start().await;
@@ -450,7 +618,7 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
for (protocol, body) in [ for (protocol, body) in [
( (
"openai", "openai",
json!({"model":"fixture-model","input":"hello","max_output_tokens":100,"reasoning":{"effort":"none"},"text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}), json!({"model":"fixture-model","input":"hello","max_output_tokens":100,"reasoning":{"effort":"high"},"temperature":0.3,"top_p":0.8,"tools":[{"type":"function","name":"pwd","parameters":{"type":"object"}}],"tool_choice":"required","text":{"format":{"type":"json_schema","schema":{"type":"object"}}}}),
), ),
( (
"anthropic", "anthropic",
@@ -501,7 +669,13 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
if protocol == "openai" { if protocol == "openai" {
assert_eq!( assert_eq!(
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"], body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
0 24576
);
assert_eq!(body["request"]["generationConfig"]["temperature"], 0.3);
assert_eq!(body["request"]["generationConfig"]["topP"], 0.8);
assert_eq!(
body["request"]["toolConfig"]["functionCallingConfig"]["mode"],
"ANY"
); );
assert_eq!( assert_eq!(
body["request"]["generationConfig"]["responseSchema"], body["request"]["generationConfig"]["responseSchema"],
@@ -531,3 +705,230 @@ async fn translated_generation_delivers_terminal_wire_after_tail_usage() {
released(&fixture).await; released(&fixture).await;
} }
} }
#[tokio::test]
async fn optional_search_preserves_functions_and_unspecified_output_limit() {
use gateway_core::{
engine::provider::ProviderRequest,
operation::{GenerateRequest, Operation, ProtocolPayload},
};
let upstream = MockServer::start().await;
Mock::given(path("/v1internal:streamGenerateContent"))
.and(body_partial_json(json!({"request":{"tools":[{"functionDeclarations":[{"name":"pwd"}]}]}})))
.respond_with(ResponseTemplate::new(200).set_body_raw(
"data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n",
"text/event-stream",
))
.expect(4).mount(&upstream).await;
let search = json!({"type":"web_search"});
let function = json!({"type":"function","name":"pwd","parameters":{"type":"object"}});
for choice in [
json!(null),
json!("auto"),
json!("required"),
json!({"type":"allowed_tools","mode":"required","tools":[search,function]}),
] {
let fixture = Fixture::new(&upstream.uri());
let mut body = json!({"model":"fixture-model","input":"hello","tools":[search,function],"tool_choice":choice});
if choice == "required" {
body["max_output_tokens"] = json!(null);
}
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let stream = fixture
.provider
.clone()
.execute(
ProviderRequest::new(operation, request(false).candidate().clone()),
context(frozen_profile(), CancellationToken::new()),
)
.await
.unwrap();
stream.try_collect::<Vec<_>>().await.unwrap();
released(&fixture).await;
}
for request in upstream.received_requests().await.unwrap() {
let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
assert!(
body["request"]["generationConfig"]
.get("maxOutputTokens")
.is_none()
);
assert!(
body["request"]["generationConfig"]
.get("thinkingConfig")
.is_none()
);
}
}
#[tokio::test]
async fn invalid_required_search_is_rejected_before_sending_and_releases_lease() {
use gateway_core::{
engine::provider::ProviderRequest,
operation::{GenerateRequest, Operation, ProtocolPayload},
};
let upstream = MockServer::start().await;
let fixture = Fixture::new(&upstream.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!(["fixture-model"]);
*bytes = value.to_string().into();
}
let search = json!({"type":"web_search"});
for (tools, message) in [
(json!([]), "The selected web search tool must be declared."),
(
json!([search, search]),
"Select one web search declaration.",
),
(
json!([{"type":"web_search","external_web_access":false}]),
"Antigravity web search requires live external web access.",
),
(
json!([{"type":"web_search","external_web_access":"cached"}]),
"Antigravity web search requires live external web access.",
),
(
json!([{"type":"web_search","user_location":{"type":"approximate","country":"US"}}]),
"Antigravity cannot honor the specified web search options.",
),
] {
let body =
json!({"model":"fixture-model","input":"hello","tools":tools,"tool_choice":search});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let error = fixture
.provider
.clone()
.execute(
ProviderRequest::new(operation, request(false).candidate().clone()),
context(frozen_profile(), CancellationToken::new()),
)
.await
.err()
.expect("invalid search request");
assert_eq!(error.kind(), ProviderErrorKind::InvalidRequest);
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
assert_eq!(
gateway_core::error::GatewayError::from_provider(&error).client_message(),
message
);
released(&fixture).await;
}
assert!(upstream.received_requests().await.unwrap().is_empty());
}
#[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)>>, pub(crate) catalog: Mutex<Option<(AccountCatalogObservation, bytes::Bytes)>>,
active_leases: Arc<AtomicUsize>, active_leases: Arc<AtomicUsize>,
pub(crate) quota: Mutex<Option<gateway_core::account::QuotaObservation>>, pub(crate) quota: Mutex<Option<gateway_core::account::QuotaObservation>>,
pub(crate) last_generation: Mutex<Option<SystemTime>>,
} }
impl MemoryPorts { impl MemoryPorts {
@@ -182,6 +183,7 @@ impl Fixture {
))), ))),
active_leases: Arc::new(AtomicUsize::new(0)), active_leases: Arc::new(AtomicUsize::new(0)),
quota: Mutex::new(None), quota: Mutex::new(None),
last_generation: Mutex::new(None),
}, },
) )
}) })
@@ -594,6 +594,22 @@ impl ProviderAccountStore for MemoryPorts {
*quota = Some(observation); *quota = Some(observation);
Ok(QuotaWriteOutcome::Updated) 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( async fn touch_quota_observation(
&self, &self,
_touch: QuotaObservationTouch, _touch: QuotaObservationTouch,
@@ -114,7 +114,7 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
"fixture-model", "fixture-model",
&access_token, &access_token,
body, body,
stream, stream.into(),
&[], &[],
) )
.await .await
@@ -192,7 +192,7 @@ async fn streamed_text_is_projected_once_across_native_frames() {
.mount(&server) .mount(&server)
.await; .await;
let response = client let response = client
.generate("p", "m", "fixture", b"{}", true, &[]) .generate("p", "m", "fixture", b"{}", true.into(), &[])
.await .await
.unwrap(); .unwrap();
let events = transport::events( 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(); 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; 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 let res = client
.generate("p", "m", "fixture", b"{}", true, &[]) .generate("p", "m", "fixture", b"{}", true.into(), &[])
.await .await
.unwrap(); .unwrap();
let result = transport::events( let result = transport::events(
@@ -283,7 +283,7 @@ async fn incomplete_native_stream_and_redirect_are_rejected() {
.await; .await;
assert!( assert!(
client client
.generate("p", "m", "fixture", b"{}", false, &[]) .generate("p", "m", "fixture", b"{}", false.into(), &[])
.await .await
.is_err() .is_err()
); );
@@ -147,7 +147,7 @@ async fn generate(
"fixture-model", "fixture-model",
token, token,
br#"{"contents":[{"parts":[{"text":"ping","thoughtSignature":"fixture-signature"}]}]}"#, br#"{"contents":[{"parts":[{"text":"ping","thoughtSignature":"fixture-signature"}]}]}"#,
false, false.into(),
&[], &[],
) )
.await .await
@@ -74,7 +74,7 @@ impl CodexProvider {
.messages_model_capabilities(selected.lease.account(), &model) .messages_model_capabilities(selected.lease.account(), &model)
.unwrap_or_default(); .unwrap_or_default();
let mut body = responses_to_messages_request(original, &capabilities) let mut body = responses_to_messages_request(original, &capabilities)
.map_err(|_| invalid_request())?; .map_err(|error| invalid_request().with_source(error))?;
// Responses 的 HTTP JSON 和 SSE 共用事件输出,跨协议上游统一请求事件流 // Responses 的 HTTP JSON 和 SSE 共用事件输出,跨协议上游统一请求事件流
body.insert("stream".to_owned(), Value::Bool(true)); body.insert("stream".to_owned(), Value::Bool(true));
body body
@@ -107,8 +107,8 @@ impl CodexProvider {
let mut source_context = generate.protocol_payload().context().clone(); let mut source_context = generate.protocol_payload().context().clone();
retain_target_headers(source, &mut source_context, &mut headers); retain_target_headers(source, &mut source_context, &mut headers);
let translator = translator::ResponsesResponseTranslator::new(original); let translator = translator::ResponsesResponseTranslator::new(original);
let mut translated = let mut translated = messages_to_responses_request(original)
messages_to_responses_request(original).map_err(|_| invalid_request())?; .map_err(|error| invalid_request().with_source(error))?;
if matches!( if matches!(
selected.lease.authentication(), selected.lease.authentication(),
CodexRuntimeAuthentication::OAuth(_) CodexRuntimeAuthentication::OAuth(_)
@@ -28,11 +28,12 @@ impl NativeResponseTranslator for MessagesResponseTranslator {
event: &ProtocolWireEvent, event: &ProtocolWireEvent,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> { ) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
if let Some(raw) = event.raw_json_body() { if let Some(raw) = event.raw_json_body() {
let message: Value = serde_json::from_slice(raw).map_err(|_| protocol_error())?; let message: Value =
serde_json::from_slice(raw).map_err(|error| protocol_error().with_source(error))?;
let event = self let event = self
.stream .stream
.complete_json_event(&message) .complete_json_event(&message)
.map_err(|_| protocol_error())?; .map_err(|error| protocol_error().with_source(error))?;
return wire_events(OPENAI_PROTOCOL, vec![event]); return wire_events(OPENAI_PROTOCOL, vec![event]);
} }
if !event.has_json_data() { if !event.has_json_data() {
@@ -41,9 +42,11 @@ impl NativeResponseTranslator for MessagesResponseTranslator {
let events = self let events = self
.stream .stream
.push(event.data()) .push(event.data())
.map_err(|_| protocol_error())?; .map_err(|error| protocol_error().with_source(error))?;
if event.data().get("type").and_then(Value::as_str) == Some("message_stop") { if event.data().get("type").and_then(Value::as_str) == Some("message_stop") {
self.stream.finish().map_err(|_| protocol_error())?; self.stream
.finish()
.map_err(|error| protocol_error().with_source(error))?;
} }
wire_events(OPENAI_PROTOCOL, events) wire_events(OPENAI_PROTOCOL, events)
} }
@@ -73,15 +76,17 @@ impl NativeResponseTranslator for ResponsesResponseTranslator {
event: &ProtocolWireEvent, event: &ProtocolWireEvent,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> { ) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
if let Some(raw) = event.raw_json_body() { if let Some(raw) = event.raw_json_body() {
let response = serde_json::from_slice(raw).map_err(|_| protocol_error())?; let response =
serde_json::from_slice(raw).map_err(|error| protocol_error().with_source(error))?;
let message = self let message = self
.stream .stream
.complete_json(&response) .complete_json(&response)
.map_err(|_| protocol_error())?; .map_err(|error| protocol_error().with_source(error))?;
let raw = serde_json::to_vec(&message).map_err(|_| protocol_error())?; let raw = serde_json::to_vec(&message)
.map_err(|error| protocol_error().with_source(error))?;
return Ok(vec![ return Ok(vec![
ProtocolWireEvent::raw_json(ANTHROPIC_PROTOCOL, raw.into()) ProtocolWireEvent::raw_json(ANTHROPIC_PROTOCOL, raw.into())
.map_err(|_| protocol_error())?, .map_err(|error| protocol_error().with_source(error))?,
]); ]);
} }
if !event.has_json_data() { if !event.has_json_data() {
@@ -90,12 +95,14 @@ impl NativeResponseTranslator for ResponsesResponseTranslator {
let events = self let events = self
.stream .stream
.push(event.data()) .push(event.data())
.map_err(|_| protocol_error())?; .map_err(|error| protocol_error().with_source(error))?;
if matches!( if matches!(
event.data().get("type").and_then(Value::as_str), event.data().get("type").and_then(Value::as_str),
Some("response.completed" | "response.incomplete") Some("response.completed" | "response.incomplete")
) { ) {
self.stream.finish().map_err(|_| protocol_error())?; self.stream
.finish()
.map_err(|error| protocol_error().with_source(error))?;
} }
wire_events(ANTHROPIC_PROTOCOL, events) wire_events(ANTHROPIC_PROTOCOL, events)
} }
@@ -113,7 +120,7 @@ fn wire_events(
value.get("type").and_then(Value::as_str).map(str::to_owned), value.get("type").and_then(Value::as_str).map(str::to_owned),
value, value,
) )
.map_err(|_| protocol_error()) .map_err(|error| protocol_error().with_source(error))
}) })
.collect() .collect()
} }
@@ -16,12 +16,10 @@ pub(super) struct CompiledStep {
impl CompiledStep { impl CompiledStep {
pub(super) fn compile(rule: &PrivacyStep) -> Result<Self, &'static str> { pub(super) fn compile(rule: &PrivacyStep) -> Result<Self, &'static str> {
if matches!( if rule.action == PrivacyAction::AnonymizeProject
rule.action, && (rule.scope != PrivacyScope::TurnMetadata
PrivacyAction::AnonymizeProject | PrivacyAction::AnonymizeWorkspace || rule.selector != "$.workspaces"
) && (rule.scope != PrivacyScope::TurnMetadata || rule.pattern.is_some())
|| rule.selector != "$.workspaces"
|| rule.pattern.is_some())
{ {
return Err("工作区匿名化仅支持 turn_metadata 的 $.workspaces,且不使用匹配表达式"); return Err("工作区匿名化仅支持 turn_metadata 的 $.workspaces,且不使用匹配表达式");
} }
@@ -104,9 +102,6 @@ impl CompiledStep {
PrivacyAction::AnonymizeProject => { PrivacyAction::AnonymizeProject => {
*count += super::workspace::anonymize_project(value, budget)?; *count += super::workspace::anonymize_project(value, budget)?;
} }
PrivacyAction::AnonymizeWorkspace => {
*count += super::workspace::anonymize(value, budget)?;
}
PrivacyAction::RemoveField => { PrivacyAction::RemoveField => {
if let Some(regex) = &self.regex { if let Some(regex) = &self.regex {
let text = value.as_str().ok_or("条件删除只能匹配字符串值")?; let text = value.as_str().ok_or("条件删除只能匹配字符串值")?;
@@ -1,4 +1,4 @@
//! 工作区路径的账号会话化名、Git 元数据裁剪与预览会话识别 //! 工作区项目名的账号会话化名与预览会话识别
use gateway_core::account::ProviderAccount; use gateway_core::account::ProviderAccount;
use reqwest::header::HeaderMap; use reqwest::header::HeaderMap;
@@ -19,39 +19,6 @@ pub(super) fn account_session_scope(session: &str, account: &ProviderAccount) ->
hex::encode(hash.finalize()) hex::encode(hash.finalize())
} }
pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<usize, &'static str> {
let count = anonymize_project(value, budget)?;
let workspaces = value.as_object_mut().ok_or("工作区映射必须是对象")?;
let mut renamed = Map::new();
// 保留已保存组合动作的用户名替换与 Git 裁剪,独立项目动作不包含这些副作用
for (path, mut metadata) in std::mem::take(workspaces) {
let object = metadata.as_object_mut().ok_or("工作区信息必须是对象")?;
object.remove("associated_remote_urls");
object.remove("latest_git_commit_hash");
let split = path.rfind(['/', '\\']).ok_or("工作区路径缺少工程目录")?;
let mut alias = String::new();
let mut username = false;
for part in path[..=split].split_inclusive(['/', '\\']) {
let component = part.trim_end_matches(['/', '\\']);
if username && !component.is_empty() {
alias.push_str("user");
alias.push_str(&part[component.len()..]);
username = false;
} else {
alias.push_str(part);
username = component.eq_ignore_ascii_case("users")
|| component.eq_ignore_ascii_case("home");
}
}
alias.push_str(&path[split + 1..]);
if renamed.insert(alias, metadata).is_some() {
return Err("工作区匿名化产生重名");
}
}
*workspaces = renamed;
Ok(count)
}
pub(super) fn anonymize_project( pub(super) fn anonymize_project(
value: &mut Value, value: &mut Value,
budget: &mut Budget<'_>, budget: &mut Budget<'_>,
@@ -1564,6 +1564,10 @@ async fn openai_admin_provider_projects_official_codex_quota_and_independent_buc
.collect::<Vec<_>>(); .collect::<Vec<_>>();
assert_eq!(monthly.len(), 1); assert_eq!(monthly.len(), 1);
assert_eq!(
monthly[0].local_usage_attribution,
QuotaLocalUsageAttribution::AccountWide
);
assert!(monthly.iter().any(|window| { assert!(monthly.iter().any(|window| {
window.label == "月额度" window.label == "月额度"
&& window.limit_id.as_deref() == Some("codex") && 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.label, "周额度");
assert_eq!(review.limit_name.as_deref(), Some("code_review")); assert_eq!(review.limit_name.as_deref(), Some("code_review"));
assert_eq!(review.role, Some(ProviderQuotaWindowRole::Primary)); assert_eq!(review.role, Some(ProviderQuotaWindowRole::Primary));
assert_eq!(
review.local_usage_attribution,
QuotaLocalUsageAttribution::Unavailable
);
let spark = quota let spark = quota
.windows .windows
.iter() .iter()
.find(|window| window.limit_id.as_deref() == Some("codex_bengalfox")) .find(|window| window.limit_id.as_deref() == Some("codex_bengalfox"))
.expect("Spark quota"); .expect("Spark quota");
assert_eq!( assert_eq!(
( spark.local_usage_attribution,
monthly[0].local_usage_attribution, QuotaLocalUsageAttribution::Unavailable
review.local_usage_attribution,
spark.local_usage_attribution,
),
(
QuotaLocalUsageAttribution::AccountWide,
QuotaLocalUsageAttribution::Unavailable,
QuotaLocalUsageAttribution::Unavailable,
),
); );
} }
@@ -1,6 +1,7 @@
//! Messages 原生 wire、跨协议头隔离和本地计数合同 //! Messages 原生 wire、跨协议头隔离和本地计数合同
mod affinity; mod affinity;
mod translator;
use super::*; use super::*;
use gateway_core::event::ProviderResponseTimings; use gateway_core::event::ProviderResponseTimings;
@@ -0,0 +1,77 @@
//! 转换失败保留受限诊断原因,不改变发送状态或公共错误
use super::*;
use gateway_core::event::{ProtocolWireEvent, ProviderEvent};
use gateway_protocol::anthropic::TranslationError;
use std::error::Error as _;
#[tokio::test]
async fn response_translation_preserves_causes_in_both_directions() {
for (target, protocol, operation, message) in [
(
ApiKeyProtocol::Messages,
"anthropic",
generate_with_downstream_headers(),
"The Messages event type is missing.",
),
(
ApiKeyProtocol::Responses,
"openai",
messages_operation(true),
"The Responses event type is missing.",
),
] {
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
seed(&store, &server, target).await;
let mut stream = provider(&store)
.execute(
planned_request("openai", operation),
context("req_translation_cause", CancellationToken::new()),
)
.await
.unwrap();
let wire =
ProtocolWireEvent::json(protocol, None, json!({"private":"PRIVATE_INPUT"})).unwrap();
let error = stream
.translate_native_response(ProviderEvent::wire(wire), false)
.unwrap_err();
assert_eq!(error.kind(), ProviderErrorKind::Protocol);
assert_eq!(error.send_state(), UpstreamSendState::Sent);
assert_eq!(
error.source().unwrap().downcast_ref::<TranslationError>(),
Some(&TranslationError::InvalidEvent(message))
);
assert!(error.error_details().unwrap().contains(message));
assert!(!format!("{error:?} {error}").contains(message));
assert!(!error.error_details().unwrap().contains("PRIVATE_INPUT"));
}
}
#[tokio::test]
async fn request_translation_preserves_the_unsent_validation_cause() {
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
seed(&store, &server, ApiKeyProtocol::Messages).await;
let body = json!({"model":"gpt-5.4","input":"hello","tool_choice":{"type":"allowed_tools","mode":"required","tools":[]}});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let error = provider(&store)
.execute(
planned_request("openai", operation),
context("req_translation_validation", CancellationToken::new()),
)
.await
.err()
.expect("invalid allowed tools");
assert_eq!(error.kind(), ProviderErrorKind::InvalidRequest);
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
assert_eq!(
error.source().unwrap().downcast_ref::<TranslationError>(),
Some(&TranslationError::InvalidRequest(
"Allowed tools must contain at least one tool."
))
);
assert!(server.received_requests().await.unwrap().is_empty());
}
@@ -1,7 +1,7 @@
//! 隐私规则在真实 HTTP、WebSocket 和发送前拒绝边界的合同 //! 隐私规则在真实 HTTP、WebSocket 和发送前拒绝边界的合同
use super::*; use super::*;
use crate::transport::privacy::{policy, rule}; use crate::transport::privacy::{policy, rule, workspace_rule};
use gateway_core::settings::privacy::{CodexPrivacyPolicy, PrivacyAction, PrivacyScope}; use gateway_core::settings::privacy::{CodexPrivacyPolicy, PrivacyAction, PrivacyScope};
fn privacy_context(policy: &CodexPrivacyPolicy, fallback: bool) -> AttemptContext { fn privacy_context(policy: &CodexPrivacyPolicy, fallback: bool) -> AttemptContext {
@@ -96,11 +96,7 @@ fn workspace_operation(session: &str, owner: &str) -> Operation {
} }
fn workspace_policy() -> CodexPrivacyPolicy { fn workspace_policy() -> CodexPrivacyPolicy {
policy(vec![rule( policy(vec![workspace_rule("user")])
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeWorkspace,
)])
} }
fn assert_workspace_alias(header: &str, body: &Value) -> String { fn assert_workspace_alias(header: &str, body: &Value) -> String {
@@ -31,6 +31,33 @@ fn step(scope: PrivacyScope, selector: &str, action: PrivacyAction) -> PrivacySt
} }
} }
pub(crate) fn workspace_rule(username: &str) -> PrivacyRule {
let mut configured = rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeProject,
);
let mut rename = step(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::RenameKey,
);
rename.pattern = Some(r"(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])".into());
rename.replacement = format!("${{1}}{username}${{2}}");
configured.steps.push(rename);
for selector in [
"$.workspaces.*.associated_remote_urls",
"$.workspaces.*.latest_git_commit_hash",
] {
configured.steps.push(step(
PrivacyScope::TurnMetadata,
selector,
PrivacyAction::RemoveField,
));
}
configured
}
pub(crate) fn policy(rules: Vec<PrivacyRule>) -> CodexPrivacyPolicy { pub(crate) fn policy(rules: Vec<PrivacyRule>) -> CodexPrivacyPolicy {
CodexPrivacyPolicy { CodexPrivacyPolicy {
enabled: true, enabled: true,
@@ -2,41 +2,6 @@
use super::*; use super::*;
fn anonymous_rule() -> PrivacyRule {
rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeWorkspace,
)
}
fn composed_rule(username: &str) -> PrivacyRule {
let mut configured = rule(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::AnonymizeProject,
);
let mut rename = step(
PrivacyScope::TurnMetadata,
"$.workspaces",
PrivacyAction::RenameKey,
);
rename.pattern = Some(r"(?i)^((?:[a-z]:)?[/\\](?:home|users)[/\\])[^/\\]+([/\\])".into());
rename.replacement = format!("${{1}}{username}${{2}}");
configured.steps.push(rename);
for selector in [
"$.workspaces.*.associated_remote_urls",
"$.workspaces.*.latest_git_commit_hash",
] {
configured.steps.push(step(
PrivacyScope::TurnMetadata,
selector,
PrivacyAction::RemoveField,
));
}
configured
}
#[test] #[test]
fn project_anonymization_preserves_usernames_and_git_information() { fn project_anonymization_preserves_usernames_and_git_information() {
for path in [ for path in [
@@ -70,15 +35,17 @@ fn project_anonymization_preserves_usernames_and_git_information() {
} }
#[test] #[test]
fn independent_steps_preserve_combined_behavior_and_allow_customization() { fn workspace_steps_allow_customizing_username_and_retaining_remotes() {
for path in [ for path in [
"/home/alex/projects/private", "/home/alex/projects/private",
"/Users/alex/private", "/Users/alex/private",
r"C:\Users\alex\private", r"C:\Users\alex\private",
] { ] {
let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}}}); let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}}});
let mut customized = workspace_rule("blg");
customized.steps.remove(2);
let mut request = sample( let mut request = sample(
vec![anonymous_rule()], vec![customized],
json!({"client_metadata":{"x-codex-turn-metadata":metadata.to_string()}}), json!({"client_metadata":{"x-codex-turn-metadata":metadata.to_string()}}),
); );
request.turn_metadata = Some(metadata.to_string()); request.turn_metadata = Some(metadata.to_string());
@@ -88,16 +55,6 @@ fn independent_steps_preserve_combined_behavior_and_allow_customization() {
request request
.headers .headers
.insert("x-codex-turn-metadata".into(), vec![metadata.to_string()]); .insert("x-codex-turn-metadata".into(), vec![metadata.to_string()]);
let combined = preview(request.clone()).unwrap();
request.policy.rules = vec![composed_rule("user")];
let composed = preview(request.clone()).unwrap();
assert_eq!(composed.body, combined.body);
assert_eq!(composed.headers, combined.headers);
assert_eq!(composed.turn_metadata, combined.turn_metadata);
let mut customized = composed_rule("blg");
customized.steps.remove(2);
request.policy.rules = vec![customized];
let output = preview(request).unwrap(); let output = preview(request).unwrap();
let value: Value = serde_json::from_str(output.turn_metadata.as_deref().unwrap()).unwrap(); let value: Value = serde_json::from_str(output.turn_metadata.as_deref().unwrap()).unwrap();
let (alias, workspace) = value["workspaces"] let (alias, workspace) = value["workspaces"]
@@ -138,7 +95,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}},"request_kind":"turn"}); let metadata = json!({"workspaces":{path:{"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true}},"request_kind":"turn"});
let original_input = json!([{"role":"user","content":format!("<cwd>{path}</cwd>")}]); let original_input = json!([{"role":"user","content":format!("<cwd>{path}</cwd>")}]);
let mut request = sample( let mut request = sample(
vec![anonymous_rule()], vec![workspace_rule("user")],
json!({ json!({
"input":original_input, "input":original_input,
"turnMetadata":metadata, "turnMetadata":metadata,
@@ -207,7 +164,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
{ {
assert_eq!(serde_json::from_str::<Value>(raw).unwrap(), expected); assert_eq!(serde_json::from_str::<Value>(raw).unwrap(), expected);
} }
assert_eq!(result.outcomes[0].matches, 7); assert_eq!(result.outcomes[0].matches, 28);
assert_eq!(preview(request.clone()).unwrap().body, result.body); assert_eq!(preview(request.clone()).unwrap().body, result.body);
request request
.headers .headers
@@ -223,7 +180,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
fn long_workspace_names_produce_valid_directory_components() { fn long_workspace_names_produce_valid_directory_components() {
let path = format!("/workspace/{}", "工程".repeat(40)); let path = format!("/workspace/{}", "工程".repeat(40));
let mut request = sample( let mut request = sample(
vec![anonymous_rule()], vec![workspace_rule("user")],
json!({"turn_metadata":{"workspaces":{path:{}}}}), json!({"turn_metadata":{"workspaces":{path:{}}}}),
); );
request request
@@ -243,7 +200,7 @@ fn long_workspace_names_produce_valid_directory_components() {
#[test] #[test]
fn multiple_workspaces_remain_stable_as_the_workspace_set_grows() { fn multiple_workspaces_remain_stable_as_the_workspace_set_grows() {
let compiled = compile(&policy(vec![anonymous_rule()])).unwrap(); let compiled = compile(&policy(vec![workspace_rule("user")])).unwrap();
let transform = |scope, count| { let transform = |scope, count| {
let mut entries = serde_json::Map::new(); let mut entries = serde_json::Map::new();
for n in 0..count { for n in 0..count {
@@ -281,7 +238,7 @@ fn multiple_workspaces_remain_stable_as_the_workspace_set_grows() {
fn workspace_failure_rolls_back_every_copy_and_respects_policy() { fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
let original = json!({"turn_metadata":{"workspaces":{"/Users/alex/projects/private":{"latest_git_commit_hash":"abc"}}}}); let original = json!({"turn_metadata":{"workspaces":{"/Users/alex/projects/private":{"latest_git_commit_hash":"abc"}}}});
for (scope, invalid_header) in [(None, false), (Some("session"), true)] { for (scope, invalid_header) in [(None, false), (Some("session"), true)] {
let mut config = policy(vec![anonymous_rule()]); let mut config = policy(vec![workspace_rule("user")]);
config.on_error = PrivacyFailureMode::SkipRule; config.on_error = PrivacyFailureMode::SkipRule;
let mut body = original.clone(); let mut body = original.clone();
let mut headers = reqwest::header::HeaderMap::new(); let mut headers = reqwest::header::HeaderMap::new();
@@ -308,7 +265,7 @@ fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
); );
} }
assert!( assert!(
preview(sample(vec![anonymous_rule()], json!({}))) preview(sample(vec![workspace_rule("user")], json!({})))
.unwrap() .unwrap()
.outcomes[0] .outcomes[0]
.matches .matches
+26 -12
View File
@@ -250,6 +250,8 @@ Messages 与 Responses 的转换边界见 [Messages 请求](#messages-请求),
客户端用 `Authorization: Bearer <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。 客户端用 `Authorization: Bearer <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。
上游目录声明的模型分组支持使用基础模型名,并通过 `generationConfig.thinkingConfig.thinkingLevel` 指定档位,例如 `gemini-4-hydrogen` 配合 `MEDIUM`。网关只选择该账号目录明确列出的分组成员,账号和分组模型限制按最终型号校验;目录中至少有一个可访问档位时才显示基础模型名。缺少或不支持的档位返回 400,显式完整型号及指向完整型号的模型映射保持原目标。分组能力随上游目录刷新,旧缓存未包含分组时仍只提供完整型号
| 方法 | 路径 | 交付 | | 方法 | 路径 | 交付 |
| --- | --- | --- | | --- | --- | --- |
| POST | `/v1beta/models/{model}:generateContent` | 原生 JSON | | POST | `/v1beta/models/{model}:generateContent` | 原生 JSON |
@@ -258,7 +260,7 @@ Messages 与 Responses 的转换边界见 [Messages 请求](#messages-请求),
| GET | `/v1beta/models`、`/v1beta/models/{model}` | Gemini 格式的模型列表与详情,见[模型目录](#模型目录) | | GET | `/v1beta/models`、`/v1beta/models/{model}` | Gemini 格式的模型列表与详情,见[模型目录](#模型目录) |
| POST | `/v1beta:{method}`(客户端后台指标) | 验证 Key 后返回 `{}`,不启动模型请求 | | 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) CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选账号与冻结画像生成。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters)
@@ -270,7 +272,13 @@ CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保
AGY 上游计数与生成响应的 `usageMetadata.promptTokenCount` 口径不完全一致:系统提示、工具定义及工具结果未完整计入计数返回值。原生与 Messages 计数均保留这一上游口径,不能作为完整上下文占用或计费用量的精确值 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 转向 GenAI 时,输出上限、采样参数和 JSON Schema 直接映射;`max_output_tokens` 省略或为 `null` 时不补写输出上限。`reasoning.effort` 显式映射为推理预算,`none` 关闭推理,`auto` 使用动态预算,未指定时保留上游默认。生成参数不受 Messages 的默认输出上限、强制工具或无思考续轮规则影响,也不因推理设置省略采样参数;具体型号支持的预算与参数组合由上游校验
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` 续接 工具多轮调用须带回完整助手输出。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` 续接
@@ -422,7 +430,7 @@ Responses 的 `allowed_tools` 只向 Messages 上游声明本轮允许的工具
强制工具与手动推理冲突时显式关闭推理;紧接着只回传工具结果且未指定 effort 时,沿用无思考模式。 强制工具与手动推理冲突时显式关闭推理;紧接着只回传工具结果且未指定 effort 时,沿用无思考模式。
adaptive 路径将普通强制选择降为 `auto`,保留串行约束。 adaptive 路径将普通强制选择降为 `auto`,保留串行约束。
仅设置 `parallel_tool_calls:false` 也会生成串行工具选择,`none` 不携带并行选项。 仅设置 `parallel_tool_calls:false` 也会生成串行工具选择,`none` 不携带并行选项。
生成启用推理的配置时省略不相容的 `temperature/top_p`,同协议不执行这些转换 转向 Messages 并启用推理时省略不相容的 `temperature/top_p`,同协议不执行这些转换
服务档位按目标协议映射:Responses `default` 对应 Messages `standard_only`,`auto` 保留,无法对应的档位省略。 服务档位按目标协议映射:Responses `default` 对应 Messages `standard_only`,`auto` 保留,无法对应的档位省略。
按 CPA 将 Responses `priority` 与 Messages `speed:fast` 双向映射;这两个字段不代表相同的服务承诺。 按 CPA 将 Responses `priority` 与 Messages `speed:fast` 双向映射;这两个字段不代表相同的服务承诺。
@@ -761,6 +769,14 @@ API Key 上游返回完整 Codex `models` 目录时沿用该合同;仅返回
xAI 没有 Codex 原生目录,使用官方 CLI proxy 当前目录生成通用画像。推理菜单读取 xAI 没有 Codex 原生目录,使用官方 CLI proxy 当前目录生成通用画像。推理菜单读取
`reasoning_efforts` 对象列表,默认值只取菜单中的显式标记;缺失时保持未知 `reasoning_efforts` 对象列表,默认值只取菜单中的显式标记;缺失时保持未知
Antigravity 在 Codex 目录中按上游声明的分组展示基础模型。思考菜单只列出当前 Key 可调用的成员档位,
默认选中 `medium`,不可用时选首个可用档位。例如对 `gemini-4-hydrogen` 发送 `reasoning.effort: "high"`,
会路由到 `gemini-4-hydrogen-high`。普通模型列表仍提供可直接调用的完整型号
分组中的可用档位和账号都支持图片时,Codex 可发送图片。网关取可用成员中最小的 `maxTokens` 作为该组的默认上下文窗口和可覆盖上限,
有成员未声明时保持未知。成员说明一致时,选模列表显示上游用途说明或下线提示。
显式请求的输出 Token 数按实际型号和账号的 `maxOutputTokens` 选路,未声明上限的账号交由上游校验
已知模型只路由到明确提供该模型的 Provider,账号不可用时不转发给其他平台的未知模型通道。 已知模型只路由到明确提供该模型的 Provider,账号不可用时不转发给其他平台的未知模型通道。
未知模型只在当前范围与路由约束下存在唯一 Provider 透传候选时发送;无法确定归属时返回不可用错误, 未知模型只在当前范围与路由约束下存在唯一 Provider 透传候选时发送;无法确定归属时返回不可用错误,
可通过 Client Key 分组限定目标平台。Provider 在选号时检查账号模型政策与目录资格, 可通过 Client Key 分组限定目标平台。Provider 在选号时检查账号模型政策与目录资格,
@@ -772,7 +788,7 @@ OpenAI 聚合当前 Key 范围内合格 OAuth 和 API Key 账号的目录。每
后台刷新失败或超时保留该账号最后成功的结果。当前范围没有任何可用的已知目录时返回 `503 model_catalog_unavailable`。 后台刷新失败或超时保留该账号最后成功的结果。当前范围没有任何可用的已知目录时返回 `503 model_catalog_unavailable`。
成功读取但全部条目被账号政策过滤时返回空列表。 成功读取但全部条目被账号政策过滤时返回空列表。
目录保留完整的原生 Codex 模型对象。对于 OpenAI API Key 普通模型列表和 xAI 目录生成的通用画像, 目录保留完整的原生 Codex 模型对象。对于 Provider 生成的通用画像,
当前 Key 可访问的适配器若声明了同名模型,其画像在原位置替换通用画像。仅由插件提供的可见模型按声明顺序追加到所属 Provider 的条目之后 当前 Key 可访问的适配器若声明了同名模型,其画像在原位置替换通用画像。仅由插件提供的可见模型按声明顺序追加到所属 Provider 的条目之后
服务启动时批量恢复账号目录;目录读取只检查本地账号资格和 Client Key 范围,不等待上游查询。 服务启动时批量恢复账号目录;目录读取只检查本地账号资格和 Client Key 范围,不等待上游查询。
@@ -1723,8 +1739,9 @@ Messages API Key 账号支持生成与输入计数,通过协议转换承接 Re
互联账号按上游 Key 已提供的最长消费窗口统计本机 Token、费用和模型用量。 互联账号按上游 Key 已提供的最长消费窗口统计本机 Token、费用和模型用量。
日、周周期的 `usage.windowKind` 分别为 `daily`、`weekly`,其他周期为 `quota`。查询边界同账号额度窗口,为 `[resetAt - windowSeconds, resetAt)`; 日、周周期的 `usage.windowKind` 分别为 `daily`、`weekly`,其他周期为 `quota`。查询边界同账号额度窗口,为 `[resetAt - windowSeconds, resetAt)`;
未开启或缺少重置边界时显示无数据,不回退到历史累计,也不采用池内其他账号的周期。 未开启或缺少重置边界时显示无数据,不回退到历史累计,也不采用池内其他账号的周期。
OAuth 账号优先按可归属整个账号的实际周/月额度窗口统计,缺少可归属窗口时使用过去 24 小时的本地请求统计 OAuth 账号优先按可归属整个账号的实际周/月额度窗口统计,缺少可归属窗口时使用 Provider 声明的本地统计范围。
此时 `usage.windowKind` 为 `daily`,Token 与模型用量共用该范围,上游额度快照缺失时仍可展示本地统计 Antigravity 按部署时区汇总今天及前 6 天,`usage.windowKind` 为 `recent_week`,管理端显示“近一周”;其他 Provider 默认使用过去 24 小时,返回 `daily`。
Token 与模型用量共用该范围,上游额度快照缺失时仍可展示本地统计;账号请求小时图仍独立展示最近 24 个 UTC 小时桶
批量导入 AT / RT 使用 `accounts` JSON 数组,最多 200 项,不接受纯文本 token 列表。例如: 批量导入 AT / RT 使用 `accounts` JSON 数组,最多 200 项,不接受纯文本 token 列表。例如:
@@ -1864,7 +1881,7 @@ Google 授权后,将浏览器中的完整 `http://localhost:8085/auth/callback
Antigravity 主动额度刷新同时读取套餐与上游模型组额度,优先采用明确的付费套餐。`g1-pro-tier`、`g1-ultra-tier` 分别显示为 `Google AI Pro`、`Google AI Ultra`,缺少套餐不推断为免费账号 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 秒 OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上游请求总超时为 60 秒
@@ -1937,8 +1954,7 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
- OAuth 账号详情的 Token 统计、模型排行和列表 Token 汇总优先使用账号级周额度窗口,无可统计的周窗口时 - OAuth 账号详情的 Token 统计、模型排行和列表 Token 汇总优先使用账号级周额度窗口,无可统计的周窗口时
使用月额度窗口;`usage.windowKind` 随选中的窗口返回 `weekly` 或 `monthly`。查询边界 使用月额度窗口;`usage.windowKind` 随选中的窗口返回 `weekly` 或 `monthly`。查询边界
严格为 `[resetAt - windowSeconds, resetAt)`,不是自然周/月或最近 7/30 天;额度刷新若返回了更早的 严格为 `[resetAt - windowSeconds, resetAt)`,不是自然周/月或最近 7/30 天;额度刷新若返回了更早的
重置时间,会按新边界重新聚合。没有边界完整、可归属到账号的周/月窗口时显示无数据,`usage.windowKind` 为 `quota` 重置时间,会按新边界重新聚合。没有可归属整号的额度窗口时,按上述 Provider 本地统计范围展示,不能把模型分组额度归为整号用量。
(周/月额度窗口),不回退到 5 小时、日窗口或历史累计。
金额原值保持完整精度,USD 展示值 金额原值保持完整精度,USD 展示值
小于 1 美元时最多保留四位小数,其余最多保留两位,小数末尾不补零。 小于 1 美元时最多保留四位小数,其余最多保留两位,小数末尾不补零。
额度百分比展示最多保留一位小数,小数末尾不补零;数值为零时返回 `0%` 额度百分比展示最多保留一位小数,小数末尾不补零;数值为零时返回 `0%`
@@ -2294,7 +2310,7 @@ xAI 由本地账号/模型冷却、无可选账号、并发容量不足及选号
默认队列满返回 `429` / `concurrency_queue_full`,排队超时返回 `429` / `concurrency_queue_timeout`; 默认队列满返回 `429` / `concurrency_queue_full`,排队超时返回 `429` / `concurrency_queue_timeout`;
WebSocket 使用对应错误事件。等待期间不发送上游请求,取消后释放等待位置,排队重查不重复计入 RPM。 WebSocket 使用对应错误事件。等待期间不发送上游请求,取消后释放等待位置,排队重查不重复计入 RPM。
SSE 在 Key 准入完成并取得执行会话前不发送保活帧,此阶段保留 HTTP 错误状态; SSE 在 Key 准入完成并取得执行会话前不发送保活帧,此阶段保留 HTTP 错误状态;
取得会话后的账号等待受 SSE 保活覆盖,已开始交付的失败沿用流内错误合同 Responses、Chat Completions 和 Messages 在取得会话后为账号等待发送心跳,已开始交付的失败沿用各入口的流内错误合同
任一周期的已落库金额与当前进程已接管的待结算费用合计达到限额后拒绝新请求,已准入请求可完成并使金额超过阈值。 任一周期的已落库金额与当前进程已接管的待结算费用合计达到限额后拒绝新请求,已准入请求可完成并使金额超过阈值。
HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly_budget_exceeded`, HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly_budget_exceeded`,
@@ -2459,8 +2475,6 @@ UA、平台参数及自动 Git 上下文版本由 [OpenAI 上游客户端身份]
换账号、新会话或更换工作区重新派生化名,切回原账号和原会话恢复对应化名,不保存路径映射表。正常令牌续期与代理出口变化不重置化名。 换账号、新会话或更换工作区重新派生化名,切回原账号和原会话恢复对应化名,不保存路径映射表。正常令牌续期与代理出口变化不重置化名。
默认组合移除 Git 远端与提交信息,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径 默认组合移除 Git 远端与提交信息,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
已保存的 `anonymize_workspace` 组合动作继续替换用户名、生成项目化名并删除 Git 信息。管理端编辑时将其展开为四个独立步骤,应用草稿并保存后生效;展开后的步骤仍计入总上限
工作区必须是绝对路径,映射值必须是对象。缺少稳定会话身份、路径无效或化名冲突时按策略失败模式处理,不随机补造会话。 工作区必须是绝对路径,映射值必须是对象。缺少稳定会话身份、路径无效或化名冲突时按策略失败模式处理,不随机补造会话。
预览从样本请求头或正文识别会话,可在样本的 `headers` 中填写 `"session-id": ["example-session"]`;预览只使用样本身份,实际出站另外按 Client Key 和选定账号隔离 预览从样本请求头或正文识别会话,可在样本的 `headers` 中填写 `"session-id": ["example-session"]`;预览只使用样本身份,实际出站另外按 Client Key 和选定账号隔离
+7 -2
View File
@@ -512,6 +512,8 @@ Messages 与 Responses 的映射、忽略和降级规则参考 CPA,
同语义字段交给目标上游校验;结构解码或必要流状态失败按协议错误终结,不补造成功结果。 同语义字段交给目标上游校验;结构解码或必要流状态失败按协议错误终结,不补造成功结果。
字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt) 字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
Responses 搜索的强制执行判定、声明选择与联网模式解析由 `gateway-protocol::openai::web_search` 统一提供。Core 用其判定路由,协议转换复用声明解析,Provider 负责账号可用的搜索模型和目标上游支持的选项。需要独立搜索转换时必须对应唯一声明,缺失或歧义按请求错误处理,不退回普通生成
Images 与 standalone Search 是 OpenAI Provider 自有端点:两者都不参与文本模型映射,只在 Client Key Images 与 standalone Search 是 OpenAI Provider 自有端点:两者都不参与文本模型映射,只在 Client Key
的账号范围确实包含 Codex 账号时生成单一 OpenAI 候选。Images 的图片模型由 Provider 从正文旁路 的账号范围确实包含 Codex 账号时生成单一 OpenAI 候选。Images 的图片模型由 Provider 从正文旁路
提取,用于账号模型政策检查,并在中间件改写后复验当前租约账号;不要求图片模型进入文本目录。 提取,用于账号模型政策检查,并在中间件改写后复验当前租约账号;不要求图片模型进入文本目录。
@@ -578,7 +580,7 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模
GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范围;列表、详情和执行使用同一份能力事实。Antigravity 声明生成与输入计数能力,原生 GenAI 和 Messages 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算 GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范围;列表、详情和执行使用同一份能力事实。Antigravity 声明生成与输入计数能力,原生 GenAI 和 Messages 计数复用选号、画像、中间件及资源释放流程,出站调用独立的 Cloud Code `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
Antigravity 目录分别声明原生 GenAI 协议和接受转换的 Responses/Messages 协议;原生能力约束仍只匹配原生协议。`gateway-protocol::genai` 持有纯内容与增量事件映射,Responses 复用已有 Messages 转换能力,Chat 复用 API 层的 Responses 入口。Provider 的 `provider/translation` 负责选择和装配转换器,`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,并按冻结画像统一替换 AGY 系统指令。默认提示和可编辑配置归 Provider 的 `profile`,纯协议转换层不持有 AGY 身份规则 Antigravity 目录分别声明原生 GenAI 协议和接受转换的 Responses/Messages 协议;原生能力约束仍只匹配原生协议。`gateway-protocol::genai` 持有纯内容与增量事件映射,Responses 复用 Messages 的内容与工具映射,生成参数直接映射到 GenAI,不继承 Messages 的默认值与模型限制;Chat 复用 API 层的 Responses 入口。Provider 的 `provider/translation` 负责选择和装配转换器,`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,并按冻结画像统一替换 AGY 系统指令。默认提示和可编辑配置归 Provider 的 `profile`,纯协议转换层不持有 AGY 身份规则
Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属 Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属
@@ -715,6 +717,8 @@ Core 按映射后的模型冻结 Provider 归属:已知模型只在明确声
未被任何目录识别的模型只有一个 Provider 透传候选时才交由上游验证,多个未知候选不按名称顺序猜选平台。 未被任何目录识别的模型只有一个 Provider 透传候选时才交由上游验证,多个未知候选不按名称顺序猜选平台。
OpenAI Provider 在选号时排除 Grok 模型的 ChatGPT OAuth 账号,API Key 兼容上游仍可透传 OpenAI Provider 在选号时排除 Grok 模型的 ChatGPT OAuth 账号,API Key 兼容上游仍可透传
Provider 可从上游目录声明模型分组的推理档位、目标型号和来源账号。Core 使用协议层提取的显式档位解析目标,再按目标型号收窄账号范围并检查权限;目录展示复用成员的授权事实,不从模型前缀推测分组或默认档位。Antigravity 保存上游分组声明,完整型号不参与分组改写
账号选择综合启停状态、credential/quota 事实、Redis cooldown、并发上限、权重和会话亲和。 账号选择综合启停状态、credential/quota 事实、Redis cooldown、并发上限、权重和会话亲和。
默认账号并发上限为 `0` 时表示无限;账号独立正数上限仍优先,未设置则继承默认值。 默认账号并发上限为 `0` 时表示无限;账号独立正数上限仍优先,未设置则继承默认值。
无限并发只跳过并发上限判断,保留在途租约计数及其他准入约束;含无限账号的容量不投影有限占用比例。 无限并发只跳过并发上限判断,保留在途租约计数及其他准入约束;含无限账号的容量不投影有限占用比例。
@@ -1086,7 +1090,8 @@ OpenAI、xAI、Antigravity 的认证及账号后台操作由各 Provider 通过
- Antigravity 使用 Google OAuth 离线授权,账号文件导出凭据、身份、有效期及已有观测,导入通过 refresh token 重新验证权限与主体,不采信文件中的历史观测。 - Antigravity 使用 Google OAuth 离线授权,账号文件导出凭据、身份、有效期及已有观测,导入通过 refresh token 重新验证权限与主体,不采信文件中的历史观测。
OAuth 每轮操作从运行策略读取全局 AGY 选择,由 `profile` 统一解析并冻结出站身份,换码、刷新和身份查询使用同一画像,不读取 Key 覆盖。 OAuth 每轮操作从运行策略读取全局 AGY 选择,由 `profile` 统一解析并冻结出站身份,换码、刷新和身份查询使用同一画像,不读取 Key 覆盖。
`loadCodeAssist` 的付费套餐优先于基础套餐;分组额度和模型额度保存到同一带凭据版本的快照,独立模型耗尽不升级为整个账号耗尽。 `loadCodeAssist` 的付费套餐优先于基础套餐;分组额度和模型额度保存到同一带凭据版本的快照,独立模型耗尽不升级为整个账号耗尽。
原生额度窗口只投影上游模型分组,不归属整号 Token;Admin 独立读取过去 24 小时的本地用量及统计周期,不向额度列表补入本地窗口。选号及互联分别读取同一份模型额度事实,失效观测保持未知。 Provider 在额度观测中保存与同次模型目录核对的分组成员 ID。Admin 按模型和窗口边界汇总本地 Token,账号用量另按部署时区今天及前 6 天统计,展示为“近一周”。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
账号列表和展开的额度面板读取已保存的快照,点击“刷新额度”时立即查询上游。后台补齐启用账号缺失或凭据版本失效的快照。健康账号仅在距上次观测已满 5 分钟、且有生成请求在该次观测后成功完成时补查。整号耗尽按重置时间复查,缺少重置时间时在耗尽观测满 5 分钟后复查
正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试 正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试
- 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后, - 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后,
由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。 由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。
+1 -1
View File
@@ -100,7 +100,7 @@ export interface AccountModelUsage {
} }
export interface AccountUsage { export interface AccountUsage {
windowKind: 'general' | 'daily' | 'weekly' | 'monthly' | 'quota' windowKind: 'general' | 'daily' | 'recent_week' | 'weekly' | 'monthly' | 'quota'
requestCount: number | null requestCount: number | null
requestCountDisplay: string requestCountDisplay: string
inputTokens: number | null inputTokens: number | null
+1 -1
View File
@@ -2,7 +2,7 @@ import type { RequestOptions } from '../../request'
import request from '../../request' import request from '../../request'
export type PrivacyScope = 'turn_metadata' | 'desktop_git_context' | 'environment_text' | 'request_body' | 'request_header' export type PrivacyScope = 'turn_metadata' | 'desktop_git_context' | 'environment_text' | 'request_body' | 'request_header'
export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_project' | 'anonymize_workspace' export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_project'
export type JsonValue = unknown export type JsonValue = unknown
export interface PrivacyRule { export interface PrivacyRule {
@@ -246,8 +246,12 @@ export function quotaWindowDetails(window: AccountQuotaWindow) {
const localUsage = accountLocalUsage(window.localUsage) const localUsage = accountLocalUsage(window.localUsage)
const tokenDisplay = localTokenDisplay(localUsage) || null const tokenDisplay = localTokenDisplay(localUsage) || null
const amountDisplay = window.amount?.usedDisplay ?? null const amountDisplay = window.amount?.usedDisplay ?? null
const hasConsumption = Boolean(tokenDisplay || amountDisplay) const showZeroTokens = !window.amount && localUsage?.totalTokens === 0
|| (!window.amount && localUsage?.totalTokens == null) const consumptionTokens = showZeroTokens ? '0' : tokenDisplay
const consumption = [
amountDisplay,
consumptionTokens && `${consumptionTokens} ${t('common.units.tokens')}`,
].filter(Boolean).join(' · ')
return { return {
stale: window.stale, stale: window.stale,
observationDisplay: [ observationDisplay: [
@@ -263,14 +267,7 @@ export function quotaWindowDetails(window: AccountQuotaWindow) {
quotaValueDisplay: window.amount && window.usedPercent === null quotaValueDisplay: window.amount && window.usedPercent === null
? window.amount.totalDisplay ? window.amount.totalDisplay
: window.usedPercentDisplay, : window.usedPercentDisplay,
consumptionDisplay: hasConsumption consumptionDisplay: consumption || (window.amount ? null : '—'),
? [
amountDisplay,
tokenDisplay || (!window.amount && localUsage?.totalTokens == null
? '—'
: null),
].filter(Boolean).join(' · ')
: null,
resetAtDisplay: window.amount && window.resetAtDisplay === '—' resetAtDisplay: window.amount && window.resetAtDisplay === '—'
? t('accounts.upstream.startsOnNextUse') ? t('accounts.upstream.startsOnNextUse')
: window.resetAtDisplay, : window.resetAtDisplay,
@@ -10,7 +10,7 @@ export const usageDataColumns = computed(() => ([
key: 'model', key: 'model',
label: t('usage.fields.model'), label: t('usage.fields.model'),
kind: 'custom', kind: 'custom',
size: 'xl', size: '2xl',
}, },
{ {
key: 'reasoningEffort', key: 'reasoningEffort',
@@ -22,7 +22,7 @@ export const usageDataColumns = computed(() => ([
key: 'route', key: 'route',
label: t('usage.fields.endpoint'), label: t('usage.fields.endpoint'),
kind: 'mono', kind: 'mono',
minWidth: 224, width: 208,
}, },
{ {
key: 'transport', key: 'transport',
@@ -332,6 +332,7 @@
"noModelUsageYet": "No model usage yet", "noModelUsageYet": "No model usage yet",
"windows": { "windows": {
"daily": "Daily usage", "daily": "Daily usage",
"recentWeek": "Last 7 days",
"general": "Total usage", "general": "Total usage",
"weekly": "Weekly usage", "weekly": "Weekly usage",
"monthly": "Monthly usage", "monthly": "Monthly usage",
@@ -332,6 +332,7 @@
"noModelUsageYet": "暂无模型用量", "noModelUsageYet": "暂无模型用量",
"windows": { "windows": {
"daily": "日用量", "daily": "日用量",
"recentWeek": "近一周",
"general": "累计用量", "general": "累计用量",
"weekly": "周用量", "weekly": "周用量",
"monthly": "月用量", "monthly": "月用量",
@@ -332,6 +332,7 @@
"noModelUsageYet": "暫無模型用量", "noModelUsageYet": "暫無模型用量",
"windows": { "windows": {
"daily": "日用量", "daily": "日用量",
"recentWeek": "近一週",
"general": "累計用量", "general": "累計用量",
"weekly": "周用量", "weekly": "周用量",
"monthly": "月用量", "monthly": "月用量",
@@ -26,7 +26,7 @@ const modelUsageColumns = computed(() => (defineTableColumns<AccountModelUsage>(
key: 'model', key: 'model',
label: t('accounts.concurrency.model'), label: t('accounts.concurrency.model'),
kind: 'text', kind: 'text',
size: 'md', size: 'xl',
}, },
{ {
key: 'requestCountDisplay', key: 'requestCountDisplay',
@@ -74,7 +74,8 @@ const modelUsageColumns = computed(() => (defineTableColumns<AccountModelUsage>(
key: 'lastUsedAt', key: 'lastUsedAt',
label: t('accounts.fields.lastUsed'), label: t('accounts.fields.lastUsed'),
kind: 'datetime', kind: 'datetime',
size: 'md', size: 'sm',
fixedWidth: true,
align: 'right', align: 'right',
}, },
]))) ])))
+1
View File
@@ -14,6 +14,7 @@ export interface AccountQuotaWindowEntry {
export const usageWindowLabels = computed<Record<AccountUsage['windowKind'], string>>(() => ({ export const usageWindowLabels = computed<Record<AccountUsage['windowKind'], string>>(() => ({
general: t('accounts.usage.windows.general'), general: t('accounts.usage.windows.general'),
daily: t('accounts.usage.windows.daily'), daily: t('accounts.usage.windows.daily'),
recent_week: t('accounts.usage.windows.recentWeek'),
weekly: t('accounts.usage.windows.weekly'), weekly: t('accounts.usage.windows.weekly'),
monthly: t('accounts.usage.windows.monthly'), monthly: t('accounts.usage.windows.monthly'),
quota: t('accounts.usage.windows.quota'), quota: t('accounts.usage.windows.quota'),
@@ -6,7 +6,7 @@ import { Play } from '@lucide/vue'
import { cloneDeep } from 'es-toolkit' import { cloneDeep } from 'es-toolkit'
import { computed, ref, shallowRef, watch } from 'vue' import { computed, ref, shallowRef, watch } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { exampleRequest, expandWorkspaceSteps, newRule, newStep } from './presets' import { exampleRequest, newRule, newStep } from './presets'
import StepFields from './StepFields.vue' import StepFields from './StepFields.vue'
import StepList from './StepList.vue' import StepList from './StepList.vue'
import { usePrivacyPreview } from './usePrivacyPreview' import { usePrivacyPreview } from './usePrivacyPreview'
@@ -46,7 +46,6 @@ watch(open, (value) => {
if (value) { if (value) {
selectedIndex.value = 0 selectedIndex.value = 0
draft.value = cloneDeep(props.rule ?? newRule()) draft.value = cloneDeep(props.rule ?? newRule())
draft.value.steps = expandWorkspaceSteps(draft.value.steps)
fixedValues.value = draft.value.steps.map(step => JSON.stringify(step.value)) fixedValues.value = draft.value.steps.map(step => JSON.stringify(step.value))
sample.value = JSON.stringify(exampleRequest(), null, 2) sample.value = JSON.stringify(exampleRequest(), null, 2)
} }
@@ -109,7 +109,7 @@ const columns = computed(() => (defineTableColumns<PrivacyRule>([
key: 'action', key: 'action',
label: t('settings.privacy.rules.processingMethod'), label: t('settings.privacy.rules.processingMethod'),
kind: 'meta', kind: 'meta',
size: 'md', size: '2xl',
}, },
{ {
key: 'actions', key: 'actions',
@@ -145,7 +145,7 @@ const columns = computed(() => (defineTableColumns<PrivacyRule>([
{{ [...new Set(row.steps.map(step => scopes.find(item => item.value === step.scope)?.label))].join('、') }} {{ [...new Set(row.steps.map(step => scopes.find(item => item.value === step.scope)?.label))].join('、') }}
</template> </template>
<template #action="{ row }"> <template #action="{ row }">
{{ [...new Set(row.steps.map(step => step.action === 'anonymize_workspace' ? t('settings.privacy.presets.anonymizeWorkspace') : actions.find(item => item.value === step.action)?.label))].join('、') }} {{ [...new Set(row.steps.map(step => actions.find(item => item.value === step.action)?.label))].join('、') }}
</template> </template>
<template #actions="{ row }"> <template #actions="{ row }">
<div class="flex items-center justify-end gap-1"> <div class="flex items-center justify-end gap-1">

Some files were not shown because too many files have changed in this diff Show More