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 | ||
|
|
05c3457ca7 | ||
|
|
d7761910bb | ||
|
|
866e812ce0 | ||
|
|
23a4fa42c4 | ||
|
|
f8a7a45b34 | ||
|
|
d777945c93 | ||
|
|
3e747cb233 | ||
|
|
ee5f42ee8e |
@@ -828,12 +828,46 @@ impl ProviderQuotaWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号用量统计周期,完整周/月额度优先,缺少可归属窗口时使用本地滚动日统计
|
||||
/// 账号用量统计周期,区分上游额度周期与独立的本地统计范围
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum AccountUsagePeriod {
|
||||
Weekly,
|
||||
Monthly,
|
||||
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 所需的公共请求事实
|
||||
|
||||
@@ -152,6 +152,11 @@ struct ProviderAdminDiagnostic {
|
||||
/// 运行时资源通知只在事务成功后发生
|
||||
#[async_trait]
|
||||
pub trait ProviderAdmin: Send + Sync {
|
||||
/// 独立本地统计不借用模型分组额度的重置时间
|
||||
fn account_usage_lookback(&self) -> crate::model::provider_credentials::AccountUsageLookback {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
fn compile_privacy_policy(
|
||||
&self,
|
||||
_policy: &gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::{
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use chrono::{Duration, Utc};
|
||||
use chrono::Utc;
|
||||
use futures::StreamExt as _;
|
||||
use gateway_core::{
|
||||
account::ProviderAccountId,
|
||||
@@ -30,11 +30,11 @@ use crate::{
|
||||
observability::TimeRange,
|
||||
provider_credentials::{
|
||||
AccountDirectoryItem, AccountDirectoryPage, AccountExportBundle, AccountPersonalInfo,
|
||||
AccountRefreshResult, AccountUsagePeriod, ConsumeProviderResetCredit,
|
||||
PrepareCredentialRefresh, ProviderModelCatalogDocument, ProviderModels,
|
||||
ProviderProfileAvatar, ProviderQuota, ProviderQuotaReadRequest, ProviderQuotaRequest,
|
||||
ProviderQuotaWindow, ProviderResetCreditResult, ProviderResetCredits,
|
||||
QuotaLocalUsageAttribution,
|
||||
AccountRefreshResult, AccountUsageLookback, AccountUsagePeriod,
|
||||
ConsumeProviderResetCredit, PrepareCredentialRefresh, ProviderModelCatalogDocument,
|
||||
ProviderModels, ProviderProfileAvatar, ProviderQuota, ProviderQuotaReadRequest,
|
||||
ProviderQuotaRequest, ProviderQuotaWindow, ProviderResetCreditResult,
|
||||
ProviderResetCredits, QuotaLocalUsageAttribution,
|
||||
},
|
||||
quota_forecast::{
|
||||
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 account = &stored.account;
|
||||
let now = Utc::now();
|
||||
let rolling_range = TimeRange {
|
||||
start: now - Duration::hours(24),
|
||||
end: now,
|
||||
};
|
||||
let lookback = provider.account_usage_lookback();
|
||||
let rolling_range = lookback
|
||||
.range(now, self.timezone)
|
||||
.map_err(|_| AdminError::internal("时间超出支持范围"))?;
|
||||
let ids = vec![account.id.clone()];
|
||||
let rolling_usage = self
|
||||
.accounts
|
||||
@@ -510,6 +510,7 @@ impl DefaultAccountsService {
|
||||
"a,
|
||||
rolling_usage,
|
||||
api_key_usage,
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
protection_rules: stored.protection_rules,
|
||||
@@ -574,10 +575,6 @@ impl AccountsService for DefaultAccountsService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "account directory"))?;
|
||||
let now = Utc::now();
|
||||
let rolling_range = TimeRange {
|
||||
start: now - Duration::hours(24),
|
||||
end: now,
|
||||
};
|
||||
let ids = page
|
||||
.items
|
||||
.iter()
|
||||
@@ -595,15 +592,33 @@ impl AccountsService for DefaultAccountsService {
|
||||
}
|
||||
}
|
||||
};
|
||||
let rolling_usage = self
|
||||
.accounts
|
||||
.load_account_usage(rolling_range, &ids)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "rolling account usage"))?;
|
||||
let mut rolling_usage = rolling_usage
|
||||
.into_iter()
|
||||
.map(|usage| (usage.account_id.clone(), usage))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let mut usage_groups = BTreeMap::<AccountUsageLookback, Vec<String>>::new();
|
||||
for item in &page.items {
|
||||
let lookback = providers
|
||||
.require(&item.account.provider_kind)
|
||||
.map(|provider| provider.account_usage_lookback())
|
||||
.unwrap_or_default();
|
||||
usage_groups
|
||||
.entry(lookback)
|
||||
.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;
|
||||
self.attach_quota_local_usage(&page.items, &mut quotas)
|
||||
.await?;
|
||||
@@ -615,10 +630,13 @@ impl AccountsService for DefaultAccountsService {
|
||||
.map(|(mut item, quota)| {
|
||||
let id = ProviderAccountId::new(item.account.id.clone())
|
||||
.map_err(|_| AdminError::invalid("服务商账号 ID 不合法"))?;
|
||||
let capabilities = providers
|
||||
let (capabilities, lookback) = providers
|
||||
.require(&item.account.provider_kind)
|
||||
.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();
|
||||
let (usage, usage_period) = resolve_account_usage(
|
||||
@@ -626,6 +644,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
"a,
|
||||
rolling_usage.remove(&item.account.id),
|
||||
api_key_usage.remove(&item.account.id),
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
protection_rules: item.protection_rules,
|
||||
@@ -1348,6 +1367,7 @@ fn resolve_account_usage(
|
||||
quota: &ProviderQuota,
|
||||
rolling_usage: Option<AccountUsage>,
|
||||
api_key_usage: Option<AccountUsage>,
|
||||
lookback: AccountUsageLookback,
|
||||
) -> (Option<AccountUsage>, Option<AccountUsagePeriod>) {
|
||||
if authentication_kind == "api_key" {
|
||||
return (api_key_usage, None);
|
||||
@@ -1356,7 +1376,7 @@ fn resolve_account_usage(
|
||||
return (window.local_usage.clone(), Some(period));
|
||||
}
|
||||
// 模型分组额度无法归属整号用量,本地统计独立回退,不能为此合成上游额度桶
|
||||
(rolling_usage, Some(AccountUsagePeriod::Daily))
|
||||
(rolling_usage, Some(lookback.period()))
|
||||
}
|
||||
|
||||
fn map_reset_credits_error_after_refresh(
|
||||
|
||||
@@ -74,6 +74,7 @@ pub(super) type EventLog = Arc<Mutex<Vec<&'static str>>>;
|
||||
|
||||
pub(super) struct FakeProviderAdmin {
|
||||
kind: ProviderKind,
|
||||
usage_lookback: Mutex<gateway_admin::model::provider_credentials::AccountUsageLookback>,
|
||||
capabilities: Mutex<gateway_admin::model::accounts::ProviderAccountCapabilities>,
|
||||
events: EventLog,
|
||||
failure: Mutex<Option<ProviderAdminError>>,
|
||||
@@ -104,6 +105,7 @@ impl FakeProviderAdmin {
|
||||
pub(super) fn new(kind: &str, events: EventLog) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
kind: ProviderKind::new(kind).expect("provider kind"),
|
||||
usage_lookback: Mutex::default(),
|
||||
capabilities: Mutex::default(),
|
||||
events,
|
||||
failure: Mutex::new(None),
|
||||
@@ -281,6 +283,12 @@ impl FakeProviderAdmin {
|
||||
|
||||
#[async_trait]
|
||||
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] {
|
||||
&["api_key"]
|
||||
}
|
||||
@@ -618,6 +626,7 @@ pub(super) struct FakeAccountStore {
|
||||
import_settings: Mutex<Vec<Option<gateway_admin::model::accounts::AccountImportSettings>>>,
|
||||
quota_window_usage: Mutex<Vec<AccountUsageWindowResult>>,
|
||||
rolling_usage: Mutex<Vec<AccountUsage>>,
|
||||
usage_queries: Mutex<Vec<(TimeRange, Vec<String>)>>,
|
||||
quota_window_queries: Mutex<Vec<AccountUsageWindowQuery>>,
|
||||
quota_forecast_history: Mutex<QuotaForecastHistory>,
|
||||
update_commands: Mutex<Vec<UpdateAccount>>,
|
||||
@@ -642,6 +651,7 @@ impl FakeAccountStore {
|
||||
import_settings: Mutex::new(Vec::new()),
|
||||
quota_window_usage: Mutex::new(Vec::new()),
|
||||
rolling_usage: Mutex::new(Vec::new()),
|
||||
usage_queries: Mutex::default(),
|
||||
quota_window_queries: Mutex::new(Vec::new()),
|
||||
quota_forecast_history: Mutex::new(QuotaForecastHistory::default()),
|
||||
update_commands: Mutex::new(Vec::new()),
|
||||
@@ -827,10 +837,21 @@ impl AccountStore for FakeAccountStore {
|
||||
|
||||
async fn load_account_usage(
|
||||
&self,
|
||||
_: TimeRange,
|
||||
_: &[String],
|
||||
range: TimeRange,
|
||||
ids: &[String],
|
||||
) -> 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(
|
||||
@@ -3001,14 +3022,25 @@ async fn api_key_list_and_detail_should_accumulate_local_usage_without_subscript
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas() {
|
||||
use gateway_admin::model::provider_credentials::AccountUsagePeriod;
|
||||
async fn accounts_list_and_detail_keep_recent_week_usage_separate_from_group_quotas() {
|
||||
use gateway_admin::model::provider_credentials::{AccountUsageLookback, AccountUsagePeriod};
|
||||
|
||||
let provider = FakeProviderAdmin::new("antigravity", events());
|
||||
*provider.usage_lookback.lock().unwrap() = AccountUsageLookback::RecentWeek;
|
||||
let store = FakeAccountStore::new("antigravity", events());
|
||||
let expected_usage = quota_local_usage("acct_test", 139);
|
||||
*store.rolling_usage.lock().unwrap() = vec![expected_usage.clone()];
|
||||
let services = accounts_service(provider.clone(), store.clone()).await;
|
||||
let mut daily_account = account_record("xai");
|
||||
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 {
|
||||
upstream: None,
|
||||
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)
|
||||
.await
|
||||
.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.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());
|
||||
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::Monthly => "monthly",
|
||||
AccountUsagePeriod::Daily => "daily",
|
||||
AccountUsagePeriod::RecentWeek => "recent_week",
|
||||
},
|
||||
target_days: forecast.target_seconds as f64 / 86_400.0,
|
||||
extrapolated: forecast.extrapolated,
|
||||
@@ -374,8 +375,18 @@ pub(super) fn account_usage_view(
|
||||
now: DateTime<Utc>,
|
||||
time: crate::time::TimePresenter,
|
||||
) -> 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 {
|
||||
return empty_account_usage();
|
||||
return AccountUsageView {
|
||||
window_kind,
|
||||
..empty_account_usage()
|
||||
};
|
||||
};
|
||||
let known_count = usage
|
||||
.cost_coverage
|
||||
@@ -389,12 +400,7 @@ pub(super) fn account_usage_view(
|
||||
"known"
|
||||
};
|
||||
AccountUsageView {
|
||||
window_kind: match period {
|
||||
Some(AccountUsagePeriod::Daily) => AccountUsageWindowKind::Daily,
|
||||
Some(AccountUsagePeriod::Weekly) => AccountUsageWindowKind::Weekly,
|
||||
Some(AccountUsagePeriod::Monthly) => AccountUsageWindowKind::Monthly,
|
||||
None => AccountUsageWindowKind::Quota,
|
||||
},
|
||||
window_kind,
|
||||
request_count: Some(usage.request_count),
|
||||
request_count_display: format_number(usage.request_count),
|
||||
input_tokens: usage.input_tokens,
|
||||
|
||||
@@ -437,6 +437,7 @@ pub struct AccountQuotaWindowView {
|
||||
pub enum AccountUsageWindowKind {
|
||||
General,
|
||||
Daily,
|
||||
RecentWeek,
|
||||
Weekly,
|
||||
Monthly,
|
||||
Quota,
|
||||
|
||||
@@ -475,17 +475,17 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
|
||||
last_error_reason: None,
|
||||
last_error_message: None,
|
||||
};
|
||||
for (authentication_kind, read, write) in [
|
||||
("api_key", Some(13), Some(7)),
|
||||
("api_key", None, None),
|
||||
("oauth", Some(13), Some(7)),
|
||||
("oauth", None, None),
|
||||
for (provider_kind, authentication_kind, window_kind, read, write) in [
|
||||
("openai", "api_key", "general", Some(13), Some(7)),
|
||||
("openai", "api_key", "general", None, None),
|
||||
("xai", "oauth", "daily", Some(13), Some(7)),
|
||||
("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);
|
||||
if authentication_kind == "oauth" {
|
||||
account.account.provider_kind =
|
||||
gateway_core::routing::ProviderKind::new("xai").unwrap();
|
||||
}
|
||||
account.account.provider_kind =
|
||||
gateway_core::routing::ProviderKind::new(provider_kind).unwrap();
|
||||
*fixture.account.lock().unwrap() = Some(account);
|
||||
let local_usage = AccountUsage {
|
||||
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();
|
||||
assert_eq!(status, StatusCode::OK, "{value}");
|
||||
let usage = &value["data"]["items"][0]["usage"];
|
||||
assert_eq!(
|
||||
usage["windowKind"],
|
||||
if authentication_kind == "oauth" {
|
||||
"daily"
|
||||
} else {
|
||||
"general"
|
||||
}
|
||||
);
|
||||
assert_eq!(usage["windowKind"], window_kind);
|
||||
assert_eq!(usage["models"][0]["successRateDisplay"], "33.3%");
|
||||
assert!((usage["models"][0]["successRate"].as_f64().unwrap() - 100.0 / 3.0).abs() < 0.001);
|
||||
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"],
|
||||
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_models = Arc::new(Mutex::new(None));
|
||||
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(
|
||||
"openai",
|
||||
Arc::clone(&provider_error),
|
||||
@@ -1735,6 +1742,16 @@ impl UnusedProvider {
|
||||
|
||||
#[async_trait]
|
||||
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(
|
||||
&self,
|
||||
_: &ProviderAccountId,
|
||||
|
||||
@@ -24,6 +24,10 @@ pub(super) fn authentication_gateway_error(error: ClientAuthenticationError) ->
|
||||
|
||||
pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError {
|
||||
match error {
|
||||
crate::validation::RoutingError::InvalidReasoningVariant => GatewayError::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
"A supported reasoning effort is required for this model group.",
|
||||
),
|
||||
crate::validation::RoutingError::GroupModelDenied => GatewayError::new(
|
||||
GatewayErrorKind::PolicyDenied,
|
||||
crate::validation::GROUP_MODEL_DENIED_MESSAGE,
|
||||
|
||||
@@ -920,6 +920,40 @@ pub enum 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(
|
||||
self,
|
||||
inherited: CapabilityRequirements,
|
||||
|
||||
@@ -12,6 +12,13 @@ use super::{
|
||||
ModelCapabilities, ModelPresentation, PublicModelId, PublicModelProfile, UpstreamModelId,
|
||||
};
|
||||
|
||||
/// Provider 声明的推理档位目标及确认该分组成员关系的账号
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ReasoningModelVariant {
|
||||
pub model: UpstreamModelId,
|
||||
pub accounts: BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContributedModelAlias {
|
||||
|
||||
@@ -13,7 +13,7 @@ pub use crate::identity::ProviderKind;
|
||||
pub use catalog::{
|
||||
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort,
|
||||
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent,
|
||||
ProviderModelDescriptor, PublicModelDescriptor,
|
||||
ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
|
||||
};
|
||||
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`
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct ConfigRevision(NonZeroU64);
|
||||
@@ -153,6 +159,7 @@ pub struct ModelCapabilities {
|
||||
upstream_validates_features: bool,
|
||||
generation_protocol: Option<&'static str>,
|
||||
translated_generation_protocols: BTreeSet<&'static str>,
|
||||
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
}
|
||||
|
||||
/// Provider 为客户端模型目录提供的展示与交互能力
|
||||
@@ -427,6 +434,7 @@ impl ModelCapabilities {
|
||||
upstream_validates_features: false,
|
||||
generation_protocol: None,
|
||||
translated_generation_protocols: BTreeSet::new(),
|
||||
reasoning_variants: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,6 +444,21 @@ impl ModelCapabilities {
|
||||
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
|
||||
#[must_use]
|
||||
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
||||
@@ -465,6 +488,11 @@ impl ModelCapabilities {
|
||||
operation: &crate::operation::Operation,
|
||||
requirements: &CapabilityRequirements,
|
||||
) -> Option<BTreeSet<Feature>> {
|
||||
if operation.requires_native_protocol()
|
||||
&& self.generation_protocol != Some(operation.protocol())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if matches!(operation, crate::operation::Operation::Generate(_))
|
||||
&& self.generation_protocol.is_some_and(|protocol| {
|
||||
protocol != operation.protocol()
|
||||
|
||||
@@ -1078,6 +1078,35 @@ impl RuntimeSnapshot {
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.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()
|
||||
}
|
||||
@@ -1172,6 +1201,13 @@ impl RuntimeSnapshot {
|
||||
return false;
|
||||
};
|
||||
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)
|
||||
|| !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(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
@@ -1244,6 +1299,12 @@ impl RuntimeSnapshot {
|
||||
scope: &FrozenAccountScope,
|
||||
) -> bool {
|
||||
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
|
||||
.model_catalog_accounts
|
||||
.get(provider)
|
||||
@@ -1461,7 +1522,13 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
.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);
|
||||
}
|
||||
@@ -1476,6 +1543,8 @@ impl RuntimeSnapshot {
|
||||
|| account_scope.provider_kinds().clone(),
|
||||
|provider| BTreeSet::from([provider.clone()]),
|
||||
);
|
||||
let mut invalid_variant = false;
|
||||
let mut group_model_denied = false;
|
||||
for provider in &providers {
|
||||
if !self.providers.contains(provider) {
|
||||
continue;
|
||||
@@ -1495,23 +1564,50 @@ impl RuntimeSnapshot {
|
||||
{
|
||||
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 授权;管理诊断的目标账号由探测入口固定
|
||||
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;
|
||||
}
|
||||
let capabilities = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(&upstream_model));
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
let native_protocol = match operation {
|
||||
Operation::Generate(request) => request.requires_native_protocol(),
|
||||
Operation::CountTokens(request) => request.requires_native_protocol(),
|
||||
_ => false,
|
||||
};
|
||||
if native_protocol
|
||||
if operation.requires_native_protocol()
|
||||
&& capabilities.and_then(|model| model.generation_protocol)
|
||||
!= Some(operation.protocol())
|
||||
{
|
||||
@@ -1530,7 +1626,6 @@ impl RuntimeSnapshot {
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let mut candidate_scope = Arc::clone(&account_scope);
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
@@ -1562,14 +1657,14 @@ impl RuntimeSnapshot {
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
account_scope.account_provider(account) == Some(provider)
|
||||
&& account_scope.allows_model(account, upstream_model.as_str())
|
||||
candidate_scope.account_provider(account) == Some(provider)
|
||||
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
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) {
|
||||
if !capable_accounts.contains(account) {
|
||||
restricted = restricted.excluding_account(account.clone());
|
||||
@@ -1582,7 +1677,7 @@ impl RuntimeSnapshot {
|
||||
continue;
|
||||
}
|
||||
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()) {
|
||||
@@ -1607,6 +1702,12 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
|
||||
if candidates.is_empty() {
|
||||
if group_model_denied {
|
||||
return Err(RoutingError::GroupModelDenied);
|
||||
}
|
||||
if invalid_variant {
|
||||
return Err(RoutingError::InvalidReasoningVariant);
|
||||
}
|
||||
// 模型存在性必须包含被请求路由限制排除的 Provider;目录未知时不能断言模型不存在
|
||||
let mut scoped_providers = providers.intersection(&self.providers).peekable();
|
||||
if scoped_providers.peek().is_some()
|
||||
|
||||
@@ -48,7 +48,7 @@ pub enum PrivacyAction {
|
||||
SetValue,
|
||||
RenameKey,
|
||||
RemoveField,
|
||||
AnonymizeWorkspace,
|
||||
AnonymizeProject,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
||||
@@ -81,6 +81,9 @@ pub enum RoutingError {
|
||||
/// 已启用的绑定分组均明确禁止请求模型
|
||||
#[error("{GROUP_MODEL_DENIED_MESSAGE}")]
|
||||
GroupModelDenied,
|
||||
/// 已知模型分组没有与本次请求匹配的推理档位
|
||||
#[error("model group requires a supported reasoning effort")]
|
||||
InvalidReasoningVariant,
|
||||
/// 快照中存在重复实体
|
||||
#[error("duplicate {entity} `{id}`")]
|
||||
DuplicateEntity {
|
||||
|
||||
@@ -26,6 +26,270 @@ use gateway_core::routing::{
|
||||
};
|
||||
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)]
|
||||
struct TestSnapshotStore {
|
||||
facts: Arc<Mutex<Result<SnapshotFacts, SnapshotStoreError>>>,
|
||||
|
||||
@@ -86,7 +86,7 @@ pub enum PrivacyAction {
|
||||
SetValue,
|
||||
RenameKey,
|
||||
RemoveField,
|
||||
AnonymizeWorkspace,
|
||||
AnonymizeProject,
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
|
||||
@@ -23,6 +23,23 @@ pub struct RequestObservation {
|
||||
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 提供,是否继承仍由当前协议的续接语义决定
|
||||
#[must_use]
|
||||
pub fn request_observation(
|
||||
|
||||
@@ -1,6 +1,35 @@
|
||||
//! 验证不同协议的共享请求事实
|
||||
|
||||
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};
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -37,6 +37,12 @@ pub(crate) struct AntigravityAdmin {
|
||||
|
||||
#[async_trait]
|
||||
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 {
|
||||
authentication_kind == "oauth"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use crate::{
|
||||
credential::{CredentialService, oauth::error},
|
||||
profile::ReleaseService,
|
||||
transport::{Catalog, CloudCodeClient, unsent},
|
||||
};
|
||||
use gateway_admin::{
|
||||
@@ -13,7 +12,9 @@ use gateway_core::{
|
||||
account::{AccountCatalogObservation, ProviderAccountId, StoredAccountCatalog},
|
||||
error::{ProviderError, ProviderErrorKind as Kind},
|
||||
operation::OperationKind,
|
||||
routing::{ModelCapabilities, ProviderModelCapabilities, UpstreamModelId},
|
||||
routing::{
|
||||
ModelCapabilities, ProviderModelCapabilities, ReasoningModelVariant, UpstreamModelId,
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
@@ -29,7 +30,6 @@ pub(crate) struct CatalogService {
|
||||
kind: gateway_core::routing::ProviderKind,
|
||||
accounts: Arc<dyn gateway_core::account::ProviderAccountStore>,
|
||||
registration: String,
|
||||
pub(crate) release: Arc<ReleaseService>,
|
||||
pub(crate) origin: url::Url,
|
||||
pub(crate) generation: AtomicU64,
|
||||
observed:
|
||||
@@ -109,7 +109,6 @@ impl CatalogService {
|
||||
credentials: Arc<CredentialService>,
|
||||
registration: String,
|
||||
origin: url::Url,
|
||||
release: Arc<ReleaseService>,
|
||||
) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
@@ -117,7 +116,6 @@ impl CatalogService {
|
||||
credentials,
|
||||
registration,
|
||||
origin,
|
||||
release,
|
||||
generation: AtomicU64::new(0),
|
||||
observed: Mutex::default(),
|
||||
refresh_cursor: AtomicUsize::new(0),
|
||||
@@ -168,7 +166,21 @@ impl CatalogService {
|
||||
&self,
|
||||
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
|
||||
let mut models: BTreeMap<UpstreamModelId, BTreeSet<ProviderAccountId>> = BTreeMap::new();
|
||||
let mut groups: BTreeMap<UpstreamModelId, BTreeMap<String, ReasoningModelVariant>> =
|
||||
BTreeMap::new();
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
for (group, level, target) in super::model_groups::variants(&catalog) {
|
||||
groups
|
||||
.entry(group)
|
||||
.or_default()
|
||||
.entry(level)
|
||||
.or_insert_with(|| ReasoningModelVariant {
|
||||
model: target,
|
||||
accounts: BTreeSet::new(),
|
||||
})
|
||||
.accounts
|
||||
.extend(accounts.iter().map(|a| a.account_id.clone()));
|
||||
}
|
||||
for key in catalog.models.into_keys() {
|
||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||
models
|
||||
@@ -177,9 +189,21 @@ impl CatalogService {
|
||||
.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
|
||||
.into_iter()
|
||||
.map(|(model, accounts)| {
|
||||
let variants = groups.remove(&model).unwrap_or_default();
|
||||
ProviderModelCapabilities::new(
|
||||
model,
|
||||
ModelCapabilities::new(
|
||||
@@ -191,7 +215,8 @@ impl CatalogService {
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
])
|
||||
.with_upstream_feature_validation(),
|
||||
.with_upstream_feature_validation()
|
||||
.with_reasoning_variants(variants),
|
||||
)
|
||||
.with_catalog_accounts(accounts)
|
||||
})
|
||||
@@ -222,12 +247,9 @@ impl CatalogService {
|
||||
.credentials
|
||||
.material(¤t)
|
||||
.map_err(|e| error(AdminKind::CredentialRefreshRequired).with_source(e))?;
|
||||
let client = CloudCodeClient::new(
|
||||
&self.origin,
|
||||
current.account.outbound_proxy(),
|
||||
&crate::profile::default_profile(&self.release),
|
||||
)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let profile = self.credentials.request_profile().await?;
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(|e| error(AdminKind::Unavailable).with_source(e))?;
|
||||
let observed_at = SystemTime::now();
|
||||
let catalog = client
|
||||
.catalog(&material.access_token)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
mod authorization;
|
||||
pub(crate) mod catalog;
|
||||
mod documents;
|
||||
mod model_groups;
|
||||
pub(crate) mod oauth;
|
||||
pub(crate) mod quota;
|
||||
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
|
||||
}
|
||||
@@ -4,7 +4,6 @@ use super::document::Document;
|
||||
use crate::{
|
||||
credential::catalog::CatalogService,
|
||||
credential::{CredentialService, oauth::error},
|
||||
profile::ReleaseService,
|
||||
transport::CloudCodeClient,
|
||||
};
|
||||
use futures::{StreamExt, stream};
|
||||
@@ -35,7 +34,6 @@ pub(crate) struct QuotaService {
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
credentials: Arc<CredentialService>,
|
||||
catalog: Arc<CatalogService>,
|
||||
release: Arc<ReleaseService>,
|
||||
origin: url::Url,
|
||||
cursor: AtomicUsize,
|
||||
}
|
||||
@@ -107,7 +105,6 @@ impl QuotaService {
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
credentials: Arc<CredentialService>,
|
||||
catalog: Arc<CatalogService>,
|
||||
release: Arc<ReleaseService>,
|
||||
origin: url::Url,
|
||||
) -> Self {
|
||||
Self {
|
||||
@@ -115,7 +112,6 @@ impl QuotaService {
|
||||
accounts,
|
||||
credentials,
|
||||
catalog,
|
||||
release,
|
||||
origin,
|
||||
cursor: AtomicUsize::new(0),
|
||||
}
|
||||
@@ -153,12 +149,9 @@ impl QuotaService {
|
||||
.credentials
|
||||
.material(¤t)
|
||||
.map_err(|e| error(Kind::CredentialRefreshRequired).with_source(e))?;
|
||||
let client = CloudCodeClient::new(
|
||||
&self.origin,
|
||||
current.account.outbound_proxy(),
|
||||
&crate::profile::default_profile(&self.release),
|
||||
)
|
||||
.map_err(upstream)?;
|
||||
let profile = self.credentials.request_profile().await?;
|
||||
let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile)
|
||||
.map_err(upstream)?;
|
||||
// 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照
|
||||
let observed_at = SystemTime::now();
|
||||
let info = client
|
||||
|
||||
@@ -32,14 +32,12 @@ pub fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigErr
|
||||
credentials.clone(),
|
||||
oauth.registration(),
|
||||
origin.clone(),
|
||||
release.clone(),
|
||||
));
|
||||
let quota = Arc::new(credential::quota::QuotaService::new(
|
||||
kind.clone(),
|
||||
ports.accounts(),
|
||||
credentials.clone(),
|
||||
catalog.clone(),
|
||||
release.clone(),
|
||||
origin.clone(),
|
||||
));
|
||||
let core = Arc::new(provider::AntigravityProvider::new(
|
||||
|
||||
@@ -20,6 +20,8 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
||||
pub(crate) struct Catalog {
|
||||
pub(crate) project: String,
|
||||
pub(crate) models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
pub(crate) grouped_models: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -101,6 +103,8 @@ impl CloudCodeClient {
|
||||
#[derive(Deserialize)]
|
||||
struct Models {
|
||||
models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
grouped_models: serde_json::Value,
|
||||
}
|
||||
let models: Models = control(
|
||||
self.post("fetchAvailableModels", token)
|
||||
@@ -118,6 +122,7 @@ impl CloudCodeClient {
|
||||
Ok(Catalog {
|
||||
project,
|
||||
models: models.models,
|
||||
grouped_models: models.grouped_models,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
mod authorization;
|
||||
#[path = "../../src/credential/documents.rs"]
|
||||
mod documents;
|
||||
#[path = "../../src/credential/model_groups.rs"]
|
||||
mod model_groups;
|
||||
#[path = "../../src/credential/oauth.rs"]
|
||||
pub(crate) mod oauth;
|
||||
#[path = "../../src/credential/refresh.rs"]
|
||||
|
||||
@@ -15,6 +15,37 @@ async fn upstream(server: &MockServer, remaining: serde_json::Value, delay: Dura
|
||||
Mock::given(path("/v1internal:retrieveUserQuotaSummary")).respond_with(ResponseTemplate::new(200).set_delay(delay).set_body_json(json!({"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.9,"resetTime":"2099-01-01T00:00:00Z"},{"bucketId":"gemini-5h","displayName":"Five hour","window":"5h","remainingFraction":remaining,"resetTime":"2099-01-01T00:00:00Z"}]},{"displayName":"Claude and GPT models","buckets":[{"bucketId":"3p-weekly","displayName":"Weekly","window":"weekly","remainingFraction":0.8,"resetTime":"2099-01-01T00:00:00Z"}]}]}))).mount(server).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_and_catalog_refresh_use_current_global_identity() {
|
||||
let server = MockServer::start().await;
|
||||
upstream(&server, json!(0.5), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
let account = f.store.primary().loaded.lock().unwrap().account.clone();
|
||||
for (version, changelist) in [("1.5.14", ""), ("1.5.15", "; cl=1027820220")] {
|
||||
*f.store.request_profile.lock().unwrap() = Some(crate::profile::object(
|
||||
json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":version,"arch":null}),
|
||||
));
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
f.quota.refresh(account.id()).await.unwrap();
|
||||
f.catalog.account_models(account.id(), true).await.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 5);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
format!(
|
||||
"antigravity/cli/{version} (aidev_client; os_type=linux; arch=amd64{changelist}; auth_method=consumer)"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
*f.store.request_profile.lock().unwrap() =
|
||||
Some(crate::profile::object(json!({"client":"unsupported"})));
|
||||
assert!(f.quota.refresh(account.id()).await.is_err());
|
||||
assert!(f.catalog.account_models(account.id(), true).await.is_err());
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 10);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
@@ -195,6 +195,122 @@ async fn mock_project(upstream: &MockServer) {
|
||||
.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]
|
||||
async fn disabled_account_probe_discovers_its_own_project_on_first_poll() {
|
||||
let upstream = MockServer::start().await;
|
||||
|
||||
@@ -226,14 +226,12 @@ impl Fixture {
|
||||
credentials.clone(),
|
||||
oauth.registration(),
|
||||
origin.clone(),
|
||||
release.clone(),
|
||||
));
|
||||
let quota = Arc::new(crate::credential::quota::QuotaService::new(
|
||||
kind.clone(),
|
||||
store.clone(),
|
||||
credentials.clone(),
|
||||
catalog.clone(),
|
||||
release.clone(),
|
||||
origin.clone(),
|
||||
));
|
||||
let provider = Arc::new(AntigravityProvider::new(
|
||||
|
||||
@@ -144,6 +144,7 @@ pub(super) fn map_oauth_error(error: CodexOAuthAdminError) -> ProviderAdminError
|
||||
}) => (Kind::Unavailable, "无法连接授权服务,请检查出站连接"),
|
||||
Error::Exchange(Exchange::Unavailable) => (Kind::Unavailable, "授权服务暂不可用"),
|
||||
Error::StorageUnavailable => (Kind::Unavailable, "授权状态存储暂不可用"),
|
||||
Error::Profile(_) => (Kind::Unavailable, "授权客户端身份暂不可用"),
|
||||
};
|
||||
provider_admin_error(kind)
|
||||
.with_public_message(message)
|
||||
@@ -169,6 +170,7 @@ pub(super) const fn oauth_error_code(error: &CodexOAuthAdminError) -> &'static s
|
||||
}) => "connect_failed",
|
||||
CodexOAuthAdminError::Exchange(Exchange::Ambiguous { .. }) => "ambiguous",
|
||||
CodexOAuthAdminError::StorageUnavailable => "storage_unavailable",
|
||||
CodexOAuthAdminError::Profile(_) => "profile_unavailable",
|
||||
CodexOAuthAdminError::Credential => "credential",
|
||||
}
|
||||
}
|
||||
@@ -179,7 +181,7 @@ pub(super) fn map_quota_error(error: CodexCredentialQuotaError) -> ProviderAdmin
|
||||
let (kind, public_message, upstream_message) = match error {
|
||||
Error::Profile(source) => {
|
||||
return provider_admin_error(Kind::Unavailable)
|
||||
.with_public_message("预热客户端身份不可用")
|
||||
.with_public_message("客户端身份不可用")
|
||||
.with_source(source);
|
||||
}
|
||||
Error::InvalidCredentialData => (Kind::Invalid, "凭据或额度数据无效", None),
|
||||
|
||||
@@ -15,6 +15,7 @@ use gateway_admin::model::{
|
||||
use gateway_core::account::{
|
||||
LoadedCredential, NewProviderAccount, ProviderAccountId, ProviderAccountStore,
|
||||
};
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use sha2::{Digest, Sha256};
|
||||
use subtle::ConstantTimeEq as _;
|
||||
@@ -32,13 +33,12 @@ use super::token_client::{
|
||||
OFFICIAL_CODEX_OAUTH_CLIENT_ID, OFFICIAL_CODEX_REDIRECT_URI,
|
||||
};
|
||||
use super::types::{parse_access_token_expiration, parse_chatgpt_jwt_claims};
|
||||
use crate::profile::CodexWireProfileState;
|
||||
use crate::profile::{CodexWireProfile, CodexWireProfileState};
|
||||
|
||||
const AUTHORIZATION_ENDPOINT: &str = "https://auth.openai.com/oauth/authorize";
|
||||
const DESKTOP_AUTH_ENDPOINT: &str = "https://chatgpt.com/codex/desktop-auth";
|
||||
const AUTHORIZATION_SCOPE: &str =
|
||||
"openid profile email offline_access api.connectors.read api.connectors.invoke";
|
||||
const AUTHORIZATION_ORIGINATOR: &str = "Codex Desktop";
|
||||
const STREAMLINED_LOGIN_QUERY: &str = "codex_streamlined_login";
|
||||
const NO_UNIVERSAL_LINKS_QUERY: &str = "no_universal_links";
|
||||
const SURFACE_STABLE_ID_DOMAIN: &[u8] = b"openai/codex-desktop/surface-stable-id/v1\0";
|
||||
@@ -336,6 +336,8 @@ pub enum CodexOAuthAdminError {
|
||||
Exchange(#[source] AuthorizationCodeExchangeError),
|
||||
#[error("Codex OAuth pending storage is unavailable")]
|
||||
StorageUnavailable,
|
||||
#[error("Codex OAuth client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("Codex OAuth account mutation failed")]
|
||||
Credential,
|
||||
}
|
||||
@@ -360,6 +362,7 @@ pub struct CodexOAuthAdminService {
|
||||
credentials: CodexCredentialAdmin,
|
||||
oauth_client_id: String,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
struct CodexOAuthAuthorizationCommitGuard {
|
||||
@@ -408,6 +411,7 @@ impl CodexOAuthAdminService {
|
||||
store: Arc<dyn ProviderAccountStore>,
|
||||
credentials: CodexCredentialAdmin,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
pending,
|
||||
@@ -416,6 +420,7 @@ impl CodexOAuthAdminService {
|
||||
credentials,
|
||||
oauth_client_id: OFFICIAL_CODEX_OAUTH_CLIENT_ID.to_owned(),
|
||||
profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -603,9 +608,12 @@ impl CodexOAuthAdminService {
|
||||
mutation,
|
||||
})
|
||||
.map_err(map_pending_error)?;
|
||||
let profile = self.profile.snapshot();
|
||||
let authorization_url =
|
||||
authorization_url(&pending, &self.oauth_client_id, &profile.desktop_version)?;
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexOAuthAdminError::Profile)?;
|
||||
let authorization_url = authorization_url(&pending, &self.oauth_client_id, &profile)?;
|
||||
self.pending
|
||||
.create(&pending)
|
||||
.await
|
||||
@@ -736,11 +744,8 @@ fn derive_surface_stable_id(installation_id: &str) -> Result<String, CodexOAuthA
|
||||
fn authorization_url(
|
||||
pending: &CodexPendingAuthorization,
|
||||
oauth_client_id: &str,
|
||||
desktop_version: &str,
|
||||
profile: &CodexWireProfile,
|
||||
) -> Result<String, CodexOAuthAdminError> {
|
||||
if !valid_text(desktop_version) {
|
||||
return Err(CodexOAuthAdminError::InvalidInput);
|
||||
}
|
||||
let mut inner =
|
||||
Url::parse(AUTHORIZATION_ENDPOINT).map_err(|_| CodexOAuthAdminError::InvalidInput)?;
|
||||
let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(
|
||||
@@ -759,8 +764,11 @@ fn authorization_url(
|
||||
.append_pair("scope", AUTHORIZATION_SCOPE)
|
||||
.append_pair("id_token_add_organizations", "true")
|
||||
.append_pair("codex_cli_simplified_flow", "true")
|
||||
.append_pair("originator", AUTHORIZATION_ORIGINATOR)
|
||||
.append_pair("codex_app_version", desktop_version)
|
||||
.append_pair("originator", &profile.originator);
|
||||
if !profile.desktop_version.is_empty() {
|
||||
query.append_pair("codex_app_version", &profile.desktop_version);
|
||||
}
|
||||
query
|
||||
.append_pair("source_surface_stable_id", &stable_id)
|
||||
.append_pair("codex_origin_stable_id", &stable_id)
|
||||
.append_pair(STREAMLINED_LOGIN_QUERY, "true");
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::Mutex,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant, SystemTime},
|
||||
};
|
||||
|
||||
use gateway_core::account::ProviderAccountId;
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use reqwest::Client;
|
||||
use secrecy::{ExposeSecret as _, SecretString};
|
||||
use thiserror::Error;
|
||||
@@ -108,6 +109,7 @@ struct CachedProfileAvatarSource {
|
||||
pub struct CodexCredentialProfileService {
|
||||
repository: CodexCredentialRepository,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
http: Client,
|
||||
base_url: String,
|
||||
avatar_sources: Mutex<HashMap<String, CachedProfileAvatarSource>>,
|
||||
@@ -120,16 +122,34 @@ impl CodexCredentialProfileService {
|
||||
profile: CodexWireProfileState,
|
||||
http: Client,
|
||||
base_url: String,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
repository,
|
||||
profile,
|
||||
http,
|
||||
base_url,
|
||||
runtime_policy,
|
||||
avatar_sources: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn global_profile_client(
|
||||
&self,
|
||||
) -> Result<CodexBackendClient, CodexProfileStatisticsError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| CodexProfileStatisticsError::TransportUnavailable)?;
|
||||
Ok(CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile))
|
||||
}
|
||||
|
||||
/// 订阅只按需读取;不缓存、不刷新凭据,也不更新额度状态
|
||||
pub async fn subscription(
|
||||
&self,
|
||||
@@ -141,23 +161,21 @@ impl CodexCredentialProfileService {
|
||||
return Ok(None);
|
||||
};
|
||||
let request_id = format!("subscription_{}", Uuid::now_v7().simple());
|
||||
let subscription = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.for_account(&account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_subscription(
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
Some(&upstream_account_id),
|
||||
&request_id,
|
||||
None,
|
||||
),
|
||||
&upstream_account_id,
|
||||
)
|
||||
.await;
|
||||
let subscription = self
|
||||
.global_profile_client()
|
||||
.await?
|
||||
.for_account(&account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_subscription(
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
Some(&upstream_account_id),
|
||||
&request_id,
|
||||
None,
|
||||
),
|
||||
&upstream_account_id,
|
||||
)
|
||||
.await;
|
||||
// 请求期间重新授权、换绑或删除账号时,丢弃旧身份的结果
|
||||
let current = self
|
||||
.repository
|
||||
@@ -183,32 +201,35 @@ impl CodexCredentialProfileService {
|
||||
) -> Result<CodexProfileStatistics, CodexProfileStatisticsError> {
|
||||
let (authorization, upstream_account_id, account) =
|
||||
self.account_authentication(account_id).await?;
|
||||
self.fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account)
|
||||
.await
|
||||
let client = self.global_profile_client().await?;
|
||||
self.fetch_profile_statistics(
|
||||
&client,
|
||||
&authorization,
|
||||
upstream_account_id.as_deref(),
|
||||
&account,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn fetch_profile_statistics(
|
||||
&self,
|
||||
client: &CodexBackendClient,
|
||||
authorization: &SecretString,
|
||||
upstream_account_id: Option<&str>,
|
||||
account: &gateway_core::account::ProviderAccount,
|
||||
) -> Result<CodexProfileStatistics, CodexProfileStatisticsError> {
|
||||
let request_id = format!("profile_statistics_{}", Uuid::now_v7().simple());
|
||||
let statistics = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.for_account(account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_profile_statistics(CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
upstream_account_id,
|
||||
&request_id,
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.map_err(map_client_error)?;
|
||||
let statistics = client
|
||||
.for_account(account)
|
||||
.map_err(map_client_error)?
|
||||
.fetch_profile_statistics(CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
upstream_account_id,
|
||||
&request_id,
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.map_err(map_client_error)?;
|
||||
self.remember_avatar_source(
|
||||
crate::request_identity::oauth_identity_key(account),
|
||||
statistics.image_url.as_deref(),
|
||||
@@ -268,12 +289,18 @@ impl CodexCredentialProfileService {
|
||||
) -> Result<CodexProfileAvatar, CodexProfileAvatarError> {
|
||||
let (authorization, upstream_account_id, account) =
|
||||
self.account_authentication(account_id).await?;
|
||||
let client = self.global_profile_client().await?;
|
||||
let source = match self
|
||||
.cached_avatar_source(&crate::request_identity::oauth_identity_key(&account))
|
||||
{
|
||||
Some(source) => source,
|
||||
None => self
|
||||
.fetch_profile_statistics(&authorization, upstream_account_id.as_deref(), &account)
|
||||
.fetch_profile_statistics(
|
||||
&client,
|
||||
&authorization,
|
||||
upstream_account_id.as_deref(),
|
||||
&account,
|
||||
)
|
||||
.await?
|
||||
.image_url
|
||||
.ok_or(CodexProfileAvatarError::Missing)?,
|
||||
@@ -290,7 +317,7 @@ impl CodexCredentialProfileService {
|
||||
fetch_profile_avatar(
|
||||
&http,
|
||||
&self.base_url,
|
||||
&self.profile.snapshot(),
|
||||
&client.profile_state().snapshot(),
|
||||
&source,
|
||||
CodexRequestContext::auxiliary(
|
||||
authorization.expose_secret(),
|
||||
|
||||
@@ -231,17 +231,7 @@ impl CodexCredentialQuotaService {
|
||||
.await?;
|
||||
return Ok(None);
|
||||
};
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile);
|
||||
let client = self.global_profile_client().await?;
|
||||
// 先持久化领取再发请求;超时、取消或重启后不重放结果不明的推理
|
||||
// 通用窗口共享请求用量,同批到期窗口只发一次轻量请求
|
||||
for (key, _, reset) in &due {
|
||||
|
||||
@@ -145,7 +145,7 @@ pub struct CodexWarmupSummary {
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CodexCredentialQuotaError {
|
||||
#[error("Codex warmup client profile is unavailable")]
|
||||
#[error("Codex quota client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("Codex quota response is invalid")]
|
||||
InvalidCredentialData,
|
||||
|
||||
@@ -126,11 +126,10 @@ impl CodexCredentialQuotaService {
|
||||
account_id: &ProviderAccountId,
|
||||
) -> Result<CodexRateLimitResetCredits, CodexResetCreditsError> {
|
||||
let account = self.reset_credit_account(account_id).await?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self
|
||||
.global_profile_client()
|
||||
.await
|
||||
.map_err(|_| CodexResetCreditsError::TransportUnavailable)?;
|
||||
let credential = self
|
||||
.repository
|
||||
.load_runtime_credential(&account)
|
||||
@@ -157,11 +156,10 @@ impl CodexCredentialQuotaService {
|
||||
let entry = self.reset_consume_locks.entry(account_id);
|
||||
let _guard = entry.lock().await;
|
||||
let account = self.reset_credit_account(account_id).await?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self
|
||||
.global_profile_client()
|
||||
.await
|
||||
.map_err(|_| CodexResetCreditsError::TransportUnavailable)?;
|
||||
let credential = self
|
||||
.repository
|
||||
.load_runtime_credential(&account)
|
||||
|
||||
@@ -35,6 +35,22 @@ fn upstream_error_status(error: &CodexClientError) -> Option<u16> {
|
||||
}
|
||||
|
||||
impl CodexCredentialQuotaService {
|
||||
pub(super) async fn global_profile_client(
|
||||
&self,
|
||||
) -> Result<CodexBackendClient, CodexCredentialQuotaError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
Ok(CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile))
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
repository: CodexCredentialRepository,
|
||||
profile: CodexWireProfileState,
|
||||
@@ -174,11 +190,17 @@ impl CodexCredentialQuotaService {
|
||||
if accounts.is_empty() {
|
||||
return Ok(summary);
|
||||
}
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = match self.global_profile_client().await {
|
||||
Ok(client) => client,
|
||||
Err(error) => {
|
||||
// 身份配置失败尚未发出请求,也需要释放已预留的首查任务
|
||||
self.scheduling.defer_failed_initial_refreshes(
|
||||
&pending_initial,
|
||||
self.initial_sync_delays.as_ref(),
|
||||
);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
for account in accounts {
|
||||
let observed_at = SystemTime::now();
|
||||
match self.fetch_usage(&client, &account).await {
|
||||
@@ -410,11 +432,7 @@ impl CodexCredentialQuotaService {
|
||||
if !access_token_is_current(&account, observed_at) {
|
||||
return Err(CodexCredentialQuotaError::CredentialRefreshRequired);
|
||||
}
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
);
|
||||
let client = self.global_profile_client().await?;
|
||||
let FetchedCodexQuota { account, value } = match self.fetch_usage(&client, &account).await {
|
||||
Ok(fetched) => fetched,
|
||||
Err(CodexQuotaFetchError::InvalidCredential) => {
|
||||
|
||||
@@ -140,17 +140,7 @@ impl CodexCredentialQuotaService {
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(CodexCredentialQuotaError::Profile)?;
|
||||
let client = CodexBackendClient::new(
|
||||
self.http.clone(),
|
||||
self.base_url.clone(),
|
||||
self.profile.clone(),
|
||||
)
|
||||
.with_request_profile(profile);
|
||||
let client = self.global_profile_client().await?;
|
||||
|
||||
for account in accounts {
|
||||
if account.quota().is_exhausted() {
|
||||
|
||||
@@ -8,10 +8,12 @@ use crate::transport::{
|
||||
tls::{build_reqwest_client_with_custom_ca, ensure_rustls_provider},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use reqwest::{Client, StatusCode, redirect::Policy};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const MAX_OAUTH_RESPONSE_BYTES: usize = 64 * 1024;
|
||||
@@ -386,6 +388,7 @@ pub struct OpenAiTokenClient {
|
||||
client: Client,
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
/// 官方 Codex token client 无法安全构建
|
||||
@@ -408,14 +411,23 @@ impl OpenAiTokenClient {
|
||||
.timeout(TOKEN_REQUEST_TIMEOUT);
|
||||
let client =
|
||||
build_reqwest_client_with_custom_ca(builder).map_err(|_| TokenClientBuildError)?;
|
||||
Ok(Self::new(client, self.config.clone(), self.profile.clone()))
|
||||
Ok(Self {
|
||||
client,
|
||||
..self.clone()
|
||||
})
|
||||
}
|
||||
/// 共享运行时画像;刷新时取快照,授权码交换仍使用 raw auth 请求
|
||||
pub fn new(client: Client, config: TokenClientConfig, profile: CodexWireProfileState) -> Self {
|
||||
/// 认证请求按执行时的全局配置解析身份
|
||||
pub fn new(
|
||||
client: Client,
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
config,
|
||||
profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,7 +451,12 @@ impl OpenAiTokenClient {
|
||||
endpoint.set_path(PERSONAL_ACCESS_TOKEN_WHOAMI_PATH);
|
||||
endpoint.set_query(None);
|
||||
endpoint.set_fragment(None);
|
||||
let headers = build_codex_profile_headers(&self.profile.snapshot())
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| PersonalAccessTokenError::Unavailable)?;
|
||||
let headers = build_codex_profile_headers(&profile)
|
||||
.map_err(|_| PersonalAccessTokenError::Unavailable)?;
|
||||
let client = self
|
||||
.with_proxy(proxy)
|
||||
@@ -495,6 +512,7 @@ impl OpenAiTokenClient {
|
||||
pub fn openai_token_client(
|
||||
config: TokenClientConfig,
|
||||
profile: CodexWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Result<OpenAiTokenClient, TokenClientBuildError> {
|
||||
ensure_rustls_provider();
|
||||
let builder = gateway_egress::http_client(None)
|
||||
@@ -503,7 +521,12 @@ pub fn openai_token_client(
|
||||
.connect_timeout(TOKEN_CONNECT_TIMEOUT)
|
||||
.timeout(TOKEN_REQUEST_TIMEOUT);
|
||||
let client = build_reqwest_client_with_custom_ca(builder).map_err(|_| TokenClientBuildError)?;
|
||||
Ok(OpenAiTokenClient::new(client, config, profile))
|
||||
Ok(OpenAiTokenClient::new(
|
||||
client,
|
||||
config,
|
||||
profile,
|
||||
runtime_policy,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -591,14 +614,22 @@ impl TokenRefresher for OpenAiTokenClient {
|
||||
.await
|
||||
}
|
||||
async fn refresh(&self, refresh_token: &str) -> Result<TokenPair, RefreshFailure> {
|
||||
let headers = build_codex_profile_headers(&self.profile.snapshot()).map_err(|source| {
|
||||
RefreshFailure::Transport {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|source| RefreshFailure::RetryableTransport {
|
||||
redacted: false,
|
||||
source: Some(source),
|
||||
message: "OpenAI OAuth refresh profile is unavailable".to_owned(),
|
||||
})?;
|
||||
let headers =
|
||||
build_codex_profile_headers(&profile).map_err(|source| RefreshFailure::Transport {
|
||||
redacted: false,
|
||||
source: Some(source.into()),
|
||||
message: Some("OpenAI OAuth refresh profile is invalid".to_owned()),
|
||||
upstream: None,
|
||||
}
|
||||
})?;
|
||||
})?;
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
@@ -642,9 +673,17 @@ impl AuthorizationCodeExchanger for OpenAiTokenClient {
|
||||
&self,
|
||||
grant: AuthorizationCodeGrant,
|
||||
) -> Result<AuthorizationTokenSet, AuthorizationCodeExchangeError> {
|
||||
let profile = self
|
||||
.profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| AuthorizationCodeExchangeError::Unavailable)?;
|
||||
let headers = build_codex_profile_headers(&profile)
|
||||
.map_err(|_| AuthorizationCodeExchangeError::Unavailable)?;
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
.headers(headers)
|
||||
.form(&[
|
||||
("grant_type", "authorization_code"),
|
||||
("client_id", self.config.client_id.as_str()),
|
||||
|
||||
@@ -162,6 +162,7 @@ pub async fn initialize(
|
||||
profile.clone(),
|
||||
http.clone(),
|
||||
config.base_url().to_owned(),
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let selector = Arc::new(CodexCredentialSelector::new(
|
||||
provider_kind.clone(),
|
||||
@@ -197,6 +198,7 @@ pub async fn initialize(
|
||||
credential::token_client::openai_token_client(
|
||||
config.token_client_config(),
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
)
|
||||
.map_err(|_| OpenAiInitializeError::TokenClient)?,
|
||||
);
|
||||
@@ -230,6 +232,7 @@ pub async fn initialize(
|
||||
Arc::clone(&accounts),
|
||||
CodexCredentialAdmin,
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
)
|
||||
.with_oauth_client_id(config.oauth_client_id()),
|
||||
);
|
||||
|
||||
@@ -10,6 +10,7 @@ pub(super) const CLI_ORIGINATOR: &str = "codex_cli_rs";
|
||||
pub(super) const TUI_ORIGINATOR: &str = "codex-tui";
|
||||
pub(super) const EXEC_ORIGINATOR: &str = "codex_exec";
|
||||
pub(super) const TERMINAL: &str = "unknown";
|
||||
pub(super) const MACOS_CLI_TERMINAL: &str = "Apple_Terminal/488.9";
|
||||
|
||||
pub(super) struct Environment {
|
||||
pub os_type: &'static str,
|
||||
@@ -19,7 +20,7 @@ pub(super) struct Environment {
|
||||
|
||||
pub(super) const MACOS_ENVIRONMENT: Environment = Environment {
|
||||
os_type: "Mac OS",
|
||||
os_version: "15.7.1",
|
||||
os_version: "27.2.1",
|
||||
arch: "arm64",
|
||||
};
|
||||
pub(super) const LINUX_ENVIRONMENT: Environment = Environment {
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(super) const USER_AGENT_PRODUCTS: [&str; 4] =
|
||||
["Codex Desktop", "codex-tui", "codex_exec", "codex_cli_rs"];
|
||||
|
||||
impl CodexWireProfileState {
|
||||
/// 后台模型操作没有 Client Key,按当前全局选择冻结整套身份
|
||||
/// 账号后台操作没有 Client Key,按当前全局选择冻结整套身份
|
||||
pub(crate) async fn resolve_global_request_profile(
|
||||
&self,
|
||||
policy: &dyn ProviderRuntimePolicyPort,
|
||||
|
||||
@@ -362,6 +362,10 @@ impl CodexWireProfileState {
|
||||
let configuration = ClientProfileSelection {
|
||||
client,
|
||||
platform,
|
||||
cli_entry: (client == ClientKind::Cli && platform == ClientPlatform::Macos)
|
||||
.then_some(CliEntry::Tui),
|
||||
terminal: (client == ClientKind::Cli && platform == ClientPlatform::Macos)
|
||||
.then(|| baseline::MACOS_CLI_TERMINAL.to_owned()),
|
||||
..ClientProfileSelection::default()
|
||||
};
|
||||
let available = configuration.resolve(self).is_ok();
|
||||
|
||||
@@ -105,6 +105,10 @@ impl CodexWireProfile {
|
||||
/// 复合 User-Agent 是两个独立 surface
|
||||
#[must_use]
|
||||
pub fn desktop_user_agent(&self) -> String {
|
||||
// 非 Desktop 预设及完整自定义 UA 没有独立桌面格式,保持所选身份
|
||||
if self.client_kind != ClientKind::Desktop || self.exact_user_agent.is_some() {
|
||||
return self.user_agent();
|
||||
}
|
||||
format!(
|
||||
"{}/{} ({}; {})",
|
||||
self.originator, self.desktop_version, self.os_type, self.arch
|
||||
|
||||
@@ -59,7 +59,7 @@ pub fn build_codex_model_headers(
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
/// Core 默认客户端身份,用于模型接口及 OAuth refresh;raw token exchange 不使用
|
||||
/// 客户端身份头供模型接口和服务端认证请求共用,不携带账号凭据
|
||||
pub fn build_codex_profile_headers(profile: &CodexWireProfile) -> CodexClientResult<HeaderMap> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
|
||||
@@ -16,7 +16,7 @@ pub(super) struct CompiledStep {
|
||||
|
||||
impl CompiledStep {
|
||||
pub(super) fn compile(rule: &PrivacyStep) -> Result<Self, &'static str> {
|
||||
if rule.action == PrivacyAction::AnonymizeWorkspace
|
||||
if rule.action == PrivacyAction::AnonymizeProject
|
||||
&& (rule.scope != PrivacyScope::TurnMetadata
|
||||
|| rule.selector != "$.workspaces"
|
||||
|| rule.pattern.is_some())
|
||||
@@ -99,8 +99,8 @@ impl CompiledStep {
|
||||
) -> Result<bool, &'static str> {
|
||||
budget.step()?;
|
||||
match self.rule.action {
|
||||
PrivacyAction::AnonymizeWorkspace => {
|
||||
*count += super::workspace::anonymize(value, budget)?;
|
||||
PrivacyAction::AnonymizeProject => {
|
||||
*count += super::workspace::anonymize_project(value, budget)?;
|
||||
}
|
||||
PrivacyAction::RemoveField => {
|
||||
if let Some(regex) = &self.regex {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 工作区路径的账号会话化名、Git 元数据裁剪与预览会话识别
|
||||
//! 工作区项目名的账号会话化名与预览会话识别
|
||||
|
||||
use gateway_core::account::ProviderAccount;
|
||||
use reqwest::header::HeaderMap;
|
||||
@@ -19,7 +19,10 @@ pub(super) fn account_session_scope(session: &str, account: &ProviderAccount) ->
|
||||
hex::encode(hash.finalize())
|
||||
}
|
||||
|
||||
pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<usize, &'static str> {
|
||||
pub(super) fn anonymize_project(
|
||||
value: &mut Value,
|
||||
budget: &mut Budget<'_>,
|
||||
) -> Result<usize, &'static str> {
|
||||
let workspaces = value.as_object().ok_or("工作区映射必须是对象")?;
|
||||
if workspaces.is_empty() {
|
||||
return Ok(0);
|
||||
@@ -32,9 +35,7 @@ pub(super) fn anonymize(value: &mut Value, budget: &mut Budget<'_>) -> Result<us
|
||||
let mut renamed = Map::new();
|
||||
for (path, metadata) in workspaces {
|
||||
budget.text(path)?;
|
||||
let mut metadata = metadata.as_object().ok_or("工作区信息必须是对象")?.clone();
|
||||
metadata.remove("associated_remote_urls");
|
||||
metadata.remove("latest_git_commit_hash");
|
||||
let metadata = metadata.as_object().ok_or("工作区信息必须是对象")?.clone();
|
||||
let alias = alias_path(path, session)?;
|
||||
if renamed.insert(alias, Value::Object(metadata)).is_some() {
|
||||
return Err("工作区匿名化产生重名");
|
||||
@@ -63,21 +64,8 @@ fn alias_path(path: &str, session: &str) -> Result<String, &'static str> {
|
||||
hash.update(session.as_bytes());
|
||||
hash.update(path.as_bytes());
|
||||
let digest = hash.finalize();
|
||||
// 保留客户端的分隔符和父目录层级,用户名与工程名改用化名
|
||||
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");
|
||||
}
|
||||
}
|
||||
// 只改工程名,父目录与用户名交给独立的字段名替换步骤
|
||||
let mut alias = path[..=split].to_owned();
|
||||
alias.push_str(&shuffled_project_name(&path[split + 1..], &digest));
|
||||
alias.push_str(&format!(
|
||||
"-{}-{}",
|
||||
|
||||
@@ -389,6 +389,7 @@ fn pat_service(server: &MockServer) -> CodexCredentialAdminService {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
runtime_policy(),
|
||||
)
|
||||
.expect("auth client");
|
||||
CodexCredentialAdminService::new(
|
||||
@@ -505,6 +506,7 @@ async fn pat_import_times_out_without_falling_back_to_document_identity() {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
runtime_policy(),
|
||||
);
|
||||
let service = CodexCredentialAdminService::new(
|
||||
Arc::new(UnusedRefresher),
|
||||
|
||||
@@ -171,6 +171,7 @@ async fn complete_with_name(
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -228,6 +229,11 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() {
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
wire_profile,
|
||||
Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
gateway_core::account::OpaqueProviderData::new(serde_json::json!({
|
||||
"client": "desktop", "platform": "macos", "versionMode": "latest", "osVersion": "27.0.1"
|
||||
}).as_object().unwrap().clone()),
|
||||
))),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -379,6 +385,54 @@ async fn authorize_url_matches_the_official_desktop_parameter_contract() {
|
||||
assert!(!parameters.contains_key("nonce"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authorization_uses_global_cli_metadata_and_rejects_invalid_configuration() {
|
||||
let document = |value: serde_json::Value| {
|
||||
gateway_core::account::OpaqueProviderData::new(value.as_object().unwrap().clone())
|
||||
};
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
document(
|
||||
serde_json::json!({"client":"cli","platform":"macos","versionMode":"fixed","codexVersion":"0.170.0"}),
|
||||
),
|
||||
)));
|
||||
let service = CodexOAuthAdminService::new(
|
||||
Arc::new(PendingStore::default()),
|
||||
Arc::new(Exchanger {
|
||||
id_token: "unused".into(),
|
||||
}),
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
policy.clone(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
mutation: mutation(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let outer = Url::parse(&started.authorization_url).unwrap();
|
||||
let inner = outer
|
||||
.query_pairs()
|
||||
.find(|(name, _)| name == "authorize_url")
|
||||
.unwrap()
|
||||
.1
|
||||
.into_owned();
|
||||
let inner = Url::parse(&inner).unwrap();
|
||||
let parameters: std::collections::BTreeMap<_, _> = inner.query_pairs().into_owned().collect();
|
||||
assert_eq!(parameters["originator"], "codex_cli_rs");
|
||||
assert!(!parameters.contains_key("codex_app_version"));
|
||||
*policy.0.lock().unwrap() = document(serde_json::json!({"client":"unsupported"}));
|
||||
assert!(matches!(
|
||||
service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
mutation: mutation()
|
||||
})
|
||||
.await,
|
||||
Err(CodexOAuthAdminError::Profile(_))
|
||||
));
|
||||
}
|
||||
|
||||
fn profile() -> CodexWireProfileState {
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default())
|
||||
}
|
||||
@@ -395,6 +449,7 @@ async fn separate_new_authorizations_use_distinct_surface_stable_ids() {
|
||||
Arc::new(MemoryAccountStore::default()),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -452,6 +507,7 @@ async fn repeated_reauthorization_preserves_surface_id_with_a_cleared_name() {
|
||||
store.clone(),
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
@@ -510,6 +566,7 @@ async fn reauthorization_binds_the_selected_slot_to_the_new_oauth_account() {
|
||||
store,
|
||||
CodexCredentialAdmin,
|
||||
profile(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let started = service
|
||||
.start_authorization(StartCodexOAuthAuthorization {
|
||||
|
||||
@@ -13,6 +13,60 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
use crate::support::{MemoryAccountStore, profile, secret};
|
||||
|
||||
#[tokio::test]
|
||||
async fn profile_subscription_and_avatar_follow_global_identity_changes() {
|
||||
let server = MockServer::start().await;
|
||||
let (store, _) = service("acct_global_profile", &server).await;
|
||||
let account = store.account("acct_global_profile").unwrap();
|
||||
for (endpoint, body) in [
|
||||
(
|
||||
"/api/codex/profiles/me",
|
||||
json!({"profile":{"profile_picture_url":"https://chatgpt.com/backend-api/estuary/public_content/enc/avatar-token="},"stats":{}}),
|
||||
),
|
||||
("/backend-api/subscriptions", json!({"will_renew":true})),
|
||||
] {
|
||||
Mock::given(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(body))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
Mock::given(path("/estuary/public_content/enc/avatar-token="))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw("<svg/>", "image/svg+xml"))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(gateway_core::account::OpaqueProviderData::new(
|
||||
Default::default(),
|
||||
)),
|
||||
));
|
||||
let service = CodexCredentialProfileService::new(
|
||||
store.repository(),
|
||||
wire_profile(),
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
server.uri(),
|
||||
policy.clone(),
|
||||
);
|
||||
for os in ["27.0.1", "27.0.2"] {
|
||||
let ua = format!("codex_cli_rs/0.170.0 (Mac OS {os}; arm64) global-test");
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(
|
||||
json!({"mode":"custom","userAgent":ua})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
service.profile_statistics(account.id()).await.unwrap();
|
||||
service.subscription(account.id()).await.unwrap();
|
||||
let mut avatar = service.profile_avatar(account.id()).await.unwrap();
|
||||
while avatar.body.try_next().await.unwrap().is_some() {}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 3);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(request.headers["user-agent"], ua);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_profile() -> CodexWireProfileState {
|
||||
CodexWireProfileState::new(CodexWireProfile {
|
||||
client_kind: provider_openai::profile::selection::ClientKind::Desktop,
|
||||
@@ -58,6 +112,7 @@ async fn service(
|
||||
.build()
|
||||
.expect("client"),
|
||||
server.uri(),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
(store, service)
|
||||
}
|
||||
|
||||
@@ -33,6 +33,74 @@ use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
use crate::support::{MemoryAccountStore, profile, secret};
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_background_operations_use_current_global_identity_and_recover_from_invalid_profile()
|
||||
{
|
||||
use gateway_core::account::OpaqueProviderData;
|
||||
let server = MockServer::start().await;
|
||||
for (endpoint, body) in [
|
||||
(
|
||||
"/api/codex/usage",
|
||||
json!({"rate_limit":{"allowed":true,"primary_window":{"used_percent":10}}}),
|
||||
),
|
||||
(
|
||||
"/api/codex/rate-limit-reset-credits",
|
||||
json!({"available_count":0,"credits":[]}),
|
||||
),
|
||||
(
|
||||
"/api/codex/rate-limit-reset-credits/consume",
|
||||
json!({"code":"reset","credit":{"id":"test-credit","reset_type":"codex_rate_limits"}}),
|
||||
),
|
||||
] {
|
||||
Mock::given(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(body))
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_global_identity").await;
|
||||
let account = store.account("acct_global_identity").unwrap();
|
||||
let document =
|
||||
|value: serde_json::Value| OpaqueProviderData::new(value.as_object().unwrap().clone());
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(document(json!({"mode":"custom","userAgent":"invalid"}))),
|
||||
));
|
||||
let service = CodexCredentialQuotaService::new(
|
||||
store.repository(),
|
||||
wire_profile(),
|
||||
reqwest::Client::builder().no_proxy().build().unwrap(),
|
||||
server.uri(),
|
||||
Arc::new(crate::support::MemoryCooldownPort::new()),
|
||||
policy.clone(),
|
||||
)
|
||||
.with_initial_sync_delays(Arc::new(|| Duration::ZERO));
|
||||
assert!(matches!(
|
||||
service.synchronize().await,
|
||||
Err(CodexCredentialQuotaError::Profile(_))
|
||||
));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
for os in ["27.0.1", "27.0.2"] {
|
||||
let ua = format!("codex_cli_rs/0.170.0 (Mac OS {os}; arm64) global-test");
|
||||
*policy.0.lock().unwrap() = document(json!({"mode":"custom","userAgent":ua}));
|
||||
let before = server.received_requests().await.unwrap().len();
|
||||
if os == "27.0.1" {
|
||||
assert_eq!(service.synchronize().await.unwrap().updated, 1);
|
||||
} else {
|
||||
service.refresh_account(account.id()).await.unwrap();
|
||||
}
|
||||
service.list_reset_credits(account.id()).await.unwrap();
|
||||
service
|
||||
.consume_reset_credit(account.id(), Some("test-credit"), uuid::Uuid::new_v4())
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len() - before, 3);
|
||||
for request in &requests[before..] {
|
||||
assert_eq!(request.headers["user-agent"], ua);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wire_profile() -> CodexWireProfileState {
|
||||
CodexWireProfileState::new(CodexWireProfile {
|
||||
client_kind: provider_openai::profile::selection::ClientKind::Desktop,
|
||||
|
||||
@@ -614,6 +614,7 @@ async fn scheduled_refresh_persists_retryable_message_inside_the_two_hour_window
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
)),
|
||||
Arc::new(RefreshLeases),
|
||||
Arc::new(RefreshCredentialState),
|
||||
|
||||
@@ -49,7 +49,7 @@ async fn refresh_and_code_exchange_use_the_selected_account_proxy() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange() {
|
||||
async fn authentication_requests_track_global_identity_and_releases() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
@@ -60,18 +60,33 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
.mount(&server)
|
||||
.await;
|
||||
let profile = provider_openai::profile::CodexWireProfileState::new(Default::default());
|
||||
let policy = std::sync::Arc::new(crate::support::RequestProfileRuntimePolicy(
|
||||
std::sync::Mutex::new(gateway_core::account::OpaqueProviderData::new(
|
||||
Default::default(),
|
||||
)),
|
||||
));
|
||||
let client = provider_openai::credential::token_client::openai_token_client(
|
||||
TokenClientConfig {
|
||||
client_id: "audit-client".to_owned(),
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
profile.clone(),
|
||||
policy.clone(),
|
||||
)
|
||||
.expect("production auth transport");
|
||||
for (core, desktop, build) in [
|
||||
("1.2.3", "26.800.10000", "8000"),
|
||||
("1.2.4", "26.901.10000", "8109"),
|
||||
for (core, desktop, build, os_version) in [
|
||||
("1.2.3", "26.800.10000", "8000", "27.0.1"),
|
||||
("1.2.4", "26.901.10000", "8109", "27.0.2"),
|
||||
] {
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(
|
||||
serde_json::json!({
|
||||
"client": "desktop", "platform": "macos", "versionMode": "latest",
|
||||
"osVersion": os_version
|
||||
})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
profile.update_bundled_release(&provider_openai::profile::CodexBundledReleaseProfile {
|
||||
codex_version: core.to_owned(),
|
||||
desktop_version: desktop.to_owned(),
|
||||
@@ -91,7 +106,9 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
let exchange = &requests[requests.len() - 1];
|
||||
assert_eq!(
|
||||
refresh.headers["user-agent"],
|
||||
profile.snapshot().user_agent()
|
||||
format!(
|
||||
"Codex Desktop/{core} (Mac OS {os_version}; arm64) unknown (Codex Desktop; {desktop})"
|
||||
)
|
||||
);
|
||||
assert_eq!(refresh.headers["originator"], "Codex Desktop");
|
||||
assert_eq!(refresh.headers["content-type"], "application/json");
|
||||
@@ -99,18 +116,32 @@ async fn refresh_tracks_the_online_profile_without_contaminating_code_exchange()
|
||||
exchange.headers["content-type"],
|
||||
"application/x-www-form-urlencoded"
|
||||
);
|
||||
for name in [
|
||||
"originator",
|
||||
"user-agent",
|
||||
"version",
|
||||
"x-openai-internal-codex-residency",
|
||||
] {
|
||||
assert!(!exchange.headers.contains_key(name), "raw exchange: {name}");
|
||||
}
|
||||
for name in ["authorization", "chatgpt-account-id", "version"] {
|
||||
assert!(!refresh.headers.contains_key(name), "refresh: {name}");
|
||||
assert_eq!(
|
||||
exchange.headers["user-agent"],
|
||||
refresh.headers["user-agent"]
|
||||
);
|
||||
assert_eq!(exchange.headers["originator"], "Codex Desktop");
|
||||
for request in [refresh, exchange] {
|
||||
for name in ["authorization", "chatgpt-account-id", "version"] {
|
||||
assert!(!request.headers.contains_key(name), "auth request: {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(Default::default());
|
||||
assert!(matches!(
|
||||
client.refresh("audit-refresh").await,
|
||||
Err(RefreshFailure::RetryableTransport { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
client
|
||||
.exchange_authorization_code(AuthorizationCodeGrant {
|
||||
code: SecretString::from("audit-code"),
|
||||
code_verifier: SecretString::from("audit-verifier")
|
||||
})
|
||||
.await,
|
||||
Err(AuthorizationCodeExchangeError::Unavailable)
|
||||
));
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 4);
|
||||
}
|
||||
|
||||
fn client(server: &MockServer) -> OpenAiTokenClient {
|
||||
@@ -124,6 +155,7 @@ fn client(server: &MockServer) -> OpenAiTokenClient {
|
||||
token_endpoint: format!("{}/oauth/token", server.uri()),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -392,6 +424,7 @@ async fn authorization_code_response_timeouts_remain_ambiguous_without_exposing_
|
||||
token_endpoint: format!("http://{address}/oauth/token?PRIVATE_URL_MARKER"),
|
||||
},
|
||||
provider_openai::profile::CodexWireProfileState::new(Default::default()),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let error = client
|
||||
.exchange_authorization_code(AuthorizationCodeGrant {
|
||||
|
||||
@@ -247,7 +247,7 @@ async fn restored_cache_release_should_stay_in_version_lag_history() {
|
||||
assert_eq!(lagged.desktop_version, "26.810.41047");
|
||||
assert_eq!(
|
||||
lagged.user_agent(),
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 27.2.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
);
|
||||
// 滞后两档落到启动种子,恢复观察与启动种子共同构成启动历史。
|
||||
assert_eq!(
|
||||
|
||||
@@ -10,7 +10,7 @@ use provider_openai::profile::{
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn six_presets_have_explicit_availability_and_cli_has_no_desktop_suffix() {
|
||||
fn six_presets_resolve_available_client_identities() {
|
||||
let state = CodexWireProfileState::new(CodexWireProfile::default());
|
||||
assert_eq!(
|
||||
ClientProfileSelection::default().resolve(&state).unwrap(),
|
||||
@@ -25,22 +25,29 @@ fn six_presets_have_explicit_availability_and_cli_has_no_desktop_suffix() {
|
||||
.iter()
|
||||
.all(|preset| preset["automaticAvailable"] == true)
|
||||
);
|
||||
for platform in [
|
||||
ClientPlatform::Macos,
|
||||
ClientPlatform::Linux,
|
||||
ClientPlatform::Windows,
|
||||
] {
|
||||
let selection = ClientProfileSelection {
|
||||
client: ClientKind::Cli,
|
||||
platform,
|
||||
..Default::default()
|
||||
};
|
||||
for preset in presets
|
||||
.iter()
|
||||
.filter(|preset| preset["configuration"]["client"] == "cli")
|
||||
{
|
||||
let selection: ClientProfileSelection =
|
||||
serde_json::from_value(preset["configuration"].clone()).unwrap();
|
||||
let profile = selection.resolve(&state).unwrap();
|
||||
assert_eq!(profile.originator, "codex_cli_rs");
|
||||
assert_eq!(profile.os_type, platform.os_type());
|
||||
if selection.platform == ClientPlatform::Macos {
|
||||
let version = &profile.codex_version;
|
||||
assert_eq!(
|
||||
profile.user_agent(),
|
||||
format!(
|
||||
"codex-tui/{version} (Mac OS 27.2.1; arm64) Apple_Terminal/488.9 (codex-tui; {version})"
|
||||
)
|
||||
);
|
||||
assert_eq!(profile.originator, "codex-tui");
|
||||
} else {
|
||||
assert_eq!(profile.originator, "codex_cli_rs");
|
||||
assert!(profile.user_agent().ends_with("unknown"));
|
||||
}
|
||||
assert_eq!(profile.os_type, selection.platform.os_type());
|
||||
assert!(profile.desktop_version.is_empty());
|
||||
assert!(!profile.user_agent().contains("Desktop"));
|
||||
assert!(profile.user_agent().ends_with("unknown"));
|
||||
assert!(profile.verified_at > chrono::DateTime::UNIX_EPOCH);
|
||||
}
|
||||
for platform in [ClientPlatform::Linux, ClientPlatform::Windows] {
|
||||
|
||||
@@ -73,7 +73,7 @@ async fn lagged_profiles_track_observed_release_history() {
|
||||
assert_eq!(lagged.desktop_version, "26.810.41047");
|
||||
assert_eq!(
|
||||
lagged.user_agent(),
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 15.7.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
"Codex Desktop/0.148.0-alpha.9 (Mac OS 27.2.1; arm64) unknown (Codex Desktop; 26.810.41047)"
|
||||
);
|
||||
assert_eq!(
|
||||
selection(Some(2)).resolve(&state).unwrap().codex_version,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 隐私规则在真实 HTTP、WebSocket 和发送前拒绝边界的合同
|
||||
|
||||
use super::*;
|
||||
use crate::transport::privacy::{policy, rule};
|
||||
use crate::transport::privacy::{policy, rule, workspace_rule};
|
||||
use gateway_core::settings::privacy::{CodexPrivacyPolicy, PrivacyAction, PrivacyScope};
|
||||
|
||||
fn privacy_context(policy: &CodexPrivacyPolicy, fallback: bool) -> AttemptContext {
|
||||
@@ -96,11 +96,7 @@ fn workspace_operation(session: &str, owner: &str) -> Operation {
|
||||
}
|
||||
|
||||
fn workspace_policy() -> CodexPrivacyPolicy {
|
||||
policy(vec![rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeWorkspace,
|
||||
)])
|
||||
policy(vec![workspace_rule("user")])
|
||||
}
|
||||
|
||||
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 {
|
||||
CodexPrivacyPolicy {
|
||||
enabled: true,
|
||||
|
||||
@@ -2,12 +2,82 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
fn anonymous_rule() -> PrivacyRule {
|
||||
rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeWorkspace,
|
||||
)
|
||||
#[test]
|
||||
fn project_anonymization_preserves_usernames_and_git_information() {
|
||||
for path in [
|
||||
"/home/alex/projects/private",
|
||||
"/Users/alex/private",
|
||||
r"C:\Users\alex\private",
|
||||
] {
|
||||
let metadata = json!({"associated_remote_urls":{"origin":"https://example.invalid/team/private"},"latest_git_commit_hash":"abc","has_changes":true});
|
||||
let mut request = sample(
|
||||
vec![rule(
|
||||
PrivacyScope::TurnMetadata,
|
||||
"$.workspaces",
|
||||
PrivacyAction::AnonymizeProject,
|
||||
)],
|
||||
json!({"turn_metadata":{"workspaces":{path:metadata}}}),
|
||||
);
|
||||
request
|
||||
.headers
|
||||
.insert("session-id".into(), vec!["sample-session".into()]);
|
||||
let output = preview(request).unwrap();
|
||||
let (alias, value) = output.body["turn_metadata"]["workspaces"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(alias.starts_with(path.rsplit_once(['/', '\\']).unwrap().0));
|
||||
assert_ne!(alias, path);
|
||||
assert_eq!(value, &metadata);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_steps_allow_customizing_username_and_retaining_remotes() {
|
||||
for path in [
|
||||
"/home/alex/projects/private",
|
||||
"/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 mut customized = workspace_rule("blg");
|
||||
customized.steps.remove(2);
|
||||
let mut request = sample(
|
||||
vec![customized],
|
||||
json!({"client_metadata":{"x-codex-turn-metadata":metadata.to_string()}}),
|
||||
);
|
||||
request.turn_metadata = Some(metadata.to_string());
|
||||
request
|
||||
.headers
|
||||
.insert("session-id".into(), vec!["sample-session".into()]);
|
||||
request
|
||||
.headers
|
||||
.insert("x-codex-turn-metadata".into(), vec![metadata.to_string()]);
|
||||
let output = preview(request).unwrap();
|
||||
let value: Value = serde_json::from_str(output.turn_metadata.as_deref().unwrap()).unwrap();
|
||||
let (alias, workspace) = value["workspaces"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap();
|
||||
assert!(
|
||||
alias.starts_with(
|
||||
&path
|
||||
.rsplit_once(['/', '\\'])
|
||||
.unwrap()
|
||||
.0
|
||||
.replace("alex", "blg")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
workspace["associated_remote_urls"],
|
||||
metadata["workspaces"][path]["associated_remote_urls"]
|
||||
);
|
||||
assert!(workspace.get("latest_git_commit_hash").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -25,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 original_input = json!([{"role":"user","content":format!("<cwd>{path}</cwd>")}]);
|
||||
let mut request = sample(
|
||||
vec![anonymous_rule()],
|
||||
vec![workspace_rule("user")],
|
||||
json!({
|
||||
"input":original_input,
|
||||
"turnMetadata":metadata,
|
||||
@@ -94,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!(result.outcomes[0].matches, 7);
|
||||
assert_eq!(result.outcomes[0].matches, 28);
|
||||
assert_eq!(preview(request.clone()).unwrap().body, result.body);
|
||||
request
|
||||
.headers
|
||||
@@ -110,7 +180,7 @@ fn aliases_preserve_path_style_and_execution_context_across_all_carriers() {
|
||||
fn long_workspace_names_produce_valid_directory_components() {
|
||||
let path = format!("/workspace/{}", "工程".repeat(40));
|
||||
let mut request = sample(
|
||||
vec![anonymous_rule()],
|
||||
vec![workspace_rule("user")],
|
||||
json!({"turn_metadata":{"workspaces":{path:{}}}}),
|
||||
);
|
||||
request
|
||||
@@ -130,7 +200,7 @@ fn long_workspace_names_produce_valid_directory_components() {
|
||||
|
||||
#[test]
|
||||
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 mut entries = serde_json::Map::new();
|
||||
for n in 0..count {
|
||||
@@ -168,7 +238,7 @@ fn multiple_workspaces_remain_stable_as_the_workspace_set_grows() {
|
||||
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"}}}});
|
||||
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;
|
||||
let mut body = original.clone();
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
@@ -195,7 +265,7 @@ fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
preview(sample(vec![anonymous_rule()], json!({})))
|
||||
preview(sample(vec![workspace_rule("user")], json!({})))
|
||||
.unwrap()
|
||||
.outcomes[0]
|
||||
.matches
|
||||
@@ -209,7 +279,7 @@ fn workspace_failure_rolls_back_every_copy_and_respects_policy() {
|
||||
compile(&policy(vec![rule(
|
||||
scope,
|
||||
selector,
|
||||
PrivacyAction::AnonymizeWorkspace
|
||||
PrivacyAction::AnonymizeProject
|
||||
)]))
|
||||
.is_err()
|
||||
);
|
||||
|
||||
@@ -94,6 +94,11 @@ pub(super) fn map_quota_error(error: GrokQuotaError) -> ProviderAdminError {
|
||||
Error::InvalidData => (Kind::Invalid, "凭据或额度数据无效"),
|
||||
Error::Upstream => (Kind::Unavailable, "额度查询失败"),
|
||||
Error::Store => (Kind::Unavailable, "额度查询暂不可用"),
|
||||
Error::Profile(source) => {
|
||||
return provider_error(Kind::Unavailable)
|
||||
.with_public_message("客户端身份不可用")
|
||||
.with_source(source);
|
||||
}
|
||||
};
|
||||
provider_error(kind).with_public_message(message)
|
||||
}
|
||||
@@ -108,6 +113,11 @@ pub(super) fn map_catalog_error(error: GrokCredentialCatalogError) -> ProviderAd
|
||||
Error::StaleCredentialSnapshot => (Kind::Conflict, "凭据已更新,请刷新账号列表"),
|
||||
Error::Upstream => (Kind::Unavailable, "模型查询失败"),
|
||||
Error::Cache | Error::Store => (Kind::Unavailable, "模型查询暂不可用"),
|
||||
Error::Profile(source) => {
|
||||
return provider_error(Kind::Unavailable)
|
||||
.with_public_message("客户端身份不可用")
|
||||
.with_source(source);
|
||||
}
|
||||
};
|
||||
provider_error(kind).with_public_message(message)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ use gateway_core::account::{
|
||||
};
|
||||
use gateway_core::provider_ports::{
|
||||
ProviderCatalogCacheKey, ProviderCatalogCachePort, ProviderCatalogScope,
|
||||
ProviderRuntimePolicyPort,
|
||||
};
|
||||
use gateway_core::routing::{ProviderCatalogGeneration, ProviderKind};
|
||||
|
||||
@@ -348,6 +349,8 @@ pub enum GrokCredentialCatalogError {
|
||||
ConflictingModelFacts,
|
||||
#[error("Grok model catalog cache update failed")]
|
||||
Cache,
|
||||
#[error("Grok client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("Grok provider account store is unavailable")]
|
||||
Store,
|
||||
}
|
||||
@@ -359,6 +362,7 @@ pub struct GrokCredentialCatalogService {
|
||||
cache: Arc<dyn GrokCredentialCatalogCache>,
|
||||
published: Arc<RwLock<PublishedCatalogState>>,
|
||||
wire_profile: XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
/// 同一目录模型可由多个套餐的成员账号发现
|
||||
@@ -377,6 +381,7 @@ impl GrokCredentialCatalogService {
|
||||
transport: Arc<dyn GrokModelCatalogTransport>,
|
||||
cache: Arc<dyn GrokCredentialCatalogCache>,
|
||||
wire_profile: XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
repository,
|
||||
@@ -384,6 +389,7 @@ impl GrokCredentialCatalogService {
|
||||
cache,
|
||||
published: Arc::new(RwLock::new(PublishedCatalogState::default())),
|
||||
wire_profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -578,12 +584,18 @@ impl GrokCredentialCatalogService {
|
||||
candidates: Vec<LoadedGrokCredential>,
|
||||
) -> Result<FetchedCredentialCatalog, GrokCredentialCatalogError> {
|
||||
let mut last_error = None;
|
||||
let profile = XaiWireProfileState::new(
|
||||
self.wire_profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(GrokCredentialCatalogError::Profile)?,
|
||||
);
|
||||
for candidate in candidates.into_iter().take(MAX_CATALOG_FETCH_ATTEMPTS) {
|
||||
match fetch_candidate_catalog(
|
||||
Arc::clone(&self.client),
|
||||
scope.clone(),
|
||||
candidate,
|
||||
self.wire_profile.clone(),
|
||||
profile.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
|
||||
use crate::credential::token::{parse_oauth_error, parse_refresh_success, parse_token_success};
|
||||
use crate::{
|
||||
AllowedRedirectUri, AuthorizationCodeGrant, DiscoveryDocument, FormField, GrokOAuthConfig,
|
||||
HttpHeader, OAuthError, OAuthHttpRequest, OAuthHttpResponse, OAuthHttpTransport,
|
||||
OAuthOperation, OAuthPrincipal, PendingAuthorization, RefreshTokenGrant, RefreshedTokenSet,
|
||||
TokenCandidate, TokenVerificationContext, TokenVerifier, VerificationFailure, VerificationFlow,
|
||||
OAuthError, OAuthHttpRequest, OAuthHttpResponse, OAuthHttpTransport, OAuthOperation,
|
||||
OAuthPrincipal, PendingAuthorization, RefreshTokenGrant, RefreshedTokenSet, TokenCandidate,
|
||||
TokenVerificationContext, TokenVerifier, VerificationFailure, VerificationFlow,
|
||||
VerificationMethod, VerifiedTokenSet,
|
||||
};
|
||||
|
||||
@@ -16,6 +18,7 @@ use crate::{
|
||||
pub struct GrokOAuthClient {
|
||||
config: GrokOAuthConfig,
|
||||
wire_profile: crate::XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
transport: Arc<dyn OAuthHttpTransport>,
|
||||
verifier: Arc<dyn TokenVerifier>,
|
||||
outbound_proxy: Option<gateway_core::account::OutboundProxy>,
|
||||
@@ -29,12 +32,14 @@ impl GrokOAuthClient {
|
||||
wire_profile: crate::XaiWireProfileState,
|
||||
transport: Arc<dyn OAuthHttpTransport>,
|
||||
verifier: Arc<dyn TokenVerifier>,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
wire_profile,
|
||||
transport,
|
||||
verifier,
|
||||
runtime_policy,
|
||||
outbound_proxy: None,
|
||||
}
|
||||
}
|
||||
@@ -59,10 +64,11 @@ impl GrokOAuthClient {
|
||||
/// transport 失败、非成功状态、JSON 非法、issuer 不匹配、端点跨 origin、
|
||||
/// 缺少 JWKS 或算法不安全时返回错误
|
||||
pub async fn discover(&self) -> Result<DiscoveryDocument, OAuthError> {
|
||||
let profile = self.request_profile(OAuthOperation::Discovery).await?;
|
||||
let response = self
|
||||
.execute(
|
||||
OAuthOperation::Discovery,
|
||||
OAuthHttpRequest::get(self.config.discovery_url()),
|
||||
OAuthHttpRequest::get(self.config.discovery_url()).with_profile(&profile),
|
||||
)
|
||||
.await?;
|
||||
if !is_success(&response) {
|
||||
@@ -101,10 +107,13 @@ impl GrokOAuthClient {
|
||||
discovery: &DiscoveryDocument,
|
||||
grant: AuthorizationCodeGrant,
|
||||
) -> Result<VerifiedTokenSet, OAuthError> {
|
||||
let profile = self
|
||||
.request_profile(OAuthOperation::AuthorizationCodeToken)
|
||||
.await?;
|
||||
let (code, redirect_uri, code_verifier, nonce) = grant.into_parts();
|
||||
let request = OAuthHttpRequest::post(
|
||||
discovery.token_endpoint().clone(),
|
||||
vec![self.version_header()],
|
||||
vec![],
|
||||
vec![
|
||||
FormField::public("grant_type", "authorization_code"),
|
||||
FormField::secret("code", code),
|
||||
@@ -114,7 +123,10 @@ impl GrokOAuthClient {
|
||||
],
|
||||
);
|
||||
let response = self
|
||||
.execute(OAuthOperation::AuthorizationCodeToken, request)
|
||||
.execute(
|
||||
OAuthOperation::AuthorizationCodeToken,
|
||||
request.with_profile(&profile),
|
||||
)
|
||||
.await?;
|
||||
if !is_success(&response) {
|
||||
return Err(parse_oauth_error(
|
||||
@@ -144,7 +156,9 @@ impl GrokOAuthClient {
|
||||
let evidence = self
|
||||
.verifier
|
||||
.verify(
|
||||
context.with_outbound_proxy(self.outbound_proxy.as_ref()),
|
||||
context
|
||||
.with_outbound_proxy(self.outbound_proxy.as_ref())
|
||||
.with_wire_profile(&profile),
|
||||
candidate,
|
||||
)
|
||||
.await?;
|
||||
@@ -172,6 +186,9 @@ impl GrokOAuthClient {
|
||||
candidate: crate::GrokOAuthImportCandidate,
|
||||
) -> Result<VerifiedTokenSet, crate::GrokOAuthImportError> {
|
||||
let validated = candidate.validate(&self.config, chrono::Utc::now())?;
|
||||
let profile = self
|
||||
.request_profile(OAuthOperation::CredentialImport)
|
||||
.await?;
|
||||
let scope = validated.scope;
|
||||
let mut tokens = validated.tokens;
|
||||
let flow = if validated.requires_refresh {
|
||||
@@ -180,7 +197,11 @@ impl GrokOAuthClient {
|
||||
.take()
|
||||
.ok_or(crate::GrokOAuthImportError::InvalidField("refresh_token"))?;
|
||||
let refreshed = self
|
||||
.refresh(discovery, &RefreshTokenGrant::new(refresh_token.clone()))
|
||||
.refresh_with_profile(
|
||||
discovery,
|
||||
&RefreshTokenGrant::new(refresh_token.clone()),
|
||||
&profile,
|
||||
)
|
||||
.await?;
|
||||
tokens = crate::credential::token::UnverifiedTokenSet {
|
||||
access_token: refreshed.access_token().clone(),
|
||||
@@ -214,7 +235,9 @@ impl GrokOAuthClient {
|
||||
let evidence = self
|
||||
.verifier
|
||||
.verify(
|
||||
context.with_outbound_proxy(self.outbound_proxy.as_ref()),
|
||||
context
|
||||
.with_outbound_proxy(self.outbound_proxy.as_ref())
|
||||
.with_wire_profile(&profile),
|
||||
verification_candidate,
|
||||
)
|
||||
.await
|
||||
@@ -250,6 +273,16 @@ impl GrokOAuthClient {
|
||||
&self,
|
||||
discovery: &DiscoveryDocument,
|
||||
grant: &RefreshTokenGrant,
|
||||
) -> Result<RefreshedTokenSet, OAuthError> {
|
||||
let profile = self.request_profile(OAuthOperation::RefreshToken).await?;
|
||||
self.refresh_with_profile(discovery, grant, &profile).await
|
||||
}
|
||||
|
||||
async fn refresh_with_profile(
|
||||
&self,
|
||||
discovery: &DiscoveryDocument,
|
||||
grant: &RefreshTokenGrant,
|
||||
profile: &crate::XaiWireProfile,
|
||||
) -> Result<RefreshedTokenSet, OAuthError> {
|
||||
let form = vec![
|
||||
FormField::public("grant_type", "refresh_token"),
|
||||
@@ -259,11 +292,8 @@ impl GrokOAuthClient {
|
||||
let response = self
|
||||
.execute(
|
||||
OAuthOperation::RefreshToken,
|
||||
OAuthHttpRequest::post(
|
||||
discovery.token_endpoint().clone(),
|
||||
vec![self.version_header()],
|
||||
form,
|
||||
),
|
||||
OAuthHttpRequest::post(discovery.token_endpoint().clone(), vec![], form)
|
||||
.with_profile(profile),
|
||||
)
|
||||
.await?;
|
||||
if !is_success(&response) {
|
||||
@@ -284,8 +314,19 @@ impl GrokOAuthClient {
|
||||
.map_err(|failure| OAuthError::transport(operation, failure))
|
||||
}
|
||||
|
||||
fn version_header(&self) -> HttpHeader {
|
||||
HttpHeader::new("x-grok-client-version", self.wire_profile.client_version())
|
||||
async fn request_profile(
|
||||
&self,
|
||||
operation: OAuthOperation,
|
||||
) -> Result<crate::XaiWireProfile, OAuthError> {
|
||||
self.wire_profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
OAuthError::transport(
|
||||
operation,
|
||||
crate::TransportFailure::new(crate::TransportFailureKind::NotSent),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -161,7 +161,9 @@ impl ReqwestOidcTokenVerifier {
|
||||
return Err(VerificationFailure::Rejected);
|
||||
}
|
||||
let kid = header.kid.as_deref().ok_or(VerificationFailure::Rejected)?;
|
||||
let key = self.decoding_key(context.jwks_uri(), kid, egress).await?;
|
||||
let key = self
|
||||
.decoding_key(context.jwks_uri(), kid, egress, context.wire_profile())
|
||||
.await?;
|
||||
|
||||
let mut validation = Validation::new(Algorithm::ES256);
|
||||
validation.leeway = 0;
|
||||
@@ -221,11 +223,12 @@ impl ReqwestOidcTokenVerifier {
|
||||
if !valid_bearer_token(access_token) {
|
||||
return Err(VerificationFailure::Rejected);
|
||||
}
|
||||
let response = egress
|
||||
let request = egress
|
||||
.client
|
||||
.get(context.userinfo_endpoint().clone())
|
||||
.header(ACCEPT, "application/json")
|
||||
.bearer_auth(access_token)
|
||||
.bearer_auth(access_token);
|
||||
let response = with_profile(request, context.wire_profile())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| VerificationFailure::Unavailable)?;
|
||||
@@ -253,6 +256,7 @@ impl ReqwestOidcTokenVerifier {
|
||||
jwks_uri: &Url,
|
||||
kid: &str,
|
||||
egress: &OidcEgress,
|
||||
profile: Option<&crate::XaiWireProfile>,
|
||||
) -> Result<DecodingKey, VerificationFailure> {
|
||||
if !valid_key_id(kid) {
|
||||
return Err(VerificationFailure::Rejected);
|
||||
@@ -270,7 +274,7 @@ impl ReqwestOidcTokenVerifier {
|
||||
}
|
||||
|
||||
// fresh cache 未命中 kid 时只强制刷新一次,以支持官方密钥轮换
|
||||
let keys = self.fetch_jwks(jwks_uri, &egress.client).await?;
|
||||
let keys = self.fetch_jwks(jwks_uri, &egress.client, profile).await?;
|
||||
cache.replace(jwks_uri.clone(), keys);
|
||||
return cache
|
||||
.keys
|
||||
@@ -280,7 +284,7 @@ impl ReqwestOidcTokenVerifier {
|
||||
}
|
||||
|
||||
// 过期缓存不会在网络或协议失败时作为 stale fallback 使用
|
||||
let keys = self.fetch_jwks(jwks_uri, &egress.client).await?;
|
||||
let keys = self.fetch_jwks(jwks_uri, &egress.client, profile).await?;
|
||||
cache.replace(jwks_uri.clone(), keys);
|
||||
cache
|
||||
.keys
|
||||
@@ -293,13 +297,15 @@ impl ReqwestOidcTokenVerifier {
|
||||
&self,
|
||||
jwks_uri: &Url,
|
||||
client: &Client,
|
||||
profile: Option<&crate::XaiWireProfile>,
|
||||
) -> Result<HashMap<String, CachedJwk>, VerificationFailure> {
|
||||
if !self.endpoint_policy.validate_jwks(jwks_uri) {
|
||||
return Err(VerificationFailure::Rejected);
|
||||
}
|
||||
let response = client
|
||||
let request = client
|
||||
.get(jwks_uri.clone())
|
||||
.header(ACCEPT, "application/json")
|
||||
.header(ACCEPT, "application/json");
|
||||
let response = with_profile(request, profile)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| VerificationFailure::Unavailable)?;
|
||||
@@ -318,6 +324,18 @@ impl ReqwestOidcTokenVerifier {
|
||||
}
|
||||
}
|
||||
|
||||
fn with_profile(
|
||||
request: reqwest::RequestBuilder,
|
||||
profile: Option<&crate::XaiWireProfile>,
|
||||
) -> reqwest::RequestBuilder {
|
||||
match profile {
|
||||
Some(profile) => request
|
||||
.header("user-agent", profile.user_agent())
|
||||
.header("x-grok-client-version", &profile.client_version),
|
||||
None => request,
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenVerifier for ReqwestOidcTokenVerifier {
|
||||
fn verify<'a>(
|
||||
&'a self,
|
||||
|
||||
@@ -10,6 +10,7 @@ use gateway_core::account::{
|
||||
AccountQuotaResetWindow, AccountQuotaSignals, CredentialRevision, ProviderAccount,
|
||||
ProviderAccountId, QuotaObservation, QuotaResetPeriod, QuotaState,
|
||||
};
|
||||
use gateway_core::provider_ports::ProviderRuntimePolicyPort;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use super::repository::{GrokCredentialRepository, LoadedGrokCredential};
|
||||
@@ -145,7 +146,7 @@ impl GrokQuotaSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[derive(Debug, Clone, thiserror::Error)]
|
||||
pub enum GrokQuotaError {
|
||||
#[error("xAI quota account is unavailable")]
|
||||
AccountUnavailable,
|
||||
@@ -155,6 +156,8 @@ pub enum GrokQuotaError {
|
||||
InvalidData,
|
||||
#[error("xAI quota upstream request failed")]
|
||||
Upstream,
|
||||
#[error("xAI quota client profile is unavailable")]
|
||||
Profile(#[source] gateway_core::error::ErrorSource),
|
||||
#[error("xAI quota store is unavailable")]
|
||||
Store,
|
||||
}
|
||||
@@ -166,6 +169,7 @@ pub struct GrokCredentialQuotaService {
|
||||
client: Arc<GrokBillingClient>,
|
||||
scheduling: GrokQuotaSchedulingProjection,
|
||||
wire_profile: XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
@@ -346,12 +350,14 @@ impl GrokCredentialQuotaService {
|
||||
repository: GrokCredentialRepository,
|
||||
transport: Arc<dyn GrokBillingTransport>,
|
||||
wire_profile: XaiWireProfileState,
|
||||
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
|
||||
) -> Self {
|
||||
Self {
|
||||
repository,
|
||||
client: Arc::new(GrokBillingClient::new(transport)),
|
||||
scheduling: GrokQuotaSchedulingProjection::default(),
|
||||
wire_profile,
|
||||
runtime_policy,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,7 +426,13 @@ impl GrokCredentialQuotaService {
|
||||
{
|
||||
return Err(GrokQuotaError::AccountUnavailable);
|
||||
}
|
||||
let session = billing_session(&loaded, &self.wire_profile)?;
|
||||
let profile = XaiWireProfileState::new(
|
||||
self.wire_profile
|
||||
.resolve_global_request_profile(self.runtime_policy.as_ref())
|
||||
.await
|
||||
.map_err(GrokQuotaError::Profile)?,
|
||||
);
|
||||
let session = billing_session(&loaded, &profile)?;
|
||||
let billing = self
|
||||
.client
|
||||
.fetch(&session)
|
||||
|
||||
@@ -91,6 +91,7 @@ pub struct TokenVerificationContext<'a> {
|
||||
signing_algorithms: &'a [String],
|
||||
expected_nonce: Option<&'a SecretValue>,
|
||||
outbound_proxy: Option<&'a gateway_core::account::OutboundProxy>,
|
||||
wire_profile: Option<&'a crate::XaiWireProfile>,
|
||||
}
|
||||
|
||||
impl<'a> TokenVerificationContext<'a> {
|
||||
@@ -112,9 +113,22 @@ impl<'a> TokenVerificationContext<'a> {
|
||||
signing_algorithms,
|
||||
expected_nonce,
|
||||
outbound_proxy: None,
|
||||
wire_profile: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 认证验证沿用当前 OAuth 操作已冻结的全局客户端身份
|
||||
#[must_use]
|
||||
pub fn with_wire_profile(mut self, profile: &'a crate::XaiWireProfile) -> Self {
|
||||
self.wire_profile = Some(profile);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn wire_profile(&self) -> Option<&crate::XaiWireProfile> {
|
||||
self.wire_profile
|
||||
}
|
||||
|
||||
/// 绑定 OAuth owner 选择的账号出口,供公开的 [`TokenVerifier`] 实现遵守同一代理合同
|
||||
/// 出口只决定路由,不改变 issuer、JWKS、签名和 nonce 的信任校验
|
||||
#[must_use]
|
||||
|
||||
@@ -129,11 +129,13 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, Xai
|
||||
catalog_transport,
|
||||
catalog_cache_port,
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let quota = Arc::new(GrokCredentialQuotaService::new(
|
||||
repository.clone(),
|
||||
billing_transport,
|
||||
profile.clone(),
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let selector: Arc<dyn GrokSessionSelector> = Arc::new(GrokAccountSessionSelector::new(
|
||||
provider_kind.clone(),
|
||||
@@ -162,6 +164,7 @@ pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, Xai
|
||||
profile.clone(),
|
||||
oauth_transport,
|
||||
token_verifier,
|
||||
Arc::clone(&runtime_policy),
|
||||
));
|
||||
let refresher: Arc<dyn GrokCredentialRefresher> =
|
||||
Arc::new(GrokOAuthRefreshClient::new(Arc::clone(&oauth)));
|
||||
|
||||
@@ -129,6 +129,14 @@ pub struct OAuthHttpRequest {
|
||||
}
|
||||
|
||||
impl OAuthHttpRequest {
|
||||
pub(crate) fn with_profile(mut self, profile: &crate::XaiWireProfile) -> Self {
|
||||
self.headers.extend([
|
||||
HttpHeader::new("x-grok-client-version", &profile.client_version),
|
||||
HttpHeader::new("user-agent", profile.user_agent()),
|
||||
]);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn get(url: Url) -> Self {
|
||||
Self {
|
||||
method: HttpMethod::Get,
|
||||
|
||||
@@ -47,6 +47,20 @@ impl XaiWireProfile {
|
||||
pub struct XaiWireProfileState(Arc<RwLock<XaiWireProfile>>);
|
||||
|
||||
impl XaiWireProfileState {
|
||||
/// 账号后台操作按当前全局配置冻结身份,不读取 Client Key 覆盖
|
||||
pub(crate) async fn resolve_global_request_profile(
|
||||
&self,
|
||||
policy: &dyn gateway_core::provider_ports::ProviderRuntimePolicyPort,
|
||||
) -> Result<XaiWireProfile, gateway_core::error::ErrorSource> {
|
||||
let kind = gateway_core::routing::ProviderKind::new("xai")?;
|
||||
let Some(configuration) = policy.load_request_profile(&kind).await? else {
|
||||
return Ok(self.snapshot());
|
||||
};
|
||||
super::selection::GrokClientProfileSelection::parse(&configuration)
|
||||
.and_then(|selection| selection.resolve(self))
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn new(profile: XaiWireProfile) -> Self {
|
||||
Self(Arc::new(RwLock::new(profile)))
|
||||
|
||||
@@ -126,6 +126,7 @@ impl GrokModelCatalogRequest {
|
||||
session.wire_profile.client_version(),
|
||||
),
|
||||
GrokHeader::public("x-grok-client-mode", session.wire_profile.client_mode()),
|
||||
GrokHeader::public("user-agent", session.wire_profile.user_agent()),
|
||||
GrokHeader::public("accept", "application/json"),
|
||||
];
|
||||
if let Some(email) = &session.email {
|
||||
@@ -289,6 +290,7 @@ impl GrokBillingRequest {
|
||||
session.wire_profile.client_version(),
|
||||
),
|
||||
GrokHeader::public("x-grok-client-mode", session.wire_profile.client_mode()),
|
||||
GrokHeader::public("user-agent", session.wire_profile.user_agent()),
|
||||
GrokHeader::public("accept", "application/json"),
|
||||
];
|
||||
if let Some(email) = &session.email {
|
||||
|
||||
@@ -27,6 +27,103 @@ use crate::support::{
|
||||
const CLI_PROXY_FIXTURE: &[u8] =
|
||||
include_bytes!("../transport/catalog/fixtures/cli_proxy_models.json");
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_billing_and_subscription_use_current_global_identity() {
|
||||
use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode};
|
||||
use provider_xai::{
|
||||
GrokBillingRequest, GrokBillingTransport, GrokBillingTransportFuture,
|
||||
GrokBillingTransportResponse, GrokCredentialCatalogService, GrokCredentialQuotaService,
|
||||
};
|
||||
#[derive(Default)]
|
||||
struct RecordingTransport(Mutex<Vec<Vec<(String, String)>>>);
|
||||
impl RecordingTransport {
|
||||
fn record(&self, headers: &[provider_xai::GrokHeader]) {
|
||||
self.0.lock().unwrap().push(
|
||||
headers
|
||||
.iter()
|
||||
.filter(|h| matches!(h.name(), "user-agent" | "x-grok-client-version"))
|
||||
.map(|h| (h.name().to_owned(), h.value().expose().to_owned()))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
impl GrokModelCatalogTransport for RecordingTransport {
|
||||
fn execute(&self, request: GrokModelCatalogRequest) -> GrokModelCatalogTransportFuture<'_> {
|
||||
self.record(request.headers());
|
||||
Box::pin(async {
|
||||
Ok(GrokModelCatalogTransportResponse::new(
|
||||
CLI_PROXY_FIXTURE,
|
||||
None,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
impl GrokBillingTransport for RecordingTransport {
|
||||
fn execute(&self, request: GrokBillingRequest) -> GrokBillingTransportFuture<'_> {
|
||||
self.record(request.headers());
|
||||
Box::pin(async {
|
||||
Ok(GrokBillingTransportResponse::new(
|
||||
br#"{"config":{"creditUsagePercent":25},"subscriptionTier":"SuperGrokPro"}"#,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
let store = MemoryProviderAccountStore::shared();
|
||||
seed_input(&store, &create_input("global_profile", "global-subject"))
|
||||
.await
|
||||
.unwrap();
|
||||
let repository = GrokCredentialRepository::new(store);
|
||||
let selected = |version: &str| {
|
||||
GrokClientProfileSelection {
|
||||
version_mode: VersionMode::Fixed,
|
||||
client_version: Some(version.into()),
|
||||
target_os: "windows".into(),
|
||||
target_arch: "arm64".into(),
|
||||
..Default::default()
|
||||
}
|
||||
.document()
|
||||
.unwrap()
|
||||
};
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
selected("9.8.7"),
|
||||
)));
|
||||
let transport = Arc::new(RecordingTransport::default());
|
||||
let catalog = GrokCredentialCatalogService::new(
|
||||
repository.clone(),
|
||||
transport.clone(),
|
||||
Arc::new(MemoryGrokCatalogCache::default()),
|
||||
crate::support::xai_wire_profile(),
|
||||
policy.clone(),
|
||||
);
|
||||
let quota = GrokCredentialQuotaService::new(
|
||||
repository,
|
||||
transport.clone(),
|
||||
crate::support::xai_wire_profile(),
|
||||
policy.clone(),
|
||||
);
|
||||
for version in ["9.8.7", "9.8.8"] {
|
||||
*policy.0.lock().unwrap() = selected(version);
|
||||
catalog
|
||||
.refresh_account_catalog(&account_id("global_profile"))
|
||||
.await
|
||||
.unwrap();
|
||||
quota
|
||||
.refresh_account(&account_id("global_profile"))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut requests = transport.0.lock().unwrap();
|
||||
assert_eq!(requests.len(), 3);
|
||||
for headers in requests.drain(..) {
|
||||
let header = |name| headers.iter().find(|h| h.0 == name).unwrap().1.as_str();
|
||||
assert_eq!(
|
||||
header("user-agent"),
|
||||
format!("grok-shell/{version} (windows; aarch64)")
|
||||
);
|
||||
assert_eq!(header("x-grok-client-version"), version);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QueueCatalogTransport {
|
||||
calls: AtomicUsize,
|
||||
responses:
|
||||
|
||||
@@ -21,6 +21,80 @@ const DISCOVERY: &[u8] = include_bytes!("fixtures/discovery.json");
|
||||
const TOKEN_SUCCESS: &[u8] = include_bytes!("fixtures/token_success.json");
|
||||
const REFRESH_SUCCESS: &[u8] = include_bytes!("fixtures/refresh_success.json");
|
||||
|
||||
#[tokio::test]
|
||||
async fn oauth_discovery_exchange_and_refresh_use_current_global_identity() {
|
||||
use provider_xai::profile::selection::{GrokClientProfileSelection, VersionMode};
|
||||
let selected = |version: &str| {
|
||||
GrokClientProfileSelection {
|
||||
version_mode: VersionMode::Fixed,
|
||||
client_version: Some(version.to_owned()),
|
||||
target_os: "windows".into(),
|
||||
target_arch: "arm64".into(),
|
||||
..Default::default()
|
||||
}
|
||||
.document()
|
||||
.unwrap()
|
||||
};
|
||||
let policy = Arc::new(crate::support::RequestProfileRuntimePolicy(Mutex::new(
|
||||
selected("9.8.7"),
|
||||
)));
|
||||
let transport = Arc::new(FixtureTransport::new(vec![
|
||||
response(200, DISCOVERY),
|
||||
response(200, TOKEN_SUCCESS),
|
||||
response(200, REFRESH_SUCCESS),
|
||||
]));
|
||||
let client = GrokOAuthClient::new(
|
||||
config(),
|
||||
crate::support::xai_wire_profile(),
|
||||
transport.clone(),
|
||||
Arc::new(FixtureVerifier),
|
||||
policy.clone(),
|
||||
);
|
||||
let discovery = client.discover().await.unwrap();
|
||||
let allowlist =
|
||||
RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"]).unwrap();
|
||||
let pending = client
|
||||
.start_authorization_code(
|
||||
&discovery,
|
||||
allowlist
|
||||
.authorize("https://gateway.example/oauth/grok/callback")
|
||||
.unwrap(),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let state = state_from_authorization_url(&pending);
|
||||
let grant = pending
|
||||
.accept_callback(
|
||||
AuthorizationCallback::parse(&format!("code=fixture-code&state={state}")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
client
|
||||
.exchange_authorization_code(&discovery, grant)
|
||||
.await
|
||||
.unwrap();
|
||||
*policy.0.lock().unwrap() = selected("9.8.8");
|
||||
let grant = RefreshTokenGrant::new(SecretValue::new("refresh-test"));
|
||||
client.refresh(&discovery, &grant).await.unwrap();
|
||||
for (request, version) in transport.requests().iter().zip(["9.8.7", "9.8.7", "9.8.8"]) {
|
||||
let header = |name| {
|
||||
request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|h| h.name() == name)
|
||||
.unwrap()
|
||||
.value()
|
||||
};
|
||||
assert_eq!(
|
||||
header("user-agent"),
|
||||
format!("grok-shell/{version} (windows; aarch64)")
|
||||
);
|
||||
assert_eq!(header("x-grok-client-version"), version);
|
||||
}
|
||||
*policy.0.lock().unwrap() = gateway_core::account::OpaqueProviderData::new(Default::default());
|
||||
assert!(client.refresh(&discovery, &grant).await.is_err());
|
||||
assert_eq!(transport.requests().len(), 3);
|
||||
}
|
||||
|
||||
struct FixtureTransport {
|
||||
responses: Mutex<VecDeque<Result<OAuthHttpResponse, TransportFailure>>>,
|
||||
requests: Mutex<Vec<OAuthHttpRequest>>,
|
||||
@@ -92,6 +166,7 @@ async fn credential_import_should_require_exact_metadata_and_official_userinfo()
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FixtureVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let now = chrono::Utc::now();
|
||||
@@ -157,6 +232,7 @@ async fn expired_import_should_refresh_then_require_authoritative_userinfo() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport.clone(),
|
||||
Arc::new(FixtureVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let now = chrono::Utc::now();
|
||||
@@ -203,6 +279,7 @@ async fn credential_import_should_reject_non_official_client_before_verification
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FixtureVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let now = chrono::Utc::now();
|
||||
@@ -260,6 +337,7 @@ async fn authorization_code_flow_should_verify_before_returning_tokens() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport.clone(),
|
||||
Arc::new(FixtureVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let allowlist = RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"])
|
||||
@@ -305,6 +383,7 @@ async fn authorization_code_flow_should_fail_closed_without_verifier() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let allowlist = RedirectUriAllowlist::new(["https://gateway.example/oauth/grok/callback"])
|
||||
@@ -344,6 +423,7 @@ async fn refresh_should_preserve_ambiguous_send_classification() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let grant = RefreshTokenGrant::new(SecretValue::new(
|
||||
@@ -369,6 +449,7 @@ async fn refresh_should_return_rotated_token_without_id_token() {
|
||||
crate::support::xai_wire_profile(),
|
||||
transport,
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("discovery succeeds");
|
||||
let grant = RefreshTokenGrant::new(SecretValue::new(
|
||||
|
||||
@@ -66,6 +66,7 @@ async fn expired_access_token_requires_official_refresh_before_identity_verifica
|
||||
crate::support::xai_wire_profile(),
|
||||
transport.clone(),
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("official discovery fixture");
|
||||
let error = client
|
||||
@@ -125,6 +126,7 @@ async fn verified_import_inside_refresh_margin_should_not_persist_a_refresh_sche
|
||||
crate::support::xai_wire_profile(),
|
||||
Arc::new(DiscoveryTransport),
|
||||
Arc::new(AcceptingUserInfoVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("official discovery fixture");
|
||||
let tokens = client
|
||||
@@ -351,6 +353,7 @@ async fn verify(candidate: GrokOAuthImportCandidate) -> GrokOAuthImportError {
|
||||
crate::support::xai_wire_profile(),
|
||||
Arc::new(DiscoveryTransport),
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
let discovery = client.discover().await.expect("official discovery fixture");
|
||||
client
|
||||
|
||||
@@ -23,6 +23,53 @@ use crate::support::loopback_endpoint_policy;
|
||||
|
||||
const CACHE_TTL: Duration = Duration::from_secs(60 * 60);
|
||||
|
||||
#[tokio::test]
|
||||
async fn jwks_and_userinfo_use_the_frozen_oauth_identity() {
|
||||
let server = MockServer::start().await;
|
||||
let endpoint = endpoints(&server);
|
||||
let key = TestKey::new(37, "global-profile-key");
|
||||
mount_jwks(&server, key.jwks(), 1).await;
|
||||
Mock::given(path("/oauth2/userinfo"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"sub":"test-user"})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let verifier = verifier(&endpoint.origin, CACHE_TTL);
|
||||
let nonce = SecretValue::new("global-profile-nonce");
|
||||
let algorithms = vec!["ES256".into()];
|
||||
let access = SecretValue::new("test-access");
|
||||
let token = SecretValue::new(key.sign(&valid_claims(&nonce), Algorithm::ES256));
|
||||
let profile = provider_xai::XaiWireProfile {
|
||||
client_version: "9.8.7".into(),
|
||||
target_os: "windows".into(),
|
||||
target_arch: "arm64".into(),
|
||||
..Default::default()
|
||||
};
|
||||
verifier
|
||||
.verify(
|
||||
auth_context(&endpoint, &algorithms, &nonce).with_wire_profile(&profile),
|
||||
TokenCandidate::new(&access, Some(&token), None),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
verifier
|
||||
.verify(
|
||||
import_context(&endpoint, &algorithms).with_wire_profile(&profile),
|
||||
TokenCandidate::new(&access, None, Some(Duration::from_secs(60))),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
for request in requests {
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
"grok-shell/9.8.7 (windows; aarch64)"
|
||||
);
|
||||
assert_eq!(request.headers["x-grok-client-version"], "9.8.7");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_jwks_cache_evicts_idle_exits_at_the_fixed_bound() {
|
||||
let origin = MockServer::start().await;
|
||||
|
||||
@@ -55,14 +55,25 @@ pub fn grok_catalog_service(
|
||||
transport: Arc<dyn GrokModelCatalogTransport>,
|
||||
cache: Arc<dyn GrokCredentialCatalogCache>,
|
||||
) -> GrokCredentialCatalogService {
|
||||
GrokCredentialCatalogService::new(repository, transport, cache, xai_wire_profile())
|
||||
GrokCredentialCatalogService::new(
|
||||
repository,
|
||||
transport,
|
||||
cache,
|
||||
xai_wire_profile(),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn grok_quota_service(
|
||||
repository: GrokCredentialRepository,
|
||||
transport: Arc<dyn GrokBillingTransport>,
|
||||
) -> GrokCredentialQuotaService {
|
||||
GrokCredentialQuotaService::new(repository, transport, xai_wire_profile())
|
||||
GrokCredentialQuotaService::new(
|
||||
repository,
|
||||
transport,
|
||||
xai_wire_profile(),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -807,6 +818,28 @@ pub fn create_input(suffix: &str, subject: &str) -> CreateGrokCredential {
|
||||
|
||||
pub struct StaticRuntimePolicy;
|
||||
|
||||
pub struct RequestProfileRuntimePolicy(pub Mutex<gateway_core::account::OpaqueProviderData>);
|
||||
|
||||
impl ProviderRuntimePolicyPort for RequestProfileRuntimePolicy {
|
||||
fn load_request_profile<'a>(
|
||||
&'a self,
|
||||
provider: &'a ProviderKind,
|
||||
) -> futures::future::BoxFuture<
|
||||
'a,
|
||||
Result<Option<gateway_core::account::OpaqueProviderData>, ProviderStoreError>,
|
||||
> {
|
||||
assert_eq!(provider.as_str(), "xai");
|
||||
let profile = self.0.lock().unwrap().clone();
|
||||
Box::pin(async move { Ok(Some(profile)) })
|
||||
}
|
||||
|
||||
fn load_refresh_policy(
|
||||
&self,
|
||||
) -> futures::future::BoxFuture<'_, Result<ProviderRefreshPolicy, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(refresh_policy()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TestSessionAffinity {
|
||||
pub bindings: Mutex<
|
||||
|
||||
@@ -208,6 +208,7 @@ async fn inference_and_oauth_connect_through_each_accounts_authenticated_proxy()
|
||||
crate::support::xai_wire_profile(),
|
||||
Arc::new(ReqwestOAuthTransport::new(Arc::new(OfficialGrokEndpointPolicy)).unwrap()),
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
)
|
||||
.with_outbound_proxy(Some(proxy));
|
||||
assert!(
|
||||
@@ -1277,6 +1278,7 @@ async fn official_oauth_transport_should_resolve_through_the_production_policy_w
|
||||
.expect("production OAuth transport"),
|
||||
),
|
||||
Arc::new(FailClosedTokenVerifier),
|
||||
crate::support::runtime_policy(),
|
||||
);
|
||||
|
||||
let discovery = client
|
||||
|
||||
+26
-10
@@ -250,6 +250,8 @@ Messages 与 Responses 的转换边界见 [Messages 请求](#messages-请求),
|
||||
|
||||
客户端用 `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 |
|
||||
@@ -1723,8 +1725,9 @@ Messages API Key 账号支持生成与输入计数,通过协议转换承接 Re
|
||||
互联账号按上游 Key 已提供的最长消费窗口统计本机 Token、费用和模型用量。
|
||||
日、周周期的 `usage.windowKind` 分别为 `daily`、`weekly`,其他周期为 `quota`。查询边界同账号额度窗口,为 `[resetAt - windowSeconds, resetAt)`;
|
||||
未开启或缺少重置边界时显示无数据,不回退到历史累计,也不采用池内其他账号的周期。
|
||||
OAuth 账号优先按可归属整个账号的实际周/月额度窗口统计,缺少可归属窗口时使用过去 24 小时的本地请求统计
|
||||
此时 `usage.windowKind` 为 `daily`,Token 与模型用量共用该范围,上游额度快照缺失时仍可展示本地统计
|
||||
OAuth 账号优先按可归属整个账号的实际周/月额度窗口统计,缺少可归属窗口时使用 Provider 声明的本地统计范围。
|
||||
Antigravity 按部署时区汇总今天及前 6 天,`usage.windowKind` 为 `recent_week`,管理端显示“近一周”;其他 Provider 默认使用过去 24 小时,返回 `daily`。
|
||||
Token 与模型用量共用该范围,上游额度快照缺失时仍可展示本地统计;账号请求小时图仍独立展示最近 24 个 UTC 小时桶
|
||||
|
||||
批量导入 AT / RT 使用 `accounts` JSON 数组,最多 200 项,不接受纯文本 token 列表。例如:
|
||||
|
||||
@@ -1937,8 +1940,7 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
|
||||
- OAuth 账号详情的 Token 统计、模型排行和列表 Token 汇总优先使用账号级周额度窗口,无可统计的周窗口时
|
||||
使用月额度窗口;`usage.windowKind` 随选中的窗口返回 `weekly` 或 `monthly`。查询边界
|
||||
严格为 `[resetAt - windowSeconds, resetAt)`,不是自然周/月或最近 7/30 天;额度刷新若返回了更早的
|
||||
重置时间,会按新边界重新聚合。没有边界完整、可归属到账号的周/月窗口时显示无数据,`usage.windowKind` 为 `quota`
|
||||
(周/月额度窗口),不回退到 5 小时、日窗口或历史累计。
|
||||
重置时间,会按新边界重新聚合。没有可归属整号的额度窗口时,按上述 Provider 本地统计范围展示,不能把模型分组额度归为整号用量。
|
||||
金额原值保持完整精度,USD 展示值
|
||||
小于 1 美元时最多保留四位小数,其余最多保留两位,小数末尾不补零。
|
||||
额度百分比展示最多保留一位小数,小数末尾不补零;数值为零时返回 `0%`
|
||||
@@ -2424,7 +2426,7 @@ Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请
|
||||
JSON 路径支持 `$`、`.成员`、`["带特殊字符的键"]`、`[索引]`、`.*` 和 `[*]`,不支持递归和过滤表达式。
|
||||
缺少字段视为未命中;类型不符属于执行失败。`regex_replace` 替换字符串,`set_value` 保持原字段类型设置 JSON 值,
|
||||
`rename_key` 替换所选对象的直接键名,重名时失败;`remove_field` 删除所选字段或数组项,不能删除作用范围根节点。
|
||||
`anonymize_workspace` 仅用于 `turn_metadata` 的 `$.workspaces`,`pattern` 必须为 `null`,按逻辑会话改写工程路径并删除 Git 远端与提交 metadata
|
||||
`anonymize_project` 仅用于 `turn_metadata` 的 `$.workspaces`,`pattern` 必须为 `null`,按账号与逻辑会话改写项目名,保留父目录、用户名及映射内的 metadata
|
||||
删除动作的 `pattern: null` 表示无条件删除,字符串模式表示只删除字符串值匹配的字段或数组项。
|
||||
请求头规则生成的值必须是 ASCII 文本,以保持 HTTP 与 WebSocket opening 的一致性;metadata 范围会自动转义 Unicode
|
||||
|
||||
@@ -2446,11 +2448,18 @@ WebSocket 请求头在握手时发送。隐私规则改变握手头时,普通
|
||||
UA、平台参数及自动 Git 上下文版本由 [OpenAI 上游客户端身份](#openai-上游客户端身份)管理。
|
||||
保存后的规则按其 `steps` 执行,不随预设定义变化
|
||||
|
||||
「按账号与会话匿名化工作区」预设使用 `anonymize_workspace`,保留路径分隔符与父目录层级,将用户目录中的用户名改为 `user`。
|
||||
「按账号与会话匿名化工作区」预设按顺序生成四个可编辑步骤:
|
||||
|
||||
1. `anonymize_project` 根据原始路径生成项目化名,保留分隔符与父目录
|
||||
2. `rename_key` 将 Linux、macOS 和 Windows 用户目录中的用户名改为 `user`,替换内容可自定义
|
||||
3. `remove_field` 删除 `$.workspaces.*.associated_remote_urls`
|
||||
4. `remove_field` 删除 `$.workspaces.*.latest_git_commit_hash`
|
||||
|
||||
各步骤可以修改、删除或调整顺序;用户名替换与 Git 信息处理不由项目匿名化动作隐式执行。
|
||||
工程名取原名的前 48 个字母或数字打乱顺序,再加两组 1~1000 的数字和短后缀;没有字母或数字时使用 `project`。
|
||||
例如 `codex-proxy-rs` 可变为 `xrpceodxroys-427-83-a1b2c3d4`。同一 Client Key、账号、逻辑会话和工作区的化名在重试与重启后保持一致;
|
||||
换账号、新会话或更换工作区重新派生化名,切回原账号和原会话恢复对应化名,不保存路径映射表。正常令牌续期与代理出口变化不重置化名。
|
||||
映射内的 `associated_remote_urls`、`latest_git_commit_hash` 被移除,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
|
||||
默认组合移除 Git 远端与提交信息,其余字段保留。真实执行目录、正文和工具参数保持原值,仍可能暴露真实路径
|
||||
|
||||
工作区必须是绝对路径,映射值必须是对象。缺少稳定会话身份、路径无效或化名冲突时按策略失败模式处理,不随机补造会话。
|
||||
预览从样本请求头或正文识别会话,可在样本的 `headers` 中填写 `"session-id": ["example-session"]`;预览只使用样本身份,实际出站另外按 Client Key 和选定账号隔离
|
||||
@@ -2669,6 +2678,10 @@ models.dev 同步只导入可表示为当前文本 Token 计价的 OpenAI/xAI
|
||||
更新时省略某项保留原值,对象替换该项,`null` 删除显式选择并使用 Provider 默认值;不清除其他 Provider 的配置。
|
||||
配置内容由对应 Provider 校验,不包含账号凭据。Key 可通过 `providerRequestProfileOverrides` 整体覆盖所属 Provider 的选择
|
||||
|
||||
OpenAI、xAI、Antigravity 的模型请求均按 Key 覆盖优先、其次全局的顺序选择身份。
|
||||
OAuth、令牌续期、额度刷新、订阅和模型目录查询等账号后台操作使用所属平台的全局身份,
|
||||
不读取单个 Key 的覆盖;修改全局配置后,下次执行采用新选择
|
||||
|
||||
各 Provider 的选项响应均包含 `globalConfiguration`。OpenAI 返回六个 `presets`、`maxVersionLag` 和
|
||||
`recognizedUserAgentPrefixes`。匹配前缀时,OpenAI 从 UA 派生 originator 与 Core 版本,其他自定义 UA 需要提供这两个字段。
|
||||
xAI 返回 `defaults`,Antigravity 返回 `defaults` 与 `presets`
|
||||
@@ -2676,9 +2689,9 @@ xAI 返回 `defaults`,Antigravity 返回 `defaults` 与 `presets`
|
||||
### OpenAI 上游客户端身份
|
||||
|
||||
OpenAI 通用身份默认使用 `MacOS · Desktop · 自动最新`。
|
||||
该配置作用于 Client Key 的 OpenAI 模型请求,适用于 HTTP/SSE、WebSocket、Images 和 Search,
|
||||
也用于账号模型目录的后台发现、手动刷新、导出及定时预热;下次执行时采用当前全局选择,不使用单个 Key 的覆盖。
|
||||
不改变 xAI、入站客户端版本门禁、账号认证或后台 Desktop 专属操作
|
||||
模型请求覆盖 HTTP/SSE、WebSocket、Images 和 Search。后台全局身份还作用于授权链接的客户端参数、
|
||||
PAT 验证、额度重置卡、资料、头像和定时预热;各端点保留各自的请求头格式。
|
||||
该配置不覆盖浏览器授权页的 UA,不保证上游登录通知中的设备标签与之相同,也不改变入站客户端版本门禁
|
||||
|
||||
自定义配置使用 `{ "mode": "custom", "userAgent": "完整 UA" }`。
|
||||
已识别的 `Codex Desktop`、`codex-tui`、`codex_exec`、`codex_cli_rs` 前缀由后端解析 `originator` 和 Core `version`,
|
||||
@@ -2707,6 +2720,9 @@ TUI 默认标识为 `codex-tui`,Exec 为 `codex_exec`,入口后缀使用同
|
||||
`originator` 覆盖只更改产品名前缀和配套头,后缀仍表示所选入口。省略 `osType` 使用平台名称;
|
||||
自定义运行环境在自动更新时保持不变。未指定 `cliEntry` 时使用 `codex_cli_rs` 默认值且不添加入口后缀
|
||||
|
||||
macOS 的默认系统版本为 `27.2.1`。选择 macOS CLI 预设时,配置包含 `cliEntry: "tui"` 和
|
||||
`terminal: "Apple_Terminal/488.9"`;已保存的入口和终端配置不随预设变化而改写
|
||||
|
||||
`terminal` 填写官方客户端的真实终端标记,如 `iTerm.app/3.5.0`、`vscode/1.99.0`、`Apple_Terminal`、
|
||||
`Ghostty`、`WindowsTerminal`、`tmux-256color`、`xterm-256color`。省略时使用 `unknown`:
|
||||
官方 Desktop 由 GUI 启动、无终端环境变量,其 UA 中的终端标记本就是 `unknown`,
|
||||
|
||||
@@ -715,6 +715,8 @@ Core 按映射后的模型冻结 Provider 归属:已知模型只在明确声
|
||||
未被任何目录识别的模型只有一个 Provider 透传候选时才交由上游验证,多个未知候选不按名称顺序猜选平台。
|
||||
OpenAI Provider 在选号时排除 Grok 模型的 ChatGPT OAuth 账号,API Key 兼容上游仍可透传
|
||||
|
||||
Provider 可从上游目录声明模型分组的推理档位、目标型号和来源账号。Core 使用协议层提取的显式档位解析目标,再按目标型号收窄账号范围并检查权限;目录展示复用成员的授权事实,不从模型前缀推测分组或默认档位。Antigravity 保存上游分组声明,完整型号不参与分组改写
|
||||
|
||||
账号选择综合启停状态、credential/quota 事实、Redis cooldown、并发上限、权重和会话亲和。
|
||||
默认账号并发上限为 `0` 时表示无限;账号独立正数上限仍优先,未设置则继承默认值。
|
||||
无限并发只跳过并发上限判断,保留在途租约计数及其他准入约束;含无限账号的容量不投影有限占用比例。
|
||||
@@ -1069,6 +1071,9 @@ OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再
|
||||
credential 与 quota 是两组独立事实:credential refresh 不等于 quota refresh,额度接口的 401/403
|
||||
也不能单独证明 refresh token 永久失效
|
||||
|
||||
OpenAI、xAI、Antigravity 的认证及账号后台操作由各 Provider 通过自身 profile 解析器读取当前全局身份,
|
||||
冻结到对应上游请求,不读取 Key 覆盖;模型请求由请求上下文按 Key 覆盖优先、其次全局解析身份
|
||||
|
||||
- OpenAI 支持 OAuth、AT/RT、PAT 和上游 API Key。OAuth 身份来自官方 JWT claims,PAT 经官方身份接口验证,
|
||||
不信任导入文档顶层身份字段。RT-only 导入先换取 AT;AT-only、PAT 与 API Key 不参加 OAuth 自动续期。
|
||||
输入形态和适用操作见 [账号能力与导入](api.md#账号能力导入与-oauth)
|
||||
@@ -1083,7 +1088,7 @@ credential 与 quota 是两组独立事实:credential refresh 不等于 quota
|
||||
- Antigravity 使用 Google OAuth 离线授权,账号文件导出凭据、身份、有效期及已有观测,导入通过 refresh token 重新验证权限与主体,不采信文件中的历史观测。
|
||||
OAuth 每轮操作从运行策略读取全局 AGY 选择,由 `profile` 统一解析并冻结出站身份,换码、刷新和身份查询使用同一画像,不读取 Key 覆盖。
|
||||
`loadCodeAssist` 的付费套餐优先于基础套餐;分组额度和模型额度保存到同一带凭据版本的快照,独立模型耗尽不升级为整个账号耗尽。
|
||||
原生额度窗口只投影上游模型分组,不归属整号 Token;Admin 独立读取过去 24 小时的本地用量及统计周期,不向额度列表补入本地窗口。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
|
||||
原生额度窗口只投影上游模型分组,不归属整号 Token;Admin 按 Provider 声明独立读取部署时区今天及前 6 天的本地用量,展示为“近一周”,不向额度列表补入本地窗口。选号及互联分别读取同一份模型额度事实,失效观测保持未知。
|
||||
正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试
|
||||
- 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后,
|
||||
由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@boxicons/vue": "1.0.1",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.1",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.2",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lucide/vue": "^1.77.0",
|
||||
|
||||
Generated
+6
-6
@@ -195,8 +195,8 @@ importers:
|
||||
specifier: 1.0.1
|
||||
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
|
||||
'@codex-proxy/ui':
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.1
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.2
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
'@fontsource-variable/inter':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
@@ -456,9 +456,9 @@ packages:
|
||||
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
|
||||
engines: {node: '>= 20.12.0'}
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee':
|
||||
resolution: {gitHosted: true, integrity: sha512-pPner6XWo+saTWErInK+LLSUxbSmTtd274hrWorFnOfLqDNN2cTwl1UwDsPvaRShl7jy4dVxPC5vDWAgszwdZQ==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee}
|
||||
version: 0.13.1
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450':
|
||||
resolution: {gitHosted: true, integrity: sha512-/lXIKZtNWb+WYmu6ImkuCpqwba7denlWbmGY5kjIrT/CpH00LOn438uIfI9Ow21FBTbt3yZrYqOBcrbQK2lXzA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450}
|
||||
version: 0.13.2
|
||||
engines: {node: '>=24'}
|
||||
peerDependencies:
|
||||
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
@@ -3590,7 +3590,7 @@ snapshots:
|
||||
fast-wrap-ansi: 0.2.2
|
||||
sisteransi: 1.0.5
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/501495d5b1e9d65840d4cdee5e0e228f361613ee(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/305d01af72f7a6353a5c01ec10ac27eae3ec8450(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
dependencies:
|
||||
'@ant-design/colors': 8.0.1
|
||||
'@ant-design/fast-color': 3.0.1
|
||||
|
||||
@@ -100,7 +100,7 @@ export interface AccountModelUsage {
|
||||
}
|
||||
|
||||
export interface AccountUsage {
|
||||
windowKind: 'general' | 'daily' | 'weekly' | 'monthly' | 'quota'
|
||||
windowKind: 'general' | 'daily' | 'recent_week' | 'weekly' | 'monthly' | 'quota'
|
||||
requestCount: number | null
|
||||
requestCountDisplay: string
|
||||
inputTokens: number | null
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { RequestOptions } from '../../request'
|
||||
import request from '../../request'
|
||||
|
||||
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_workspace'
|
||||
export type PrivacyAction = 'regex_replace' | 'set_value' | 'rename_key' | 'remove_field' | 'anonymize_project'
|
||||
export type JsonValue = unknown
|
||||
|
||||
export interface PrivacyRule {
|
||||
|
||||
@@ -1,40 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
|
||||
import { LayoutGrid } from '@lucide/vue'
|
||||
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
|
||||
defineProps<{ disabled?: boolean }>()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const provider = defineModel<string>({ required: true })
|
||||
const options = computed(() => ([
|
||||
{
|
||||
label: t('common.providers.all'),
|
||||
value: '',
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
...PROVIDER_IDS.map(value => ({
|
||||
label: formatProviderLabel(value),
|
||||
value,
|
||||
icon: providerIcon(value),
|
||||
})),
|
||||
]))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-w-0 max-w-full items-center gap-1">
|
||||
<div class="min-w-0 overflow-x-auto">
|
||||
<ZSegmented
|
||||
<ProviderSelect
|
||||
v-model="provider"
|
||||
:aria-label="t('common.providers.filter')"
|
||||
display="icon"
|
||||
:style="{ width: `${options.length * 40 + 4}px` }"
|
||||
:options="options"
|
||||
:leading-option="{ label: t('common.providers.all'), value: '', icon: LayoutGrid }"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<script setup lang="ts" generic="Value extends string">
|
||||
import type { SegmentedOption } from '@codex-proxy/ui'
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
providers?: readonly Value[]
|
||||
leadingOption?: SegmentedOption
|
||||
display?: 'icon' | 'label'
|
||||
size?: 'small' | 'default' | 'large'
|
||||
disabled?: boolean
|
||||
ariaLabel?: string
|
||||
}>(), {
|
||||
display: 'icon',
|
||||
disabled: false,
|
||||
})
|
||||
const provider = defineModel<Value>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const options = computed(() => [
|
||||
...(props.leadingOption
|
||||
? [props.leadingOption]
|
||||
: []),
|
||||
...(props.providers ?? PROVIDER_IDS).map(value => ({
|
||||
value,
|
||||
label: formatProviderLabel(value),
|
||||
icon: providerIcon(value),
|
||||
})),
|
||||
])
|
||||
const style = computed(() => props.display === 'icon'
|
||||
? { width: `${options.value.length * 40 + 4}px` }
|
||||
: undefined)
|
||||
|
||||
function selectProvider(value: string) {
|
||||
if (options.value.some(option => option.value === value))
|
||||
provider.value = value as Value
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZSegmented
|
||||
:model-value="provider"
|
||||
:options="options"
|
||||
:display="display"
|
||||
:size="size"
|
||||
:disabled="disabled"
|
||||
:aria-label="ariaLabel ?? t('common.providers.select')"
|
||||
:style="style"
|
||||
@update:model-value="selectProvider"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
|
||||
defineProps<{ disabled?: boolean }>()
|
||||
const provider = defineModel<BuiltinProvider>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="grid min-w-0 gap-4" :aria-label="t('common.providers.settings')">
|
||||
<div class="flex justify-end">
|
||||
<ProviderSelect
|
||||
v-model="provider"
|
||||
:disabled="disabled"
|
||||
class="shrink-0"
|
||||
/>
|
||||
</div>
|
||||
<slot />
|
||||
</section>
|
||||
</template>
|
||||
@@ -2,12 +2,12 @@
|
||||
import type { Component } from 'vue'
|
||||
import type { ProviderRequestProfile, ProviderRequestProfiles, ProviderRequestProfileUpdates } from '@/api'
|
||||
import type { BuiltinProvider } from '@/providers/catalog'
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
import { isEqual } from 'es-toolkit'
|
||||
import { computed, shallowRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
import AntigravityRequestProfileEditor from '@/providers/antigravity/request-profile/AntigravityRequestProfileEditor.vue'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
import { PROVIDER_IDS } from '@/providers/catalog'
|
||||
import OpenAiRequestProfileEditor from '@/providers/openai/request-profile/OpenAiRequestProfileEditor.vue'
|
||||
import XaiRequestProfileEditor from '@/providers/xai/request-profile/XaiRequestProfileEditor.vue'
|
||||
|
||||
@@ -37,12 +37,6 @@ const model = defineModel<ProviderRequestProfiles>({
|
||||
const updates = defineModel<ProviderRequestProfileUpdates>('updates')
|
||||
const selectedProvider = shallowRef<BuiltinProvider>(PROVIDER_IDS[0]!)
|
||||
const provider = computed(() => props.provider ?? selectedProvider.value)
|
||||
const providerOptions = PROVIDER_IDS.map(value => ({
|
||||
value,
|
||||
label: formatProviderLabel(value),
|
||||
icon: providerIcon(value),
|
||||
}))
|
||||
const providerSelectorStyle = { width: `${providerOptions.length * 40}px` }
|
||||
const drafts = shallowRef<ProviderRequestProfiles>({})
|
||||
const profile = computed<ProviderRequestProfile | null | undefined>({
|
||||
get: () => {
|
||||
@@ -84,15 +78,12 @@ watch(() => props.active, (active) => {
|
||||
|
||||
<template>
|
||||
<div class="grid min-w-0 gap-4">
|
||||
<ZSegmented
|
||||
<ProviderSelect
|
||||
v-if="!allowInherit && !props.provider"
|
||||
v-model="selectedProvider"
|
||||
class="max-w-full justify-self-end"
|
||||
:aria-label="t('settings.clientProfile.clientIdentityProvider')"
|
||||
:options="providerOptions"
|
||||
:disabled="disabled"
|
||||
:style="providerSelectorStyle"
|
||||
display="icon"
|
||||
/>
|
||||
<component
|
||||
:is="editors[provider]"
|
||||
@@ -104,15 +95,12 @@ watch(() => props.active, (active) => {
|
||||
:disabled="disabled"
|
||||
>
|
||||
<template #source-extra>
|
||||
<ZSegmented
|
||||
<ProviderSelect
|
||||
v-if="!props.provider"
|
||||
v-model="selectedProvider"
|
||||
class="max-w-full shrink-0"
|
||||
:aria-label="t('settings.clientProfile.upstreamIdentityPlatform')"
|
||||
:options="providerOptions"
|
||||
:disabled="disabled"
|
||||
:style="providerSelectorStyle"
|
||||
display="icon"
|
||||
/>
|
||||
</template>
|
||||
</component>
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
"noModelUsageYet": "No model usage yet",
|
||||
"windows": {
|
||||
"daily": "Daily usage",
|
||||
"recentWeek": "Last 7 days",
|
||||
"general": "Total usage",
|
||||
"weekly": "Weekly usage",
|
||||
"monthly": "Monthly usage",
|
||||
|
||||
@@ -70,7 +70,9 @@
|
||||
"filter": "Filter by platform",
|
||||
"unknown": "Unknown platform",
|
||||
"customAuth": "Custom authentication · {normalized}",
|
||||
"unknownAuth": "Unknown authentication type"
|
||||
"unknownAuth": "Unknown authentication type",
|
||||
"settings": "Platform settings",
|
||||
"select": "Select platform"
|
||||
},
|
||||
"location": {
|
||||
"resolving": "Resolving exit location",
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"subagents": "Collaborative subagents",
|
||||
"memberModels": "Member account models",
|
||||
"fastModeHelp": "Default follows the client. Disable downgrades both accelerated tiers to standard. A forced tier overrides the client selection when the model supports it.",
|
||||
"subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent."
|
||||
"subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent.",
|
||||
"noProviderSettings": "No group-specific settings for this platform"
|
||||
},
|
||||
"metrics": {
|
||||
"restricted": "Restricted",
|
||||
|
||||
@@ -592,8 +592,7 @@
|
||||
"fieldPath": "Field path",
|
||||
"fieldPathSyntax": "Field path syntax",
|
||||
"jsonPathHelp": "Supports object members, quoted keys, array indexes, and * wildcards, for example $[\"workspaces\"][\"/home/alex/demo\"]",
|
||||
"sessionAliasEffect": "Stable per account and session; Git metadata removed",
|
||||
"anonymizeWorkspaceHelp": "Shuffle the project name and add numbers; rotate aliases for new accounts or sessions, remove Git metadata, and preserve execution paths",
|
||||
"sessionAliasEffect": "Stable project alias per account and session",
|
||||
"targetHelp": "Use $ for environment text and a header name for request headers",
|
||||
"commonFields": "Common fields",
|
||||
"deleteMatchHelp": "Remove only fields or array items whose values match the regular expression",
|
||||
@@ -647,6 +646,7 @@
|
||||
"gitCommitId": "Git commit ID",
|
||||
"gitRemoteCollection": "Git remote collection",
|
||||
"workspaceFingerprint": "Workspace fingerprint",
|
||||
"anonymizeProject": "Anonymize project name by account and session",
|
||||
"anonymizeWorkspace": "Anonymize workspace by account and session",
|
||||
"unifyWorkspaceInformation": "Unify workspace information"
|
||||
},
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
"noModelUsageYet": "暂无模型用量",
|
||||
"windows": {
|
||||
"daily": "日用量",
|
||||
"recentWeek": "近一周",
|
||||
"general": "累计用量",
|
||||
"weekly": "周用量",
|
||||
"monthly": "月用量",
|
||||
|
||||
@@ -70,7 +70,9 @@
|
||||
"filter": "按平台筛选",
|
||||
"unknown": "未知平台",
|
||||
"customAuth": "自定义认证 · {normalized}",
|
||||
"unknownAuth": "未知认证类型"
|
||||
"unknownAuth": "未知认证类型",
|
||||
"settings": "平台设置",
|
||||
"select": "选择平台"
|
||||
},
|
||||
"location": {
|
||||
"resolving": "正在解析出口位置",
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"subagents": "协作子代理",
|
||||
"memberModels": "成员账号模型",
|
||||
"fastModeHelp": "默认跟随客户端。禁用会将加速请求降为标准档。选择快速或超快速时,若模型支持该档位,分组设置会覆盖客户端选择",
|
||||
"subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求"
|
||||
"subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求",
|
||||
"noProviderSettings": "该平台暂无分组专属设置"
|
||||
},
|
||||
"metrics": {
|
||||
"restricted": "受限",
|
||||
|
||||
@@ -592,8 +592,7 @@
|
||||
"fieldPath": "字段路径",
|
||||
"fieldPathSyntax": "字段路径语法",
|
||||
"jsonPathHelp": "支持对象成员、双引号键名、数组索引和 * 通配,例如 $[\"workspaces\"][\"/home/alex/demo\"]",
|
||||
"sessionAliasEffect": "同账号同会话化名固定,移除 Git 信息",
|
||||
"anonymizeWorkspaceHelp": "打乱工程名并加数字,换账号或新会话时更换化名;移除 Git 信息,保留真实执行路径",
|
||||
"sessionAliasEffect": "同账号同会话项目化名固定",
|
||||
"targetHelp": "环境文本使用 $,请求头直接填写名称",
|
||||
"commonFields": "常用字段",
|
||||
"deleteMatchHelp": "仅删除值匹配正则的字段或数组项",
|
||||
@@ -647,6 +646,7 @@
|
||||
"gitCommitId": "Git 提交 ID",
|
||||
"gitRemoteCollection": "Git 远端集合",
|
||||
"workspaceFingerprint": "工作区指纹",
|
||||
"anonymizeProject": "按账号与会话匿名化项目名",
|
||||
"anonymizeWorkspace": "按账号与会话匿名化工作区",
|
||||
"unifyWorkspaceInformation": "统一工作区信息"
|
||||
},
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
"noModelUsageYet": "暫無模型用量",
|
||||
"windows": {
|
||||
"daily": "日用量",
|
||||
"recentWeek": "近一週",
|
||||
"general": "累計用量",
|
||||
"weekly": "周用量",
|
||||
"monthly": "月用量",
|
||||
|
||||
@@ -70,7 +70,9 @@
|
||||
"filter": "按平臺篩選",
|
||||
"unknown": "未知平臺",
|
||||
"customAuth": "自定義認證 · {normalized}",
|
||||
"unknownAuth": "未知認證類型"
|
||||
"unknownAuth": "未知認證類型",
|
||||
"settings": "平台設定",
|
||||
"select": "選擇平台"
|
||||
},
|
||||
"location": {
|
||||
"resolving": "正在解析出口位置",
|
||||
|
||||
@@ -44,7 +44,8 @@
|
||||
"subagents": "協作子代理",
|
||||
"memberModels": "成員帳號模型",
|
||||
"fastModeHelp": "預設跟隨用戶端。禁用會將加速請求降為標準檔。選擇快速或超快速時,若模型支援該檔位,分組設定會覆寫用戶端選擇",
|
||||
"subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求"
|
||||
"subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求",
|
||||
"noProviderSettings": "此平台暫無分組專屬設定"
|
||||
},
|
||||
"metrics": {
|
||||
"restricted": "受限",
|
||||
|
||||
@@ -592,8 +592,7 @@
|
||||
"fieldPath": "字段路徑",
|
||||
"fieldPathSyntax": "字段路徑語法",
|
||||
"jsonPathHelp": "支持對象成員、雙引號鍵名、數組索引和 * 通配,例如 $[\"workspaces\"][\"/home/alex/demo\"]",
|
||||
"sessionAliasEffect": "同賬號同會話化名固定,移除 Git 資訊",
|
||||
"anonymizeWorkspaceHelp": "打亂工程名並加數字,換賬號或新會話時更換化名;移除 Git 資訊,保留真實執行路徑",
|
||||
"sessionAliasEffect": "同賬號同會話專案化名固定",
|
||||
"targetHelp": "環境文本使用 $,請求頭直接填寫名稱",
|
||||
"commonFields": "常用字段",
|
||||
"deleteMatchHelp": "僅刪除值匹配正則的字段或數組項",
|
||||
@@ -647,6 +646,7 @@
|
||||
"gitCommitId": "Git 提交 ID",
|
||||
"gitRemoteCollection": "Git 遠端集合",
|
||||
"workspaceFingerprint": "工作區指紋",
|
||||
"anonymizeProject": "按賬號與會話匿名化專案名稱",
|
||||
"anonymizeWorkspace": "按賬號與會話匿名化工作區",
|
||||
"unifyWorkspaceInformation": "統一工作區信息"
|
||||
},
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Fingerprint, Plug } from '@lucide/vue'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
const providers = {
|
||||
openai: { label: 'Codex', icon: Openai },
|
||||
openai: { label: 'OpenAI', icon: Openai },
|
||||
xai: { label: 'xAI', icon: Xai },
|
||||
antigravity: { label: 'Antigravity', icon: GoogleAntigravity },
|
||||
} as const
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ZFormItem, ZIconButton, ZInput } from '@codex-proxy/ui'
|
||||
import { Dices } from '@lucide/vue'
|
||||
import { useTemplateRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
import { generateRequestId as generateUuid } from '@/utils/operation'
|
||||
@@ -8,6 +9,10 @@ import { generateRequestId as generateUuid } from '@/utils/operation'
|
||||
defineProps<{ disabled: boolean, placeholder: string, error: string }>()
|
||||
const seed = defineModel<string>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const input = useTemplateRef<InstanceType<typeof ZInput>>('input')
|
||||
defineExpose({
|
||||
focus: () => input.value?.focus(),
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -26,6 +31,7 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
</ZIconButton>
|
||||
</template>
|
||||
<ZInput
|
||||
ref="input"
|
||||
v-model="seed"
|
||||
:aria-label="t('settings.clientProfile.installationSeed')"
|
||||
:aria-invalid="!!error"
|
||||
|
||||
+8
-19
@@ -1,52 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
import type { AccountCreateSource } from '../../utils/accountCreate'
|
||||
|
||||
import { ZSegmented } from '@codex-proxy/ui'
|
||||
import { LayoutGrid } from '@lucide/vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/catalog'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
import { isBuiltinProvider } from '@/providers/catalog'
|
||||
|
||||
defineProps<{ disabled: boolean }>()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
|
||||
const source = defineModel<AccountCreateSource | null>({ required: true })
|
||||
const options = computed(() => ([
|
||||
{
|
||||
value: 'bundle',
|
||||
label: t('accounts.onboarding.batchImport'),
|
||||
icon: LayoutGrid,
|
||||
},
|
||||
...PROVIDER_IDS.map(provider => ({
|
||||
value: `provider:${provider}`,
|
||||
label: formatProviderLabel(provider),
|
||||
icon: providerIcon(provider),
|
||||
})),
|
||||
]))
|
||||
const selected = computed({
|
||||
get: () => source.value?.kind === 'provider'
|
||||
? `provider:${source.value.id}`
|
||||
? source.value.id
|
||||
: source.value?.kind ?? '',
|
||||
set: (value: string) => {
|
||||
if (!options.value.some(option => option.value === value))
|
||||
if (value !== 'bundle' && !isBuiltinProvider(value))
|
||||
return
|
||||
source.value = value === 'bundle'
|
||||
? { kind: 'bundle' }
|
||||
: {
|
||||
kind: 'provider',
|
||||
id: value.slice('provider:'.length),
|
||||
id: value,
|
||||
}
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZSegmented
|
||||
<ProviderSelect
|
||||
v-model="selected"
|
||||
class="w-full"
|
||||
:aria-label="t('accounts.onboarding.selectAccountPlatform')"
|
||||
:options="options"
|
||||
:leading-option="{ value: 'bundle', label: t('accounts.onboarding.batchImport'), icon: LayoutGrid }"
|
||||
display="label"
|
||||
:disabled="disabled"
|
||||
size="large"
|
||||
/>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user