mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 08:01:04 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5c23374e7 | ||
|
|
83bf9fafb3 | ||
|
|
409e36bf95 | ||
|
|
77ff65f400 | ||
|
|
75d0d0e0f8 | ||
|
|
1d92d638ba | ||
|
|
4e96567b6d | ||
|
|
42fdaecd7a |
+2
-2
@@ -144,8 +144,8 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
|
||||
| [插件使用](docs/plugins.md) | 如何安装、授权、配置和使用插件 | 管理员操作与影响,不展开 SDK 调用或宿主事务实现 |
|
||||
| [插件 SDK](backend/crates/gateway-plugin/sdk/README.md) / [CLI](backend/apps/plugin-cli/README.md) | 如何编写和打包插件 | 作者合同、权限边界、示例与打包验证 |
|
||||
| [数据库迁移](backend/migrations/README.md) | 如何维护 schema 和准备测试库 | 冻结规则、升级约束和测试环境,不罗列迁移历史 |
|
||||
| [共用组件](modules/ui/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](modules/plugins/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [共用组件](https://github.com/zyycn/codex-proxy-ui/blob/main/README.md)及其组件参考 | 如何安装、使用和开发独立 UI 库 | 组件公开 API、主题能力与库内开发;宿主页面约定归管理端主题,跨仓库联调归开发文档 |
|
||||
| [官方插件示例](https://github.com/zyycn/codex-proxy-plugins/blob/main/README.md)及其示例说明 | 如何构建、使用和维护示例插件 | 示例自身的功能、配置与验证;通用协议归 SDK,宿主安装操作归插件使用文档 |
|
||||
| [AGENTS.md](AGENTS.md) 与[项目技能](.agents/skills/cpr-dev-guide/SKILL.md) | AI 如何选择并执行任务流程 | 任务匹配、执行步骤和规范入口,不另建模块合同、版本表或协作标准 |
|
||||
| 本文 | 如何协作、审查和交付 | 流程、判断标准与验证要求,任务入口由 [开发技能](.agents/skills/cpr-dev-guide/SKILL.md) 串联 |
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
面向 Codex 的自托管多账号 AI 网关
|
||||
|
||||
[](https://github.com/zyycn/codex-proxy-rs/actions/workflows/ci.yml)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/releases)
|
||||
[](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
|
||||
[](LICENSE)
|
||||
|
||||
|
||||
@@ -131,6 +131,7 @@ fn config_loader_should_ignore_unknown_fields_in_configuration_sections() {
|
||||
let mut document = valid_config_document();
|
||||
document["host"]["system_update"] = serde_json::json!({});
|
||||
document["store"]["pool"] = serde_json::json!({});
|
||||
document["openai"] = serde_json::json!({});
|
||||
for path in [
|
||||
"",
|
||||
"/host",
|
||||
@@ -369,31 +370,6 @@ fn config_loader_should_reject_zero_server_port() {
|
||||
assert_rejected(valid_config().replace("port: 8080", "port: 0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_loader_should_accept_optional_openai_routing_strings() {
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!("us"),
|
||||
serde_json::json!("custom-value"),
|
||||
serde_json::json!(""),
|
||||
] {
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]["residency"] = value.clone();
|
||||
document["openai"]["account_routing_override"] = value;
|
||||
parse_config(&document.to_string()).expect("optional routing strings");
|
||||
}
|
||||
let mut document = valid_config_document();
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("residency");
|
||||
document["openai"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("account_routing_override");
|
||||
parse_config(&document.to_string()).expect("omitted routing strings");
|
||||
}
|
||||
|
||||
fn assert_rejected(config: String) {
|
||||
assert!(parse_config(&config).is_err());
|
||||
}
|
||||
|
||||
@@ -1170,6 +1170,7 @@ pub struct DiagnosticObservation {
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
|
||||
@@ -1052,14 +1052,23 @@ pub struct ProviderResetCreditResult {
|
||||
pub credit: Option<ProviderResetCredit>,
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 保留账号已有的套餐子类型,仅在缺失时使用上游额度快照补全
|
||||
pub(crate) fn fill_missing_plan_type(&self, account_plan_type: &mut Option<String>) {
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = explicit_plan_type(self.plan_type.as_deref()).map(str::to_owned);
|
||||
}
|
||||
/// 用额度观测补齐缺失的套餐 ID,只采用与账号套餐相符的描述
|
||||
pub fn resolve_observed_plan<'a>(
|
||||
account_plan_type: &mut Option<String>,
|
||||
observed_type: Option<&str>,
|
||||
observed_display: Option<&'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let observed_type = explicit_plan_type(observed_type);
|
||||
if explicit_plan_type(account_plan_type.as_deref()).is_none() {
|
||||
*account_plan_type = observed_type.map(str::to_owned);
|
||||
}
|
||||
observed_display.filter(|_| {
|
||||
observed_type
|
||||
.is_none_or(|id| Some(id.trim()) == account_plan_type.as_deref().map(str::trim))
|
||||
})
|
||||
}
|
||||
|
||||
impl ProviderQuota {
|
||||
/// 选择账号用量统计窗口,同时返回展示所需的周期事实
|
||||
///
|
||||
/// 周/月额度使用边界完整、可归属到整个账号的窗口
|
||||
|
||||
@@ -45,8 +45,7 @@ pub use gateway_core::account::RotationStrategy;
|
||||
/// 运行设置的共同值;版本、Provider 画像更新和数据库秘密由外层类型拥有
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RuntimeSettingsValues {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -201,9 +200,7 @@ impl RuntimeSettingsValues {
|
||||
{
|
||||
return Err("reset_credit_max_weekly_remaining_percent");
|
||||
}
|
||||
self.openai_request_country
|
||||
.validate()
|
||||
.map_err(|_| "openai_request_country")?;
|
||||
self.openai_request_settings.validate()?;
|
||||
self.request_location
|
||||
.validate()
|
||||
.map_err(|_| "request_location")?;
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::model::provider_credentials::{
|
||||
ProviderExport, ProviderExportCredentialInput, ProviderModelCatalogDocument, ProviderModels,
|
||||
ProviderProfileAvatar, ProviderProfileStatistics, ProviderQuota, ProviderQuotaReadRequest,
|
||||
ProviderQuotaRequest, ProviderResetCreditResult, ProviderResetCredits, ProviderSubscription,
|
||||
explicit_plan_type,
|
||||
explicit_plan_type, resolve_observed_plan,
|
||||
};
|
||||
use crate::model::{
|
||||
provider_credentials::{ProviderDocument, ProviderQuotaWindow},
|
||||
@@ -558,15 +558,14 @@ impl ProviderAdminRegistry {
|
||||
plan_type: &mut Option<String>,
|
||||
quota: Option<&ProviderQuota>,
|
||||
) -> Option<String> {
|
||||
if let Some(quota) = quota {
|
||||
quota.fill_missing_plan_type(plan_type);
|
||||
// 保留账号已知的套餐,不能给它配上另一档快照的描述
|
||||
let quota_id = explicit_plan_type(quota.plan_type.as_deref()).map(str::trim);
|
||||
if let Some(display) = "a.plan_type_display
|
||||
&& quota_id.is_none_or(|id| Some(id) == plan_type.as_deref().map(str::trim))
|
||||
{
|
||||
return Some(display.clone());
|
||||
}
|
||||
if let Some(quota) = quota
|
||||
&& let Some(display) = resolve_observed_plan(
|
||||
plan_type,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_type_display.as_deref(),
|
||||
)
|
||||
{
|
||||
return Some(display.to_owned());
|
||||
}
|
||||
self.plan_type_display(provider_kind, plan_type.as_deref())
|
||||
}
|
||||
|
||||
@@ -380,11 +380,10 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: item.account_provider_kind.as_deref().and_then(
|
||||
|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, item.account_plan_type.as_deref())
|
||||
},
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
item.account_provider_kind.as_deref(),
|
||||
item.account_plan_type.as_deref(),
|
||||
),
|
||||
account_plan_type: item.account_plan_type,
|
||||
request_count: item.request_count,
|
||||
@@ -422,17 +421,26 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "operations errors"))?;
|
||||
for error in &mut page.items {
|
||||
error.provider_account_plan_type_display =
|
||||
error.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, error.provider_account_plan_type.as_deref())
|
||||
});
|
||||
error.provider_account_plan_type_display = self.historical_plan_display(
|
||||
error.provider_account_plan_type_display.take(),
|
||||
error.provider_kind.as_deref(),
|
||||
error.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultObservabilityService {
|
||||
fn historical_plan_display(
|
||||
&self,
|
||||
display: Option<String>,
|
||||
provider: Option<&str>,
|
||||
plan_type: Option<&str>,
|
||||
) -> Option<String> {
|
||||
display.or_else(|| self.providers.plan_type_display(provider?, plan_type))
|
||||
}
|
||||
|
||||
async fn current_upstream_peers<'a>(
|
||||
&self,
|
||||
ids: impl Iterator<Item = &'a str>,
|
||||
@@ -540,11 +548,11 @@ impl DefaultObservabilityService {
|
||||
.provider_account_ref
|
||||
.as_ref()
|
||||
.and_then(|id| peers.get(id).copied());
|
||||
record.provider_account_plan_type_display =
|
||||
record.provider_kind.as_deref().and_then(|provider| {
|
||||
self.providers
|
||||
.plan_type_display(provider, record.provider_account_plan_type.as_deref())
|
||||
});
|
||||
record.provider_account_plan_type_display = self.historical_plan_display(
|
||||
record.provider_account_plan_type_display.take(),
|
||||
record.provider_kind.as_deref(),
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
);
|
||||
let Some(UsageBilling::Total { source, total }) = record.billing.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -117,7 +117,13 @@ fn validate_settings(command: &ReplaceRuntimeSettings) -> Result<(), AdminError>
|
||||
)
|
||||
.map_err(|_| AdminError::invalid("运行时设置不满足约束"))?;
|
||||
command.values.validate().map_err(|field| match field {
|
||||
"openai_request_country" => AdminError::invalid("请求国家必须是两位大写 ASCII 字母"),
|
||||
"openai_request_settings.residency"
|
||||
| "openai_request_settings.account_routing_override" => {
|
||||
AdminError::invalid("数据驻留和账号路由必须是有效的单行请求头值")
|
||||
}
|
||||
"openai_request_settings.request_country" => {
|
||||
AdminError::invalid("请求国家必须是两位大写 ASCII 字母")
|
||||
}
|
||||
_ => AdminError::invalid("运行时设置不满足约束"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1200,8 +1200,10 @@ impl SettingsStore for StaticSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -33,8 +33,10 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
rotation_strategy: gateway_admin::model::settings::RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -337,8 +337,10 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: false,
|
||||
openai_request_country: Default::default(),
|
||||
openai_request_settings: gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: false,
|
||||
..Default::default()
|
||||
},
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -541,6 +543,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
account_provider_kind: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
key: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
request_count,
|
||||
|
||||
@@ -225,6 +225,10 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
"AccountErrorOperator",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/openai.rs",
|
||||
&["OpenAiRequestSettings", "OpenAiRequestCountry"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/privacy.rs",
|
||||
&[
|
||||
@@ -254,7 +258,7 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/location.rs",
|
||||
&["RequestLocation", "OpenAiRequestCountry"][..],
|
||||
&["RequestLocation"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/account/scheduling.rs",
|
||||
|
||||
@@ -349,8 +349,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
model_mappings: Default::default(),
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -36,8 +36,7 @@ pub type ProviderRequestProfileUpdates =
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RuntimeSettingsFields {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: gateway_core::account::OpenAiRequestCountry,
|
||||
pub openai_request_settings: gateway_core::settings::OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: gateway_core::account::RequestLocation,
|
||||
@@ -581,7 +580,12 @@ fn map_wire_error(error: WireValidationError) -> AdminError {
|
||||
"settingsUsageRetentionOverflow" => "用量记录保留天数不合法".to_owned(),
|
||||
"settingsOpsRetentionOverflow" => "运维事件保留天数不合法".to_owned(),
|
||||
"settingsAuditRetentionOverflow" => "审计记录保留天数不合法".to_owned(),
|
||||
"openaiRequestCountry" => "自定义请求国家必须是两位大写 ASCII 字母".to_owned(),
|
||||
"openaiRequestSettings.residency" | "openaiRequestSettings.accountRoutingOverride" => {
|
||||
"数据驻留和账号路由必须是有效的单行请求头值".to_owned()
|
||||
}
|
||||
"openaiRequestSettings.requestCountry" => {
|
||||
"自定义请求国家必须是两位大写 ASCII 字母".to_owned()
|
||||
}
|
||||
"requestLocation" => "请求位置的国家代码、地区或城市不合法".to_owned(),
|
||||
"providerRequestProfiles" => "服务商客户端身份配置无效".to_owned(),
|
||||
"minCodexDesktopVersion" => "Codex Desktop 最低版本格式不合法".to_owned(),
|
||||
@@ -705,8 +709,7 @@ impl RuntimeSettingsFields {
|
||||
self,
|
||||
) -> Result<gateway_admin::model::settings::RuntimeSettingsValues, WireValidationError> {
|
||||
let values = gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: self.openai_oauth_guardian_review_model,
|
||||
openai_request_country: self.openai_request_country,
|
||||
openai_request_settings: self.openai_request_settings,
|
||||
codex_privacy_policy: self.codex_privacy_policy,
|
||||
request_location_enabled: self.request_location_enabled,
|
||||
request_location: self
|
||||
@@ -756,8 +759,7 @@ impl RuntimeSettingsFields {
|
||||
impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSettingsFields {
|
||||
fn from(settings: gateway_admin::model::settings::RuntimeSettingsValues) -> Self {
|
||||
crate::admin::settings::RuntimeSettingsFields {
|
||||
openai_oauth_guardian_review_model: settings.openai_oauth_guardian_review_model,
|
||||
openai_request_country: settings.openai_request_country,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
request_location_enabled: settings.request_location_enabled,
|
||||
request_location: settings.request_location,
|
||||
@@ -811,7 +813,11 @@ fn settings_validation_error(field: &'static str) -> WireValidationError {
|
||||
"max_waiting_per_key" => "maxWaitingPerKey",
|
||||
"min_codex_cli_version" => "minCodexCliVersion",
|
||||
"min_codex_desktop_version" => "minCodexDesktopVersion",
|
||||
"openai_request_country" => "openaiRequestCountry",
|
||||
"openai_request_settings.request_country" => "openaiRequestSettings.requestCountry",
|
||||
"openai_request_settings.residency" => "openaiRequestSettings.residency",
|
||||
"openai_request_settings.account_routing_override" => {
|
||||
"openaiRequestSettings.accountRoutingOverride"
|
||||
}
|
||||
"account_affinity" => "accountAffinity",
|
||||
"openai_guardian_reserved_concurrency" => "openaiGuardianReservedConcurrency",
|
||||
"session_affinity_ttl_hours" => "sessionAffinityTtlHours",
|
||||
|
||||
@@ -1989,8 +1989,7 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
rotation_strategy: RotationStrategy::Smart,
|
||||
updated_at: Utc::now(),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
|
||||
@@ -751,6 +751,7 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
account_provider_kind: Some("openai".to_owned()),
|
||||
account_authentication_kind: authentication_kind.map(str::to_owned),
|
||||
account_plan_type: plan_type.map(str::to_owned),
|
||||
account_plan_type_display: None,
|
||||
name: "diag@example.invalid".to_owned(),
|
||||
request_count: 2,
|
||||
success_count: 2,
|
||||
@@ -1093,6 +1094,12 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
closed.error_message =
|
||||
Some("OpenAI WebSocket closed before a terminal response".to_owned());
|
||||
records.push(closed);
|
||||
let mut agy = records[0].clone();
|
||||
agy.id = "request_antigravity".to_owned();
|
||||
agy.provider_kind = Some("antigravity".to_owned());
|
||||
agy.provider_account_plan_type = Some("g1-pro-tier".to_owned());
|
||||
agy.provider_account_plan_type_display = Some("Pro subscription".to_owned());
|
||||
records.push(agy);
|
||||
}
|
||||
let response = observability::router::<AdminTestState>()
|
||||
.with_state(fixture.state())
|
||||
@@ -1112,6 +1119,11 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
.expect("usage response body");
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).expect("usage response JSON");
|
||||
|
||||
assert_eq!(value["data"]["items"][5]["accountPlanType"], "g1-pro-tier");
|
||||
assert_eq!(
|
||||
value["data"]["items"][5]["accountPlanTypeDisplay"],
|
||||
"Pro subscription"
|
||||
);
|
||||
assert!(value["data"]["items"][0]["errorCode"].is_null());
|
||||
assert!(value["data"]["items"][0]["errorMessage"].is_null());
|
||||
assert_eq!(value["data"]["items"][3]["errorCode"], "server_error");
|
||||
@@ -1248,6 +1260,7 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
"$0.007"
|
||||
);
|
||||
|
||||
let value_before_peer_refresh = value["data"]["items"].as_array().unwrap();
|
||||
// 互联标识随当前摘要变化,重复请求共享同一账号,既有请求快照保持原值
|
||||
for peer in [
|
||||
Some((true, true)),
|
||||
@@ -1277,7 +1290,15 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
json!(peer.map(|(d, o)| d && o))
|
||||
);
|
||||
assert_eq!(item["accountName"], "Snapshot Alpha");
|
||||
assert_eq!(item["accountPlanType"], "supergrok_plus");
|
||||
let old = value_before_peer_refresh
|
||||
.iter()
|
||||
.find(|old| old["id"] == item["id"])
|
||||
.unwrap();
|
||||
assert_eq!(item["accountPlanType"], old["accountPlanType"]);
|
||||
assert_eq!(
|
||||
item["accountPlanTypeDisplay"],
|
||||
old["accountPlanTypeDisplay"]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,8 +75,7 @@ fn backup_settings_report_secret_presence_without_serializing_the_secret() {
|
||||
fn update_body() -> Value {
|
||||
json!({
|
||||
"configRevision": 7,
|
||||
"openaiOauthGuardianReviewModel": true,
|
||||
"openaiRequestCountry": {"mode": "follow_location"},
|
||||
"openaiRequestSettings": {"requestCountry": {"mode":"follow_location"}, "oauthGuardianReviewModel":true,"residency": null, "accountRoutingOverride": null},
|
||||
"codexPrivacyPolicy": {"enabled":false,"onError":"skip_rule","rules":[]},
|
||||
"requestLocationEnabled": false,
|
||||
"requestLocation": {"country":"US", "region":"Ohio", "city":"Piketon", "timezone":"America/New_York"},
|
||||
@@ -575,8 +574,7 @@ fn settings_service_contract_flattens_values_and_rejects_unknown_fields() {
|
||||
command
|
||||
);
|
||||
for field in [
|
||||
"openai_oauth_guardian_review_model",
|
||||
"openai_request_country",
|
||||
"openai_request_settings",
|
||||
"reset_credit_on_low_weekly_quota",
|
||||
] {
|
||||
let mut incomplete = wire.clone();
|
||||
@@ -1473,28 +1471,39 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
))
|
||||
};
|
||||
let initial = response_json(read().await.unwrap()).await["data"].clone();
|
||||
assert_eq!(initial["openaiOauthGuardianReviewModel"], true);
|
||||
assert_eq!(
|
||||
initial["openaiRequestCountry"],
|
||||
initial["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
initial["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"follow_location"})
|
||||
);
|
||||
let mut body = update_body();
|
||||
body["configRevision"] = initial["configRevision"].clone();
|
||||
body["openaiOauthGuardianReviewModel"] = json!(false);
|
||||
body["openaiRequestCountry"] = json!({"mode":"custom","country":"CA"});
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = json!(false);
|
||||
body["openaiRequestSettings"]["requestCountry"] = json!({"mode":"custom","country":"CA"});
|
||||
body["openaiRequestSettings"]["residency"] = json!("us");
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = json!("us_cr");
|
||||
body["resetCreditOnLowWeeklyQuota"] = json!(true);
|
||||
let response = save(body.clone()).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let saved = response_json(response).await["data"].clone();
|
||||
assert_eq!(saved["resetCreditOnLowWeeklyQuota"], true);
|
||||
assert_eq!(saved["openaiOauthGuardianReviewModel"], false);
|
||||
assert_eq!(saved["openaiRequestCountry"], body["openaiRequestCountry"]);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"]["requestCountry"],
|
||||
body["openaiRequestSettings"]["requestCountry"]
|
||||
);
|
||||
assert_eq!(
|
||||
saved["openaiRequestSettings"],
|
||||
body["openaiRequestSettings"]
|
||||
);
|
||||
|
||||
for field in [
|
||||
"openaiOauthGuardianReviewModel",
|
||||
"openaiRequestCountry",
|
||||
"resetCreditOnLowWeeklyQuota",
|
||||
] {
|
||||
for field in ["openaiRequestSettings", "resetCreditOnLowWeeklyQuota"] {
|
||||
let mut incomplete = update_body();
|
||||
incomplete["configRevision"] = saved["configRevision"].clone();
|
||||
incomplete.as_object_mut().unwrap().remove(field);
|
||||
@@ -1508,8 +1517,10 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
body["openaiOauthGuardianReviewModel"] = json!(true);
|
||||
body["openaiRequestCountry"] = json!({"mode":"passthrough"});
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = json!(true);
|
||||
body["openaiRequestSettings"]["requestCountry"] = json!({"mode":"passthrough"});
|
||||
body["openaiRequestSettings"]["residency"] = Value::Null;
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = Value::Null;
|
||||
assert_eq!(
|
||||
save(body.clone()).await.unwrap().status(),
|
||||
StatusCode::CONFLICT
|
||||
@@ -1520,9 +1531,16 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
let response = save(body).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let changed = response_json(response).await["data"].clone();
|
||||
assert_eq!(changed["openaiOauthGuardianReviewModel"], true);
|
||||
assert_eq!(
|
||||
changed["openaiRequestCountry"],
|
||||
changed["openaiRequestSettings"]["oauthGuardianReviewModel"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
changed["openaiRequestSettings"],
|
||||
json!({"requestCountry":{"mode":"passthrough"},"oauthGuardianReviewModel":true,"residency":null,"accountRoutingOverride":null})
|
||||
);
|
||||
assert_eq!(
|
||||
changed["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"passthrough"})
|
||||
);
|
||||
}
|
||||
@@ -1541,14 +1559,14 @@ fn openai_request_settings_validate_modes_and_country_codes() {
|
||||
json!({"mode":"unknown"}),
|
||||
] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestCountry"] = invalid.clone();
|
||||
body["openaiRequestSettings"]["requestCountry"] = invalid.clone();
|
||||
if let Ok(request) = serde_json::from_value::<UpdateRuntimeSettingsRequest>(body) {
|
||||
assert!(request.validate().is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
for invalid in [json!(null), json!("true"), json!(1)] {
|
||||
let mut body = update_body();
|
||||
body["openaiOauthGuardianReviewModel"] = invalid;
|
||||
body["openaiRequestSettings"]["oauthGuardianReviewModel"] = invalid;
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1732,3 +1750,33 @@ fn reset_credit_weekly_threshold_accepts_unset_and_zero_to_one_hundred() {
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_request_settings_validate_without_normalizing_values() {
|
||||
for value in [
|
||||
None,
|
||||
Some(""),
|
||||
Some("us"),
|
||||
Some("us_cr"),
|
||||
Some("custom-value"),
|
||||
Some(" US "),
|
||||
] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestSettings"]["residency"] = json!(value);
|
||||
body["openaiRequestSettings"]["accountRoutingOverride"] = json!(value);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
request.validate().unwrap();
|
||||
assert_eq!(
|
||||
request.values.openai_request_settings.residency.as_deref(),
|
||||
value
|
||||
);
|
||||
}
|
||||
for field in ["residency", "accountRoutingOverride"] {
|
||||
for value in ["us\r\nx-injected: true", "us\n", "\0", "国"] {
|
||||
let mut body = update_body();
|
||||
body["openaiRequestSettings"][field] = json!(value);
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(body).unwrap();
|
||||
assert!(request.validate().is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,31 +11,6 @@ pub struct RequestLocation {
|
||||
pub timezone: chrono_tz::Tz,
|
||||
}
|
||||
|
||||
/// 独立选择 OpenAI 请求的国家字段,仅自定义模式需要国家代码
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
|
||||
impl Default for OpenAiRequestCountry {
|
||||
fn default() -> Self {
|
||||
Self::FollowLocation {}
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAiRequestCountry {
|
||||
pub fn validate(&self) -> Result<(), InvalidRequestLocation> {
|
||||
if let Self::Custom { country } = self {
|
||||
validate_country(country)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum InvalidRequestLocation {
|
||||
#[error("country must contain two uppercase ASCII letters")]
|
||||
@@ -83,7 +58,7 @@ impl RequestLocation {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_country(country: &str) -> Result<(), InvalidRequestLocation> {
|
||||
pub(crate) fn validate_country(country: &str) -> Result<(), InvalidRequestLocation> {
|
||||
if country.len() == 2 && country.bytes().all(|byte| byte.is_ascii_uppercase()) {
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
@@ -6,7 +6,8 @@ pub use error_protection::*;
|
||||
mod fast_mode;
|
||||
pub use fast_mode::FastMode;
|
||||
mod location;
|
||||
pub use location::{InvalidRequestLocation, OpenAiRequestCountry, RequestLocation};
|
||||
pub(crate) use location::validate_country;
|
||||
pub use location::{InvalidRequestLocation, RequestLocation};
|
||||
mod model;
|
||||
mod model_access;
|
||||
pub use model_access::{
|
||||
|
||||
@@ -817,6 +817,8 @@ pub struct AccountHistorySnapshot {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plan_type_snapshot: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub plan_type_display_snapshot: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub notes_snapshot: Option<String>,
|
||||
}
|
||||
|
||||
@@ -828,6 +830,7 @@ impl AccountHistorySnapshot {
|
||||
email: account.email().map(str::to_owned),
|
||||
authentication_kind: account.authentication_kind().to_owned(),
|
||||
plan_type_snapshot: account.plan_type().map(str::to_owned),
|
||||
plan_type_display_snapshot: None,
|
||||
notes_snapshot: account.notes().map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1206,7 +1206,7 @@ where
|
||||
.with_fast_mode(self.plan.fast_mode())
|
||||
.with_pricing(self.plan.pricing())
|
||||
.with_request_location(self.plan.request_location().cloned())
|
||||
.with_openai_request_country(self.plan.openai_request_country().clone())
|
||||
.with_openai_request_settings(self.plan.openai_request_settings().clone())
|
||||
.with_privacy(self.plan.privacy())
|
||||
.with_request_body_limit(self.plan.request_body_limit())
|
||||
.with_concurrency_wait_budget(self.concurrency_wait_budget.clone())
|
||||
|
||||
@@ -320,7 +320,7 @@ pub struct RequestAttemptContext {
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
openai_request_country: crate::account::OpenAiRequestCountry,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
privacy: Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>>,
|
||||
request_id: ModelRequestId,
|
||||
@@ -419,11 +419,11 @@ impl RequestAttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_country(
|
||||
pub fn with_openai_request_settings(
|
||||
mut self,
|
||||
country: crate::account::OpenAiRequestCountry,
|
||||
settings: crate::settings::OpenAiRequestSettings,
|
||||
) -> Self {
|
||||
self.openai_request_country = country;
|
||||
self.openai_request_settings = settings;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -448,7 +448,7 @@ impl RequestAttemptContext {
|
||||
request_profile: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_request_country: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
request_location: None,
|
||||
privacy: None,
|
||||
timing_started_at: Instant::now(),
|
||||
@@ -726,8 +726,8 @@ impl AttemptContext {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_country(&self) -> &crate::account::OpenAiRequestCountry {
|
||||
&self.request.openai_request_country
|
||||
pub const fn openai_request_settings(&self) -> &crate::settings::OpenAiRequestSettings {
|
||||
&self.request.openai_request_settings
|
||||
}
|
||||
|
||||
/// 当前 attempt 的诊断关联;克隆后可传给后台 transport 任务
|
||||
|
||||
@@ -13,6 +13,13 @@ pub trait ProviderRuntimePolicyPort: Send + Sync {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
/// 后台 OpenAI 操作读取当前全局请求设置
|
||||
fn load_openai_request_settings(
|
||||
&self,
|
||||
) -> BoxFuture<'_, Result<crate::settings::OpenAiRequestSettings, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(Default::default()) })
|
||||
}
|
||||
|
||||
/// 原子推进预热执行游标,重启或时钟回拨后不重复领取已消费的时刻
|
||||
fn claim_warmup_slot<'a>(
|
||||
&'a self,
|
||||
|
||||
@@ -699,7 +699,7 @@ pub struct RoutingPlan {
|
||||
request_body_limit: usize,
|
||||
max_retry_after: std::time::Duration,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
openai_request_country: crate::account::OpenAiRequestCountry,
|
||||
openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
request_location: Option<crate::account::RequestLocation>,
|
||||
privacy: Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>>,
|
||||
config_revision: ConfigRevision,
|
||||
@@ -755,8 +755,8 @@ impl RoutingPlan {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_request_country(&self) -> &crate::account::OpenAiRequestCountry {
|
||||
&self.openai_request_country
|
||||
pub const fn openai_request_settings(&self) -> &crate::settings::OpenAiRequestSettings {
|
||||
&self.openai_request_settings
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
|
||||
@@ -1919,7 +1919,7 @@ impl RuntimeSnapshot {
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
openai_request_country: self.settings.values.openai_request_country().clone(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
request_location: self.settings.request_location.clone(),
|
||||
privacy: self.settings.privacy.clone(),
|
||||
account_error_protection: Arc::clone(&self.settings.account_error_protection),
|
||||
@@ -2010,7 +2010,7 @@ impl RuntimeSnapshot {
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
openai_request_country: self.settings.values.openai_request_country().clone(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
request_location: self.settings.request_location.clone(),
|
||||
privacy: self.settings.privacy.clone(),
|
||||
account_error_protection: Arc::clone(&self.settings.account_error_protection),
|
||||
|
||||
@@ -112,7 +112,7 @@ impl CompiledSettings {
|
||||
timeout: Duration::from_secs(u64::from(settings.key_queue_timeout_seconds)),
|
||||
};
|
||||
settings
|
||||
.openai_request_country
|
||||
.openai_request_settings
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
let request_location = settings
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! 运行设置的纯值、校验与编译结果
|
||||
|
||||
pub(crate) mod compiled;
|
||||
mod openai;
|
||||
pub mod privacy;
|
||||
pub mod request_profiles;
|
||||
mod values;
|
||||
pub use openai::{OpenAiRequestCountry, OpenAiRequestSettings};
|
||||
pub use values::{
|
||||
SettingsValues, client_min_versions, response_body_limit, validate_request_limits,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! OpenAI 请求的国家、路由头与 OAuth 审核模型设置
|
||||
|
||||
/// OpenAI 请求策略与覆盖值,独立于客户端身份和并发调度
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OpenAiRequestSettings {
|
||||
pub request_country: OpenAiRequestCountry,
|
||||
pub oauth_guardian_review_model: bool,
|
||||
pub residency: Option<String>,
|
||||
pub account_routing_override: Option<String>,
|
||||
}
|
||||
|
||||
impl OpenAiRequestSettings {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
self.request_country
|
||||
.validate()
|
||||
.map_err(|_| "openai_request_settings.request_country")?;
|
||||
for (field, value) in [
|
||||
(
|
||||
"openai_request_settings.residency",
|
||||
self.residency.as_deref(),
|
||||
),
|
||||
(
|
||||
"openai_request_settings.account_routing_override",
|
||||
self.account_routing_override.as_deref(),
|
||||
),
|
||||
] {
|
||||
let Some(value) = value else { continue };
|
||||
// WebSocket 握手也通过字符串构造头,提前拒绝无法在两种传输间一致发送的值
|
||||
if !http::HeaderValue::from_str(value).is_ok_and(|header| header.to_str().is_ok()) {
|
||||
return Err(field);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for OpenAiRequestSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
request_country: Default::default(),
|
||||
oauth_guardian_review_model: true,
|
||||
residency: None,
|
||||
account_routing_override: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 独立选择 OpenAI 请求的国家字段,仅自定义模式需要国家代码
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
|
||||
impl Default for OpenAiRequestCountry {
|
||||
fn default() -> Self {
|
||||
Self::FollowLocation {}
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAiRequestCountry {
|
||||
pub fn validate(&self) -> Result<(), crate::account::InvalidRequestLocation> {
|
||||
if let Self::Custom { country } = self {
|
||||
crate::account::validate_country(country)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,7 @@ pub struct SettingsValues {
|
||||
pub(crate) switch_account_on_queue_failure: bool,
|
||||
pub(crate) max_retry_after_seconds: u32,
|
||||
pub(crate) openai_guardian_reserved_concurrency: u32,
|
||||
pub(crate) openai_oauth_guardian_review_model: bool,
|
||||
pub(crate) openai_request_country: crate::account::OpenAiRequestCountry,
|
||||
pub(crate) openai_request_settings: crate::settings::OpenAiRequestSettings,
|
||||
pub(crate) account_affinity: crate::account::AccountAffinity,
|
||||
pub(crate) max_account_rotations: u32,
|
||||
pub(crate) session_affinity_ttl_hours: u32,
|
||||
@@ -111,28 +110,17 @@ impl SettingsValues {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_openai_oauth_guardian_review_model(mut self, enabled: bool) -> Self {
|
||||
self.openai_oauth_guardian_review_model = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn openai_oauth_guardian_review_model(&self) -> bool {
|
||||
self.openai_oauth_guardian_review_model
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_openai_request_country(
|
||||
pub fn with_openai_request_settings(
|
||||
mut self,
|
||||
policy: crate::account::OpenAiRequestCountry,
|
||||
settings: crate::settings::OpenAiRequestSettings,
|
||||
) -> Self {
|
||||
self.openai_request_country = policy;
|
||||
self.openai_request_settings = settings;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn openai_request_country(&self) -> &crate::account::OpenAiRequestCountry {
|
||||
&self.openai_request_country
|
||||
pub const fn openai_request_settings(&self) -> &crate::settings::OpenAiRequestSettings {
|
||||
&self.openai_request_settings
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -234,8 +222,7 @@ impl SettingsValues {
|
||||
switch_account_on_queue_failure: false,
|
||||
max_retry_after_seconds: 240,
|
||||
openai_guardian_reserved_concurrency: 0,
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
account_affinity: crate::account::AccountAffinity::default(),
|
||||
max_account_rotations: 3,
|
||||
session_affinity_ttl_hours: 24,
|
||||
|
||||
@@ -5276,14 +5276,12 @@ fn invalid_request_settings_leave_the_prepared_execution_unchanged() {
|
||||
let client = service.authenticate("sk_start_test").unwrap();
|
||||
let prepared = service.prepare_verified_execution(client).unwrap();
|
||||
let baseline = prepared.request_settings().execution_values().unwrap();
|
||||
for field in [
|
||||
"openai_oauth_guardian_review_model",
|
||||
"openai_request_country",
|
||||
] {
|
||||
let mut incomplete = serde_json::to_value(&baseline).unwrap();
|
||||
incomplete["runtime"].as_object_mut().unwrap().remove(field);
|
||||
assert!(serde_json::from_value::<ExecutionSettings>(incomplete).is_err());
|
||||
}
|
||||
let mut incomplete = serde_json::to_value(&baseline).unwrap();
|
||||
incomplete["runtime"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("openai_request_settings");
|
||||
assert!(serde_json::from_value::<ExecutionSettings>(incomplete).is_err());
|
||||
let mut invalid = serde_json::to_value(&baseline).unwrap();
|
||||
invalid["runtime"]["responses_max_decompressed_body_bytes"] = json!(0);
|
||||
invalid["fast_mode"] = json!("disabled");
|
||||
|
||||
@@ -2266,8 +2266,9 @@ fn revision(value: u64) -> ConfigRevision {
|
||||
|
||||
#[test]
|
||||
fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
use gateway_core::account::{OpenAiRequestCountry, ProviderAccountId, RequestLocation};
|
||||
use gateway_core::account::{ProviderAccountId, RequestLocation};
|
||||
use gateway_core::runtime::RuntimeSnapshotHandle;
|
||||
use gateway_core::settings::OpenAiRequestCountry;
|
||||
let make_snapshot = |version, timezone: &str, enabled, country| {
|
||||
let location = RequestLocation {
|
||||
timezone: timezone.parse().unwrap(),
|
||||
@@ -2278,7 +2279,12 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
revision(version),
|
||||
SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
|
||||
.with_request_location(location, enabled)
|
||||
.with_openai_request_country(country),
|
||||
.with_openai_request_settings(gateway_core::settings::OpenAiRequestSettings {
|
||||
request_country: country,
|
||||
residency: (version == 1).then(|| "us".to_owned()),
|
||||
account_routing_override: (version == 1).then(|| "us_cr".to_owned()),
|
||||
..Default::default()
|
||||
}),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec![SnapshotProviderAccountFacts::new(
|
||||
@@ -2321,12 +2327,29 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
OpenAiRequestCountry::FollowLocation {},
|
||||
));
|
||||
assert_eq!(
|
||||
old_plan.openai_request_country(),
|
||||
&OpenAiRequestCountry::Passthrough {}
|
||||
old_plan.openai_request_settings().residency.as_deref(),
|
||||
Some("us")
|
||||
);
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap()).openai_request_country(),
|
||||
&OpenAiRequestCountry::FollowLocation {}
|
||||
old_plan
|
||||
.openai_request_settings()
|
||||
.account_routing_override
|
||||
.as_deref(),
|
||||
Some("us_cr")
|
||||
);
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap()).openai_request_settings(),
|
||||
&Default::default()
|
||||
);
|
||||
assert_eq!(
|
||||
old_plan.openai_request_settings().request_country,
|
||||
OpenAiRequestCountry::Passthrough {}
|
||||
);
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap())
|
||||
.openai_request_settings()
|
||||
.request_country,
|
||||
OpenAiRequestCountry::FollowLocation {}
|
||||
);
|
||||
assert_eq!(
|
||||
old_plan.request_location().unwrap().timezone.name(),
|
||||
|
||||
@@ -78,14 +78,16 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
|
||||
|
||||
let mut command = ReplaceRuntimeSettings::from(original);
|
||||
command.values.refresh_margin_seconds = 999;
|
||||
command.values.openai_oauth_guardian_review_model = false;
|
||||
command.values.openai_request_country = gateway_core::account::OpenAiRequestCountry::Custom {
|
||||
country: "CA".into(),
|
||||
};
|
||||
for field in [
|
||||
"openai_oauth_guardian_review_model",
|
||||
"openai_request_country",
|
||||
] {
|
||||
command
|
||||
.values
|
||||
.openai_request_settings
|
||||
.oauth_guardian_review_model = false;
|
||||
command.values.openai_request_settings.request_country =
|
||||
gateway_core::settings::OpenAiRequestCountry::Custom {
|
||||
country: "CA".into(),
|
||||
};
|
||||
{
|
||||
let field = "openai_request_settings";
|
||||
let mut args = serde_json::to_value((mutation(), &command)).unwrap();
|
||||
args[1].as_object_mut().unwrap().remove(field);
|
||||
assert!(
|
||||
@@ -117,10 +119,15 @@ async fn explicit_service_dispatch_composes_once_and_preserves_native_transactio
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(current.values.refresh_margin_seconds, 1234);
|
||||
assert!(!current.values.openai_oauth_guardian_review_model);
|
||||
assert!(
|
||||
!current
|
||||
.values
|
||||
.openai_request_settings
|
||||
.oauth_guardian_review_model
|
||||
);
|
||||
assert_eq!(
|
||||
current.values.openai_request_country,
|
||||
command.values.openai_request_country
|
||||
current.values.openai_request_settings.request_country,
|
||||
command.values.openai_request_settings.request_country
|
||||
);
|
||||
assert_eq!(
|
||||
core.snapshots()
|
||||
|
||||
@@ -349,7 +349,7 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与
|
||||
|
||||
`Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令;
|
||||
`Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。
|
||||
每次写入都必须提供 `openai_oauth_guardian_review_model`、`openai_request_country` 和 `reset_credit_on_low_weekly_quota`。
|
||||
每次写入都必须提供 `openai_request_settings` 和 `reset_credit_on_low_weekly_quota`。
|
||||
版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务
|
||||
|
||||
`accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、
|
||||
|
||||
@@ -57,6 +57,22 @@ pub enum AccountErrorOperator {
|
||||
Equals,
|
||||
Contains,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OpenAiRequestSettings {
|
||||
pub request_country: OpenAiRequestCountry,
|
||||
pub oauth_guardian_review_model: bool,
|
||||
pub residency: Option<String>,
|
||||
pub account_routing_override: Option<String>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CodexPrivacyPolicy {
|
||||
@@ -137,8 +153,7 @@ pub struct PrivacyPreviewResult {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RuntimeSettings {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: OpenAiRequestCountry,
|
||||
pub openai_request_settings: OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: RequestLocation,
|
||||
@@ -179,8 +194,7 @@ pub struct RuntimeSettings {
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ReplaceRuntimeSettings {
|
||||
pub openai_oauth_guardian_review_model: bool,
|
||||
pub openai_request_country: OpenAiRequestCountry,
|
||||
pub openai_request_settings: OpenAiRequestSettings,
|
||||
pub codex_privacy_policy: CodexPrivacyPolicy,
|
||||
pub request_location_enabled: bool,
|
||||
pub request_location: RequestLocation,
|
||||
@@ -252,14 +266,6 @@ pub struct RequestLocation {
|
||||
pub city: String,
|
||||
pub timezone: String,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum OpenAiRequestCountry {
|
||||
Default {},
|
||||
Passthrough {},
|
||||
FollowLocation {},
|
||||
Custom { country: String },
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct SmartSchedulingConfig {
|
||||
@@ -401,8 +407,7 @@ impl Operation for PreviewClientProfile {
|
||||
impl From<RuntimeSettings> for ReplaceRuntimeSettings {
|
||||
fn from(settings: RuntimeSettings) -> Self {
|
||||
Self {
|
||||
openai_oauth_guardian_review_model: settings.openai_oauth_guardian_review_model,
|
||||
openai_request_country: settings.openai_request_country,
|
||||
openai_request_settings: settings.openai_request_settings,
|
||||
codex_privacy_policy: settings.codex_privacy_policy,
|
||||
request_location_enabled: settings.request_location_enabled,
|
||||
request_location: settings.request_location,
|
||||
|
||||
@@ -108,8 +108,7 @@ impl SettingsStore for AdminSettingsStoreAdapter {
|
||||
"switch_account_on_queue_failure".to_owned(),
|
||||
"max_retry_after_seconds".to_owned(),
|
||||
"openai_guardian_reserved_concurrency".to_owned(),
|
||||
"openai_oauth_guardian_review_model".to_owned(),
|
||||
"openai_request_country".to_owned(),
|
||||
"openai_request_settings_json".to_owned(),
|
||||
"account_affinity".to_owned(),
|
||||
"max_account_rotations".to_owned(),
|
||||
"session_affinity_ttl_hours".to_owned(),
|
||||
|
||||
@@ -947,6 +947,7 @@ fn account_snapshot_bytes(
|
||||
snapshot.email.as_deref(),
|
||||
Some(snapshot.authentication_kind.as_str()),
|
||||
snapshot.plan_type_snapshot.as_deref(),
|
||||
snapshot.plan_type_display_snapshot.as_deref(),
|
||||
snapshot.notes_snapshot.as_deref(),
|
||||
])
|
||||
})
|
||||
|
||||
@@ -637,6 +637,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
account_provider_kind: None,
|
||||
account_authentication_kind: None,
|
||||
account_plan_type: None,
|
||||
account_plan_type_display: None,
|
||||
request_count: metrics.request_count,
|
||||
success_count: metrics.success_count,
|
||||
failure_count: metrics.failure_count,
|
||||
@@ -670,9 +671,9 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map(|item| item.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let statement = if dimension == DiagnosticDimension::Account {
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, historical.provider_kind, historical.provider_account_authentication_kind_snapshot as authentication_kind, historical.provider_account_plan_type_snapshot as plan_type, historical.provider_account_plan_type_display_snapshot as plan_type_display, coalesce(historical.provider_account_email_snapshot,historical.provider_account_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select provider_kind,provider_account_authentication_kind_snapshot,provider_account_plan_type_snapshot,provider_account_plan_type_display_snapshot,provider_account_email_snapshot,provider_account_name_snapshot from model_request_observations mr where mr.provider_account_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
} else {
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type,coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
"select requested.id, null::text as provider_kind, null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display, coalesce(historical.client_api_key_name_snapshot,requested.id) as name from unnest($1::text[]) requested(id) left join lateral (select client_api_key_name_snapshot from model_request_observations mr where mr.client_api_key_ref=requested.id order by mr.started_at desc,mr.id desc limit 1) historical on true"
|
||||
};
|
||||
let labels = sqlx::query(statement)
|
||||
.bind(ids)
|
||||
@@ -686,6 +687,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
item.account_provider_kind = get(&row, "provider_kind")?;
|
||||
item.account_authentication_kind = get(&row, "authentication_kind")?;
|
||||
item.account_plan_type = get(&row, "plan_type")?;
|
||||
item.account_plan_type_display = get(&row, "plan_type_display")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,6 +282,7 @@ fn admin_diagnostic_observation(
|
||||
account_provider_kind: observation.account_provider_kind,
|
||||
account_authentication_kind: observation.account_authentication_kind,
|
||||
account_plan_type: observation.account_plan_type,
|
||||
account_plan_type_display: observation.account_plan_type_display,
|
||||
request_count: observation.request_count,
|
||||
success_count: observation.success_count,
|
||||
failure_count: observation.failure_count,
|
||||
@@ -391,7 +392,7 @@ pub(crate) fn usage_list_record_from_row(
|
||||
provider_account_notes: get(row, "provider_account_notes")?,
|
||||
provider_account_upstream_peer: None,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
provider_account_plan_type_display: None,
|
||||
provider_account_plan_type_display: get(row, "provider_account_plan_type_display")?,
|
||||
provider_account_authentication_kind: get(row, "provider_account_authentication_kind")?,
|
||||
upstream_model_id: get(row, "upstream_model_id")?,
|
||||
upstream_transport: get(row, "upstream_transport")?,
|
||||
@@ -558,7 +559,7 @@ pub(crate) fn ops_error_from_row(row: &sqlx::postgres::PgRow) -> StoreResult<Ops
|
||||
provider_account_name: get(row, "provider_account_name")?,
|
||||
provider_account_email: get(row, "provider_account_email")?,
|
||||
provider_account_plan_type: get(row, "provider_account_plan_type")?,
|
||||
provider_account_plan_type_display: None,
|
||||
provider_account_plan_type_display: get(row, "provider_account_plan_type_display")?,
|
||||
provider_account_authentication_kind: get(row, "provider_account_authentication_kind")?,
|
||||
upstream_model_id: get(row, "upstream_model_id")?,
|
||||
upstream_transport: get(row, "upstream_transport")?,
|
||||
|
||||
@@ -386,6 +386,7 @@ pub struct DiagnosticObservation {
|
||||
pub account_provider_kind: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
pub request_count: u64,
|
||||
pub success_count: u64,
|
||||
pub failure_count: u64,
|
||||
|
||||
@@ -11,6 +11,7 @@ const REQUEST_ERROR_SELECT: &str = "select 'model_request'::text as source,
|
||||
mr.provider_account_name_snapshot as provider_account_name,
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
mr.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
mr.upstream_model_id, mr.upstream_transport,
|
||||
@@ -43,6 +44,7 @@ const OPS_EVENT_SELECT: &str = "select 'ops_event'::text as source,
|
||||
oe.provider_account_name_snapshot as provider_account_name,
|
||||
oe.provider_account_email_snapshot as provider_account_email,
|
||||
oe.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
oe.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
oe.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
oe.upstream_model_id, null::text as upstream_transport, oe.failure_kind,
|
||||
|
||||
@@ -138,6 +138,7 @@ pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||
mr.provider_account_email_snapshot as provider_account_email,
|
||||
mr.provider_account_notes_snapshot as provider_account_notes,
|
||||
mr.provider_account_plan_type_snapshot as provider_account_plan_type,
|
||||
mr.provider_account_plan_type_display_snapshot as provider_account_plan_type_display,
|
||||
mr.provider_account_authentication_kind_snapshot
|
||||
as provider_account_authentication_kind,
|
||||
mr.upstream_model_id, mr.upstream_transport, mr.service_tier,
|
||||
|
||||
@@ -109,6 +109,7 @@ impl OpsEventRepository for PgOpsEventRepository {
|
||||
provider_kind, provider_account_ref, upstream_model_id,
|
||||
provider_account_name_snapshot, provider_account_email_snapshot,
|
||||
provider_account_authentication_kind_snapshot, provider_account_plan_type_snapshot,
|
||||
provider_account_plan_type_display_snapshot,
|
||||
failure_kind, upstream_send_state, status_code, provider_error_code, retry_after_ms,
|
||||
upstream_request_id, latency_ms, message, error_details,
|
||||
created_at
|
||||
@@ -117,6 +118,7 @@ impl OpsEventRepository for PgOpsEventRepository {
|
||||
$8::jsonb ->> 'name',
|
||||
$8::jsonb ->> 'email',
|
||||
$8::jsonb ->> 'authenticationKind', $8::jsonb ->> 'planTypeSnapshot',
|
||||
$8::jsonb ->> 'planTypeDisplaySnapshot',
|
||||
$11, $12, $13, $14, $15, $16, $17, $18, $19, $20
|
||||
)",
|
||||
)
|
||||
|
||||
@@ -155,7 +155,7 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul
|
||||
refresh_concurrency, max_concurrent_per_account,
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
account_error_protection_json, account_error_protection_revision,
|
||||
account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota
|
||||
from runtime_settings where id = 1",
|
||||
@@ -172,6 +172,28 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul
|
||||
}
|
||||
|
||||
impl ProviderRuntimePolicyPort for PgRuntimeSettingsRepository {
|
||||
fn load_openai_request_settings(
|
||||
&self,
|
||||
) -> futures::future::BoxFuture<
|
||||
'_,
|
||||
Result<gateway_core::settings::OpenAiRequestSettings, ProviderStoreError>,
|
||||
> {
|
||||
Box::pin(async move {
|
||||
let settings = sqlx::query_scalar::<
|
||||
_,
|
||||
sqlx::types::Json<gateway_core::settings::OpenAiRequestSettings>,
|
||||
>(
|
||||
"select openai_request_settings_json from runtime_settings where id = 1",
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("load OpenAI request settings", source)
|
||||
})?;
|
||||
Ok(settings.0)
|
||||
})
|
||||
}
|
||||
|
||||
fn claim_warmup_slot<'a>(
|
||||
&'a self,
|
||||
timezone: gateway_core::time::DeploymentTimeZone,
|
||||
@@ -336,7 +358,7 @@ pub(crate) async fn load_runtime_settings_in_transaction(
|
||||
refresh_concurrency, max_concurrent_per_account,
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
account_error_protection_json, account_error_protection_revision,
|
||||
account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota
|
||||
from runtime_settings where id = 1",
|
||||
@@ -422,8 +444,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
switch_account_on_queue_failure = $33,
|
||||
reset_credit_on_low_weekly_quota = $34,
|
||||
quota_reset_window_weights_json = $35,
|
||||
openai_oauth_guardian_review_model = $36,
|
||||
openai_request_country_json = $37,
|
||||
openai_request_settings_json = $36,
|
||||
updated_at = now()
|
||||
where id = 1
|
||||
returning config_revision",
|
||||
@@ -471,8 +492,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
.bind(update.values.switch_account_on_queue_failure)
|
||||
.bind(update.values.reset_credit_on_low_weekly_quota)
|
||||
.bind(sqlx::types::Json(update.values.quota_reset_window_weights))
|
||||
.bind(update.values.openai_oauth_guardian_review_model)
|
||||
.bind(sqlx::types::Json(&update.values.openai_request_country))
|
||||
.bind(sqlx::types::Json(&update.values.openai_request_settings))
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("update runtime settings in transaction", source))?
|
||||
@@ -566,8 +586,7 @@ struct RuntimeSettingsRow {
|
||||
switch_account_on_queue_failure: bool,
|
||||
max_retry_after_seconds: i64,
|
||||
openai_guardian_reserved_concurrency: i64,
|
||||
openai_oauth_guardian_review_model: bool,
|
||||
openai_request_country_json: sqlx::types::Json<gateway_core::account::OpenAiRequestCountry>,
|
||||
openai_request_settings_json: sqlx::types::Json<gateway_core::settings::OpenAiRequestSettings>,
|
||||
account_affinity: String,
|
||||
max_account_rotations: i64,
|
||||
session_affinity_ttl_hours: i64,
|
||||
@@ -607,8 +626,7 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult<RuntimeSett
|
||||
model_mappings: row.model_mappings_json.0,
|
||||
updated_at: row.updated_at,
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: row.openai_oauth_guardian_review_model,
|
||||
openai_request_country: row.openai_request_country_json.0,
|
||||
openai_request_settings: row.openai_request_settings_json.0,
|
||||
refresh_margin_seconds: to_u64(row.refresh_margin_seconds)?,
|
||||
refresh_concurrency: to_u32(row.refresh_concurrency)?,
|
||||
max_concurrent_per_account: to_u32(row.max_concurrent_per_account)?,
|
||||
|
||||
@@ -237,8 +237,7 @@ struct SnapshotSettingsRow {
|
||||
switch_account_on_queue_failure: bool,
|
||||
max_retry_after_seconds: i64,
|
||||
openai_guardian_reserved_concurrency: i64,
|
||||
openai_oauth_guardian_review_model: bool,
|
||||
openai_request_country_json: sqlx::types::Json<gateway_core::account::OpenAiRequestCountry>,
|
||||
openai_request_settings_json: sqlx::types::Json<gateway_core::settings::OpenAiRequestSettings>,
|
||||
account_affinity: String,
|
||||
max_account_rotations: i64,
|
||||
session_affinity_ttl_hours: i64,
|
||||
@@ -255,7 +254,7 @@ async fn load_settings(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
) -> StoreResult<(Revision, SettingsValues)> {
|
||||
let row = sqlx::query_as::<_, SnapshotSettingsRow>(
|
||||
"select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_oauth_guardian_review_model, openai_request_country_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1",
|
||||
"select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1",
|
||||
)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
@@ -280,8 +279,7 @@ async fn load_settings(
|
||||
.with_openai_guardian_reserved_concurrency(to_u32(
|
||||
row.openai_guardian_reserved_concurrency,
|
||||
)?)
|
||||
.with_openai_oauth_guardian_review_model(row.openai_oauth_guardian_review_model)
|
||||
.with_openai_request_country(row.openai_request_country_json.0)
|
||||
.with_openai_request_settings(row.openai_request_settings_json.0)
|
||||
.with_account_affinity(
|
||||
gateway_core::account::AccountAffinity::parse(&row.account_affinity)
|
||||
.ok_or_else(|| invalid("invalid account affinity"))?,
|
||||
|
||||
@@ -42,11 +42,15 @@ async fn control_plane_replacement_commits_one_writer_per_revision_and_preserves
|
||||
customized
|
||||
.settings
|
||||
.values
|
||||
.openai_oauth_guardian_review_model = false;
|
||||
customized.settings.values.openai_request_country =
|
||||
gateway_core::account::OpenAiRequestCountry::Custom {
|
||||
country: "CA".into(),
|
||||
};
|
||||
.openai_request_settings
|
||||
.oauth_guardian_review_model = false;
|
||||
customized
|
||||
.settings
|
||||
.values
|
||||
.openai_request_settings
|
||||
.request_country = gateway_core::settings::OpenAiRequestCountry::Custom {
|
||||
country: "CA".into(),
|
||||
};
|
||||
let (first, second) = tokio::join!(
|
||||
repository.replace_control_plane(customized),
|
||||
repository.replace_control_plane(replacement("second", 7200)),
|
||||
|
||||
@@ -22,8 +22,7 @@ pub(super) fn settings_with_margin(refresh_margin_seconds: u64) -> RuntimeSettin
|
||||
("grok-latest".to_owned(), "grok-4.5".to_owned()),
|
||||
]),
|
||||
values: gateway_admin::model::settings::RuntimeSettingsValues {
|
||||
openai_oauth_guardian_review_model: true,
|
||||
openai_request_country: Default::default(),
|
||||
openai_request_settings: Default::default(),
|
||||
codex_privacy_policy: Default::default(),
|
||||
request_location_enabled: false,
|
||||
request_location: Default::default(),
|
||||
@@ -575,7 +574,7 @@ async fn retry_after_limit_defaults_and_updates_reach_the_runtime_snapshot() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
use gateway_core::account::OpenAiRequestCountry;
|
||||
use gateway_core::settings::OpenAiRequestCountry;
|
||||
use gateway_store::postgres::{PgRuntimeSnapshotRepository, RuntimeSnapshotRepository};
|
||||
let Some(database) = TestDatabase::create("openai_request_settings").await else {
|
||||
return;
|
||||
@@ -583,10 +582,15 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
let repository = PgRuntimeSettingsRepository::new(database.pool.clone());
|
||||
let snapshots = PgRuntimeSnapshotRepository::new(database.pool.clone());
|
||||
let initial = snapshots.load_runtime_snapshot().await.unwrap();
|
||||
assert!(initial.settings.openai_oauth_guardian_review_model());
|
||||
assert!(
|
||||
initial
|
||||
.settings
|
||||
.openai_request_settings()
|
||||
.oauth_guardian_review_model
|
||||
);
|
||||
assert_eq!(
|
||||
initial.settings.openai_request_country(),
|
||||
&OpenAiRequestCountry::FollowLocation {}
|
||||
initial.settings.openai_request_settings().request_country,
|
||||
OpenAiRequestCountry::FollowLocation {}
|
||||
);
|
||||
|
||||
for (enabled, country) in [
|
||||
@@ -601,18 +605,48 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
(false, OpenAiRequestCountry::Default {}),
|
||||
] {
|
||||
let mut update = settings_with_margin(600);
|
||||
update.values.openai_oauth_guardian_review_model = enabled;
|
||||
update.values.openai_request_country = country.clone();
|
||||
let headers = gateway_core::settings::OpenAiRequestSettings {
|
||||
request_country: country.clone(),
|
||||
oauth_guardian_review_model: enabled,
|
||||
residency: enabled.then(|| "us".to_owned()),
|
||||
account_routing_override: enabled.then(|| "us_cr".to_owned()),
|
||||
};
|
||||
update.values.openai_request_settings = headers.clone();
|
||||
repository.update_runtime_settings(update).await.unwrap();
|
||||
let saved = repository.load_runtime_settings().await.unwrap();
|
||||
assert_eq!(saved.values.openai_oauth_guardian_review_model, enabled);
|
||||
assert_eq!(saved.values.openai_request_country, country);
|
||||
let snapshot = snapshots.load_runtime_snapshot().await.unwrap();
|
||||
assert_eq!(
|
||||
snapshot.settings.openai_oauth_guardian_review_model(),
|
||||
saved
|
||||
.values
|
||||
.openai_request_settings
|
||||
.oauth_guardian_review_model,
|
||||
enabled
|
||||
);
|
||||
assert_eq!(snapshot.settings.openai_request_country(), &country);
|
||||
assert_eq!(
|
||||
saved.values.openai_request_settings.request_country,
|
||||
country
|
||||
);
|
||||
assert_eq!(saved.values.openai_request_settings, headers);
|
||||
assert_eq!(
|
||||
gateway_core::provider_ports::ProviderRuntimePolicyPort::load_openai_request_settings(
|
||||
&repository
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
headers
|
||||
);
|
||||
let snapshot = snapshots.load_runtime_snapshot().await.unwrap();
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.settings
|
||||
.openai_request_settings()
|
||||
.oauth_guardian_review_model,
|
||||
enabled
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.settings.openai_request_settings().request_country,
|
||||
country
|
||||
);
|
||||
assert_eq!(snapshot.settings.openai_request_settings(), &headers);
|
||||
assert_eq!(snapshot.config_revision, saved.config_revision);
|
||||
}
|
||||
for invalid in [
|
||||
@@ -623,7 +657,7 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
] {
|
||||
assert!(
|
||||
sqlx::query(
|
||||
"update runtime_settings set openai_request_country_json = $1 where id = 1"
|
||||
"update runtime_settings set openai_request_settings_json = jsonb_set(openai_request_settings_json, '{requestCountry}', $1) where id = 1"
|
||||
)
|
||||
.bind(sqlx::types::Json(invalid))
|
||||
.execute(&database.pool)
|
||||
|
||||
@@ -164,10 +164,14 @@ async fn request_snapshots_should_survive_account_deletion() {
|
||||
)
|
||||
.await;
|
||||
let store = PgExecutionStore::new(database.pool.clone());
|
||||
let mut first_attempt = attempt(&database.pool, "req_snap_a", 1, "acct_snap_a").await;
|
||||
let snapshot = first_attempt.account_snapshot.as_mut().unwrap();
|
||||
snapshot.plan_type_snapshot = Some("g1-pro-tier".to_owned());
|
||||
snapshot.plan_type_display_snapshot = Some("Pro subscription".to_owned());
|
||||
store
|
||||
.insert_model_request_with_first_attempt(
|
||||
new_request("req_snap_a", started_at),
|
||||
attempt(&database.pool, "req_snap_a", 1, "acct_snap_a").await,
|
||||
first_attempt,
|
||||
)
|
||||
.await
|
||||
.expect("insert request with first attempt");
|
||||
@@ -217,6 +221,15 @@ async fn request_snapshots_should_survive_account_deletion() {
|
||||
)
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
record.provider_account_plan_type.as_deref(),
|
||||
Some("g1-pro-tier")
|
||||
);
|
||||
assert_eq!(
|
||||
record.provider_account_plan_type_display.as_deref(),
|
||||
Some("Pro subscription")
|
||||
);
|
||||
|
||||
let detail = repository
|
||||
.usage_record_detail("req_snap_a")
|
||||
.await
|
||||
@@ -1282,6 +1295,7 @@ async fn account_snapshot(
|
||||
email,
|
||||
authentication_kind,
|
||||
plan_type_snapshot,
|
||||
plan_type_display_snapshot: None,
|
||||
notes_snapshot,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,6 +147,12 @@ impl Document {
|
||||
valid_until,
|
||||
})
|
||||
}
|
||||
pub(super) fn plan_display(&self) -> Option<&str> {
|
||||
self.plan_description
|
||||
.as_deref()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn plan_type(&self) -> Option<String> {
|
||||
self.tier
|
||||
.as_ref()
|
||||
@@ -254,11 +260,7 @@ impl Document {
|
||||
}),
|
||||
limit_reached: self.access(observed).is_exhausted(),
|
||||
plan_type: self.plan_type(),
|
||||
plan_type_display: self
|
||||
.plan_description
|
||||
.as_ref()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.cloned(),
|
||||
plan_type_display: self.plan_display().map(str::to_owned),
|
||||
observed_at: Some(DateTime::<Utc>::from(observed)),
|
||||
windows,
|
||||
..Default::default()
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
mod document;
|
||||
mod service;
|
||||
|
||||
pub(crate) use service::{QuotaService, QuotaTask};
|
||||
pub(crate) use service::{CandidateQuota, QuotaService, QuotaTask};
|
||||
|
||||
@@ -29,6 +29,13 @@ use std::{
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
pub(crate) struct CandidateQuota {
|
||||
pub(crate) exhausted: bool,
|
||||
pub(crate) signals: Option<AccountQuotaSignals>,
|
||||
pub(crate) plan_type: Option<String>,
|
||||
pub(crate) plan_display: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct QuotaService {
|
||||
kind: ProviderKind,
|
||||
accounts: Arc<dyn ProviderAccountStore>,
|
||||
@@ -245,8 +252,7 @@ impl QuotaService {
|
||||
&self,
|
||||
accounts: &[ProviderAccount],
|
||||
model: &str,
|
||||
) -> Result<BTreeMap<ProviderAccountId, (bool, Option<AccountQuotaSignals>)>, ProviderAdminError>
|
||||
{
|
||||
) -> Result<BTreeMap<ProviderAccountId, CandidateQuota>, ProviderAdminError> {
|
||||
let owners: BTreeMap<_, _> = accounts.iter().map(|a| (a.id().clone(), a)).collect();
|
||||
let ids: Vec<_> = owners.keys().cloned().collect();
|
||||
let observations = self.accounts.get_quotas(&ids).await.map_err(unavailable)?;
|
||||
@@ -260,13 +266,20 @@ impl QuotaService {
|
||||
.map(|account| (o, account))
|
||||
})
|
||||
.map(|(o, account)| {
|
||||
let result = parse(&o)?.model_signals(
|
||||
let document = parse(&o)?;
|
||||
let (exhausted, signals) = document.model_signals(
|
||||
model,
|
||||
account.auto_use_quota_credits(),
|
||||
o.observed_at,
|
||||
now,
|
||||
);
|
||||
Ok((o.account_id, result))
|
||||
let quota = CandidateQuota {
|
||||
exhausted,
|
||||
signals,
|
||||
plan_type: document.plan_type(),
|
||||
plan_display: document.plan_display().map(str::to_owned),
|
||||
};
|
||||
Ok((o.account_id, quota))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! 从本地目录、凭据版本、额度和租约信号构建本轮候选
|
||||
|
||||
use super::AntigravityProvider;
|
||||
use crate::transport::unsent;
|
||||
use crate::{credential::quota::CandidateQuota, transport::unsent};
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountCandidate, AccountSelectionContext, AccountStatus, CredentialRevision,
|
||||
@@ -22,6 +22,7 @@ pub(super) enum Project {
|
||||
pub(super) struct CandidatePool {
|
||||
pub(super) accounts: Vec<AccountCandidate>,
|
||||
pub(super) projects: BTreeMap<ProviderAccountId, (CredentialRevision, Project)>,
|
||||
pub(super) quotas: BTreeMap<ProviderAccountId, CandidateQuota>,
|
||||
pub(super) selection: AccountSelectionContext,
|
||||
}
|
||||
|
||||
@@ -72,13 +73,11 @@ impl AntigravityProvider {
|
||||
.iter()
|
||||
.map(|account| account.id().clone())
|
||||
.collect();
|
||||
let mut quota = if diagnostic {
|
||||
BTreeMap::new()
|
||||
} else {
|
||||
self.quota
|
||||
.scheduling(&accounts, model.as_str())
|
||||
.await
|
||||
.map_err(super::unavailable)?
|
||||
let mut quotas = match self.quota.scheduling(&accounts, model.as_str()).await {
|
||||
Ok(quotas) => quotas,
|
||||
// 固定探测绕过额度门槛,读取不到套餐快照也应能继续
|
||||
Err(_) if diagnostic => BTreeMap::new(),
|
||||
Err(error) => return Err(super::unavailable(error)),
|
||||
};
|
||||
let scheduling = self
|
||||
.leases
|
||||
@@ -118,7 +117,6 @@ impl AntigravityProvider {
|
||||
let mut candidates = Vec::new();
|
||||
let mut model_exhausted = false;
|
||||
for account in accounts {
|
||||
let (exhausted, quota_signals) = quota.remove(account.id()).unwrap_or_default();
|
||||
if projects
|
||||
.get(account.id())
|
||||
.is_none_or(|(revision, _)| *revision != account.revision())
|
||||
@@ -127,7 +125,8 @@ impl AntigravityProvider {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if exhausted {
|
||||
let quota = quotas.get_mut(account.id()).filter(|_| !diagnostic);
|
||||
if quota.as_ref().is_some_and(|q| q.exhausted) {
|
||||
model_exhausted |= !excluded.contains(account.id())
|
||||
&& matches!(
|
||||
account.status_projection(now, None).status,
|
||||
@@ -143,7 +142,7 @@ impl AntigravityProvider {
|
||||
.cloned()
|
||||
.ok_or_else(|| unsent(Kind::ProviderInfrastructureUnavailable))?
|
||||
.with_runtime_health(failure_rate, first_output_latency)
|
||||
.with_provider_quota(quota_signals);
|
||||
.with_provider_quota(quota.and_then(|q| q.signals.take()));
|
||||
candidates.push(AccountCandidate {
|
||||
account,
|
||||
signals,
|
||||
@@ -168,6 +167,7 @@ impl AntigravityProvider {
|
||||
Ok(CandidatePool {
|
||||
accounts: candidates,
|
||||
projects,
|
||||
quotas,
|
||||
selection,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ use super::{AntigravityProvider, candidates::Project};
|
||||
use crate::transport::unsent;
|
||||
use futures::StreamExt;
|
||||
use gateway_core::{
|
||||
account::AccountHistorySnapshot,
|
||||
engine::{
|
||||
AttemptContext,
|
||||
provider::{
|
||||
@@ -68,9 +67,7 @@ impl AntigravityProvider {
|
||||
)
|
||||
.with_credential_revision(selected.account.revision())
|
||||
.with_selection_observation(selection)
|
||||
.with_account_snapshot(Some(AccountHistorySnapshot::from_account(
|
||||
&selected.account,
|
||||
)));
|
||||
.with_account_snapshot(Some(selected.snapshot));
|
||||
let cancellation = ctx.cancellation().clone();
|
||||
let deadline = ctx.deadline();
|
||||
let started_at = ctx.timing_started_at();
|
||||
|
||||
@@ -5,10 +5,11 @@ use super::{
|
||||
candidates::{CandidatePool, Project},
|
||||
};
|
||||
use crate::{credential::Material, transport::unsent};
|
||||
use gateway_admin::model::provider_credentials::resolve_observed_plan;
|
||||
use gateway_core::{
|
||||
account::{
|
||||
AccountCapacitySnapshot, AccountSelector, PreferredAccountSelection, ProviderAccount,
|
||||
RotationStrategy,
|
||||
AccountCapacitySnapshot, AccountHistorySnapshot, AccountSelector,
|
||||
PreferredAccountSelection, ProviderAccount, RotationStrategy,
|
||||
},
|
||||
concurrency::{CapacityWait, ConcurrencyQueuePolicy, QueueRejection},
|
||||
engine::{
|
||||
@@ -29,6 +30,7 @@ pub(super) struct SelectedAccount {
|
||||
pub(super) account: ProviderAccount,
|
||||
pub(super) capacity: Option<AccountCapacitySnapshot>,
|
||||
pub(super) material: Material,
|
||||
pub(super) snapshot: AccountHistorySnapshot,
|
||||
pub(super) project: Project,
|
||||
pub(super) lease: Box<dyn ProviderLeaseGuard>,
|
||||
pub(super) account_switch: bool,
|
||||
@@ -102,6 +104,7 @@ impl AntigravityProvider {
|
||||
let CandidatePool {
|
||||
accounts,
|
||||
mut projects,
|
||||
mut quotas,
|
||||
mut selection,
|
||||
} = self.load_candidates(model, ctx, search).await?;
|
||||
let affinity = match affinity_key.filter(|_| !ctx.is_diagnostic_required_account()) {
|
||||
@@ -233,9 +236,16 @@ impl AntigravityProvider {
|
||||
|| ctx
|
||||
.account_state_owner()
|
||||
.is_some_and(|owner| !owner.matches(&self.kind, account.id()));
|
||||
let selected = self
|
||||
.load_selected(account, project, lease, capacity, account_switch, ctx)
|
||||
.await?;
|
||||
let (current, material) = self.load_selected(account, ctx).await?;
|
||||
let mut snapshot = AccountHistorySnapshot::from_account(¤t);
|
||||
if let Some(quota) = quotas.remove(account.id()) {
|
||||
snapshot.plan_type_display_snapshot = resolve_observed_plan(
|
||||
&mut snapshot.plan_type_snapshot,
|
||||
quota.plan_type.as_deref(),
|
||||
quota.plan_display.as_deref(),
|
||||
)
|
||||
.map(str::to_owned);
|
||||
}
|
||||
let claim = affinity.as_ref().map(|affinity| {
|
||||
affinity.claim(
|
||||
account.id(),
|
||||
@@ -265,11 +275,19 @@ impl AntigravityProvider {
|
||||
.await
|
||||
.map_err(super::unavailable)?
|
||||
{
|
||||
selected.lease.release().await.map_err(super::unavailable)?;
|
||||
lease.release().await.map_err(super::unavailable)?;
|
||||
tokio::task::yield_now().await;
|
||||
continue 'refresh;
|
||||
}
|
||||
return Ok(selected);
|
||||
return Ok(SelectedAccount {
|
||||
account: current,
|
||||
snapshot,
|
||||
capacity,
|
||||
material,
|
||||
project,
|
||||
lease,
|
||||
account_switch,
|
||||
});
|
||||
}
|
||||
ProviderLeaseAcquisition::Busy { retry_after: delay } => {
|
||||
if let Some(delay) = delay {
|
||||
@@ -309,12 +327,8 @@ impl AntigravityProvider {
|
||||
async fn load_selected(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
project: Project,
|
||||
lease: Box<dyn ProviderLeaseGuard>,
|
||||
capacity: Option<AccountCapacitySnapshot>,
|
||||
account_switch: bool,
|
||||
ctx: &AttemptContext,
|
||||
) -> Result<SelectedAccount, ProviderError> {
|
||||
) -> Result<(ProviderAccount, Material), ProviderError> {
|
||||
let current = self
|
||||
.credentials
|
||||
.current(account.id())
|
||||
@@ -326,13 +340,6 @@ impl AntigravityProvider {
|
||||
return Err(unsent(Kind::NoEligibleAccount));
|
||||
}
|
||||
let material = self.credentials.material(¤t)?;
|
||||
Ok(SelectedAccount {
|
||||
account: current.account,
|
||||
capacity,
|
||||
material,
|
||||
project,
|
||||
lease,
|
||||
account_switch,
|
||||
})
|
||||
Ok((current.account, material))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 只改写 Cloud Code 身份字段,其他字段直接复制原始 JSON 字节
|
||||
//! 合成系统提示并改写 Cloud Code 身份字段,其他字段保留原始 JSON 字节
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
@@ -16,6 +16,7 @@ pub(super) fn request_body(
|
||||
) -> Result<Box<RawValue>, ProviderError> {
|
||||
let rewrite = || {
|
||||
let raw: &RawValue = serde_json::from_slice(body)?;
|
||||
let instruction = prepend_system_prompt(raw, instruction)?;
|
||||
edit_object(
|
||||
raw,
|
||||
|name, value| {
|
||||
@@ -59,12 +60,51 @@ pub(super) fn request_body(
|
||||
}
|
||||
Ok(Edit::Keep)
|
||||
},
|
||||
Some(("systemInstruction", instruction)),
|
||||
Some(("systemInstruction", &instruction)),
|
||||
)
|
||||
};
|
||||
rewrite().map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))
|
||||
}
|
||||
|
||||
fn prepend_system_prompt(
|
||||
request: &RawValue,
|
||||
prompt: &RawValue,
|
||||
) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
let Fields(fields) = serde_json::from_str(request.get())?;
|
||||
let client = ["systemInstruction", "system_instruction"]
|
||||
.into_iter()
|
||||
.find_map(|key| {
|
||||
fields
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(name, _)| name == key)
|
||||
.map(|(_, value)| *value)
|
||||
});
|
||||
let Some(client) = client.filter(|value| value.get() != "null") else {
|
||||
return Ok(prompt.to_owned());
|
||||
};
|
||||
#[derive(Deserialize)]
|
||||
struct Content<'a> {
|
||||
#[serde(default, borrow)]
|
||||
parts: Vec<&'a RawValue>,
|
||||
}
|
||||
let mut parts = serde_json::from_str::<Content<'_>>(prompt.get())?.parts;
|
||||
// 客户端系统指令还包含规则、工具说明和工作区上下文,不能按身份提示整体替换
|
||||
parts.extend(serde_json::from_str::<Content<'_>>(client.get())?.parts);
|
||||
let parts = serde_json::value::to_raw_value(&parts)?;
|
||||
edit_object(
|
||||
client,
|
||||
|name, _| {
|
||||
Ok(if name == "parts" {
|
||||
Edit::Remove
|
||||
} else {
|
||||
Edit::Keep
|
||||
})
|
||||
},
|
||||
Some(("parts", &parts)),
|
||||
)
|
||||
}
|
||||
|
||||
enum Edit {
|
||||
Keep,
|
||||
Remove,
|
||||
|
||||
@@ -195,7 +195,10 @@ async fn quota_and_catalog_refresh_use_current_global_identity() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_plan_uses_the_desktop_description_for_every_tier() {
|
||||
async fn account_and_request_plans_use_the_desktop_description_for_every_tier() {
|
||||
use crate::support::{context, request};
|
||||
use gateway_core::engine::provider::Provider as _;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
upstream(&server, json!(1.0), Duration::ZERO).await;
|
||||
let f = Fixture::new(&server.uri());
|
||||
@@ -228,6 +231,23 @@ async fn account_plan_uses_the_desktop_description_for_every_tier() {
|
||||
let view = f.quota.read(account.id()).await.unwrap();
|
||||
assert_eq!(view.plan_type.as_deref(), paid_id.or(Some("free-tier")));
|
||||
assert_eq!(view.plan_type_display.as_deref(), description);
|
||||
let stream = f
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
context(
|
||||
crate::profile::Selection::default()
|
||||
.resolve("2.34.0")
|
||||
.frozen(),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot = stream.metadata().account_snapshot().unwrap();
|
||||
assert_eq!(snapshot.plan_type_snapshot, view.plan_type);
|
||||
assert_eq!(snapshot.plan_type_display_snapshot.as_deref(), description);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,10 +290,14 @@ async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
.scheduling(std::slice::from_ref(&account), "other-model")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(gemini[account.id()].0);
|
||||
assert!(!claude[account.id()].0);
|
||||
assert!(gemini[account.id()].exhausted);
|
||||
assert!(!claude[account.id()].exhausted);
|
||||
assert_eq!(
|
||||
claude[account.id()].1.as_ref().unwrap().remaining_rank(),
|
||||
claude[account.id()]
|
||||
.signals
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.remaining_rank(),
|
||||
Some(8000)
|
||||
);
|
||||
{
|
||||
@@ -285,8 +309,8 @@ async fn quota_refresh_projects_paid_plan_without_exhausting_other_models() {
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!expired[account.id()].0);
|
||||
assert!(expired[account.id()].1.is_none());
|
||||
assert!(!expired[account.id()].exhausted);
|
||||
assert!(expired[account.id()].signals.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -305,7 +329,7 @@ async fn unknown_quota_preserves_only_observed_windows_without_inventing_percent
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap()[account.id()]
|
||||
.0
|
||||
.exhausted
|
||||
);
|
||||
}
|
||||
|
||||
@@ -500,14 +524,14 @@ async fn google_one_credits_require_opt_in_and_sufficient_balance() {
|
||||
.unwrap();
|
||||
assert_eq!(credits.balance.as_deref(), Some(balance));
|
||||
assert_eq!(credits.has_credits, usable);
|
||||
let (blocked, _) = fixture
|
||||
let quota = fixture
|
||||
.quota
|
||||
.scheduling(std::slice::from_ref(&account), "fixture-model")
|
||||
.await
|
||||
.unwrap()
|
||||
.remove(account.id())
|
||||
.unwrap();
|
||||
assert_eq!(blocked, !(enabled && usable));
|
||||
assert_eq!(quota.exhausted, !(enabled && usable));
|
||||
let result = fixture
|
||||
.provider
|
||||
.clone()
|
||||
|
||||
@@ -697,6 +697,10 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let mut body = json!({"model":"fixture-model","stream":streaming,"messages":[{"role":"user","content":"hello"}],"max_completion_tokens":100,"reasoning_effort":"high","temperature":0.3,"top_p":0.8,"tools":[{"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}],"tool_choice":"required","response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object"}}}});
|
||||
body["messages"].as_array_mut().unwrap().insert(
|
||||
0,
|
||||
json!({"role":"system","content":"Preserve the caller's project rules."}),
|
||||
);
|
||||
if streaming {
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
@@ -776,6 +780,10 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
body["request"]["systemInstruction"]["parts"][0]["text"],
|
||||
"Frozen AGY prompt"
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["systemInstruction"]["parts"][1]["text"],
|
||||
"Preserve the caller's project rules."
|
||||
);
|
||||
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
|
||||
assert_eq!(
|
||||
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
|
||||
|
||||
@@ -78,7 +78,8 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("You are Antigravity,")
|
||||
&& !system.to_string().contains("Claude Code")
|
||||
&& system["parts"][1]["text"] == "You are Claude Code."
|
||||
&& system["parts"].as_array().unwrap().len() == 2
|
||||
};
|
||||
post("/v1internal:generateContent")
|
||||
.and(received_body)
|
||||
|
||||
@@ -114,6 +114,10 @@ async fn native_and_provider_count_share_identity_and_never_generate_usage() {
|
||||
sent["request"]["systemInstruction"]["parts"][0]["text"],
|
||||
"count identity"
|
||||
);
|
||||
assert_eq!(
|
||||
sent["request"]["systemInstruction"]["parts"][1]["text"],
|
||||
"client identity"
|
||||
);
|
||||
assert_eq!(sent["request"]["contents"][0]["parts"][0]["text"], "hello");
|
||||
assert_eq!(
|
||||
sent["request"]["tools"][0]["functionDeclarations"][0]["name"],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! 身份字段局部修改与其余 JSON 原始字节保留
|
||||
//! 系统指令合成、身份字段局部修改与其余 JSON 原始字节保留
|
||||
|
||||
use crate::{profile, transport::CloudCodeClient};
|
||||
use serde_json::json;
|
||||
@@ -83,3 +83,66 @@ async fn oauth_identity_edits_preserve_remaining_json_bytes_and_duplicate_busine
|
||||
}
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 6);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generation_and_count_preserve_client_rules_and_instruction_metadata() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{}})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:countTokens"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let selection = profile::Selection {
|
||||
system_prompt: Some("Configured prompt".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&selection.resolve("2.34.0"),
|
||||
)
|
||||
.unwrap();
|
||||
// CLI 1.5.18 Gateway 请求把全局和项目规则放在系统指令中
|
||||
let parts = r#"{"text":"Client tool instructions"},{ "text" : "<user_rules><user_global>Global rule</user_global><workspace>Project rule</workspace></user_rules>", "extension":1e+09 }"#;
|
||||
let instruction =
|
||||
format!(r#"{{"role":"system", "extension":98765432109876543210987654,"parts":[{parts}]}}"#);
|
||||
for field in [
|
||||
"systemInstruction",
|
||||
"system_instruction",
|
||||
"system\\u0049nstruction",
|
||||
] {
|
||||
let body = format!(r#"{{"{field}":{instruction},"contents":[]}}"#);
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
"model",
|
||||
"token",
|
||||
body.as_bytes(),
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
client
|
||||
.count_tokens("token", body.as_bytes(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
for request in requests.iter().rev().take(2) {
|
||||
let body: std::collections::BTreeMap<String, &serde_json::value::RawValue> =
|
||||
serde_json::from_slice(&request.body).unwrap();
|
||||
let body: std::collections::BTreeMap<String, &serde_json::value::RawValue> =
|
||||
serde_json::from_str(body["request"].get()).unwrap();
|
||||
assert_eq!(
|
||||
body["systemInstruction"].get(),
|
||||
format!(
|
||||
r#"{{"role":"system", "extension":98765432109876543210987654,"parts":[{{"text":"Configured prompt"}},{parts}]}}"#
|
||||
)
|
||||
);
|
||||
assert!(!body.contains_key("system_instruction"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,10 +42,6 @@ pub struct OpenAiConfig {
|
||||
pub auth: CodexAuthSettings,
|
||||
#[serde(default = "default_stream_max_retries")]
|
||||
pub stream_max_retries: u64,
|
||||
#[serde(default)]
|
||||
pub residency: Option<String>,
|
||||
#[serde(default)]
|
||||
pub account_routing_override: Option<String>,
|
||||
#[serde(skip)]
|
||||
identity_secret_path: PathBuf,
|
||||
}
|
||||
@@ -126,8 +122,6 @@ impl Default for OpenAiConfig {
|
||||
quota: CodexQuotaSettings::default(),
|
||||
auth: CodexAuthSettings::default(),
|
||||
stream_max_retries: DEFAULT_STREAM_MAX_RETRIES,
|
||||
residency: None,
|
||||
account_routing_override: None,
|
||||
identity_secret_path: PathBuf::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,11 +77,7 @@ pub async fn initialize(
|
||||
profile::identity::RequestProfileSelection::parse(&configured_profile)
|
||||
.map_err(|_| OpenAiInitializeError::RuntimePolicy)?;
|
||||
let credential_state = ports.credential_state();
|
||||
let profile = profile::CodexWireProfileState::new(profile::CodexWireProfile {
|
||||
residency: config.residency.clone(),
|
||||
account_routing_override: config.account_routing_override.clone(),
|
||||
..Default::default()
|
||||
});
|
||||
let profile = profile::CodexWireProfileState::new(profile::CodexWireProfile::default());
|
||||
let artifact_cache =
|
||||
CodexArtifactProfileCache::new(provider_kind.clone(), ports.artifact_profiles());
|
||||
let configured_build = profile.snapshot().desktop_build.parse::<u64>().ok();
|
||||
|
||||
@@ -24,16 +24,21 @@ impl CodexWireProfileState {
|
||||
policy: &dyn ProviderRuntimePolicyPort,
|
||||
) -> Result<CodexWireProfile, ErrorSource> {
|
||||
let provider = ProviderKind::new("openai").map_err(ErrorSource::new)?;
|
||||
let Some(configuration) = policy
|
||||
let configuration = policy
|
||||
.load_request_profile(&provider)
|
||||
.await
|
||||
.map_err(ErrorSource::new)?
|
||||
else {
|
||||
return Ok(self.snapshot());
|
||||
.map_err(ErrorSource::new)?;
|
||||
let profile = match configuration {
|
||||
Some(configuration) => RequestProfileSelection::parse(&configuration)
|
||||
.and_then(|selection| selection.resolve(self))
|
||||
.map_err(ErrorSource::new)?,
|
||||
None => self.snapshot(),
|
||||
};
|
||||
RequestProfileSelection::parse(&configuration)
|
||||
.and_then(|selection| selection.resolve(self))
|
||||
.map_err(ErrorSource::new)
|
||||
let settings = policy
|
||||
.load_openai_request_settings()
|
||||
.await
|
||||
.map_err(ErrorSource::new)?;
|
||||
Ok(profile.with_request_settings(&settings))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +56,16 @@ enum ParsedSelection {
|
||||
}
|
||||
|
||||
impl CodexWireProfile {
|
||||
pub(crate) fn with_request_settings(
|
||||
mut self,
|
||||
settings: &gateway_core::settings::OpenAiRequestSettings,
|
||||
) -> Self {
|
||||
self.residency.clone_from(&settings.residency);
|
||||
self.account_routing_override
|
||||
.clone_from(&settings.account_routing_override);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn effective_installation_id(
|
||||
&self,
|
||||
client_key_id: &gateway_core::policy::ClientApiKeyId,
|
||||
|
||||
@@ -38,7 +38,7 @@ pub struct CodexWireProfile {
|
||||
pub installation_seed: Option<String>,
|
||||
/// 未配置时不发送 residency 头;不随制品版本更新而改变
|
||||
pub residency: Option<String>,
|
||||
/// 部署指定的账号路由头;未配置时不发送,不随客户端身份选择改变
|
||||
/// 请求快照指定的账号路由头;未配置时不发送,不随客户端身份选择改变
|
||||
pub account_routing_override: Option<String>,
|
||||
/// 版本元组最后一次经制品核验的时间;不表示 TLS 传输已重新核验
|
||||
pub verified_at: DateTime<Utc>,
|
||||
|
||||
@@ -304,22 +304,25 @@ impl CodexProvider {
|
||||
.peer_route()
|
||||
.filter(|_| self.selector.is_peer(account))
|
||||
.cloned();
|
||||
let Some(profile) = context.request_profile() else {
|
||||
return Ok(client);
|
||||
};
|
||||
let profile = serde_json::from_value(Value::Object(profile.expose_to_provider().clone()))
|
||||
let profile = match context.request_profile() {
|
||||
None => self.client.profile_state().snapshot(),
|
||||
Some(profile) => serde_json::from_value::<crate::profile::CodexWireProfile>(
|
||||
Value::Object(profile.expose_to_provider().clone()),
|
||||
)
|
||||
.map_err(|error: serde_json::Error| {
|
||||
let diagnostic = ProviderDiagnostic::new(format!(
|
||||
"OpenAI request profile decoding failed: {:?}, line={}, column={}",
|
||||
error.classify(),
|
||||
error.line(),
|
||||
error.column(),
|
||||
))
|
||||
.with_classification("prepare", "request_profile_decode_failed");
|
||||
provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent)
|
||||
.with_diagnostic(diagnostic)
|
||||
})?;
|
||||
Ok(client.with_request_profile(profile))
|
||||
let diagnostic = ProviderDiagnostic::new(format!(
|
||||
"OpenAI request profile decoding failed: {:?}, line={}, column={}",
|
||||
error.classify(),
|
||||
error.line(),
|
||||
error.column(),
|
||||
))
|
||||
.with_classification("prepare", "request_profile_decode_failed");
|
||||
provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent)
|
||||
.with_diagnostic(diagnostic)
|
||||
})?,
|
||||
};
|
||||
Ok(client
|
||||
.with_request_profile(profile.with_request_settings(context.openai_request_settings())))
|
||||
}
|
||||
|
||||
// Provider 构造集中装配独立领域服务和透明传输依赖,拆分参数会模糊所有权
|
||||
@@ -419,7 +422,9 @@ impl Provider for CodexProvider {
|
||||
settings: &gateway_core::settings::SettingsValues,
|
||||
) -> Option<UpstreamModelId> {
|
||||
guardian::review_model(
|
||||
settings.openai_oauth_guardian_review_model(),
|
||||
settings
|
||||
.openai_request_settings()
|
||||
.oauth_guardian_review_model,
|
||||
model,
|
||||
operation,
|
||||
previous,
|
||||
@@ -1142,7 +1147,7 @@ impl CodexProvider {
|
||||
apply_codex_request_country(
|
||||
upstream_request.body_mut(),
|
||||
location,
|
||||
context.openai_request_country(),
|
||||
&context.openai_request_settings().request_country,
|
||||
);
|
||||
}
|
||||
align_structured_location_fields(upstream_request.body_mut(), location);
|
||||
|
||||
@@ -34,7 +34,7 @@ pub(super) fn is_managed_identity_header(name: &str) -> bool {
|
||||
| "originator"
|
||||
| "user-agent"
|
||||
| "version"
|
||||
// 地域和账号路由统一按部署配置生成
|
||||
// 地域和账号路由统一按运行设置生成
|
||||
| "x-openai-internal-codex-residency"
|
||||
| "x-openai-account-routing-override"
|
||||
| "x-oai-attestation"
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::io;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::{account::OpenAiRequestCountry, operation::GenerateRequest};
|
||||
use gateway_core::{operation::GenerateRequest, settings::OpenAiRequestCountry};
|
||||
use gateway_protocol::http::is_transport_managed_request_header;
|
||||
use gateway_protocol::openai::{
|
||||
OPENAI_PROTOCOL, WS_REQUEST_HEADER_RESPONSES_LITE_CLIENT_METADATA_KEY,
|
||||
|
||||
@@ -4,39 +4,6 @@ use std::{path::Path, time::Duration};
|
||||
|
||||
use provider_openai::config::{MAX_STREAM_MAX_RETRIES, OpenAiConfig};
|
||||
|
||||
#[test]
|
||||
fn openai_config_preserves_optional_routing_header_values() {
|
||||
for (document, expected) in [
|
||||
(r#"{}"#, (None, None)),
|
||||
(
|
||||
r#"{"residency":null,"account_routing_override":null}"#,
|
||||
(None, None),
|
||||
),
|
||||
(
|
||||
r#"{"residency":"us","account_routing_override":"us"}"#,
|
||||
(Some("us"), Some("us")),
|
||||
),
|
||||
(
|
||||
r#"{"residency":"custom-region","account_routing_override":"custom-route"}"#,
|
||||
(Some("custom-region"), Some("custom-route")),
|
||||
),
|
||||
(
|
||||
r#"{"residency":"","account_routing_override":"NO_CONSTRAINT"}"#,
|
||||
(Some(""), Some("NO_CONSTRAINT")),
|
||||
),
|
||||
] {
|
||||
let config: OpenAiConfig = serde_json::from_str(document).unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
config.residency.as_deref(),
|
||||
config.account_routing_override.as_deref()
|
||||
),
|
||||
expected,
|
||||
"{document}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_config_derives_identity_secret_from_runtime_data_dir() {
|
||||
let mut config = valid_config();
|
||||
|
||||
@@ -22,8 +22,12 @@ fn reviewer_operation(model: &str, source: &str, subagent: &str, input: Value) -
|
||||
}
|
||||
|
||||
fn settings(enabled: bool) -> SettingsValues {
|
||||
SettingsValues::new(2, "smart", Default::default(), None, None)
|
||||
.with_openai_oauth_guardian_review_model(enabled)
|
||||
SettingsValues::new(2, "smart", Default::default(), None, None).with_openai_request_settings(
|
||||
gateway_core::settings::OpenAiRequestSettings {
|
||||
oauth_guardian_review_model: enabled,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn selected_session(model: &str) -> ProviderSessionState {
|
||||
|
||||
@@ -41,8 +41,8 @@ use chrono::Utc;
|
||||
use futures::{SinkExt, StreamExt, future::BoxFuture};
|
||||
use gateway_core::account::{
|
||||
AccountFeedbackStats, AccountWeight, CredentialState, FastMode, OpaqueProviderData,
|
||||
OpenAiRequestCountry, ProviderAccountId, ProviderAccountStore as _, QuotaAccessChange,
|
||||
QuotaAccessState, QuotaEvidence, QuotaObservation, QuotaState,
|
||||
ProviderAccountId, ProviderAccountStore as _, QuotaAccessChange, QuotaAccessState,
|
||||
QuotaEvidence, QuotaObservation, QuotaState,
|
||||
};
|
||||
use gateway_core::engine::continuation::{
|
||||
ContinuationBinding, NativeContinuationPin, PreviousResponseId,
|
||||
@@ -75,6 +75,7 @@ use gateway_core::routing::{
|
||||
ProviderKind, ProviderModel, PublicModelId, RoutingContext, RuntimeAccount,
|
||||
RuntimeAccountDirectory, RuntimeSnapshot, UpstreamModelId,
|
||||
};
|
||||
use gateway_core::settings::OpenAiRequestCountry;
|
||||
use gateway_core::settings::SettingsValues;
|
||||
use gateway_core::upstream::UpstreamSendState;
|
||||
use provider_openai::config::DEFAULT_STREAM_MAX_RETRIES;
|
||||
@@ -1797,7 +1798,10 @@ fn context_with_request_settings(
|
||||
ClientApiKeyId::new("key_openai_contract").expect("client key id"),
|
||||
)
|
||||
.with_request_location(location)
|
||||
.with_openai_request_country(country)
|
||||
.with_openai_request_settings(gateway_core::settings::OpenAiRequestSettings {
|
||||
request_country: country,
|
||||
..Default::default()
|
||||
})
|
||||
.with_request_profile(profile),
|
||||
NonZeroU32::new(1).expect("attempt"),
|
||||
SystemTime::now() + Duration::from_secs(30),
|
||||
@@ -6303,6 +6307,103 @@ async fn opaque_provider_options_do_not_change_openai_account_selection() {
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_routing_headers_override_request_identity_and_clear_when_unset() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_provider_contract").await;
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/codex/responses"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_raw(CAPTURE_COMPLETED_SSE, "text/event-stream"),
|
||||
)
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let provider = provider_with_base_url(&store, server.uri());
|
||||
let selection = OpaqueProviderData::new(
|
||||
json!({
|
||||
"client":"cli", "platform":"linux", "versionMode":"fixed", "codexVersion":"1.0.0"
|
||||
})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
);
|
||||
let profile = provider.resolve_request_profile(&selection).unwrap();
|
||||
let mut stale_profile = profile.expose_to_provider().clone();
|
||||
stale_profile.insert("residency".into(), json!("stale-region"));
|
||||
for (index, profile) in [None, Some(OpaqueProviderData::new(stale_profile))]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let settings = gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: (index == 0).then(|| "us".to_owned()),
|
||||
account_routing_override: (index == 0).then(|| "us_cr".to_owned()),
|
||||
..Default::default()
|
||||
};
|
||||
let context = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new(format!("req_routing_{index}")).unwrap(),
|
||||
ClientApiKeyId::new("key_routing").unwrap(),
|
||||
)
|
||||
.with_openai_request_settings(settings)
|
||||
.with_request_profile(profile),
|
||||
NonZeroU32::new(1).unwrap(),
|
||||
SystemTime::now() + Duration::from_secs(30),
|
||||
account_policy(),
|
||||
AccountAttemptContext::new(
|
||||
BTreeSet::new(),
|
||||
Some(ProviderAccountId::new("acct_provider_contract").unwrap()),
|
||||
None,
|
||||
)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let payload = ProtocolPayload::json_object(
|
||||
"openai",
|
||||
json!({"model":"gpt-5.4","input":"hello"})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_context(Map::from_iter([("use_websocket".into(), json!(false))]));
|
||||
let mut stream = Arc::clone(&provider)
|
||||
.execute(
|
||||
planned_request(
|
||||
"openai",
|
||||
Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
|
||||
),
|
||||
context,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
while let Some(event) = stream.next().await {
|
||||
event.unwrap();
|
||||
}
|
||||
}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(
|
||||
requests[0].headers["x-openai-internal-codex-residency"],
|
||||
"us"
|
||||
);
|
||||
assert_eq!(
|
||||
requests[0].headers["x-openai-account-routing-override"],
|
||||
"us_cr"
|
||||
);
|
||||
assert!(
|
||||
!requests[1]
|
||||
.headers
|
||||
.contains_key("x-openai-internal-codex-residency")
|
||||
);
|
||||
assert!(
|
||||
!requests[1]
|
||||
.headers
|
||||
.contains_key("x-openai-account-routing-override")
|
||||
);
|
||||
}
|
||||
|
||||
const KEY_INSTALLATION_SEED: &str = "3b11bc82-c666-417d-b9ff-2a34fd040385";
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -754,7 +754,14 @@ async fn verify_live_call_identity() {
|
||||
gateway_core::engine::ModelRequestId::new("req_live_frozen_profile").unwrap(),
|
||||
ClientApiKeyId::new("key_openai_contract").unwrap(),
|
||||
)
|
||||
.with_request_profile(Some(opaque_profile(&profile))),
|
||||
.with_request_profile(Some(opaque_profile(&profile)))
|
||||
.with_openai_request_settings(
|
||||
gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: Some("us".to_owned()),
|
||||
account_routing_override: None,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
std::num::NonZeroU32::new(1).unwrap(),
|
||||
std::time::SystemTime::now() + std::time::Duration::from_secs(30),
|
||||
crate::support::account_policy(),
|
||||
|
||||
@@ -142,7 +142,7 @@ fn deployment_routing_survives_artifact_updates_and_profile_selection() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_transports_apply_deployment_routing_with_or_without_client_headers() {
|
||||
async fn model_transports_apply_routing_settings_with_or_without_client_headers() {
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use gateway_core::operation::{GenerateRequest, ProtocolPayload};
|
||||
|
||||
@@ -153,15 +153,15 @@ async fn model_transports_apply_deployment_routing_with_or_without_client_header
|
||||
for (document, expected) in [
|
||||
(r#"{}"#, [None, None]),
|
||||
(
|
||||
r#"{"residency":null,"account_routing_override":null}"#,
|
||||
r#"{"residency":null,"accountRoutingOverride":null}"#,
|
||||
[None, None],
|
||||
),
|
||||
(
|
||||
r#"{"residency":"us","account_routing_override":"us"}"#,
|
||||
r#"{"residency":"us","accountRoutingOverride":"us"}"#,
|
||||
[Some("us"), Some("us")],
|
||||
),
|
||||
(
|
||||
r#"{"account_routing_override":"us_cr"}"#,
|
||||
r#"{"accountRoutingOverride":"us_cr"}"#,
|
||||
[None, Some("us_cr")],
|
||||
),
|
||||
(
|
||||
@@ -169,11 +169,11 @@ async fn model_transports_apply_deployment_routing_with_or_without_client_header
|
||||
[Some("custom-region"), None],
|
||||
),
|
||||
(
|
||||
r#"{"residency":"","account_routing_override":"custom-route"}"#,
|
||||
r#"{"residency":"","accountRoutingOverride":"custom-route"}"#,
|
||||
[Some(""), Some("custom-route")],
|
||||
),
|
||||
(
|
||||
r#"{"account_routing_override":"NO_CONSTRAINT"}"#,
|
||||
r#"{"accountRoutingOverride":"NO_CONSTRAINT"}"#,
|
||||
[None, Some("NO_CONSTRAINT")],
|
||||
),
|
||||
] {
|
||||
@@ -224,8 +224,15 @@ async fn model_transports_apply_deployment_routing_with_or_without_client_header
|
||||
}),
|
||||
)
|
||||
};
|
||||
let config: provider_openai::config::OpenAiConfig =
|
||||
serde_json::from_str(document).unwrap();
|
||||
let mut settings =
|
||||
serde_json::to_value(gateway_core::settings::OpenAiRequestSettings::default())
|
||||
.unwrap();
|
||||
settings
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(serde_json::from_str::<serde_json::Map<String, Value>>(document).unwrap());
|
||||
let config: gateway_core::settings::OpenAiRequestSettings =
|
||||
serde_json::from_value(settings).unwrap();
|
||||
let profile = CodexWireProfileState::new(CodexWireProfile {
|
||||
residency: config.residency,
|
||||
account_routing_override: config.account_routing_override,
|
||||
|
||||
@@ -44,3 +44,5 @@ aeff99fee7cef5a553ae49ffe27a48f49e31ccfb3fbc61a2482c9b109478202d 0041_account_m
|
||||
23eeb6ef99de2315cf4a198638e9c73b364fb1cb40b7e571a3f15d3e9d15f67c 0044_account_quota_settings.sql
|
||||
5cfe0227e2a4b26c268bf5b6ef7f93904e02c57d9d2d05cfe2e32db0a7d4e7a2 0045_account_group_policies_and_openai_request_settings.sql
|
||||
e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_and_runtime_settings.sql
|
||||
98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql
|
||||
b75c2b2588389478fff3443cf7c5775b8552ad38dae7ae95e5b0ffe8de902646 0048_openai_request_settings.sql
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
-- 请求与运维事件保留各自选中账号时的套餐描述
|
||||
alter table ops_events add column provider_account_plan_type_display_snapshot text;
|
||||
|
||||
create or replace function model_request_observation_valid(document jsonb) returns boolean
|
||||
language plpgsql immutable parallel safe as $$
|
||||
declare
|
||||
spec record;
|
||||
item jsonb;
|
||||
number numeric;
|
||||
begin
|
||||
if document is null or jsonb_typeof(document) <> 'object'
|
||||
or octet_length(document::text) > 1048576 then
|
||||
return false;
|
||||
end if;
|
||||
for spec in select * from (values
|
||||
('{}'::text[], array['account','continuation','error','recovery','request','response','routing','scheduling','timings','transport']::text[]),
|
||||
('{request}'::text[], array['clientApiKeyNameSnapshot','clientIp','compact','configRevision','endpoint','protocol','reasoningEffort','reasoningPreset','subagentKind','userAgent']::text[]),
|
||||
('{account}'::text[], array['authenticationKind','email','name','planTypeSnapshot','planTypeDisplaySnapshot','notesSnapshot']::text[]),
|
||||
('{routing}'::text[], array['groupNamesSnapshot','groupRefs','scope']::text[]),
|
||||
('{error}'::text[], array['message','providerErrorCode','retryAfterMs']::text[]),
|
||||
('{timings}'::text[], array['local','upstream']::text[]),
|
||||
('{timings,local}'::text[], array['connectMs','firstEventMs','firstReasoningMs','firstTextMs','firstTokenMs','headersMs','latencyMs','transportDecisionWaitMs']::text[]),
|
||||
('{timings,upstream}'::text[], array['processingMs','responseMs','apiOverheadMs','engineMs','engineIapiTtftMs','engineServiceTtftMs','engineIapiTbtMs','engineServiceTbtMs']::text[]),
|
||||
('{scheduling}'::text[], array['accountSelectionWaitMs','admissionDecisionMs','capacityTotalSlots','capacityUsedSlots']::text[]),
|
||||
('{transport}'::text[], array['connection','httpVersion','websocketPool']::text[]),
|
||||
('{transport,connection}'::text[], array['ageMs','exitReason','id','idleMs']::text[]),
|
||||
('{response}'::text[], array['responseModel']::text[]),
|
||||
('{continuation}'::text[], array['previousResponseIdHash','unavailableReason']::text[]),
|
||||
('{recovery}'::text[], array['retryDelayMs','totalLatencyMs']::text[])) as groups(path, allowed_keys) loop
|
||||
item := document #> spec.path;
|
||||
if item is not null and (jsonb_typeof(item) <> 'object' or item - spec.allowed_keys <> '{}'::jsonb) then
|
||||
return false;
|
||||
end if;
|
||||
end loop;
|
||||
for spec in select * from (values
|
||||
('{request,configRevision}'::text[], 'number'),
|
||||
('{request,protocol}'::text[], 'string'),
|
||||
('{request,endpoint}'::text[], 'string'),
|
||||
('{request,clientApiKeyNameSnapshot}'::text[], 'string'),
|
||||
('{account,planTypeSnapshot}'::text[], 'string'),
|
||||
('{account,planTypeDisplaySnapshot}'::text[], 'string'),
|
||||
('{account,notesSnapshot}'::text[], 'string'),
|
||||
('{account,name}'::text[], 'string'),
|
||||
('{account,email}'::text[], 'string'),
|
||||
('{account,authenticationKind}'::text[], 'string'),
|
||||
('{routing,scope}'::text[], 'string'),
|
||||
('{routing,groupRefs}'::text[], 'array'),
|
||||
('{routing,groupNamesSnapshot}'::text[], 'array'),
|
||||
('{error,providerErrorCode}'::text[], 'string'),
|
||||
('{error,message}'::text[], 'string'),
|
||||
('{error,retryAfterMs}'::text[], 'number'),
|
||||
('{request,clientIp}'::text[], 'string'),
|
||||
('{request,userAgent}'::text[], 'string'),
|
||||
('{request,reasoningEffort}'::text[], 'string'),
|
||||
('{request,reasoningPreset}'::text[], 'string'),
|
||||
('{request,subagentKind}'::text[], 'string'),
|
||||
('{request,compact}'::text[], 'boolean'),
|
||||
('{timings,local,transportDecisionWaitMs}'::text[], 'number'),
|
||||
('{timings,local,connectMs}'::text[], 'number'),
|
||||
('{timings,local,headersMs}'::text[], 'number'),
|
||||
('{timings,local,firstEventMs}'::text[], 'number'),
|
||||
('{timings,local,firstReasoningMs}'::text[], 'number'),
|
||||
('{timings,local,firstTextMs}'::text[], 'number'),
|
||||
('{timings,local,firstTokenMs}'::text[], 'number'),
|
||||
('{timings,local,latencyMs}'::text[], 'number'),
|
||||
('{timings,upstream,processingMs}'::text[], 'number'),
|
||||
('{timings,upstream,apiOverheadMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineIapiTtftMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineServiceTtftMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineIapiTbtMs}'::text[], 'milliseconds'),
|
||||
('{timings,upstream,engineServiceTbtMs}'::text[], 'milliseconds'),
|
||||
('{scheduling,admissionDecisionMs}'::text[], 'number'),
|
||||
('{scheduling,accountSelectionWaitMs}'::text[], 'number'),
|
||||
('{scheduling,capacityUsedSlots}'::text[], 'number'),
|
||||
('{scheduling,capacityTotalSlots}'::text[], 'number'),
|
||||
('{transport,httpVersion}'::text[], 'string'),
|
||||
('{transport,websocketPool}'::text[], 'string'),
|
||||
('{transport,connection,id}'::text[], 'string'),
|
||||
('{transport,connection,exitReason}'::text[], 'string'),
|
||||
('{transport,connection,ageMs}'::text[], 'number'),
|
||||
('{transport,connection,idleMs}'::text[], 'number'),
|
||||
('{response,responseModel}'::text[], 'string'),
|
||||
('{continuation,previousResponseIdHash}'::text[], 'string'),
|
||||
('{continuation,unavailableReason}'::text[], 'string'),
|
||||
('{recovery,retryDelayMs}'::text[], 'number'),
|
||||
('{recovery,totalLatencyMs}'::text[], 'number'),
|
||||
('{timings,upstream,responseMs}'::text[], 'number')) as fields(path, kind) loop
|
||||
item := document #> spec.path;
|
||||
if item is null or item = 'null'::jsonb then continue; end if;
|
||||
if spec.kind = 'milliseconds' then
|
||||
if jsonb_typeof(item) <> 'number' then return false; end if;
|
||||
number := (item #>> '{}')::numeric;
|
||||
if number < 0 or number > 9223372036854775807 then return false; end if;
|
||||
continue;
|
||||
end if;
|
||||
if jsonb_typeof(item) <> spec.kind then return false; end if;
|
||||
if spec.kind = 'number' then
|
||||
number := (item #>> '{}')::numeric;
|
||||
if item #>> '{}' !~ '^[0-9]+$' or number > 9223372036854775807 then return false; end if;
|
||||
elsif spec.kind = 'array' then
|
||||
if exists (select 1 from jsonb_array_elements(item) member where jsonb_typeof(member) <> 'string') then return false; end if;
|
||||
end if;
|
||||
end loop;
|
||||
if (document #> '{request,configRevision}' is not null
|
||||
and document #> '{request,configRevision}' <> 'null'::jsonb
|
||||
and document #> '{request,compact}' in ('true'::jsonb, 'false'::jsonb)
|
||||
and coalesce(length(document #>> '{request,protocol}'), 0) > 0
|
||||
and coalesce(length(document #>> '{request,endpoint}'), 0) > 0
|
||||
and jsonb_typeof(document #> '{routing,scope}') = 'string'
|
||||
and jsonb_typeof(document #> '{routing,groupRefs}') = 'array'
|
||||
and jsonb_typeof(document #> '{routing,groupNamesSnapshot}') = 'array') is not true then
|
||||
return false;
|
||||
end if;
|
||||
if document #>> '{request,clientIp}' is not null then
|
||||
perform (document #>> '{request,clientIp}')::inet;
|
||||
end if;
|
||||
return true;
|
||||
exception when invalid_text_representation or numeric_value_out_of_range then
|
||||
return false;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace view model_request_observations as
|
||||
select mr.*,
|
||||
coalesce(lease.lease_expires_at, mr.recovery_lease_expires_at) as effective_recovery_lease_expires_at,
|
||||
(mr.request_observation_json #>> '{request,configRevision}')::bigint as config_revision,
|
||||
(mr.request_observation_json #>> '{request,protocol}') as protocol,
|
||||
(mr.request_observation_json #>> '{request,endpoint}') as endpoint,
|
||||
(mr.request_observation_json #>> '{account,name}') as provider_account_name_snapshot,
|
||||
(mr.request_observation_json #>> '{account,email}') as provider_account_email_snapshot,
|
||||
(mr.request_observation_json #>> '{account,authenticationKind}') as provider_account_authentication_kind_snapshot,
|
||||
(mr.request_observation_json #>> '{routing,scope}') as routing_scope,
|
||||
array(select jsonb_array_elements_text(mr.request_observation_json #> '{routing,groupRefs}')) as routing_group_refs,
|
||||
(mr.request_observation_json #> '{routing,groupNamesSnapshot}') as routing_group_names_snapshot,
|
||||
(mr.request_observation_json #>> '{error,providerErrorCode}') as provider_error_code,
|
||||
(mr.request_observation_json #>> '{error,message}') as error_message,
|
||||
(mr.request_observation_json #>> '{error,retryAfterMs}')::bigint as retry_after_ms,
|
||||
(mr.request_observation_json #>> '{request,clientIp}')::inet as client_ip,
|
||||
(mr.request_observation_json #>> '{request,userAgent}') as user_agent,
|
||||
(mr.request_observation_json #>> '{request,reasoningEffort}') as reasoning_effort,
|
||||
(mr.request_observation_json #>> '{request,reasoningPreset}') as reasoning_preset,
|
||||
(mr.request_observation_json #>> '{request,subagentKind}') as subagent_kind,
|
||||
(mr.request_observation_json #>> '{request,compact}')::boolean as compact,
|
||||
measured.transport_decision_wait_ms as transport_decision_wait_ms,
|
||||
measured.connect_ms as connect_ms,
|
||||
measured.headers_ms as headers_ms,
|
||||
measured.first_event_ms as first_event_ms,
|
||||
measured.first_reasoning_ms as first_reasoning_ms,
|
||||
measured.first_text_ms as first_text_ms,
|
||||
measured.first_token_ms as first_token_ms,
|
||||
measured.latency_ms as latency_ms,
|
||||
measured.provider_processing_ms as provider_processing_ms,
|
||||
measured.admission_decision_ms as admission_decision_ms,
|
||||
measured.account_selection_wait_ms as account_selection_wait_ms,
|
||||
measured.capacity_used_slots as capacity_used_slots,
|
||||
measured.capacity_total_slots as capacity_total_slots,
|
||||
(mr.request_observation_json #>> '{transport,httpVersion}') as http_version,
|
||||
(mr.request_observation_json #>> '{transport,websocketPool}') as websocket_pool,
|
||||
(mr.request_observation_json #>> '{transport,connection,id}') as upstream_connection_id,
|
||||
(mr.request_observation_json #>> '{transport,connection,exitReason}') as upstream_connection_exit_reason,
|
||||
(mr.request_observation_json #>> '{transport,connection,ageMs}')::bigint as upstream_connection_age_ms,
|
||||
(mr.request_observation_json #>> '{transport,connection,idleMs}')::bigint as upstream_connection_idle_ms,
|
||||
(mr.request_observation_json #>> '{response,responseModel}') as upstream_response_model,
|
||||
(mr.request_observation_json #>> '{continuation,previousResponseIdHash}') as continuation_previous_response_id_hash,
|
||||
(mr.request_observation_json #>> '{continuation,unavailableReason}') as continuation_unavailable_reason,
|
||||
(mr.request_observation_json #>> '{recovery,retryDelayMs}')::bigint as recovery_retry_delay_ms,
|
||||
(mr.request_observation_json #>> '{recovery,totalLatencyMs}')::bigint as recovery_total_latency_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,apiOverheadMs}')::double precision as upstream_api_overhead_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineMs}')::double precision as upstream_engine_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineIapiTtftMs}')::double precision as upstream_engine_iapi_ttft_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineServiceTtftMs}')::double precision as upstream_engine_service_ttft_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineIapiTbtMs}')::double precision as upstream_engine_iapi_tbt_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,engineServiceTbtMs}')::double precision as upstream_engine_service_tbt_ms,
|
||||
measured.upstream_response_ms as upstream_response_ms,
|
||||
mr.request_observation_json #>> '{request,clientApiKeyNameSnapshot}' as client_api_key_name_snapshot,
|
||||
mr.request_observation_json #>> '{account,planTypeSnapshot}' as provider_account_plan_type_snapshot,
|
||||
mr.request_observation_json #>> '{account,notesSnapshot}' as provider_account_notes_snapshot,
|
||||
mr.request_observation_json #>> '{account,planTypeDisplaySnapshot}' as provider_account_plan_type_display_snapshot
|
||||
from model_requests mr
|
||||
left join model_request_leases lease on lease.request_id = mr.id
|
||||
cross join lateral (
|
||||
select (mr.request_observation_json #>> '{timings,local,transportDecisionWaitMs}')::bigint as transport_decision_wait_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,connectMs}')::bigint as connect_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,headersMs}')::bigint as headers_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,firstEventMs}')::bigint as first_event_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,firstReasoningMs}')::bigint as first_reasoning_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,firstTextMs}')::bigint as first_text_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,firstTokenMs}')::bigint as first_token_ms,
|
||||
(mr.request_observation_json #>> '{timings,local,latencyMs}')::bigint as latency_ms,
|
||||
(mr.request_observation_json #>> '{timings,upstream,processingMs}')::bigint as provider_processing_ms,
|
||||
(mr.request_observation_json #>> '{scheduling,admissionDecisionMs}')::bigint as admission_decision_ms,
|
||||
(mr.request_observation_json #>> '{scheduling,accountSelectionWaitMs}')::bigint as account_selection_wait_ms,
|
||||
(mr.request_observation_json #>> '{scheduling,capacityUsedSlots}')::bigint as capacity_used_slots,
|
||||
(mr.request_observation_json #>> '{scheduling,capacityTotalSlots}')::bigint as capacity_total_slots,
|
||||
(mr.request_observation_json #>> '{timings,upstream,responseMs}')::bigint as upstream_response_ms
|
||||
) measured;
|
||||
@@ -0,0 +1,32 @@
|
||||
-- 按请求职责归组 OpenAI 设置,保留既有国家策略和 OAuth 审核模型开关
|
||||
alter table runtime_settings
|
||||
add column openai_request_settings_json jsonb not null default '{"requestCountry":{"mode":"follow_location"},"oauthGuardianReviewModel":true,"residency":null,"accountRoutingOverride":null}'::jsonb;
|
||||
|
||||
update runtime_settings
|
||||
set openai_request_settings_json = jsonb_build_object(
|
||||
'requestCountry', openai_request_country_json,
|
||||
'oauthGuardianReviewModel', openai_oauth_guardian_review_model,
|
||||
'residency', null,
|
||||
'accountRoutingOverride', null
|
||||
);
|
||||
|
||||
alter table runtime_settings
|
||||
drop column openai_request_country_json,
|
||||
drop column openai_oauth_guardian_review_model,
|
||||
add constraint runtime_settings_openai_request_settings_ck check (
|
||||
jsonb_typeof(openai_request_settings_json) = 'object'
|
||||
and openai_request_settings_json ?& array['requestCountry', 'oauthGuardianReviewModel', 'residency', 'accountRoutingOverride']
|
||||
and openai_request_settings_json - 'requestCountry' - 'oauthGuardianReviewModel' - 'residency' - 'accountRoutingOverride' = '{}'::jsonb
|
||||
and jsonb_typeof(openai_request_settings_json->'oauthGuardianReviewModel') = 'boolean'
|
||||
and jsonb_typeof(openai_request_settings_json->'residency') in ('null', 'string')
|
||||
and jsonb_typeof(openai_request_settings_json->'accountRoutingOverride') in ('null', 'string')
|
||||
and (
|
||||
openai_request_settings_json->'requestCountry' in ('{"mode":"default"}', '{"mode":"passthrough"}', '{"mode":"follow_location"}')
|
||||
or (
|
||||
(openai_request_settings_json->'requestCountry') ?& array['mode', 'country']
|
||||
and openai_request_settings_json->'requestCountry' = jsonb_build_object('mode', 'custom', 'country', openai_request_settings_json->'requestCountry'->>'country')
|
||||
and (openai_request_settings_json->'requestCountry'->>'country') collate "C" ~ '^[A-Z]{2}$'
|
||||
and jsonb_typeof(openai_request_settings_json->'requestCountry'->'country') = 'string'
|
||||
)
|
||||
)
|
||||
);
|
||||
+15
-16
@@ -414,21 +414,19 @@ PostgreSQL/Redis 启动密码。日常校验使用 `config --quiet`
|
||||
|
||||
| 设置 | 入口与边界 |
|
||||
| --- | --- |
|
||||
| 上游客户端身份 | “系统设置 → 上游配置 → 客户端身份”;Key 可按 Provider 覆盖,OpenAI Key 可独立配置[安装身份种子](../docs/api.md#key-客户端身份) |
|
||||
| 并发与排队 | “系统设置 → 运行设置”;Key 与账号分别设置排队容量和超时,可选择账号排队失败后换号,见[排队规则](../docs/api.md#并发与排队) |
|
||||
| 账号错误保护 | “系统设置 → 运行设置 → 错误保护”;默认关闭,按[自定义规则](../docs/api.md#账号错误保护)暂停账号调度 |
|
||||
| 全局请求位置 | “系统设置 → 上游配置 → 请求位置覆盖”,默认关闭 |
|
||||
| Codex OAuth 请求国家 | “系统设置 → 上游配置 → 请求国家”,默认跟随位置,也可选择“空值”“透传”或“自定义” |
|
||||
| OpenAI OAuth 同步审核模型 | “系统设置 → 上游配置 → 模型映射”中的“专用审核模型”默认开启,关闭后沿用客户端模型。[适用条件](../docs/api.md#正文兼容) |
|
||||
| 上游客户端身份 | 在“系统设置 → 平台设置”选择平台后编辑“客户端身份”。Key 可按 Provider 覆盖,OpenAI Key 可独立配置[安装身份种子](../docs/api.md#key-客户端身份) |
|
||||
| 并发与排队 | “系统设置 → 通用设置 → 并发与排队”分别配置 Key 与账号的排队容量和超时。账号排队失败后的处理在同页“重试与换号”中设置,见[排队规则](../docs/api.md#并发与排队) |
|
||||
| 账号错误保护 | “系统设置 → 通用设置 → 错误保护”默认关闭,按[自定义规则](../docs/api.md#账号错误保护)暂停账号调度 |
|
||||
| 全局请求位置 | “系统设置 → 平台设置 → OpenAI → 请求位置覆盖”,默认关闭 |
|
||||
| Codex OAuth 请求国家 | “系统设置 → 平台设置 → OpenAI → 请求国家”,默认跟随位置,也可选择“空值”“透传”或“自定义” |
|
||||
| OpenAI OAuth 同步审核模型 | “系统设置 → 平台设置 → OpenAI → 自动审批”中的“专用审核模型”默认开启,关闭后沿用客户端模型。[适用条件](../docs/api.md#正文兼容) |
|
||||
| 代理位置 | “代理管理”;优先于全局位置,全局关闭时仍可独立生效 |
|
||||
|
||||
位置覆盖只影响 OpenAI 请求中受支持的位置与时区信息,不改变上下文日期、真实出口 IP、epoch 时间戳或系统时区。
|
||||
`openai.residency` 和 `openai.account_routing_override` 是独立于客户端身份的启动配置,
|
||||
分别指定 `x-openai-internal-codex-residency` 和 `x-openai-account-routing-override` 请求头。
|
||||
两项均为可选字符串,配置值原样发送并覆盖客户端同名头,支持自定义地域或路由值。
|
||||
省略或设为 `null` 时删除对应请求头。
|
||||
修改后重启应用生效。身份与位置字段见 [运行设置 API](../docs/api.md#8-运行设置)
|
||||
后台账号操作使用 Provider 自己的官方画像;发布资料刷新不改写用户选择或 `config.yaml`
|
||||
数据驻留与账号路由在“系统设置 → 平台设置 → OpenAI → 请求设置”中填写,支持自定义值,留空删除对应请求头。
|
||||
保存后对新请求生效,无需重启。字段与适用范围见 [运行设置 API](../docs/api.md#数据驻留与路由)
|
||||
已有部署若在 `config.yaml` 中设置了 `openai.residency` 或 `openai.account_routing_override`,升级后须在平台设置中重新保存,并删除配置文件中的旧字段
|
||||
OAuth 续期和额度刷新等后台操作使用对应平台的全局客户端身份。发布资料刷新不改写用户选择或 `config.yaml`,见 [Provider 客户端身份](../docs/api.md#provider-客户端身份)
|
||||
|
||||
### CPR 互联
|
||||
|
||||
@@ -517,7 +515,7 @@ Compose 默认只绑定 `127.0.0.1`。从其他设备访问时,在应用前配
|
||||
HTTP 传输不加密,公网部署仍建议使用 HTTPS。
|
||||
会话 Cookie 合同见 [管理接口鉴权](../docs/api.md#管理接口)
|
||||
|
||||
反向代理应保留客户端发送的 `Authorization`、`x-api-key`、`anthropic-version` 和 `anthropic-beta` 请求头,
|
||||
反向代理应保留客户端发送的 `Authorization`、`x-api-key`、`x-goog-api-key`、`anthropic-version` 和 `anthropic-beta` 请求头,
|
||||
支持 `/v1/responses` 的 WebSocket Upgrade,并关闭 SSE 响应缓冲。读取超时应覆盖长时间生成任务。
|
||||
客户端连接网关的部署地址,不要使用前端开发服务的 `5173/dev/v1`。
|
||||
当前应用只支持单副本,不能通过复制容器扩容
|
||||
@@ -607,7 +605,7 @@ example.com {
|
||||
|
||||
Caddy 与应用同在容器网络时,将回源地址改为 `codex-proxy-rs:8080`。
|
||||
合并到已有站点时,将子路径处理放在兜底路由之前,保留浏览器的 `Origin` 和鉴权头。
|
||||
管理入口为 `/proxy/`,模型客户端使用 `/proxy/v1`。
|
||||
管理入口为 `/proxy/`。在[客户端配置](#客户端配置)表中,将 Base URL 的 `http://127.0.0.1:8080` 替换为 `https://example.com/proxy`
|
||||
|
||||
系统在线更新会替换前端资源。子路径部署在 `config.yaml` 的 `host` 下配置
|
||||
`system_update.update_repository: null`,通过重新构建镜像升级。
|
||||
@@ -621,8 +619,9 @@ Caddy 与应用同在容器网络时,将回源地址改为 `codex-proxy-rs:808
|
||||
| --- | --- |
|
||||
| OpenAI Responses `/responses`、Chat Completions `/chat/completions` | `http://127.0.0.1:8080/v1` |
|
||||
| Anthropic Messages `/v1/messages` | `http://127.0.0.1:8080` |
|
||||
| Gemini GenAI `/v1beta/models/{model}:generateContent` | `http://127.0.0.1:8080` |
|
||||
|
||||
直接发送 HTTP 请求可参考 [Messages 示例](../docs/api.md#messages-请求)
|
||||
直接发送 HTTP 请求时,参见 [Messages 示例](../docs/api.md#messages-请求)和 [GenAI 接口与鉴权](../docs/api.md#antigravity-客户端原生生成)
|
||||
|
||||
使用 Codex 时,打开「使用密钥」,按操作系统复制 `config.toml`。
|
||||
已有配置先备份,合并后完全退出并重启 Codex。代理密钥由 Provider 配置提供,
|
||||
@@ -902,7 +901,7 @@ OAuth 恢复开关为 `host.logging.oauth_recovery`,默认关闭,与普通
|
||||
|
||||
## 密码语义
|
||||
|
||||
- **管理员**:`admin.default_password` 只在创建首个管理员时使用。已有管理员在「系统设置 → 安全与访问 → 管理员密码」验证当前密码后修改,所有管理员会话须重新登录
|
||||
- **管理员**:`admin.default_password` 只在创建首个管理员时使用。已有管理员在「系统设置 → 通用设置 → 管理员密码」验证当前密码后修改,所有管理员会话须重新登录
|
||||
- **PostgreSQL**:镜像只在空数据目录初始化时设置 `database.password`。轮换须先修改数据库用户密码,再同步更新 `config.yaml`,否则应用无法连接
|
||||
- **Redis**:容器创建时读取 `redis.password`。在维护窗口更新配置并重新创建 Redis 和应用容器,保留数据目录
|
||||
|
||||
|
||||
@@ -79,12 +79,7 @@ api:
|
||||
request_timeout_seconds: null
|
||||
request_id_header: 'x-request-id'
|
||||
|
||||
openai:
|
||||
# 以下两项原样发送配置值;省略或设为 null 时删除对应请求头
|
||||
# 数据驻留参考值:us
|
||||
residency: us
|
||||
# 账号路由参考值:us、us_cr
|
||||
account_routing_override: null
|
||||
# openai:
|
||||
# Responses 上游 WS 池配置,可单独覆盖下列默认值
|
||||
# ws_pool:
|
||||
# enabled: true
|
||||
|
||||
+37
-17
@@ -235,7 +235,7 @@ WebSocket message 和 frame 不设置网关私有长度上限;请求字段与
|
||||
| `GET` | `/v1/usage` | 查询当前 Client Key 的日与周额度,仅使用网关已结算的 USD 账本 |
|
||||
| `GET` | `/v1/cpr/link` | 返回当前 Key 获准公开的预算及直连账号池观测 |
|
||||
|
||||
生成接口接受 Responses、Messages、GenAI 和 Chat。API Key 账号通过 `protocol` 选择 Responses 或 Messages 上游,仍使用 `openai` Provider;OAuth 账号使用 Responses 上游。xAI 使用原生 Responses,Antigravity 使用 GenAI
|
||||
OpenAI Provider 的 OAuth 账号使用 Responses 上游,API Key 账号通过 `protocol` 选择 Responses 或 Messages。xAI 使用 Responses,Antigravity 使用 GenAI
|
||||
|
||||
| 入站 | Responses 上游 | Messages 上游 | GenAI 上游 |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -266,7 +266,7 @@ WebSocket message 和 frame 不设置网关私有长度上限;请求字段与
|
||||
|
||||
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选 OAuth 账号与冻结画像生成。`X-Goog-Api-Client` 与 Gateway 的 `X-Goog-Ext-525006001-Bin` 不进入 Cloud Code 请求。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters)
|
||||
|
||||
Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文只局部替换配置的 `systemInstruction`、移除其蛇形别名,以及 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建
|
||||
Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文在 `systemInstruction.parts` 前添加配置的提示词,保留客户端原有 parts 及系统指令的其他字段,并移除 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。系统指令也接受 `system_instruction`,两者同时提供时以 `systemInstruction` 为准,出站统一使用驼峰名称。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建
|
||||
|
||||
同账号及归属未知时保留追踪头;会话绑定或本次执行的已有账号归属明确发生切换时,CPR 清理入站或中间件带入的 `traceparent`、`tracestate`、`sentry-trace`、`baggage`。该清理作用于本次出站请求,不修改工具结果、思考签名或业务正文
|
||||
|
||||
@@ -278,7 +278,7 @@ AGY 上游计数与生成响应的 `usageMetadata.promptTokenCount` 口径不完
|
||||
|
||||
Antigravity 模型也可通过 `/v1/chat/completions` 调用,支持 JSON 与 SSE;不接受 Responses 或 Messages 的内置跨协议调用。
|
||||
Chat 直接映射文本、图片/文档、函数与 custom 工具历史、生成参数和 JSON Schema。未知内容块或无法表达的语义返回请求错误,模型参数的实际支持范围由上游校验。
|
||||
原生入口保留工具结果和思考签名;常规生成与计数在出站时使用同一份 AGY 系统提示词配置,替换客户端系统指令,其余原生字段保持原始表达
|
||||
原生入口保留工具结果和思考签名;常规生成与计数共用上述系统指令合成规则
|
||||
|
||||
Chat 工具多轮调用须携带完整助手输出和对应结果。Chat 只返回可读思考内容;对 Chat 历史中的工具调用使用 Google 的 `skip_thought_signature_validator` 标记,不增加服务端签名缓存。
|
||||
原生 GenAI 的真实签名仍原样回传,见 [Google 签名规则](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures)
|
||||
@@ -527,9 +527,8 @@ Responses API Key 与 OAuth 共用模拟客户端画像(`User-Agent`、`origin
|
||||
Responses 的安装身份通过正文 `client_metadata` 及 turn metadata 发送,不默认添加独立的
|
||||
`x-codex-installation-id` 请求头,也不透传下游同名头。Key 配置种子时,安装身份由种子、Key ID 与选中账号 ID
|
||||
稳定派生;未配置时使用账号已持久化的安装 ID。Images、Search 和 Live 保留各自的安装头
|
||||
`x-openai-internal-codex-residency` 和 `x-openai-account-routing-override` 分别由部署配置
|
||||
`openai.residency`、`openai.account_routing_override` 控制,配置值原样发送并覆盖客户端同名头,
|
||||
省略或 `null` 时删除对应请求头。配置说明见 [部署与运维](../deploy/README.md#启动后的运行设置)
|
||||
`x-openai-internal-codex-residency` 和 `x-openai-account-routing-override` 由运行设置
|
||||
[`openaiRequestSettings`](#数据驻留与路由) 控制,覆盖客户端同名头
|
||||
`x-openai-fedramp` 默认按业务头透传并保留原始多值,Responses 明确换号时清理客户端值。
|
||||
所选 OpenAI OAuth 令牌声明 FedRAMP 时,网关为模型请求设置唯一的 `x-openai-fedramp: true`。
|
||||
同账号轮换令牌导致该声明变化时,新请求使用新的上游 WS 连接,旧连接上的精确续接需要客户端重放。
|
||||
@@ -607,12 +606,11 @@ WS 握手的轮次元数据头只随首次请求转发,后续帧在正文中
|
||||
请求头过滤不提供客户端匿名化;系统提示词、工具定义、工具结果、工作目录及其他业务 metadata
|
||||
保持原有语义,可能包含客户端环境信息。
|
||||
环境正文中的工作区路径、shell 和文件权限信息不会因位置覆盖而隐藏。
|
||||
turn metadata 的 `workspaces` 也会保留仓库绝对路径、Git 远端地址、提交及工作区变更状态;
|
||||
安装身份和账号绑定字段的处理不提供这些信息的脱敏
|
||||
turn metadata 中的 `workspaces` 可能包含仓库绝对路径、Git 远端地址、提交及工作区变更状态。这些字段的处理取决于已启用的[隐私策略](#隐私策略)
|
||||
|
||||
Codex 客户端按本地登录方式和模型卡选择同步 Guardian 审核模型。使用默认模型卡时,
|
||||
API Key 登录通常选择 `gpt-5.6-luna`,ChatGPT 登录选择 `codex-auto-review`。
|
||||
“系统设置 → 上游配置”中的“专用审核模型”默认开启。关闭后沿用客户端模型。开启时,网关按当前请求的
|
||||
“系统设置 → 平台设置 → OpenAI → 自动审批”中的“专用审核模型”默认开启。关闭后沿用客户端模型。开启时,网关按当前请求的
|
||||
Guardian 身份识别同步审核和审核预热,优先选择允许 `codex-auto-review` 的原生 OAuth 账号。
|
||||
入站审核模型可以是任意名称。普通请求、后台分类和会话整理沿用原模型。
|
||||
缺少合格账号时,网关按客户端模型正常选路。严格会话亲和下,如果父账号不在专用模型候选中,子审核沿用客户端模型并跟随父账号。
|
||||
@@ -1809,7 +1807,7 @@ OAuth start 使用:
|
||||
|
||||
Antigravity 的全局客户端设置保存在 `providerRequestProfiles.antigravity`,Key 可用 `providerRequestProfileOverrides.antigravity` 覆盖。配置使用 `client`(`desktop` 或 `cli`)、`platform`(`macos`、`linux` 或 `windows`)、`versionMode`、`clientVersion` 和 `arch`。`arch: null` 使用预设架构:macOS 为 `arm64`,Linux 与 Windows 为 `amd64`;也可显式选择 `arm64` 或 `amd64`
|
||||
|
||||
`systemPrompt` 可在 AGY 设置中编辑,省略、`null` 或空白值使用内置默认,最长 16 KiB。默认取自已核对的 AGY CLI 1.5.15 身份模板,不包含客户端专属工具和工作区模板;选项接口返回 `defaultSystemPrompt` 与 `systemPromptSource`,客户端版本轮询不会改写它。提示词随请求画像一起冻结,原生和转换入口均用它替换客户端的系统指令
|
||||
`systemPrompt` 可在 AGY 设置中编辑,省略、`null` 或空白值使用内置默认,最长 16 KiB。默认取自已核对的 AGY CLI 1.5.15 身份模板,不包含客户端专属工具和工作区模板;选项接口返回 `defaultSystemPrompt` 与 `systemPromptSource`,客户端版本轮询不会改写它。提示词随请求画像一起冻结,原生和转换入口均将它放在客户端系统指令之前。客户端的全局规则、项目规则、工具说明及其他系统指令保持原样;未提供客户端系统指令时只使用配置提示词
|
||||
|
||||
自动版本示例:
|
||||
|
||||
@@ -2329,8 +2327,8 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly
|
||||
| --- | --- |
|
||||
| 并发控制版本 | `configRevision` |
|
||||
| [客户端身份](#provider-客户端身份) | `providerRequestProfiles` |
|
||||
| [请求位置](#请求位置) | `requestLocationEnabled`、`requestLocation`、`openaiRequestCountry` |
|
||||
| [OpenAI OAuth 同步审核模型](#正文兼容) | `openaiOauthGuardianReviewModel`,默认 `true` |
|
||||
| [请求位置](#请求位置) | `requestLocationEnabled`、`requestLocation` |
|
||||
| [OpenAI 请求设置](#openai-请求设置) | `openaiRequestSettings` |
|
||||
| [隐私策略](#隐私策略) | `codexPrivacyPolicy` |
|
||||
| 模型映射 | `modelMappings` |
|
||||
| 凭据刷新 | `refreshMarginSeconds`、`refreshConcurrency` |
|
||||
@@ -2382,7 +2380,22 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly
|
||||
|
||||
Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请求中的位置相关业务字段继续透传;网络出口仍使用所选账号的代理
|
||||
|
||||
`openaiRequestCountry` 仅控制发往 Codex OAuth 上游的 Responses 请求顶层字段 `request_country`。API Key 上游保留客户端原值,包括显式 `null`,客户端省略时也省略。保存后对新请求生效
|
||||
### OpenAI 请求设置
|
||||
|
||||
`openaiRequestSettings` 统一保存请求国家、OAuth 审核模型、数据驻留和账号路由。更新设置时必须提交完整对象;仅修改其他设置时,从当前设置读取并原样提交。默认值如下:
|
||||
|
||||
```json
|
||||
{
|
||||
"requestCountry": { "mode": "follow_location" },
|
||||
"oauthGuardianReviewModel": true,
|
||||
"residency": null,
|
||||
"accountRoutingOverride": null
|
||||
}
|
||||
```
|
||||
|
||||
`oauthGuardianReviewModel` 控制 [OAuth 同步审核专用模型](#正文兼容),必须为布尔值
|
||||
|
||||
`openaiRequestSettings.requestCountry` 仅控制发往 Codex OAuth 上游的 Responses 请求顶层字段 `request_country`。API Key 上游保留客户端原值,包括显式 `null`,客户端省略时也省略。保存后对新请求生效
|
||||
|
||||
| 管理端选项 | 设置值 | 发往上游的字段 |
|
||||
| --- | --- | --- |
|
||||
@@ -2391,7 +2404,13 @@ Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请
|
||||
| 透传 | `{"mode":"passthrough"}` | 保留客户端原值,包括显式 `null`;客户端省略时也省略 |
|
||||
| 自定义 | `{"mode":"custom","country":"CA"}` | 始终发送指定的两位大写 ASCII 国家码,独立于城市、时区和全局位置开关 |
|
||||
|
||||
更新设置时必须同时提交 `openaiRequestCountry` 和 `openaiOauthGuardianReviewModel`。仅修改其他设置时,请从当前设置读取并原样提交这两项
|
||||
#### 数据驻留与路由
|
||||
|
||||
`openaiRequestSettings` 中的 `residency` 和 `accountRoutingOverride` 独立于客户端身份与请求位置,均为可选字符串,默认 `null`,分别设置 `x-openai-internal-codex-residency` 和
|
||||
`x-openai-account-routing-override`。值必须能作为 HTTP/WebSocket 请求头发送(ASCII 文本),原样保留,不限制为固定选项。
|
||||
参考值分别为 `us` 和 `us`、`us_cr`。字段省略或为 `null` 时删除对应请求头,空字符串发送空头值;管理端留空保存为 `null`
|
||||
|
||||
保存后对新请求及后续后台操作生效,无需重启。正在执行的请求及其重试保留原值,WebSocket 连接按最终握手头隔离。
|
||||
|
||||
### 隐私策略
|
||||
|
||||
@@ -2763,7 +2782,7 @@ Grok CLI 通用身份默认使用 `grok-shell / headless / linux / x86_64`,版
|
||||
```
|
||||
|
||||
配置作用于 Client Key 的 xAI 模型请求,影响 `x-grok-client-version`、`x-grok-client-identifier`、
|
||||
`x-grok-client-mode` 与 User-Agent;OAuth、后台目录和额度查询使用 Provider 内置官方画像。
|
||||
`x-grok-client-mode` 与 User-Agent。OAuth、后台目录和额度查询使用 xAI 的全局客户端身份。
|
||||
User-Agent 使用 `grok-shell/<版本> (<系统>; <架构>)`,其中 `arm64` 按官方规则展示为 `aarch64`。
|
||||
`clientIdentifier` 只控制对应请求头,不替换 User-Agent 中的 `grok-shell` 产品名。
|
||||
每个请求开始时解析并冻结身份,重试和换号沿用该身份;保存后新请求生效,密钥独立配置优先于通用设置
|
||||
@@ -3058,7 +3077,7 @@ HTTP SSE 请求可能在返回 HTTP 200 后流内失败;WebSocket 已升级时
|
||||
`retryCount` 为额外执行尝试次数之和,`retryRate` 为发生过重试的请求数占该组请求数的比例,同一请求多次重试只计一次
|
||||
|
||||
使用记录列表和错误排查列表的 `accountPlanType` / `accountPlanTypeDisplay` 来自记录保存的账号订阅快照。
|
||||
Antigravity 请求快照只保存套餐 ID,历史记录的展示名为空。
|
||||
Antigravity 的展示名取自请求时已观测到的 Google 套餐描述,快照缺少描述时为 `null`
|
||||
账号维度诊断使用该账号最近请求的订阅快照,并通过 `authenticationKind` 返回同一请求的认证类型快照;未保存的字段为 `null`,非账号维度的认证类型为 `null`
|
||||
|
||||
管理端请求列表及 Dashboard 最近请求中的 `accountNotes` 来自请求保存的账号备注快照,未保存时为 `null`
|
||||
@@ -3365,7 +3384,8 @@ Host 关闭或任务取消会记录失败终态;状态查询会收敛无执行
|
||||
制品 `metadata` 返回 `pluginId`、`name`、`displayName`、`publisher`、可为 `null` 的 `author`、`version`、
|
||||
`description`、`license`、`sha256`、`platforms`、可为 `null` 的 `icon`、`contributes`、
|
||||
`configurationSchema`、`secretFields` 和 `stateNamespaces`。`contributes` 是以稳定 snake_case capability 为 key 的对象;每个值包含
|
||||
`id`、`version`、`stages`、`inputFormats` 和 `outputFormats`。`id` 是实例绑定引用的完整贡献项 ID,客户端必须通过
|
||||
`id`、`version`、`stages`、`inputFormats` 和 `outputFormats`。中间件还可返回 `omitBodyAt` 和 `websocketErrorCodes`,分别列出省略请求正文的阶段和订阅的原生 Responses WebSocket 下行错误码。这两个字段为空时省略,见 [SDK 清单](../backend/crates/gateway-plugin/sdk/docs/manifest.md#扩展项简写)。
|
||||
`id` 是实例绑定引用的完整贡献项 ID,客户端必须通过
|
||||
当前制品的 `contributes` 映射确定其 capability,不能解析 ID 文本推测能力
|
||||
|
||||
#### 图标读取
|
||||
|
||||
@@ -355,7 +355,7 @@ Provider 可为模型提供来源账号集合;Core 在公开目录查询时结
|
||||
|
||||
### 3.4 前端模块职责
|
||||
|
||||
`frontend/src` 持有应用状态和业务交互,基础组件与主题算法由 `@codex-proxy/ui` 提供,组件目录与合同见 [UI 组件架构](../modules/ui/playground/guide/architecture.md):
|
||||
`frontend/src` 持有应用状态和业务交互,基础组件与主题算法由 `@codex-proxy/ui` 提供,组件目录与合同见 [UI 组件架构](https://github.com/zyycn/codex-proxy-ui/blob/main/playground/guide/architecture.md):
|
||||
|
||||
| 入口 | 职责 |
|
||||
| --- | --- |
|
||||
@@ -598,7 +598,7 @@ GenAI 模型目录通过 Core 的原生操作路由判断过滤冻结账号范
|
||||
|
||||
Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。
|
||||
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
|
||||
并按冻结画像统一替换 AGY 系统指令。默认提示和可编辑配置归 Provider 的 `profile`,纯协议层不持有 AGY 身份规则
|
||||
并将冻结画像的提示词前置到客户端系统指令,保留客户端规则、工具说明和工作区上下文。默认提示和可编辑配置归 Provider 的 `profile`,纯协议层不持有 AGY 身份规则
|
||||
|
||||
Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属
|
||||
|
||||
@@ -696,10 +696,8 @@ OpenAI 模型目录用于发现与原生 Responses 账号资格筛选。
|
||||
OpenAI Provider 按 Key 种子、Key ID 与账号 ID 派生出站安装身份;未配置种子时使用账号身份,不改写账号凭据。
|
||||
普通连接按生效身份匹配,精确续写固定原连接与身份;配置合同见 [Key 客户端身份](api.md#key-客户端身份)。
|
||||
OpenAI 账号目录发现和定时预热每轮读取并解析一次当前全局画像,查询版本和请求头使用同一快照,不接受 Key 覆盖。
|
||||
其余后台账号和 Desktop 专属操作使用独立官方 Desktop 画像。
|
||||
管理端连接测试从本次发布快照携带全局画像,经 Provider 解析后冻结为探测身份。
|
||||
xAI 以内置画像为版本检查基线,在进程内更新 Grok CLI 发布资料;模型请求使用已保存的用户选择,
|
||||
OAuth、后台目录和额度查询使用内置官方画像
|
||||
xAI 以内置版本为基线,在进程内更新 Grok CLI 发布资料。各平台后台操作的身份来源见[凭据、额度与主动重置](#凭据额度与主动重置)
|
||||
|
||||
xAI 的 Chat 路径将 custom 工具包装为 function 输入,并在直接返回 Chat 时还原;原生 Responses 不做该转换。
|
||||
原生续接的账号归属仍由既有会话 owner 管理,同账号重放保留完整上游输出;跨账号重放只清理无法携带的账号绑定状态。
|
||||
|
||||
+3
-3
@@ -12,7 +12,7 @@
|
||||
|
||||
## 环境与依赖
|
||||
|
||||
使用 Node.js 26.13.1、PostgreSQL、Redis 和各前端 `packageManager` 指定的 pnpm。宿主 CI 与 Docker 读取 `frontend/package.json`。
|
||||
使用 PostgreSQL 16 或更高版本、Redis 和各前端 `packageManager` 指定的 pnpm。Node.js 版本与 [Dockerfile](../deploy/Dockerfile) 的 `frontend-builder` 一致,CI 从该镜像声明读取版本。
|
||||
在仓库根目录运行 Cargo 时,用 `+版本号` 选择 `backend/rust-toolchain.toml` 指定的[工具链](architecture.md#验证命令)
|
||||
|
||||
```bash
|
||||
@@ -54,7 +54,7 @@ pnpm --dir frontend dev
|
||||
|
||||
## 源码入口
|
||||
|
||||
[后端 Workspace 边界](architecture.md#3-workspace-边界) · [前端模块职责](architecture.md#34-前端模块职责) · [共享 UI 组件架构](../modules/ui/playground/guide/architecture.md)
|
||||
[后端 Workspace 边界](architecture.md#3-workspace-边界) · [前端模块职责](architecture.md#34-前端模块职责) · [共享 UI 组件架构](https://github.com/zyycn/codex-proxy-ui/blob/main/playground/guide/architecture.md)
|
||||
|
||||
Chat Completions 到 Responses、Messages、GenAI 的纯协议转换位于 `backend/crates/gateway-protocol/src/chat_completions/`,
|
||||
Chat HTTP 入口位于 `backend/crates/gateway-api/src/data_plane/chat_completions/`,各 Provider 的 `provider/chat/` 或 `provider/chat.rs` 负责调用获准的转换。
|
||||
@@ -139,7 +139,7 @@ pnpm --dir modules/plugins/examples/workbench/frontend build:source
|
||||
)
|
||||
```
|
||||
|
||||
独立插件的构建、打包和安装后功能验证见 [Workbench 示例](../modules/plugins/examples/workbench/README.md)。
|
||||
独立插件的构建、打包和安装后功能验证见 [Workbench 示例](https://github.com/zyycn/codex-proxy-plugins/blob/main/examples/workbench/README.md)。
|
||||
宿主插件集成测试的数据库与 Redis 配置见[本地测试库](../backend/migrations/README.md#本地测试库)
|
||||
|
||||
## 编辑与提交
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@
|
||||
“设置”按当前包的 schema 显示参数,敏感字段单独保存且不回显。每项显示保存状态,留空保留现有值,填写新值替换该项;
|
||||
“清除”只删除对应字段,保存前可撤销。首次补齐必填项后“保存并启用”;其他设置修改保持
|
||||
原有启停状态。请求处理能力随包自动注册,无需在安装时逐项勾选;可在“高级设置”中调整各挂载阶段的启停、顺序和失败处理。
|
||||
模型请求阶段支持 Key、分组、模型等作用范围;HTTP、WebSocket 消息和服务调用全局生效,具体匹配由插件处理。
|
||||
模型请求阶段支持 Key、分组、模型等作用范围。HTTP、WebSocket 消息和服务调用使用全局绑定。若插件在[清单](../backend/crates/gateway-plugin/sdk/docs/manifest.md#扩展项简写)中订阅了特定错误码,该插件的 WebSocket 中间件只收到原生 Responses 下行消息中匹配的错误。
|
||||
客户端 Key、账号分组、Provider 和模型等范围同时满足才生效,同一范围内任一值匹配即可
|
||||
|
||||
“事件观察”可独立开关“请求完成与用量”和“上游 WebSocket 事件”。改写请求、响应或消息须使用对应中间件
|
||||
|
||||
+4
-4
@@ -45,7 +45,7 @@ Vue 组件通过 CSS Variables 和 Tailwind CSS 4 使用主题,无需 Ant Desi
|
||||
| 页面头部 | `@codex-proxy/ui` 的 `ZPageHeader`、[系统概览](../frontend/src/views/dashboard/components/DashboardOverview.vue) | 简短标题、必要的统计范围或状态、就近操作 |
|
||||
| 内容与指标 | `@codex-proxy/ui` 的 `ZCard`、[用量概览卡片](../frontend/src/views/usage/components/UsageSummaryCards.vue) | 可选说明、紧凑摘要、数值与辅助信息的主次 |
|
||||
| 表单帮助 | [API Key 账号字段](../frontend/src/providers/openai/accounts/ApiKeyFields.vue) | 直接命名字段,在对应位置提供短提示和示例 |
|
||||
| 详细规则 | [自动审批并发帮助](../frontend/src/views/settings/components/ConcurrencyPolicyCard.vue) | 标签旁帮助图标打开 Popover,页面保留短提示,浮层补充规则和示例 |
|
||||
| 详细规则 | [自动审批并发帮助](../frontend/src/views/settings/components/GuardianReviewCard.vue) | 标签旁帮助图标打开 Popover,页面保留短提示,浮层补充规则和示例 |
|
||||
| 账号与用量展示 | [账号额度窗口](../frontend/src/components/account-usage-window/index.vue)、[共用用量表格](../frontend/src/components/usage-records-table/index.vue) | 复用后端展示字段和共享 presenter,管理端与 Key 页保持同一展示口径 |
|
||||
|
||||
页面查询、表单状态与纯展示逻辑的归属见 [前端模块职责](architecture.md#34-前端模块职责)
|
||||
@@ -65,7 +65,7 @@ Vue 组件通过 CSS Variables 和 Tailwind CSS 4 使用主题,无需 Ant Desi
|
||||
- 繁体中文只转换简体原文的字形,保持措辞与语序,不替换地区用词,例如 `数据 → 數據`、`设置 → 設置`
|
||||
- 只翻译应用拥有的文本,具体后端错误、上游诊断、日志和独立插件内容保留原文;固定错误码在请求层映射,业务分类码优先保留后端公开的具体原因,无原因时使用本地兜底文案
|
||||
- 侧边栏语言图标展开就地选项,选择后切换并收起;品牌区固定显示 `Codex Proxy`、`Rust build` 和版本号
|
||||
- UI 库默认文案由 `ZConfigProvider` 提供,命令式通知通过 `plugins/notification.ts` 绑定同一个语言来源,组件约定见 [UI 国际化](../modules/ui/playground/guide/i18n.md)
|
||||
- UI 库默认文案由 `ZConfigProvider` 提供,命令式通知通过 `plugins/notification.ts` 绑定同一个语言来源,组件约定见 [UI 国际化](https://github.com/zyycn/codex-proxy-ui/blob/main/playground/guide/i18n.md)
|
||||
|
||||
正文默认使用 Inter Variable,中文及缺失字形按系统无衬线字体栈回退。代码使用 JetBrains Mono Variable,中文由系统字体补齐,不随语言切换额外修改字重。默认值由 UI 库持有,应用负责加载字体包,图表读取同一字体 Token
|
||||
|
||||
@@ -303,7 +303,7 @@ Theme Store 统一读取持久化配置并初始化主题,首个 Vue 组件渲
|
||||
|
||||
主题内部和持久化配置使用 `color-primary`、`input-bg` 等语义 Token 名,不包含 CSS 前缀。
|
||||
UI 构建插件 `CodexProxyUI({ themePrefix: 'z' })` 同时配置变量生成与样式引用,默认前缀为 `z`;
|
||||
它与组件导出名、DOM 类名和 utility 类名独立,修改后需重新构建。配置方式见 UI 的[主题定制](../modules/ui/playground/guide/theme.md#自定义主题前缀)
|
||||
它与组件导出名、DOM 类名和 utility 类名独立,修改后需重新构建。配置方式见 UI 的[主题定制](https://github.com/zyycn/codex-proxy-ui/blob/main/playground/guide/theme.md#自定义主题前缀)
|
||||
|
||||
全局主题由 `<head>` 中唯一的运行时样式节点承载:
|
||||
|
||||
@@ -367,7 +367,7 @@ Store 在其他入口发生变化时更新保存基线;没有未保存修改
|
||||
|
||||
### 隔离预览
|
||||
|
||||
[`ThemePreviewScope.vue`](../frontend/src/views/theme/components/ThemePreviewScope.vue) 创建开放 Shadow Root,复制应用
|
||||
[`ThemePreviewScope.vue`](../frontend/src/views/theme/components/theme-preview-canvas/ThemePreviewScope.vue) 创建开放 Shadow Root,复制应用
|
||||
样式,并把预览内容 Teleport 到影子根中。预览可独立切换浅色和深色,不受外层主题影响。
|
||||
画布和操作控件先显示,选中的预览内容异步加载,就绪前画布留空,资源加载完成后同步影子根样式
|
||||
|
||||
|
||||
@@ -53,10 +53,14 @@ export interface RuntimeSettings {
|
||||
providerRequestProfiles: ProviderRequestProfiles
|
||||
|
||||
codexPrivacyPolicy: CodexPrivacyPolicy
|
||||
openaiRequestCountry: OpenAiRequestCountry
|
||||
openaiRequestSettings: {
|
||||
requestCountry: OpenAiRequestCountry
|
||||
oauthGuardianReviewModel: boolean
|
||||
residency: string | null
|
||||
accountRoutingOverride: string | null
|
||||
}
|
||||
requestLocationEnabled: boolean
|
||||
requestLocation: RequestLocation
|
||||
openaiOauthGuardianReviewModel: boolean
|
||||
modelMappings: Record<string, string>
|
||||
refreshMarginSeconds: number
|
||||
refreshConcurrency: number
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"forecastWeeklyMonthlyQuota": "Forecast weekly/monthly quota",
|
||||
"queryUnsupported": "Upstream quota queries are not supported",
|
||||
"quotaDetails": "Quota details",
|
||||
"quotaManagement": "Quota management",
|
||||
"viewDetails": "View {detailTitle} details",
|
||||
"details": "{detailTitle} details",
|
||||
"statisticalMethod": "Statistical method",
|
||||
@@ -551,7 +552,6 @@
|
||||
"weeklyThreshold": "Weekly quota remaining ≤ {percent}%",
|
||||
"minutesInAdvance": "{leadMinutes} min in advance",
|
||||
"nextUse": "Scheduled expiry use: {nextConsumeAtDisplay}",
|
||||
"limitReset": "Limit reset",
|
||||
"confirmLastReset": "Confirm last reset",
|
||||
"confirmResetAmount": "Confirm reset amount",
|
||||
"pendingAction": "View reset credits, an operation is awaiting confirmation",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"settings": {
|
||||
"clientProfile": {
|
||||
"systemPrompt": "System prompt",
|
||||
"systemPromptHint": "Replaces client system instructions · Default from {source}",
|
||||
"systemPromptHint": "Prepended to client system instructions · Default from {source}",
|
||||
"restoreSystemPrompt": "Restore default",
|
||||
"userAgent": "User agent",
|
||||
"clientIdentitySource": "Client identity source",
|
||||
@@ -329,10 +329,8 @@
|
||||
"day": "d",
|
||||
"location": {
|
||||
"requestCountry": "Request country",
|
||||
"requestCountryDescription": "Choose how requests send the country code",
|
||||
"requestCountryScope": "Applies only to OAuth accounts",
|
||||
"countryHelp": "Request country mode help",
|
||||
"countryMode": "Policy",
|
||||
"countryModes": {
|
||||
"default": "Null",
|
||||
"passthrough": "Pass through",
|
||||
@@ -780,6 +778,17 @@
|
||||
"resetPriority": {
|
||||
"description": "Rank by reset times and weights of the selected windows",
|
||||
"windowHelp": "Weights control each window's relative influence; 0 ignores a window, and all zeros use the earliest valid reset time"
|
||||
},
|
||||
"requestOptions": {
|
||||
"title": "Request settings",
|
||||
"residency": "Data residency",
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "Account routing",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "About residency",
|
||||
"accountRoutingOverrideHelp": "About account routing",
|
||||
"headerHelp": "Sends the header value as entered, or omits the header when left blank",
|
||||
"description": "Configure parameters sent to the upstream provider"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"forecastWeeklyMonthlyQuota": "预测周/月额度",
|
||||
"queryUnsupported": "暂不支持查询上游额度",
|
||||
"quotaDetails": "额度详情",
|
||||
"quotaManagement": "额度管理",
|
||||
"viewDetails": "查看{detailTitle}详情",
|
||||
"details": "{detailTitle}详情",
|
||||
"statisticalMethod": "统计方式",
|
||||
@@ -551,7 +552,6 @@
|
||||
"weeklyThreshold": "剩余周额度 ≤ {percent}%",
|
||||
"minutesInAdvance": "提前 {leadMinutes} 分钟",
|
||||
"nextUse": "临期用卡时间 {nextConsumeAtDisplay}",
|
||||
"limitReset": "额度重置",
|
||||
"confirmLastReset": "确认上次重置",
|
||||
"confirmResetAmount": "确认重置额度",
|
||||
"pendingAction": "查看主动重置卡,有一项操作待确认",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"settings": {
|
||||
"clientProfile": {
|
||||
"systemPrompt": "系统提示词",
|
||||
"systemPromptHint": "替换客户端系统提示,默认来自 {source}",
|
||||
"systemPromptHint": "前置系统提示,保留客户端指令,默认来自 {source}",
|
||||
"restoreSystemPrompt": "恢复默认",
|
||||
"userAgent": "用户代理",
|
||||
"clientIdentitySource": "客户端身份来源",
|
||||
@@ -329,10 +329,8 @@
|
||||
"day": "天",
|
||||
"location": {
|
||||
"requestCountry": "请求国家",
|
||||
"requestCountryDescription": "设置请求如何发送国家代码",
|
||||
"requestCountryScope": "仅用于 OAuth 账号",
|
||||
"countryHelp": "请求国家模式说明",
|
||||
"countryMode": "策略",
|
||||
"countryModes": {
|
||||
"default": "空值",
|
||||
"passthrough": "透传",
|
||||
@@ -780,6 +778,17 @@
|
||||
"resetPriority": {
|
||||
"description": "按所选窗口的重置时间和系数排序",
|
||||
"windowHelp": "系数决定各窗口的相对占比,0 表示忽略该窗口,全部为 0 时按最近的有效重置时间排序"
|
||||
},
|
||||
"requestOptions": {
|
||||
"title": "请求设置",
|
||||
"residency": "数据驻留",
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "账号路由",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "数据驻留说明",
|
||||
"accountRoutingOverrideHelp": "账号路由说明",
|
||||
"headerHelp": "按填写值发送请求头,留空则不发送",
|
||||
"description": "配置发往上游的请求参数"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"forecastWeeklyMonthlyQuota": "預測周/月額度",
|
||||
"queryUnsupported": "暫不支持查詢上游額度",
|
||||
"quotaDetails": "額度詳情",
|
||||
"quotaManagement": "額度管理",
|
||||
"viewDetails": "查看{detailTitle}詳情",
|
||||
"details": "{detailTitle}詳情",
|
||||
"statisticalMethod": "統計方式",
|
||||
@@ -551,7 +552,6 @@
|
||||
"weeklyThreshold": "剩餘週額度 ≤ {percent}%",
|
||||
"minutesInAdvance": "提前 {leadMinutes} 分鐘",
|
||||
"nextUse": "臨期用卡時間 {nextConsumeAtDisplay}",
|
||||
"limitReset": "額度重置",
|
||||
"confirmLastReset": "確認上次重置",
|
||||
"confirmResetAmount": "確認重置額度",
|
||||
"pendingAction": "查看主動重置卡,有一項操作待確認",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"settings": {
|
||||
"clientProfile": {
|
||||
"systemPrompt": "系統提示詞",
|
||||
"systemPromptHint": "取代客戶端系統提示,預設來自 {source}",
|
||||
"systemPromptHint": "前置系統提示,保留客戶端指令,預設來自 {source}",
|
||||
"restoreSystemPrompt": "恢復預設",
|
||||
"userAgent": "用戶代理",
|
||||
"clientIdentitySource": "客戶端身份來源",
|
||||
@@ -329,10 +329,8 @@
|
||||
"day": "天",
|
||||
"location": {
|
||||
"requestCountry": "請求國家",
|
||||
"requestCountryDescription": "設定請求如何傳送國家代碼",
|
||||
"requestCountryScope": "僅用於 OAuth 帳號",
|
||||
"countryHelp": "請求國家模式說明",
|
||||
"countryMode": "策略",
|
||||
"countryModes": {
|
||||
"default": "空值",
|
||||
"passthrough": "透傳",
|
||||
@@ -780,6 +778,17 @@
|
||||
"resetPriority": {
|
||||
"description": "按所選視窗的重置時間和係數排序",
|
||||
"windowHelp": "係數決定各視窗的相對占比,0 表示忽略該視窗,全部為 0 時按最近的有效重置時間排序"
|
||||
},
|
||||
"requestOptions": {
|
||||
"title": "請求設置",
|
||||
"residency": "資料駐留",
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "帳號路由",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "數據駐留說明",
|
||||
"accountRoutingOverrideHelp": "賬號路由說明",
|
||||
"headerHelp": "按填寫值發送請求頭,留空則不發送",
|
||||
"description": "配置發往上游的請求參數"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ const {
|
||||
|
||||
const modalTitle = computed(() => {
|
||||
if (!confirmation.value)
|
||||
return t('accounts.quotaReset.limitReset')
|
||||
return t('accounts.quota.quotaManagement')
|
||||
return confirmation.value.ambiguous
|
||||
? t('accounts.quotaReset.confirmLastReset')
|
||||
: t('accounts.quotaReset.confirmResetAmount')
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import type { Account } from '@/api'
|
||||
|
||||
import { ZEmpty, ZScrollbar } from '@codex-proxy/ui'
|
||||
import { ZDialog, ZEmpty, ZScrollbar } from '@codex-proxy/ui'
|
||||
|
||||
import { ChartNoAxesCombined, Link2, RefreshCw, UserRound } from '@lucide/vue'
|
||||
import { ChartNoAxesCombined, Link2, RefreshCw, TicketCheck, UserRound } from '@lucide/vue'
|
||||
|
||||
import { computed, shallowRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -12,6 +12,7 @@ import { formatRelativeTime } from '@/utils/relative-time'
|
||||
import { groupedAccountQuotaWindows, orderedPanelQuotaWindows } from '../../constants'
|
||||
import AccountProfileModal from '../account-profile-modal/index.vue'
|
||||
import AccountQuotaForecastModal from '../account-quota-forecast-modal/index.vue'
|
||||
import AccountQuotaCredits from './Credits.vue'
|
||||
import AccountQuotaPanelEntry from './Entry.vue'
|
||||
import QuotaActionButton from './QuotaActionButton.vue'
|
||||
import QuotaSettings from './QuotaSettings.vue'
|
||||
@@ -47,6 +48,7 @@ const quotaEntries = computed(() => {
|
||||
: windows.filter(window => !window.sourceAccountId)
|
||||
return groupedAccountQuotaWindows(orderedPanelQuotaWindows(visibleWindows))
|
||||
})
|
||||
const creditsOpen = shallowRef(false)
|
||||
const profileOpen = shallowRef(false)
|
||||
const forecastOpen = shallowRef(false)
|
||||
const hasPlanBadge = computed(() => Boolean(props.account.planType) || props.account.authenticationKind === 'api_key')
|
||||
@@ -54,7 +56,7 @@ const hasForecast = computed(() => props.account.authenticationKind !== 'api_key
|
||||
const hasPersonalInfo = computed(() => props.account.capabilities.profile || props.account.capabilities.subscription)
|
||||
const needsPeerDiscovery = computed(() => props.account.upstream?.discovered === false)
|
||||
const canRefresh = computed(() => props.account.capabilities.quotaRefresh || props.account.upstream != null)
|
||||
const hasActions = computed(() => hasPersonalInfo.value || hasForecast.value || canRefresh.value || props.account.capabilities.resetCredits)
|
||||
const hasActions = computed(() => hasPersonalInfo.value || hasForecast.value || canRefresh.value || props.account.capabilities.resetCredits || props.account.capabilities.quotaCredits)
|
||||
const lastRefreshed = computed(() => {
|
||||
const { upstream, quota } = props.account
|
||||
if (upstream?.discovered && !upstream.observedAt)
|
||||
@@ -109,6 +111,19 @@ watch(hasPersonalInfo, (available) => {
|
||||
@account-updated="emit('accountUpdated', $event)"
|
||||
@consumed="emit('quotaReset', $event)"
|
||||
/>
|
||||
<template v-else-if="account.capabilities.quotaCredits">
|
||||
<QuotaActionButton
|
||||
:label="t('accounts.quota.quotaPoints')"
|
||||
aria-haspopup="dialog"
|
||||
:aria-pressed="creditsOpen || undefined"
|
||||
@click="creditsOpen = true"
|
||||
>
|
||||
<TicketCheck class="size-3.5" />
|
||||
</QuotaActionButton>
|
||||
<ZDialog v-model="creditsOpen" :title="t('accounts.quota.quotaManagement')" width="36rem">
|
||||
<AccountQuotaCredits :key="account.id" :account="account" @account-updated="emit('accountUpdated', $event)" />
|
||||
</ZDialog>
|
||||
</template>
|
||||
<QuotaActionButton
|
||||
v-if="hasForecast"
|
||||
:label="t('accounts.quota.forecastWeeklyMonthlyQuota')"
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
<script setup lang="ts">
|
||||
import type { SelectOption } from '@codex-proxy/ui/select'
|
||||
import type { OpenAiRequestCountry } from '@/api'
|
||||
import { ZCard, ZFormItem, ZInput, ZSelect } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import CountryCodeField from '@/components/CountryCodeField.vue'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
|
||||
defineProps<{ disabled: boolean }>()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const requestCountry = defineModel<OpenAiRequestCountry>('requestCountry', { required: true })
|
||||
const residency = defineModel<string>('residency', { required: true })
|
||||
const accountRoutingOverride = defineModel<string>('accountRoutingOverride', { required: true })
|
||||
const modes = computed<Array<SelectOption<OpenAiRequestCountry['mode']> & { help: string }>>(() => [
|
||||
{
|
||||
value: 'follow_location',
|
||||
label: t('settings.location.countryModes.follow_location'),
|
||||
help: t('settings.location.countryHints.follow_location'),
|
||||
},
|
||||
{
|
||||
value: 'default',
|
||||
label: t('settings.location.countryModes.default'),
|
||||
help: t('settings.location.countryHints.default'),
|
||||
},
|
||||
{
|
||||
value: 'passthrough',
|
||||
label: t('settings.location.countryModes.passthrough'),
|
||||
help: t('settings.location.countryHints.passthrough'),
|
||||
},
|
||||
{
|
||||
value: 'custom',
|
||||
label: t('settings.location.countryModes.custom'),
|
||||
help: t('settings.location.countryHints.custom'),
|
||||
},
|
||||
])
|
||||
|
||||
function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
|
||||
if (mode && mode !== requestCountry.value.mode) {
|
||||
requestCountry.value = mode === 'custom'
|
||||
? { mode, country: '' }
|
||||
: { mode }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZCard class="@container" :title="t('settings.requestOptions.title')" :description="t('settings.requestOptions.description')">
|
||||
<div class="grid min-w-0 items-start gap-4.5 @md:grid-cols-3">
|
||||
<div class="grid min-w-0 gap-4.5">
|
||||
<ZFormItem :label="t('settings.location.requestCountry')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('settings.location.countryHelp')">
|
||||
<p class="mb-2 font-emphasis text-z-text">
|
||||
{{ t('settings.location.requestCountryScope') }}
|
||||
</p>
|
||||
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2">
|
||||
<template v-for="mode in modes" :key="mode.value">
|
||||
<dt class="font-emphasis text-z-text">
|
||||
{{ mode.label }}
|
||||
</dt>
|
||||
<dd>{{ mode.help }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
</HelpPopover>
|
||||
</template>
|
||||
<ZSelect :model-value="requestCountry.mode" :options="modes" :aria-label="t('settings.location.requestCountry')" :disabled="disabled" @update:model-value="setMode" />
|
||||
</ZFormItem>
|
||||
<CountryCodeField
|
||||
v-if="requestCountry.mode === 'custom'"
|
||||
:model-value="requestCountry.country"
|
||||
form-prop="openaiRequestSettings.requestCountry.country"
|
||||
:label="t('settings.location.customCountryCode')"
|
||||
:disabled="disabled"
|
||||
@update:model-value="requestCountry = { mode: 'custom', country: $event }"
|
||||
/>
|
||||
</div>
|
||||
<ZFormItem :label="t('settings.requestOptions.residency')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('settings.requestOptions.residencyHelp')">
|
||||
{{ t('settings.requestOptions.headerHelp') }}
|
||||
</HelpPopover>
|
||||
</template>
|
||||
<ZInput v-model="residency" :aria-label="t('settings.requestOptions.residency')" :placeholder="t('settings.requestOptions.residencyPlaceholder')" :disabled="disabled" clearable />
|
||||
</ZFormItem>
|
||||
<ZFormItem :label="t('settings.requestOptions.accountRoutingOverride')">
|
||||
<template #label-extra>
|
||||
<HelpPopover :label="t('settings.requestOptions.accountRoutingOverrideHelp')">
|
||||
{{ t('settings.requestOptions.headerHelp') }}
|
||||
</HelpPopover>
|
||||
</template>
|
||||
<ZInput v-model="accountRoutingOverride" :aria-label="t('settings.requestOptions.accountRoutingOverride')" :placeholder="t('settings.requestOptions.accountRoutingPlaceholder')" :disabled="disabled" clearable />
|
||||
</ZFormItem>
|
||||
</div>
|
||||
</ZCard>
|
||||
</template>
|
||||
@@ -1,80 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { SelectOption } from '@codex-proxy/ui/select'
|
||||
import type { OpenAiRequestCountry } from '@/api'
|
||||
import { ZCard, ZFormItem, ZSelect } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import CountryCodeField from '@/components/CountryCodeField.vue'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
|
||||
defineProps<{ disabled: boolean }>()
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const requestCountry = defineModel<OpenAiRequestCountry>({ required: true })
|
||||
const modes = computed<Array<SelectOption<OpenAiRequestCountry['mode']> & { help: string }>>(() => [
|
||||
{
|
||||
value: 'follow_location',
|
||||
label: t('settings.location.countryModes.follow_location'),
|
||||
help: t('settings.location.countryHints.follow_location'),
|
||||
},
|
||||
{
|
||||
value: 'default',
|
||||
label: t('settings.location.countryModes.default'),
|
||||
help: t('settings.location.countryHints.default'),
|
||||
},
|
||||
{
|
||||
value: 'passthrough',
|
||||
label: t('settings.location.countryModes.passthrough'),
|
||||
help: t('settings.location.countryHints.passthrough'),
|
||||
},
|
||||
{
|
||||
value: 'custom',
|
||||
label: t('settings.location.countryModes.custom'),
|
||||
help: t('settings.location.countryHints.custom'),
|
||||
},
|
||||
])
|
||||
|
||||
function setMode(mode: OpenAiRequestCountry['mode'] | undefined) {
|
||||
if (mode && mode !== requestCountry.value.mode) {
|
||||
requestCountry.value = mode === 'custom'
|
||||
? { mode, country: '' }
|
||||
: { mode }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZCard class="@container" :description="t('settings.location.requestCountryDescription')">
|
||||
<template #title>
|
||||
<span class="inline-flex items-center gap-1.5">
|
||||
{{ t('settings.location.requestCountry') }}
|
||||
<HelpPopover :label="t('settings.location.countryHelp')">
|
||||
<p class="mb-2 font-emphasis text-z-text">
|
||||
{{ t('settings.location.requestCountryScope') }}
|
||||
</p>
|
||||
<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-2">
|
||||
<template v-for="mode in modes" :key="mode.value">
|
||||
<dt class="font-emphasis text-z-text">
|
||||
{{ mode.label }}
|
||||
</dt>
|
||||
<dd>{{ mode.help }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
</HelpPopover>
|
||||
</span>
|
||||
</template>
|
||||
<div class="grid min-w-0 items-start gap-4.5" :class="requestCountry.mode === 'custom' ? '@md:grid-cols-2' : undefined">
|
||||
<ZFormItem :label="t('settings.location.countryMode')">
|
||||
<ZSelect :model-value="requestCountry.mode" :options="modes" :aria-label="t('settings.location.countryMode')" :disabled="disabled" @update:model-value="setMode" />
|
||||
</ZFormItem>
|
||||
<CountryCodeField
|
||||
v-if="requestCountry.mode === 'custom'"
|
||||
:model-value="requestCountry.country"
|
||||
form-prop="openaiRequestCountry.country"
|
||||
:label="t('settings.location.customCountryCode')"
|
||||
:disabled="disabled"
|
||||
@update:model-value="requestCountry = { mode: 'custom', country: $event }"
|
||||
/>
|
||||
</div>
|
||||
</ZCard>
|
||||
</template>
|
||||
@@ -34,8 +34,12 @@ export function useSettingsForm() {
|
||||
quotaResetWindowWeights: undefined as ResetWindowWeights | undefined,
|
||||
providerRequestProfiles: {} as ProviderRequestProfiles,
|
||||
codexPrivacyPolicy: { enabled: false, onError: 'skip_rule', rules: [] } as CodexPrivacyPolicy,
|
||||
openaiOauthGuardianReviewModel: true,
|
||||
openaiRequestCountry: { mode: 'follow_location' } as OpenAiRequestCountry,
|
||||
openaiRequestSettings: {
|
||||
requestCountry: { mode: 'follow_location' } as OpenAiRequestCountry,
|
||||
oauthGuardianReviewModel: true,
|
||||
residency: '',
|
||||
accountRoutingOverride: '',
|
||||
},
|
||||
requestLocationEnabled: false,
|
||||
requestLocation: {
|
||||
country: '',
|
||||
@@ -135,8 +139,11 @@ export function useSettingsForm() {
|
||||
function applySettings(data: Awaited<ReturnType<typeof getSettings>>) {
|
||||
form.codexPrivacyPolicy = cloneDeep(data.codexPrivacyPolicy)
|
||||
form.configRevision = data.configRevision
|
||||
form.openaiOauthGuardianReviewModel = data.openaiOauthGuardianReviewModel
|
||||
form.openaiRequestCountry = data.openaiRequestCountry
|
||||
form.openaiRequestSettings = {
|
||||
...cloneDeep(data.openaiRequestSettings),
|
||||
residency: data.openaiRequestSettings.residency ?? '',
|
||||
accountRoutingOverride: data.openaiRequestSettings.accountRoutingOverride ?? '',
|
||||
}
|
||||
form.requestLocationEnabled = data.requestLocationEnabled
|
||||
form.requestLocation = { ...data.requestLocation }
|
||||
form.refreshMarginSeconds = data.refreshMarginSeconds
|
||||
@@ -270,15 +277,20 @@ export function useSettingsForm() {
|
||||
form.providerRequestProfiles,
|
||||
),
|
||||
codexPrivacyPolicy: cloneDeep(form.codexPrivacyPolicy),
|
||||
openaiRequestCountry: form.openaiRequestCountry.mode === 'custom'
|
||||
? {
|
||||
mode: 'custom',
|
||||
country: form.openaiRequestCountry.country.trim().toUpperCase(),
|
||||
}
|
||||
: { mode: form.openaiRequestCountry.mode },
|
||||
openaiRequestSettings: {
|
||||
oauthGuardianReviewModel: form.openaiRequestSettings.oauthGuardianReviewModel,
|
||||
requestCountry: form.openaiRequestSettings.requestCountry.mode === 'custom'
|
||||
? {
|
||||
mode: 'custom',
|
||||
country: form.openaiRequestSettings.requestCountry.country.trim().toUpperCase(),
|
||||
}
|
||||
: { mode: form.openaiRequestSettings.requestCountry.mode },
|
||||
|
||||
residency: form.openaiRequestSettings.residency || null,
|
||||
accountRoutingOverride: form.openaiRequestSettings.accountRoutingOverride || null,
|
||||
},
|
||||
requestLocationEnabled: form.requestLocationEnabled,
|
||||
requestLocation,
|
||||
openaiOauthGuardianReviewModel: form.openaiOauthGuardianReviewModel,
|
||||
modelMappings: Object.fromEntries(mappings.value.map(row => [
|
||||
row.requestedModel.trim(),
|
||||
row.upstreamModel.trim(),
|
||||
|
||||
@@ -18,9 +18,9 @@ import ConcurrencyPolicyCard from './components/ConcurrencyPolicyCard.vue'
|
||||
import AccountErrorProtectionCard from './components/error-protection/index.vue'
|
||||
import GuardianReviewCard from './components/GuardianReviewCard.vue'
|
||||
import ModelAliasesCard from './components/ModelAliasesCard.vue'
|
||||
import OpenAiRequestCard from './components/OpenAiRequestCard.vue'
|
||||
import PricingSection from './components/pricing/index.vue'
|
||||
import PrivacyPolicyCard from './components/privacy/index.vue'
|
||||
import RequestCountryCard from './components/RequestCountryCard.vue'
|
||||
import RequestHistoryCard from './components/RequestHistoryCard.vue'
|
||||
import RequestLocationCard from './components/RequestLocationCard.vue'
|
||||
import RequestProfileCard from './components/RequestProfileCard.vue'
|
||||
@@ -287,9 +287,14 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) =>
|
||||
:detecting-location="detectingLocation"
|
||||
@detect-location="detectLocation"
|
||||
/>
|
||||
<RequestCountryCard v-model="form.openaiRequestCountry" :disabled="disabled" />
|
||||
<OpenAiRequestCard
|
||||
v-model:request-country="form.openaiRequestSettings.requestCountry"
|
||||
v-model:residency="form.openaiRequestSettings.residency"
|
||||
v-model:account-routing-override="form.openaiRequestSettings.accountRoutingOverride"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
<GuardianReviewCard
|
||||
v-model="form.openaiOauthGuardianReviewModel"
|
||||
v-model="form.openaiRequestSettings.oauthGuardianReviewModel"
|
||||
v-model:reserved-concurrency="openaiGuardianReservedConcurrencyValue"
|
||||
:disabled="disabled"
|
||||
/>
|
||||
|
||||
+19
-8
@@ -1,23 +1,34 @@
|
||||
# v3.56.0
|
||||
# v3.56.1
|
||||
|
||||
## 协议变更与升级
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 从 v3.56.0 起,网关移除了原生协议之间的内置转换。Responses、Messages 和 GenAI 请求各走对应的上游。Chat Completions 继续适配这三种上游,支持 JSON 和流式响应。
|
||||
>
|
||||
>做 2API 时,跨协议转换很容易变成长期维护负担。工具调用、流式事件和会话续接各有自己的规则,有些天生就不一致,即使是相当热门的开源项目,当下也正在频繁的遇到转换问题,甚至被拖着迈不动脚。这段时间我就在想,这是不是伪需求,发展线路正不正确,客户端更新新功能,转换逻辑就得跟着修,而且虽然各家推出了各家的协议文档,但是放到客户端上总有差别,甚至要花费海量的精力去处理因此带来的问题,更别提安全性,用钦定平台都会被风控,换一个就更别说了。
|
||||
>
|
||||
>后续我会把精力放在原生透传和链路安全上,尽量去抹平 apikey 接入带来的风险,实现 OAuth 级别的一致,继续把 Chat Completions 到各上游的适配做稳,为什么是 Chat 呢,因为它已经是成熟非变更的协议,而且国内很多客户端也都是走 Chat。
|
||||
>
|
||||
>当然如果有三方 harness 声明支持平台协议,我也很愿意去花费精力去适配少量的协议差错,但是不同的是,这次转变了,不再是网关,而是客户端。
|
||||
>
|
||||
>有特定跨协议需求时,可以通过上游适配插件实现,插件系统完全支持。[上游适配器文档](https://github.com/zyycn/codex-proxy-rs/blob/v3.56.1/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md)
|
||||
|
||||
- 此前用 Responses 调用 Messages API Key 账号的客户端,请切换到 `/v1/messages` 或 `/v1/chat/completions`
|
||||
- Codex 的模型列表只显示当前 Key 能通过 Responses 调用的模型。此前在 Codex 中选用 Antigravity 模型的用户,可切换到原生 GenAI 客户端或 Chat Completions
|
||||
|
||||
## 新增功能
|
||||
|
||||
- Antigravity OAuth 账号可开启自动使用 Google AI 点数,套餐额度耗尽后按上游余额和最低使用门槛继续生成
|
||||
- 中间件可用 `omitBodyAt` 省略指定阶段的请求正文,或用 `websocketErrorCodes` 仅订阅指定的 Responses WebSocket 下行错误
|
||||
|
||||
## 优化改进
|
||||
|
||||
- Chat Completions 直接适配 Responses、Messages 和 GenAI 上游,支持 JSON 和 SSE
|
||||
- Antigravity 原生 GenAI 接口支持 `x-goog-api-key` 传入网关 Client Key,桌面端和 CLI 按 Google 的菜单顺序显示当前 Key 可用的型号
|
||||
- xAI 原生 Responses 请求保留工具、推理参数和上游续接语义
|
||||
|
||||
## 问题修复
|
||||
|
||||
- Antigravity OAuth 账号的额度面板补上「额度点数」入口,可查看 Google AI 点数余额并设置是否自动使用
|
||||
- Codex 压缩请求从 HTTP 进入且无需 WebSocket 时,默认沿用 HTTP/SSE
|
||||
- Antigravity 刷新额度后,账号页使用 Google 返回的套餐描述
|
||||
- Antigravity 的新请求记录恢复显示请求发生时的订阅名称
|
||||
- 管理端与 Client Key 用量明细的思考档位列统一左对齐
|
||||
|
||||
## 升级须知
|
||||
|
||||
- 原生 Responses、Messages 和 GenAI 请求只匹配支持对应协议的上游;此前通过 Responses 调用已导入的 Messages API Key 账号时,请切换到 `/v1/messages` 或 `/v1/chat/completions`
|
||||
- Codex 模型目录只显示当前 Key 可通过 Responses 执行的模型,Antigravity 模型请通过原生 GenAI 客户端或 Chat Completions 调用
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.56.0
|
||||
version: 3.56.1
|
||||
published:
|
||||
'3':
|
||||
stable: 3.55.3
|
||||
rc: 3.55.3
|
||||
beta: 3.55.3
|
||||
alpha: 3.55.3
|
||||
stable: 3.56.1
|
||||
rc: 3.56.1
|
||||
beta: 3.56.1
|
||||
alpha: 3.56.1
|
||||
|
||||
Reference in New Issue
Block a user