mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-25 16:01:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
add1f9f40f | ||
|
|
080d3867f1 | ||
|
|
0bf3c8daaf | ||
|
|
9d3d7ef223 | ||
|
|
c843a4d380 |
@@ -828,12 +828,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 所需的公共请求事实
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -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 {
|
|||||||
"a,
|
"a,
|
||||||
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 {
|
|||||||
"a,
|
"a,
|
||||||
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(
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ 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::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,
|
||||||
|
|||||||
@@ -920,6 +920,40 @@ 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅提取本次正文明确声明的推理档位,路由不继承 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,13 @@ 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>,
|
||||||
|
}
|
||||||
|
|
||||||
/// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
|
/// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ContributedModelAlias {
|
pub struct ContributedModelAlias {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ pub use crate::identity::ProviderKind;
|
|||||||
pub use catalog::{
|
pub use catalog::{
|
||||||
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort,
|
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort,
|
||||||
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent,
|
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent,
|
||||||
ProviderModelDescriptor, PublicModelDescriptor,
|
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,7 @@ 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Provider 为客户端模型目录提供的展示与交互能力
|
/// Provider 为客户端模型目录提供的展示与交互能力
|
||||||
@@ -427,6 +434,7 @@ 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(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -436,6 +444,21 @@ 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
|
||||||
|
}
|
||||||
|
|
||||||
/// 将请求形态 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 +488,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()
|
||||||
|
|||||||
@@ -1078,6 +1078,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()
|
||||||
}
|
}
|
||||||
@@ -1172,6 +1201,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 +1273,25 @@ 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 {
|
||||||
|
variant.accounts.iter().any(|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 +1299,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 +1522,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 +1543,8 @@ 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;
|
||||||
for provider in &providers {
|
for provider in &providers {
|
||||||
if !self.providers.contains(provider) {
|
if !self.providers.contains(provider) {
|
||||||
continue;
|
continue;
|
||||||
@@ -1495,23 +1564,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 +1626,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 +1657,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 +1677,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()) {
|
||||||
@@ -1607,6 +1702,12 @@ impl RuntimeSnapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if candidates.is_empty() {
|
if candidates.is_empty() {
|
||||||
|
if group_model_denied {
|
||||||
|
return Err(RoutingError::GroupModelDenied);
|
||||||
|
}
|
||||||
|
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)]
|
||||||
|
|||||||
@@ -81,6 +81,9 @@ 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("duplicate {entity} `{id}`")]
|
#[error("duplicate {entity} `{id}`")]
|
||||||
DuplicateEntity {
|
DuplicateEntity {
|
||||||
|
|||||||
@@ -26,6 +26,270 @@ 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::{
|
||||||
|
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 group = gateway_core::routing::AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||||
|
let scope = Arc::new(FrozenAccountScope::new(
|
||||||
|
Arc::new(
|
||||||
|
RuntimeAccountDirectory::new(BTreeMap::from_iter(
|
||||||
|
[declared.clone(), other.clone()].into_iter().map(|id| {
|
||||||
|
(
|
||||||
|
id,
|
||||||
|
RuntimeAccount::new(provider.clone(), BTreeSet::from([group.clone()])),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
))
|
||||||
|
.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_upstream_feature_validation()
|
||||||
|
};
|
||||||
|
let variants = BTreeMap::from_iter(["medium", "high"].map(|level| {
|
||||||
|
(
|
||||||
|
level.into(),
|
||||||
|
ReasoningModelVariant {
|
||||||
|
model: UpstreamModelId::new(format!("family-{level}")).unwrap(),
|
||||||
|
accounts: BTreeSet::from([declared.clone()]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
let snapshot = RuntimeSnapshot::new(
|
||||||
|
revision(1),
|
||||||
|
SettingsValues::new(
|
||||||
|
2,
|
||||||
|
"smart",
|
||||||
|
BTreeMap::from([("alias".into(), "family".into())]),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
vec![provider.clone()],
|
||||||
|
vec![
|
||||||
|
ProviderModel::new(
|
||||||
|
provider.clone(),
|
||||||
|
UpstreamModelId::new("family").unwrap(),
|
||||||
|
caps().with_reasoning_variants(variants),
|
||||||
|
),
|
||||||
|
ProviderModel::new(
|
||||||
|
provider.clone(),
|
||||||
|
UpstreamModelId::new("family-medium").unwrap(),
|
||||||
|
caps(),
|
||||||
|
),
|
||||||
|
ProviderModel::new(
|
||||||
|
provider.clone(),
|
||||||
|
UpstreamModelId::new("family-high").unwrap(),
|
||||||
|
caps(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
vec![],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
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();
|
||||||
|
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
|
||||||
|
.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)]
|
||||||
|
|||||||
@@ -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(
|
||||||
|
|||||||
@@ -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]
|
||||||
|
|||||||
@@ -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"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ 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::{
|
||||||
|
ModelCapabilities, ProviderModelCapabilities, ReasoningModelVariant, UpstreamModelId,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use std::{
|
use std::{
|
||||||
collections::{BTreeMap, BTreeSet},
|
collections::{BTreeMap, BTreeSet},
|
||||||
@@ -164,7 +166,21 @@ impl CatalogService {
|
|||||||
&self,
|
&self,
|
||||||
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
|
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
|
||||||
let mut models: BTreeMap<UpstreamModelId, BTreeSet<ProviderAccountId>> = BTreeMap::new();
|
let mut models: BTreeMap<UpstreamModelId, BTreeSet<ProviderAccountId>> = BTreeMap::new();
|
||||||
|
let mut groups: BTreeMap<UpstreamModelId, BTreeMap<String, ReasoningModelVariant>> =
|
||||||
|
BTreeMap::new();
|
||||||
for (accounts, catalog) in self.catalogs().await? {
|
for (accounts, catalog) in self.catalogs().await? {
|
||||||
|
for (group, level, target) in super::model_groups::variants(&catalog) {
|
||||||
|
groups
|
||||||
|
.entry(group)
|
||||||
|
.or_default()
|
||||||
|
.entry(level)
|
||||||
|
.or_insert_with(|| ReasoningModelVariant {
|
||||||
|
model: target,
|
||||||
|
accounts: BTreeSet::new(),
|
||||||
|
})
|
||||||
|
.accounts
|
||||||
|
.extend(accounts.iter().map(|a| a.account_id.clone()));
|
||||||
|
}
|
||||||
for key in catalog.models.into_keys() {
|
for key in catalog.models.into_keys() {
|
||||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||||
models
|
models
|
||||||
@@ -173,9 +189,21 @@ impl CatalogService {
|
|||||||
.extend(accounts.iter().map(|a| a.account_id.clone()));
|
.extend(accounts.iter().map(|a| a.account_id.clone()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 上游已有同名实体时保留原生型号,不让其他账号的分组覆盖它
|
||||||
|
groups.retain(|group, _| !models.contains_key(group));
|
||||||
|
for (group, variants) in &groups {
|
||||||
|
models.insert(
|
||||||
|
group.clone(),
|
||||||
|
variants
|
||||||
|
.values()
|
||||||
|
.flat_map(|v| v.accounts.iter().cloned())
|
||||||
|
.collect(),
|
||||||
|
);
|
||||||
|
}
|
||||||
Ok(models
|
Ok(models
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(model, accounts)| {
|
.map(|(model, accounts)| {
|
||||||
|
let variants = groups.remove(&model).unwrap_or_default();
|
||||||
ProviderModelCapabilities::new(
|
ProviderModelCapabilities::new(
|
||||||
model,
|
model,
|
||||||
ModelCapabilities::new(
|
ModelCapabilities::new(
|
||||||
@@ -187,7 +215,8 @@ impl CatalogService {
|
|||||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||||
])
|
])
|
||||||
.with_upstream_feature_validation(),
|
.with_upstream_feature_validation()
|
||||||
|
.with_reasoning_variants(variants),
|
||||||
)
|
)
|
||||||
.with_catalog_accounts(accounts)
|
.with_catalog_accounts(accounts)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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,39 @@
|
|||||||
|
//! 从上游分组声明提取实际存在的推理档位,不按型号前缀猜测成员
|
||||||
|
|
||||||
|
use crate::transport::Catalog;
|
||||||
|
use gateway_core::routing::UpstreamModelId;
|
||||||
|
|
||||||
|
pub(super) fn variants(catalog: &Catalog) -> Vec<(UpstreamModelId, String, UpstreamModelId)> {
|
||||||
|
let mut variants = Vec::new();
|
||||||
|
let Some(groups) = catalog.grouped_models.as_object() else {
|
||||||
|
return variants;
|
||||||
|
};
|
||||||
|
for (group, description) in groups {
|
||||||
|
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.is_empty()
|
||||||
|
|| !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)
|
||||||
|
{
|
||||||
|
variants.push((group_id.clone(), level, target));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
variants
|
||||||
|
}
|
||||||
@@ -20,6 +20,8 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
|||||||
pub(crate) struct Catalog {
|
pub(crate) struct Catalog {
|
||||||
pub(crate) project: String,
|
pub(crate) project: 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)]
|
||||||
@@ -101,6 +103,8 @@ impl CloudCodeClient {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Models {
|
struct Models {
|
||||||
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 +122,7 @@ impl CloudCodeClient {
|
|||||||
Ok(Catalog {
|
Ok(Catalog {
|
||||||
project,
|
project,
|
||||||
models: models.models,
|
models: models.models,
|
||||||
|
grouped_models: models.grouped_models,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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"]
|
||||||
|
|||||||
@@ -195,6 +195,122 @@ async fn mock_project(upstream: &MockServer) {
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
|
||||||
|
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"},
|
||||||
|
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High"},
|
||||||
|
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"}
|
||||||
|
},
|
||||||
|
"groupedModels": {
|
||||||
|
"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();
|
||||||
|
assert_eq!(
|
||||||
|
group
|
||||||
|
.capabilities()
|
||||||
|
.reasoning_variants()
|
||||||
|
.keys()
|
||||||
|
.map(String::as_str)
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec!["high", "medium"]
|
||||||
|
);
|
||||||
|
let snapshot = RuntimeSnapshot::new(
|
||||||
|
ConfigRevision::new(1).unwrap(),
|
||||||
|
SettingsValues::new(2, "smart", Default::default(), None, None),
|
||||||
|
vec![kind.clone()],
|
||||||
|
models
|
||||||
|
.iter()
|
||||||
|
.map(|model| {
|
||||||
|
ProviderModel::new(
|
||||||
|
kind.clone(),
|
||||||
|
model.upstream_model().clone(),
|
||||||
|
model.capabilities().clone(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
vec![],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[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;
|
||||||
|
|||||||
@@ -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<'_>,
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
+6
-6
@@ -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 |
|
||||||
@@ -1723,8 +1725,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 列表。例如:
|
||||||
|
|
||||||
@@ -1937,8 +1940,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%`
|
||||||
@@ -2459,8 +2461,6 @@ UA、平台参数及自动 Git 上下文版本由 [OpenAI 上游客户端身份]
|
|||||||
换账号、新会话或更换工作区重新派生化名,切回原账号和原会话恢复对应化名,不保存路径映射表。正常令牌续期与代理出口变化不重置化名。
|
换账号、新会话或更换工作区重新派生化名,切回原账号和原会话恢复对应化名,不保存路径映射表。正常令牌续期与代理出口变化不重置化名。
|
||||||
默认组合移除 Git 远端与提交信息,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
|
默认组合移除 Git 远端与提交信息,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
|
||||||
|
|
||||||
已保存的 `anonymize_workspace` 组合动作继续替换用户名、生成项目化名并删除 Git 信息。管理端编辑时将其展开为四个独立步骤,应用草稿并保存后生效;展开后的步骤仍计入总上限
|
|
||||||
|
|
||||||
工作区必须是绝对路径,映射值必须是对象。缺少稳定会话身份、路径无效或化名冲突时按策略失败模式处理,不随机补造会话。
|
工作区必须是绝对路径,映射值必须是对象。缺少稳定会话身份、路径无效或化名冲突时按策略失败模式处理,不随机补造会话。
|
||||||
预览从样本请求头或正文识别会话,可在样本的 `headers` 中填写 `"session-id": ["example-session"]`;预览只使用样本身份,实际出站另外按 Client Key 和选定账号隔离
|
预览从样本请求头或正文识别会话,可在样本的 `headers` 中填写 `"session-id": ["example-session"]`;预览只使用样本身份,实际出站另外按 Client Key 和选定账号隔离
|
||||||
|
|
||||||
|
|||||||
@@ -715,6 +715,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 +1088,7 @@ 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 小时的本地用量及统计周期,不向额度列表补入本地窗口。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
|
原生额度窗口只投影上游模型分组,不归属整号 Token;Admin 按 Provider 声明独立读取部署时区今天及前 6 天的本地用量,展示为“近一周”,不向额度列表补入本地窗口。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
|
||||||
正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试
|
正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试
|
||||||
- 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后,
|
- 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后,
|
||||||
由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。
|
由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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": "月用量",
|
||||||
|
|||||||
@@ -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">
|
||||||
|
|||||||
@@ -182,24 +182,13 @@ export function createPreset(key: string): PrivacyRule {
|
|||||||
return {
|
return {
|
||||||
...newRule(),
|
...newRule(),
|
||||||
name: preset.name,
|
name: preset.name,
|
||||||
steps: createSteps(preset.steps),
|
steps: preset.steps.map(step => ({
|
||||||
|
...newStep(),
|
||||||
|
...cloneDeep(step),
|
||||||
|
})),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function createSteps(steps: Partial<PrivacyStep>[]): PrivacyStep[] {
|
|
||||||
return steps.map(step => ({
|
|
||||||
...newStep(),
|
|
||||||
...cloneDeep(step),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
export function expandWorkspaceSteps(steps: PrivacyStep[]): PrivacyStep[] {
|
|
||||||
// 只展开编辑草稿,已保存的组合动作由后端保持原行为
|
|
||||||
return steps.flatMap(step => step.action === 'anonymize_workspace'
|
|
||||||
? createSteps(workspaceSteps)
|
|
||||||
: [step])
|
|
||||||
}
|
|
||||||
|
|
||||||
// 样本使用虚构仓库、路径与标识,字段形状对应官方 Core 和 Desktop Git 上下文
|
// 样本使用虚构仓库、路径与标识,字段形状对应官方 Core 和 Desktop Git 上下文
|
||||||
const metadata = {
|
const metadata = {
|
||||||
workspaces: {
|
workspaces: {
|
||||||
|
|||||||
+12
-6
@@ -1,12 +1,18 @@
|
|||||||
# v3.55.1
|
# v3.55.2
|
||||||
|
|
||||||
|
## 新增功能
|
||||||
|
|
||||||
|
- Antigravity 账号支持近一周用量统计,按部署时区汇总当天及前六天
|
||||||
|
|
||||||
## 优化改进
|
## 优化改进
|
||||||
|
|
||||||
- 统一各页面的平台选择器,分组和密钥按平台展示专属配置,通用项保持独立
|
- 加宽隐私规则的处理方式列,便于查看多个独立步骤
|
||||||
- 工作区匿名化拆分为项目名、用户名、Git 远端及提交信息四个可编辑步骤,已有组合规则继续生效
|
|
||||||
- 更新 macOS 客户端身份预设,CLI 预设默认使用 TUI 入口和 Apple Terminal,保留已保存的入口与终端配置
|
|
||||||
|
|
||||||
## 问题修复
|
## 问题修复
|
||||||
|
|
||||||
- 修复 OpenAI、xAI 和 Antigravity 的账号后台操作未使用全局上游身份的问题,覆盖 OAuth、令牌续期、额度刷新及目录查询等场景
|
- 修复 AGY 原生请求使用基础模型名时提示模型不可用的问题,按思考档位匹配上游已声明的型号,并按实际型号校验账号权限
|
||||||
- 修复插件 SDK 未同步项目匿名化动作的问题,使其与宿主隐私配置合同保持一致
|
|
||||||
|
## 升级须知
|
||||||
|
|
||||||
|
- AGY 模型分组能力在升级并刷新账号模型目录后生效
|
||||||
|
- 旧 `anonymize_workspace` 组合动作已移除,相关隐私规则需在升级前改为项目名、用户名、Git 远端及提交信息的独立处理步骤
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
version: 3.55.1
|
version: 3.55.2
|
||||||
published:
|
published:
|
||||||
'3':
|
'3':
|
||||||
stable: 3.55.0
|
stable: 3.55.1
|
||||||
rc: 3.55.0
|
rc: 3.55.1
|
||||||
beta: 3.55.0
|
beta: 3.55.1
|
||||||
alpha: 3.55.0
|
alpha: 3.55.1
|
||||||
|
|||||||
Reference in New Issue
Block a user