mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-01 16:01:04 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
914c4c24d3 | ||
|
|
7251546c75 | ||
|
|
3c38925716 | ||
|
|
43ca35b027 | ||
|
|
95d545a7d8 | ||
|
|
db3324f90a | ||
|
|
30bcff3419 | ||
|
|
329503d967 | ||
|
|
eae19e211e | ||
|
|
294e9c8bd8 | ||
|
|
1b92c552b9 | ||
|
|
c9fb2ac465 | ||
|
|
6bf109e784 | ||
|
|
fa187c5031 | ||
|
|
5f7e1723f3 | ||
|
|
7d34be5d02 | ||
|
|
ebb3c4b1fa |
@@ -21,6 +21,9 @@
|
||||
|
||||
普通维护和新增业务页面沿用现有设计;设计技能中的配色、字体、布局探索不覆盖项目规范,主题算法只在涉及时读取
|
||||
|
||||
- 页面和组件不添加浏览器原生提示的 `title` 属性。确需补充说明时,按内容复用已有的 Tooltip 或 Popover
|
||||
- 列表行需要快速展示少量字段时,先核对列表接口已返回的字段和后端查询已读取的数据。能随当前页低成本返回的字段直接用于展示,完整详情在用户打开详情时加载
|
||||
|
||||
## 验收范围与收尾
|
||||
|
||||
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
|
||||
|
||||
@@ -55,7 +55,7 @@ pub struct AccountImportSettings {
|
||||
/// 账号列表排序字段
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AccountSortField {
|
||||
Email,
|
||||
Name,
|
||||
Status,
|
||||
PlanType,
|
||||
Usage,
|
||||
|
||||
@@ -889,12 +889,14 @@ impl UsageErrorOrigin {
|
||||
}
|
||||
|
||||
/// 使用记录表格的窄读模型
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct UsageListRecord {
|
||||
pub platform_icon: Option<String>,
|
||||
pub outcome: RequestOutcome,
|
||||
/// 已保存的上游错误对象含非空字符串 code、type 或 message
|
||||
pub has_upstream_error: bool,
|
||||
pub upstream_error_message: Option<String>,
|
||||
pub retry_after_ms: Option<u64>,
|
||||
pub error_code: Option<String>,
|
||||
pub error_message: Option<String>,
|
||||
pub error_kind: Option<String>,
|
||||
@@ -961,6 +963,17 @@ pub struct UsageListRecord {
|
||||
pub started_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// 上游错误原文只交付给管理端,避免整行调试输出带出正文
|
||||
impl std::fmt::Debug for UsageListRecord {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("UsageListRecord")
|
||||
.field("id", &self.id)
|
||||
.field("outcome", &self.outcome)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// 受控请求详情中的上游错误字段,不参与错误分类或普通日志输出
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct UsageUpstreamError {
|
||||
@@ -1169,6 +1182,7 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
@@ -1647,6 +1661,7 @@ pub struct DiagnosticsItem {
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
/// 仅账号维度补充当前互联识别结果
|
||||
|
||||
@@ -1342,7 +1342,8 @@ impl AccountsService for DefaultAccountsService {
|
||||
.map(ToOwned::to_owned);
|
||||
let upstream_body = error
|
||||
.upstream_response()
|
||||
.map(|response| String::from_utf8_lossy(response.body()).into_owned());
|
||||
.and_then(gateway_core::engine::probe::AccountProbeUpstreamResponse::body)
|
||||
.map(|body| String::from_utf8_lossy(body).into_owned());
|
||||
let message = error.client_message().to_owned();
|
||||
vec![AccountConnectionTestEvent::Failed {
|
||||
source: error.source(),
|
||||
|
||||
@@ -379,6 +379,7 @@ impl ObservabilityService for DefaultObservabilityService {
|
||||
account_upstream_peer: peers.get(&item.key).copied(),
|
||||
key: item.key,
|
||||
name: item.name,
|
||||
account_email: item.account_email,
|
||||
account_authentication_kind: item.account_authentication_kind,
|
||||
account_plan_type_display: self.historical_plan_display(
|
||||
item.account_plan_type_display,
|
||||
|
||||
@@ -454,6 +454,8 @@ fn total_record(
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
upstream_error_message: None,
|
||||
retry_after_ms: None,
|
||||
error_code: None,
|
||||
error_message: None,
|
||||
error_kind: None,
|
||||
@@ -550,6 +552,7 @@ fn diagnostic(name: &str, request_count: u64) -> DiagnosticObservation {
|
||||
account_plan_type_display: None,
|
||||
key: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
account_email: None,
|
||||
request_count,
|
||||
success_count: request_count,
|
||||
failure_count: 0,
|
||||
|
||||
@@ -203,7 +203,7 @@ fn parse_provider(value: &str) -> Result<Option<ProviderKind>, WireValidationErr
|
||||
|
||||
fn parse_sort_field(value: &str) -> Option<AccountSortField> {
|
||||
match value.trim() {
|
||||
"email" => Some(AccountSortField::Email),
|
||||
"name" => Some(AccountSortField::Name),
|
||||
"status" => Some(AccountSortField::Status),
|
||||
"planType" => Some(AccountSortField::PlanType),
|
||||
"usage" => Some(AccountSortField::Usage),
|
||||
|
||||
@@ -263,6 +263,8 @@ pub(crate) fn usage_list_record_view(
|
||||
upstream_status_code: record.upstream_status_code,
|
||||
error_code: record.error_code,
|
||||
error_message: record.error_message,
|
||||
upstream_error_message: record.upstream_error_message,
|
||||
retry_after_ms: record.retry_after_ms,
|
||||
error_kind: record.error_kind,
|
||||
websocket_close_code: record.websocket_close_code,
|
||||
continuation_unavailable_reason: record.continuation_unavailable_reason,
|
||||
@@ -1354,13 +1356,14 @@ pub(crate) fn diagnostics_view(
|
||||
.map(|item| DiagnosticItemView {
|
||||
providers: item.providers,
|
||||
platform_icon: item.platform_icon,
|
||||
key: item.key,
|
||||
account_email: item.account_email,
|
||||
authentication_kind: item.account_authentication_kind,
|
||||
name: if item.name == "__none__" {
|
||||
name: if item.key == "__none__" {
|
||||
"未知".to_owned()
|
||||
} else {
|
||||
item.name
|
||||
},
|
||||
key: item.key,
|
||||
request_count: item.request_count,
|
||||
account_plan_type: item.account_plan_type,
|
||||
account_plan_type_display: item.account_plan_type_display,
|
||||
|
||||
@@ -92,6 +92,8 @@ pub struct UsageListRecordView {
|
||||
pub upstream_status_code: Option<u16>,
|
||||
pub error_code: Option<String>,
|
||||
pub error_message: Option<String>,
|
||||
pub upstream_error_message: Option<String>,
|
||||
pub retry_after_ms: Option<u64>,
|
||||
pub error_kind: Option<String>,
|
||||
pub websocket_close_code: Option<u16>,
|
||||
pub continuation_unavailable_reason: Option<String>,
|
||||
@@ -878,6 +880,7 @@ pub struct DiagnosticItemView {
|
||||
pub platform_icon: Option<String>,
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub authentication_kind: Option<String>,
|
||||
pub account_plan_type: Option<String>,
|
||||
pub account_plan_type_display: Option<String>,
|
||||
|
||||
@@ -72,10 +72,6 @@ pub(crate) fn client_error_code(code: &str) -> &str {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_retry_after_header(name: &str) -> bool {
|
||||
name.eq_ignore_ascii_case("retry-after") || name.eq_ignore_ascii_case("retry-after-ms")
|
||||
}
|
||||
|
||||
/// 为 HTTP 错误或流内失败保留原有字段,仅投影客户端需要的重试信号
|
||||
pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
||||
const CODE_PATHS: [&str; 2] = ["/error/code", "/response/error/code"];
|
||||
@@ -91,12 +87,6 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
||||
return None;
|
||||
}
|
||||
let mut projected = data.clone();
|
||||
// 容量等待与换号已由网关执行;旧账号的等待提示不能再次阻塞客户端的新一轮路由
|
||||
for path in ["/headers", "/error/headers", "/response/error/headers"] {
|
||||
if let Some(Value::Object(headers)) = projected.pointer_mut(path) {
|
||||
headers.retain(|name, _| !is_retry_after_header(name));
|
||||
}
|
||||
}
|
||||
for path in CODE_PATHS {
|
||||
if let Some(code) = projected.pointer_mut(path)
|
||||
&& capacity_code(code)
|
||||
|
||||
@@ -15,7 +15,7 @@ use serde_json::{Value, json};
|
||||
|
||||
pub use gateway_core::engine::execution::gateway_error_from_engine;
|
||||
|
||||
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client, is_retry_after_header};
|
||||
use crate::client_error::{ProtocolErrorBody, capacity_error_for_client};
|
||||
|
||||
pub use crate::client_error::{
|
||||
gateway_error_contract, gateway_error_response, openai_error_response,
|
||||
@@ -109,6 +109,29 @@ pub fn model_not_found_response() -> (StatusCode, Json<Value>) {
|
||||
)
|
||||
}
|
||||
|
||||
/// 已提交的 Responses 流通过终止事件交付容量错误的等待头
|
||||
pub(crate) fn capacity_retry_headers(error: &EngineError) -> serde_json::Map<String, Value> {
|
||||
let mut headers = serde_json::Map::new();
|
||||
if let EngineError::Provider(provider) = error
|
||||
&& provider.kind() == ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
&& let Some(response) = provider.client_visible_upstream_response()
|
||||
{
|
||||
for header in response.headers() {
|
||||
if (header.name().eq_ignore_ascii_case("retry-after")
|
||||
|| header.name().eq_ignore_ascii_case("retry-after-ms"))
|
||||
&& let Ok(value) = HeaderValue::from_bytes(header.value())
|
||||
&& let Ok(value) = value.to_str()
|
||||
{
|
||||
headers.insert(
|
||||
header.name().to_ascii_lowercase(),
|
||||
Value::String(value.to_owned()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
/// 在下游尚未提交时交付 Provider 的 HTTP 失败响应,并应用客户端容量恢复合同
|
||||
pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
let capacity_unavailable = matches!(error, EngineError::Provider(error)
|
||||
@@ -122,7 +145,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
let projected = serde_json::from_slice::<Value>(upstream.body())
|
||||
.ok()
|
||||
.and_then(|body| capacity_error_for_client(&body));
|
||||
let suppress_retry_after = capacity_unavailable || projected.is_some();
|
||||
let mut response = match projected {
|
||||
Some(body) => {
|
||||
let mut response = Response::new(Body::from(body.to_string()));
|
||||
@@ -145,9 +167,6 @@ pub fn engine_error_response(error: &EngineError) -> Response {
|
||||
response.headers_mut().insert(CONTENT_TYPE, content_type);
|
||||
}
|
||||
for header in upstream.headers() {
|
||||
if suppress_retry_after && is_retry_after_header(header.name()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -830,7 +830,10 @@ impl StreamingExecutionBody {
|
||||
}
|
||||
Ok(None) => return Err(invalid_execution_stream()),
|
||||
Err(error) if self.committed => {
|
||||
self.push_stream_error(gateway_error_from_engine(&error));
|
||||
self.push_stream_error(
|
||||
gateway_error_from_engine(&error),
|
||||
crate::data_plane::error::capacity_retry_headers(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(MiddlewareError::Engine(error)),
|
||||
@@ -893,9 +896,13 @@ impl StreamingExecutionBody {
|
||||
}
|
||||
}
|
||||
|
||||
fn push_stream_error(&mut self, error: GatewayError) {
|
||||
fn push_stream_error(
|
||||
&mut self,
|
||||
error: GatewayError,
|
||||
headers: serde_json::Map<String, serde_json::Value>,
|
||||
) {
|
||||
self.pending.push_back(MiddlewareFrame::new(
|
||||
self.encoder.error_frame(&error),
|
||||
self.encoder.error_frame(&error, headers),
|
||||
MiddlewareFraming::SseEvent,
|
||||
false,
|
||||
));
|
||||
@@ -935,7 +942,7 @@ impl MiddlewareBody for StreamingExecutionBody {
|
||||
"Gateway response stream could not be delivered.",
|
||||
),
|
||||
};
|
||||
self.push_stream_error(error);
|
||||
self.push_stream_error(error, Default::default());
|
||||
}
|
||||
Ok(self.pending.pop_front())
|
||||
})
|
||||
@@ -972,7 +979,7 @@ impl MiddlewareBody for StreamingExecutionBody {
|
||||
"The Chat response could not be finalized.",
|
||||
),
|
||||
};
|
||||
self.push_stream_error(error);
|
||||
self.push_stream_error(error, Default::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
|
||||
use gateway_protocol::{
|
||||
anthropic::MessagesAccumulator,
|
||||
openai::sse::{
|
||||
DONE_SSE_FRAME, encode_sse_event_with_metadata, response_failed_sse_event_with_id,
|
||||
DONE_SSE_FRAME, encode_sse_event, encode_sse_event_with_metadata,
|
||||
response_failed_sse_data_with_id,
|
||||
},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
@@ -159,7 +160,11 @@ impl GenerationEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
|
||||
pub(super) fn error_frame(
|
||||
&self,
|
||||
error: &GatewayError,
|
||||
headers: serde_json::Map<String, Value>,
|
||||
) -> Bytes {
|
||||
let (status, error_type, code) = gateway_error_contract(error.kind());
|
||||
match self {
|
||||
Self::Chat(_) => {
|
||||
@@ -169,12 +174,21 @@ impl GenerationEncoder {
|
||||
"message": error.client_message(),
|
||||
}}))
|
||||
}
|
||||
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id(
|
||||
encoder.response_id(),
|
||||
error.client_error_type().unwrap_or(error_type),
|
||||
crate::client_error::client_error_code(error.client_error_code().unwrap_or(code)),
|
||||
error.client_message(),
|
||||
)),
|
||||
Self::Responses(encoder) => {
|
||||
let mut data = response_failed_sse_data_with_id(
|
||||
encoder.response_id(),
|
||||
error.client_error_type().unwrap_or(error_type),
|
||||
crate::client_error::client_error_code(
|
||||
error.client_error_code().unwrap_or(code),
|
||||
),
|
||||
error.client_message(),
|
||||
);
|
||||
if !headers.is_empty() {
|
||||
data["response"]["error"]["headers"] = json!(headers);
|
||||
data["error"]["headers"] = Value::Object(headers);
|
||||
}
|
||||
Bytes::from(encode_sse_event("response.failed", &data.to_string()))
|
||||
}
|
||||
Self::GenAi { .. } => {
|
||||
crate::data_plane::genai::error_frame(status, error.client_message())
|
||||
}
|
||||
|
||||
@@ -575,7 +575,10 @@ impl WebSocketExecutionBody {
|
||||
Ok(Some(delivery)) => delivery,
|
||||
Ok(None) => return Err(MiddlewareError::InvalidState),
|
||||
Err(error) if self.committed => {
|
||||
self.push_gateway_error(gateway_error_from_engine(&error));
|
||||
self.push_gateway_error(
|
||||
gateway_error_from_engine(&error),
|
||||
crate::data_plane::error::capacity_retry_headers(&error),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(MiddlewareError::Engine(error)),
|
||||
@@ -635,7 +638,11 @@ impl WebSocketExecutionBody {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn push_gateway_error(&mut self, error: GatewayError) {
|
||||
fn push_gateway_error(
|
||||
&mut self,
|
||||
error: GatewayError,
|
||||
headers: serde_json::Map<String, serde_json::Value>,
|
||||
) {
|
||||
let (status, default_type, default_code) = gateway_error_contract(error.kind());
|
||||
self.pending.push_back(MiddlewareFrame::new(
|
||||
Bytes::from(
|
||||
@@ -646,7 +653,7 @@ impl WebSocketExecutionBody {
|
||||
error.client_message(),
|
||||
None,
|
||||
Some(&self.request_id),
|
||||
serde_json::Map::new(),
|
||||
headers,
|
||||
)
|
||||
.to_string(),
|
||||
),
|
||||
|
||||
@@ -126,7 +126,7 @@ mod query {
|
||||
"provider": "xai",
|
||||
"search": " operator ",
|
||||
"status": "normal",
|
||||
"sortBy": "lastUsedAt",
|
||||
"sortBy": "name",
|
||||
"sortDirection": "desc"
|
||||
}))
|
||||
.expect("deserialize account query");
|
||||
@@ -139,10 +139,7 @@ mod query {
|
||||
));
|
||||
assert_eq!(query.search.as_deref(), Some("operator"));
|
||||
assert_eq!(query.status, Some(AccountStatus::Normal));
|
||||
assert_eq!(
|
||||
query.sort.expect("sort").field,
|
||||
AccountSortField::LastUsedAt
|
||||
);
|
||||
assert_eq!(query.sort.expect("sort").field, AccountSortField::Name);
|
||||
assert_eq!(
|
||||
query.sort.expect("copy sort").direction,
|
||||
SortDirection::Desc
|
||||
|
||||
@@ -753,7 +753,8 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
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(),
|
||||
account_email: Some("diag@example.invalid".to_owned()),
|
||||
name: "__none__".to_owned(),
|
||||
request_count: 2,
|
||||
success_count: 2,
|
||||
failure_count: 0,
|
||||
@@ -813,11 +814,13 @@ async fn diagnostics_should_keep_stable_key_and_display_name_contract() {
|
||||
(
|
||||
&value["data"]["items"][0]["key"],
|
||||
&value["data"]["items"][0]["name"],
|
||||
&value["data"]["items"][0]["accountEmail"],
|
||||
&value["data"]["items"][0]["latencyP95Ms"],
|
||||
&value["data"]["dimension"],
|
||||
),
|
||||
(
|
||||
&serde_json::json!("acct_diag"),
|
||||
&serde_json::json!("__none__"),
|
||||
&serde_json::json!("diag@example.invalid"),
|
||||
&serde_json::json!(3800),
|
||||
&serde_json::json!("account"),
|
||||
@@ -987,6 +990,8 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
upstream_error_message: None,
|
||||
retry_after_ms: None,
|
||||
error_code: None,
|
||||
error_message: None,
|
||||
error_kind: None,
|
||||
@@ -1089,6 +1094,8 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
failed.upstream_status_code = Some(429);
|
||||
failed.error_code = Some("server_error".to_owned());
|
||||
failed.error_message = Some("The upstream service is temporarily unavailable.".to_owned());
|
||||
failed.upstream_error_message = Some("Retry once capacity is available.".to_owned());
|
||||
failed.retry_after_ms = Some(30_000);
|
||||
records.push(failed);
|
||||
let mut closed = records[0].clone();
|
||||
closed.id = "request_ws_closed".to_owned();
|
||||
@@ -1131,6 +1138,11 @@ async fn usage_route_projects_request_facts_and_billing() {
|
||||
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");
|
||||
assert_eq!(
|
||||
value["data"]["items"][3]["upstreamErrorMessage"],
|
||||
"Retry once capacity is available."
|
||||
);
|
||||
assert_eq!(value["data"]["items"][3]["retryAfterMs"], 30_000);
|
||||
assert_eq!(value["data"]["items"][3]["clientStatusCode"], 503);
|
||||
assert_eq!(value["data"]["items"][3]["upstreamStatusCode"], 429);
|
||||
assert_eq!(value["data"]["items"][3]["errorOrigin"], "upstream");
|
||||
|
||||
@@ -1540,7 +1540,7 @@ async fn runtime_settings_reject_incomplete_and_stale_replacements() {
|
||||
);
|
||||
assert_eq!(
|
||||
initial["openaiRequestSettings"]["requestCountry"],
|
||||
json!({"mode":"follow_location"})
|
||||
json!({"mode":"default"})
|
||||
);
|
||||
let mut body = update_body();
|
||||
body["configRevision"] = initial["configRevision"].clone();
|
||||
|
||||
@@ -101,8 +101,8 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
if raw_response {
|
||||
assert_eq!(response.headers()["x-request-id"], "req_capacity");
|
||||
assert!(!response.headers().contains_key("retry-after"));
|
||||
assert!(!response.headers().contains_key("retry-after-ms"));
|
||||
assert_eq!(response.headers()["retry-after"], "7");
|
||||
assert_eq!(response.headers()["retry-after-ms"], "7000");
|
||||
}
|
||||
let body: Value = serde_json::from_slice(
|
||||
&to_bytes(response.into_body(), 4096)
|
||||
@@ -116,7 +116,6 @@ async fn capacity_errors_offer_client_retry_without_changing_upstream_facts() {
|
||||
if raw_response {
|
||||
let mut expected = original.clone();
|
||||
expected["error"]["code"] = json!("server_error");
|
||||
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
|
||||
assert_eq!(body, expected);
|
||||
}
|
||||
let EngineError::Provider(provider) = error else {
|
||||
|
||||
@@ -2214,14 +2214,13 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
|
||||
|
||||
#[tokio::test]
|
||||
async fn streaming_upstream_error_event_should_be_translated_to_response_failed_for_sse() {
|
||||
for (error_type, code, client_code, kind, client_status, keeps_retry_after) in [
|
||||
for (error_type, code, client_code, kind, client_status) in [
|
||||
(
|
||||
"service_unavailable_error",
|
||||
"server_is_overloaded",
|
||||
"server_error",
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
503,
|
||||
false,
|
||||
),
|
||||
(
|
||||
"rate_limit_error",
|
||||
@@ -2229,7 +2228,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
"turn_rate_limit_exceeded",
|
||||
ProviderErrorKind::RateLimited,
|
||||
429,
|
||||
true,
|
||||
),
|
||||
] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
@@ -2306,16 +2304,17 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||
.expect("translated response.failed event");
|
||||
let failed: Value = serde_json::from_str(&failed.data).expect("response.failed JSON");
|
||||
let mut expected = json!({
|
||||
let expected = json!({
|
||||
"type": "response.failed",
|
||||
"status": client_status,
|
||||
"headers": {"x-request-id": "req_test"},
|
||||
"headers": {"Retry-After": "24", "retry-after-ms": "24000", "x-request-id": "req_test"},
|
||||
"response": {
|
||||
"id": "resp_test",
|
||||
"model": "public-model",
|
||||
"status": "failed",
|
||||
"error": {
|
||||
"type": error_type,
|
||||
"headers": {"retry-after": "24", "retry-after-ms": "24000"},
|
||||
"code": client_code,
|
||||
"message": "Our servers are currently overloaded. Please try again later.",
|
||||
"param": null,
|
||||
@@ -2326,11 +2325,6 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
"sequence_number": 2,
|
||||
"future_event_field": {"keep": true}
|
||||
});
|
||||
if keeps_retry_after {
|
||||
expected["headers"]["Retry-After"] = json!("24");
|
||||
expected["headers"]["retry-after-ms"] = json!("24000");
|
||||
expected["response"]["error"]["headers"] = json!({"retry-after": "24"});
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
@@ -2347,12 +2341,23 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
||||
|
||||
#[tokio::test]
|
||||
async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
||||
for code in ["server_is_overloaded", "slow_down"] {
|
||||
for (code, expected) in [
|
||||
("server_is_overloaded", "server_error"),
|
||||
("slow_down", "server_error"),
|
||||
("previous_response_not_found", "previous_response_not_found"),
|
||||
] {
|
||||
let trace = Arc::new(Trace::default());
|
||||
let error = ProviderError::new(
|
||||
ProviderErrorKind::UpstreamCapacityUnavailable,
|
||||
UpstreamSendState::Sent,
|
||||
)
|
||||
.with_client_visible_upstream_response(
|
||||
ClientVisibleUpstreamResponse::new(400, None, Bytes::new()).with_headers(vec![
|
||||
ProviderResponseHeader::new("Retry-After", Bytes::from_static(b"309")),
|
||||
ProviderResponseHeader::new("retry-after-ms", Bytes::from_static(b"309001")),
|
||||
ProviderResponseHeader::new("x-unrelated", Bytes::from_static(b"omit")),
|
||||
]),
|
||||
)
|
||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
"busy",
|
||||
Some(code.to_owned()),
|
||||
@@ -2377,7 +2382,11 @@ async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
||||
.find(|event| event.event.as_deref() == Some("response.failed"))
|
||||
.expect("failed event");
|
||||
let failed: Value = serde_json::from_str(&failed.data).expect("JSON");
|
||||
assert_eq!(failed["response"]["error"]["code"], "server_error");
|
||||
assert_eq!(failed["response"]["error"]["code"], expected);
|
||||
assert_eq!(
|
||||
failed["response"]["error"]["headers"],
|
||||
json!({"retry-after": "309", "retry-after-ms": "309001"})
|
||||
);
|
||||
assert_eq!(failed["response"]["error"]["message"], "busy");
|
||||
assert_eq!(text.matches("event: response.failed").count(), 1);
|
||||
assert!(text.ends_with("data: [DONE]\n\n"));
|
||||
|
||||
@@ -1256,16 +1256,12 @@ fn capacity_failure_projection_preserves_wire_metadata_and_original_events() {
|
||||
assert_eq!(sse_data["response"]["error"]["code"], "server_error");
|
||||
assert_eq!(sse_data["response"]["error"]["message"], "busy");
|
||||
assert_eq!(sse_data["response"]["error"]["future"], 42);
|
||||
assert_eq!(
|
||||
sse_data["response"]["error"]["headers"],
|
||||
json!({"x-request-id":"req_capacity"})
|
||||
);
|
||||
assert_eq!(sse_data["response"]["error"]["headers"], error["headers"]);
|
||||
let messages = ws.push_websocket(&event);
|
||||
let ws_data: Value = serde_json::from_str(&messages[0]).expect("JSON");
|
||||
if event_type == "error" && status.is_some() {
|
||||
let mut expected = original.clone();
|
||||
expected["error"]["code"] = json!("server_error");
|
||||
expected["error"]["headers"] = json!({"x-request-id":"req_capacity"});
|
||||
expected["status_code"] = json!(503);
|
||||
assert_eq!(ws_data, expected);
|
||||
} else {
|
||||
|
||||
@@ -340,8 +340,8 @@ async fn initial_capacity_failure_offers_client_retry_with_upstream_correlation(
|
||||
assert_eq!(error["error"]["code"], "server_error");
|
||||
assert_eq!(error["error"]["message"], "busy");
|
||||
assert_eq!(error["headers"]["x-request-id"], "req_capacity");
|
||||
assert!(error["headers"].get("retry-after").is_none());
|
||||
assert!(error["headers"].get("retry-after-ms").is_none());
|
||||
assert_eq!(error["headers"]["retry-after"], "7");
|
||||
assert_eq!(error["headers"]["retry-after-ms"], "7000");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,8 @@ fn usage_record() -> UsageListRecord {
|
||||
platform_icon: None,
|
||||
provider_account_upstream_peer: None,
|
||||
has_upstream_error: false,
|
||||
upstream_error_message: Some("private-sentinel-upstream".into()),
|
||||
retry_after_ms: Some(30_000),
|
||||
error_code: None,
|
||||
error_message: None,
|
||||
error_kind: None,
|
||||
|
||||
@@ -1480,7 +1480,7 @@ where
|
||||
&& let Some(original) = self.last_retryable_failure.take()
|
||||
{
|
||||
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
||||
error = original.with_client_recovery_from(error);
|
||||
error = original.with_client_recovery_from(error, &self.last_retryable_failure_events);
|
||||
self.last_retryable_failure_events.clear();
|
||||
}
|
||||
let kind = error.kind();
|
||||
|
||||
@@ -1547,11 +1547,8 @@ impl DefaultExecutionService {
|
||||
) -> AccountProbeError {
|
||||
let (source, send_state, upstream_response) = match error {
|
||||
EngineError::Provider(provider_error) => {
|
||||
let upstream_response = provider_error
|
||||
.client_visible_upstream_response()
|
||||
.map(AccountProbeUpstreamResponse::from_client_response);
|
||||
let upstream_response = AccountProbeUpstreamResponse::from_provider(provider_error);
|
||||
let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent
|
||||
|| provider_error.upstream_status().is_some()
|
||||
|| provider_error.upstream_code().is_some()
|
||||
|| provider_error.client_visible_upstream_error().is_some()
|
||||
|| upstream_response.is_some();
|
||||
|
||||
@@ -5,9 +5,7 @@ use std::fmt;
|
||||
use bytes::Bytes;
|
||||
use futures::future::BoxFuture;
|
||||
|
||||
use crate::error::{
|
||||
ClientVisibleUpstreamResponse, GatewayError, GatewayErrorKind, ProxyConnectionHint,
|
||||
};
|
||||
use crate::error::{GatewayError, GatewayErrorKind, ProviderError, ProxyConnectionHint};
|
||||
use crate::identity::ProviderKind;
|
||||
use crate::routing::UpstreamModelId;
|
||||
use crate::{
|
||||
@@ -60,16 +58,18 @@ pub struct AccountProbeResult {
|
||||
pub struct AccountProbeUpstreamResponse {
|
||||
status: u16,
|
||||
content_type: Option<Vec<u8>>,
|
||||
body: Bytes,
|
||||
body: Option<Bytes>,
|
||||
}
|
||||
|
||||
impl AccountProbeUpstreamResponse {
|
||||
pub(crate) fn from_client_response(response: &ClientVisibleUpstreamResponse) -> Self {
|
||||
Self {
|
||||
status: response.status(),
|
||||
content_type: response.content_type().map(<[u8]>::to_vec),
|
||||
body: response.body().clone(),
|
||||
}
|
||||
pub(crate) fn from_provider(error: &ProviderError) -> Option<Self> {
|
||||
let response = error.client_visible_upstream_response();
|
||||
// 即使没有可展示的响应正文,Provider 收到的状态码仍可用于诊断
|
||||
Some(Self {
|
||||
status: response.map(|r| r.status()).or(error.upstream_status())?,
|
||||
content_type: response.and_then(|r| r.content_type()).map(<[u8]>::to_vec),
|
||||
body: response.map(|r| r.body().clone()),
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -83,8 +83,8 @@ impl AccountProbeUpstreamResponse {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn body(&self) -> &Bytes {
|
||||
&self.body
|
||||
pub const fn body(&self) -> Option<&Bytes> {
|
||||
self.body.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ impl fmt::Debug for AccountProbeUpstreamResponse {
|
||||
"content_type",
|
||||
&self.content_type.as_ref().map(|_| "<present>"),
|
||||
)
|
||||
.field("body", &"<redacted>")
|
||||
.field("body", &self.body.as_ref().map(|_| "<redacted>"))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1094,7 +1094,43 @@ impl ProviderError {
|
||||
}
|
||||
|
||||
/// 绑定迁移完成后仅替换客户端恢复投影,保留原始失败的诊断与计费事实
|
||||
pub(crate) fn with_client_recovery_from(mut self, recovery: Self) -> Self {
|
||||
pub(crate) fn with_client_recovery_from(
|
||||
mut self,
|
||||
mut recovery: Self,
|
||||
events: &[ProviderEvent],
|
||||
) -> Self {
|
||||
if self.kind() == ProviderErrorKind::UpstreamCapacityUnavailable
|
||||
&& let Some(response) = recovery.client_visible_upstream_response.as_deref_mut()
|
||||
{
|
||||
// 迁移响应继承原失败的等待头;其余旧账号头和错误正文不属于新响应
|
||||
let original = self.client_visible_upstream_response();
|
||||
let body = original.and_then(|original| serde_json::from_slice(original.body()).ok());
|
||||
let event = events
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(ProviderEvent::wire_event)
|
||||
.map(|wire| wire.data());
|
||||
for name in ["retry-after", "retry-after-ms"] {
|
||||
if let Some(header) = original.and_then(|original| {
|
||||
original
|
||||
.headers()
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|h| h.name().eq_ignore_ascii_case(name))
|
||||
}) {
|
||||
response.headers.push(header.clone());
|
||||
} else if let Some(value) =
|
||||
event.into_iter().chain(body.as_ref()).find_map(|value| {
|
||||
gateway_protocol::openai::events::error_event_header(value, name)
|
||||
})
|
||||
{
|
||||
response.headers.push(ProviderResponseHeader::new(
|
||||
name,
|
||||
Bytes::copy_from_slice(value.as_bytes()),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(reason) = recovery.continuation_unavailable_reason() {
|
||||
self = self.with_continuation_unavailable_reason(reason);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ impl Default for OpenAiRequestSettings {
|
||||
Self {
|
||||
request_country: Default::default(),
|
||||
oauth_guardian_review_model: true,
|
||||
residency: Some("us".to_owned()),
|
||||
residency: None,
|
||||
account_routing_override: None,
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ pub enum OpenAiRequestCountry {
|
||||
|
||||
impl Default for OpenAiRequestCountry {
|
||||
fn default() -> Self {
|
||||
Self::FollowLocation {}
|
||||
Self::Default {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2525,11 +2525,33 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
||||
.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
);
|
||||
let original = if committed_prelude {
|
||||
let event = json!({"type":"response.failed", "response":{"error":{
|
||||
"headers":{"Retry-After":seconds.to_string(), "Retry-After-Ms":"317001", "x-private":"omit"}
|
||||
}}});
|
||||
original.with_atomic_client_events(vec![ProviderEvent::wire(
|
||||
ProtocolWireEvent::json("openai", Some("response.failed".to_owned()), event)
|
||||
.unwrap(),
|
||||
)])
|
||||
} else {
|
||||
original.with_client_visible_upstream_response(
|
||||
ClientVisibleUpstreamResponse::new(503, None, Bytes::from(original_body.clone()))
|
||||
.with_headers(vec![gateway_core::event::ProviderResponseHeader::new(
|
||||
"Retry-After-Ms",
|
||||
Bytes::from_static(b"309001"),
|
||||
)]),
|
||||
)
|
||||
};
|
||||
let recovery = if replacement {
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::ContinuationRecoveryRequired,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
|
||||
400,
|
||||
None,
|
||||
Bytes::from_static(b"{}"),
|
||||
))
|
||||
.with_continuation_unavailable_reason("account_rotated")
|
||||
.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
@@ -2602,6 +2624,29 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
||||
error.continuation_unavailable_reason(),
|
||||
(replacement && expected_attempts == 2).then_some("account_rotated")
|
||||
);
|
||||
if replacement && expected_attempts == 2 {
|
||||
let response = error.client_visible_upstream_response().unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
let headers: Vec<_> = response
|
||||
.headers()
|
||||
.iter()
|
||||
.map(|header| (header.name().to_ascii_lowercase(), header.value().as_ref()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
headers,
|
||||
vec![
|
||||
("retry-after".to_owned(), seconds.to_string().as_bytes()),
|
||||
(
|
||||
"retry-after-ms".to_owned(),
|
||||
if committed_prelude {
|
||||
b"317001"
|
||||
} else {
|
||||
b"309001"
|
||||
}
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
let contexts = provider.contexts.lock().unwrap();
|
||||
assert_eq!(contexts.len(), expected_attempts);
|
||||
if contexts.len() == 2 {
|
||||
|
||||
@@ -3509,8 +3509,10 @@ fn account_probe_should_not_write_to_the_persistent_execution_store() {
|
||||
#[test]
|
||||
fn probe_failures_should_be_observable_without_a_model_request_row() {
|
||||
let store = Arc::new(TrackingExecutionStore::default());
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let providers = ProviderRegistry::new([
|
||||
Arc::new(FailingProvider { include_body: true }) as Arc<dyn Provider>
|
||||
])
|
||||
.expect("provider registry");
|
||||
let service = DefaultExecutionService::new(
|
||||
RuntimeSnapshotHandle::new(probe_snapshot()),
|
||||
store.clone(),
|
||||
@@ -3547,7 +3549,9 @@ fn probe_failures_should_be_observable_without_a_model_request_row() {
|
||||
);
|
||||
assert_eq!(
|
||||
upstream.body(),
|
||||
&Bytes::from_static(br#"{"error":{"message":"source upstream failure"}}"#),
|
||||
Some(&Bytes::from_static(
|
||||
br#"{"error":{"message":"source upstream failure"}}"#
|
||||
)),
|
||||
);
|
||||
assert!(!format!("{error:?}").contains("source upstream failure"));
|
||||
assert!(!store.touched.load(Ordering::SeqCst));
|
||||
@@ -3687,8 +3691,10 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
|
||||
fail_probe_observation: AtomicBool::new(true),
|
||||
..TrackingExecutionStore::default()
|
||||
});
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider {
|
||||
include_body: false,
|
||||
}) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let service = DefaultExecutionService::new(
|
||||
RuntimeSnapshotHandle::new(probe_snapshot()),
|
||||
store.clone(),
|
||||
@@ -3715,9 +3721,15 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
|
||||
assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert!(!store.touched.load(Ordering::SeqCst));
|
||||
assert!(store.probe_failures().is_empty());
|
||||
let upstream = error.upstream_response().unwrap();
|
||||
assert_eq!(upstream.status(), 403);
|
||||
assert!(upstream.body().is_none());
|
||||
assert!(upstream.content_type().is_none());
|
||||
}
|
||||
|
||||
struct FailingProvider;
|
||||
struct FailingProvider {
|
||||
include_body: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CatalogProvider {
|
||||
@@ -4055,6 +4067,13 @@ impl Provider for FailingProvider {
|
||||
_request: ProviderRequest,
|
||||
_context: AttemptContext,
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
if !self.include_body {
|
||||
return Err(ProviderError::new(
|
||||
ProviderErrorKind::PermissionDenied,
|
||||
UpstreamSendState::Sent,
|
||||
)
|
||||
.with_status(403));
|
||||
}
|
||||
Err(
|
||||
ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent)
|
||||
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
|
||||
|
||||
@@ -2617,7 +2617,7 @@ fn global_request_location_should_be_frozen_when_snapshot_is_published() {
|
||||
assert_eq!(
|
||||
plan(&handle.acquire().unwrap()).openai_request_settings(),
|
||||
&gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: None,
|
||||
request_country: OpenAiRequestCountry::FollowLocation {},
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
||||
@@ -228,12 +228,32 @@ fn retry_after_seconds_field(value: &Value) -> Option<u64> {
|
||||
|
||||
/// 同时保留原始头值与解析秒数,供事件转换和重试观测共用官方头部规则
|
||||
pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
|
||||
let (value, header) = event_header(value, "retry-after")?;
|
||||
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
|
||||
Some((value, seconds))
|
||||
}
|
||||
|
||||
/// 从客户端可见的错误事件读取指定头,嵌套错误优先于事件头
|
||||
pub fn error_event_header(event: &Value, name: &str) -> Option<http::HeaderValue> {
|
||||
let error = event
|
||||
.pointer("/response/error")
|
||||
.or_else(|| event.get("error"));
|
||||
error
|
||||
.and_then(|error| event_header(error, name))
|
||||
.or_else(|| event_header(event, name))
|
||||
.map(|(_, header)| header)
|
||||
}
|
||||
|
||||
pub(super) fn event_header<'a>(
|
||||
value: &'a Value,
|
||||
wanted: &str,
|
||||
) -> Option<(&'a Value, http::HeaderValue)> {
|
||||
let headers = value.get("headers")?.as_object()?;
|
||||
// 官方先按 HTTP 头值校验,再覆盖大小写不同的同名头;最后才解释重试时间
|
||||
// 合法但无法解析为时间的末项也会覆盖前值,非法头值和数组不参与覆盖
|
||||
let (value, header) = headers
|
||||
headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case("retry-after"))
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case(wanted))
|
||||
.filter_map(|(_, value)| {
|
||||
let header = match value {
|
||||
Value::String(value) => http::HeaderValue::from_str(value).ok(),
|
||||
@@ -244,9 +264,7 @@ pub(super) fn retry_after_header(value: &Value) -> Option<(&Value, u64)> {
|
||||
}?;
|
||||
Some((value, header))
|
||||
})
|
||||
.next_back()?;
|
||||
let seconds = crate::http::parse_retry_after_seconds(header.to_str().ok()?)?;
|
||||
Some((value, seconds))
|
||||
.next_back()
|
||||
}
|
||||
|
||||
/// 判断上游错误是否携带 `x-retry-metadata: NO_MORE_RETRY`
|
||||
|
||||
@@ -322,9 +322,18 @@ pub fn response_failed_sse_data_from_error_event(
|
||||
let mut error = event.remove("error").filter(Value::is_object)?;
|
||||
// 官方 WS 先读错误头、再读事件头,SSE 只读 response.error.headers
|
||||
// 仅补充有效的等待建议,保留原始日期或秒数,不复制其他事件级响应头
|
||||
if super::events::retry_after_header(&error).is_none()
|
||||
&& let Some((retry_after, _)) = super::events::retry_after_header(error_event)
|
||||
{
|
||||
let seconds = super::events::retry_after_header(&error)
|
||||
.is_none()
|
||||
.then(|| super::events::retry_after_header(error_event))
|
||||
.flatten()
|
||||
.map(|(value, _)| value);
|
||||
let millis = super::events::event_header(&error, "retry-after-ms")
|
||||
.is_none()
|
||||
.then(|| super::events::event_header(error_event, "retry-after-ms"))
|
||||
.flatten()
|
||||
.map(|(value, _)| value);
|
||||
for (name, value) in [("retry-after", seconds), ("retry-after-ms", millis)] {
|
||||
let Some(value) = value else { continue };
|
||||
let headers = error
|
||||
.as_object_mut()?
|
||||
.entry("headers")
|
||||
@@ -333,8 +342,8 @@ pub fn response_failed_sse_data_from_error_event(
|
||||
*headers = json!({});
|
||||
}
|
||||
let headers = headers.as_object_mut()?;
|
||||
headers.retain(|name, _| !name.eq_ignore_ascii_case("retry-after"));
|
||||
headers.insert("retry-after".to_owned(), retry_after.clone());
|
||||
headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
|
||||
headers.insert(name.to_owned(), value.clone());
|
||||
}
|
||||
let mut response = response
|
||||
.and_then(Value::as_object)
|
||||
|
||||
@@ -634,6 +634,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
observations.push(DiagnosticObservation {
|
||||
key: key.clone(),
|
||||
name: key,
|
||||
account_email: None,
|
||||
providers: state.providers.iter().cloned().collect(),
|
||||
platform_icon: None,
|
||||
account_authentication_kind: None,
|
||||
@@ -672,9 +673,29 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
.map(|item| item.key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let statement = if dimension == DiagnosticDimension::Account {
|
||||
"select requested.id, coalesce(historical.provider_kind,a.provider_kind) as provider_kind, a.platform_icon, 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 provider_accounts a on a.id=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"
|
||||
"select requested.id, coalesce(h.provider_kind, a.provider_kind) as provider_kind,
|
||||
a.platform_icon, h.authentication_kind, h.plan_type, h.plan_type_display,
|
||||
coalesce(h.account_name, h.account_email, requested.id) as name, h.account_email
|
||||
from unnest($1::text[]) requested(id)
|
||||
left join provider_accounts a on a.id = requested.id
|
||||
left join lateral (
|
||||
select provider_kind, provider_account_authentication_kind_snapshot as authentication_kind,
|
||||
provider_account_plan_type_snapshot as plan_type,
|
||||
provider_account_plan_type_display_snapshot as plan_type_display,
|
||||
nullif(btrim(provider_account_name_snapshot), '') as account_name,
|
||||
nullif(btrim(provider_account_email_snapshot), '') as account_email
|
||||
from model_request_observations where provider_account_ref = requested.id
|
||||
order by started_at desc, id desc limit 1
|
||||
) h on true"
|
||||
} else {
|
||||
"select requested.id, null::text as provider_kind, null::text as platform_icon, 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"
|
||||
"select requested.id, null::text as provider_kind, null::text as platform_icon,
|
||||
null::text as authentication_kind, null::text as plan_type, null::text as plan_type_display,
|
||||
coalesce(h.client_api_key_name_snapshot, requested.id) as name, null::text as account_email
|
||||
from unnest($1::text[]) requested(id)
|
||||
left join lateral (
|
||||
select client_api_key_name_snapshot from model_request_observations
|
||||
where client_api_key_ref = requested.id order by started_at desc, id desc limit 1
|
||||
) h on true"
|
||||
};
|
||||
let labels = sqlx::query(statement)
|
||||
.bind(ids)
|
||||
@@ -685,6 +706,7 @@ impl<'a> AnalyticsSnapshot<'a> {
|
||||
let id: String = get(&row, "id")?;
|
||||
if let Some(item) = observations.iter_mut().find(|item| item.key == id) {
|
||||
item.name = get(&row, "name")?;
|
||||
item.account_email = get(&row, "account_email")?;
|
||||
item.providers = get::<Option<String>>(&row, "provider_kind")?
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
@@ -280,6 +280,7 @@ fn admin_diagnostic_observation(
|
||||
admin_observability::DiagnosticObservation {
|
||||
key: observation.key,
|
||||
name: observation.name,
|
||||
account_email: observation.account_email,
|
||||
providers: observation.providers,
|
||||
platform_icon: observation.platform_icon,
|
||||
account_authentication_kind: observation.account_authentication_kind,
|
||||
@@ -369,6 +370,8 @@ pub(crate) fn usage_list_record_from_row(
|
||||
)?;
|
||||
Ok(UsageListRecord {
|
||||
has_upstream_error: get(row, "has_upstream_error")?,
|
||||
upstream_error_message: get(row, "upstream_error_message")?,
|
||||
retry_after_ms: optional_unsigned(row, "retry_after_ms")?,
|
||||
error_code: get(row, "error_code")?,
|
||||
error_message: get(row, "error_message")?,
|
||||
error_kind: get(row, "error_kind")?,
|
||||
|
||||
@@ -384,6 +384,7 @@ pub struct DiagnosticsObservation {
|
||||
pub struct DiagnosticObservation {
|
||||
pub key: String,
|
||||
pub name: String,
|
||||
pub account_email: Option<String>,
|
||||
pub providers: Vec<String>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub account_authentication_kind: Option<String>,
|
||||
|
||||
@@ -130,7 +130,7 @@ pub(crate) fn push_usage_filter(
|
||||
pub(crate) const USAGE_LIST_RECORD_SELECT: &str =
|
||||
"select mr.id, mr.outcome, mr.provider_error_code as error_code, mr.error_message, mr.client_status_code, mr.client_api_key_name_snapshot as client_api_key_name, mr.endpoint, mr.client_transport, mr.requested_model_id,
|
||||
mr.error_kind, mr.upstream_status_code,
|
||||
facts.has_upstream_error, facts.websocket_close_code,
|
||||
facts.has_upstream_error, facts.websocket_close_code, facts.upstream_error_message, mr.retry_after_ms,
|
||||
mr.continuation_unavailable_reason, mr.upstream_connection_exit_reason,
|
||||
(mr.recovery_request_id is not null and mr.recovered_at is not null) as recovered,
|
||||
mr.provider_kind, mr.provider_account_ref,
|
||||
@@ -166,6 +166,13 @@ const SAVED_ERROR_FACTS: &str = "(select exists (
|
||||
) as field(value)
|
||||
where jsonb_typeof(field.value) = 'string' and field.value <> '\"\"'::jsonb
|
||||
) as has_upstream_error,
|
||||
coalesce(
|
||||
case when jsonb_typeof(saved_error.body -> 'message') = 'string'
|
||||
then nullif(saved_error.body ->> 'message', '') end,
|
||||
case when saved_upstream.body ->> 'type' = 'websocket.close'
|
||||
and jsonb_typeof(saved_upstream.body -> 'reason') = 'string'
|
||||
then nullif(saved_upstream.body ->> 'reason', '') end
|
||||
) as upstream_error_message,
|
||||
case when saved_upstream.body ->> 'type' = 'websocket.close'
|
||||
and jsonb_typeof(saved_upstream.body -> 'code') = 'number'
|
||||
and (saved_upstream.body ->> 'code') ~ '^[0-9]{1,5}$'
|
||||
|
||||
@@ -253,7 +253,9 @@ fn admin_account_order(sort: Option<AdminAccountSort>) -> String {
|
||||
return "a.id asc".to_owned();
|
||||
};
|
||||
let expression = match sort.field {
|
||||
AdminAccountSortField::Email => "a.email",
|
||||
AdminAccountSortField::Name => {
|
||||
"lower(coalesce(nullif(btrim(a.name), ''), nullif(btrim(a.email), ''), a.upstream_account_id, a.id))"
|
||||
}
|
||||
AdminAccountSortField::Status => {
|
||||
"case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
|
||||
}
|
||||
|
||||
@@ -101,6 +101,15 @@ impl TestDatabase {
|
||||
.run(&pool)
|
||||
.await
|
||||
.expect("apply test migrations");
|
||||
// 功能测试从统一版本基线验证递增与回滚,不依赖数据迁移累计的版本
|
||||
sqlx::query(
|
||||
"update runtime_settings
|
||||
set config_revision = 1, settings_revision = 1, account_error_protection_revision = 1
|
||||
where id = 1",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.expect("initialize test runtime settings revisions");
|
||||
Some(Self {
|
||||
admin,
|
||||
pool,
|
||||
|
||||
@@ -125,7 +125,7 @@ async fn usage_error_origins_agree_for_saved_errors_without_failure_status() {
|
||||
"update model_requests
|
||||
set client_status_code = 200, upstream_status_code = 200, error_kind = 'unavailable',
|
||||
request_observation_json = jsonb_set(request_observation_json, '{error}',
|
||||
'{\"message\":\"Upstream error summary\"}'::jsonb)
|
||||
'{\"message\":\"Upstream error summary\",\"retryAfterMs\":30000}'::jsonb)
|
||||
where id = 'req_observe_failed'",
|
||||
)
|
||||
.execute(&database.pool)
|
||||
@@ -191,6 +191,13 @@ async fn usage_error_origins_agree_for_saved_errors_without_failure_status() {
|
||||
assert_eq!(detail.request.provider_error_code, None);
|
||||
assert_eq!(list.client_status_code, Some(200));
|
||||
assert_eq!(list.upstream_status_code, Some(200));
|
||||
let expected_message = error
|
||||
.get("message")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.filter(|value| !value.is_empty());
|
||||
assert_eq!(list.upstream_error_message.as_deref(), expected_message);
|
||||
assert_eq!(list.retry_after_ms, Some(30_000));
|
||||
assert_eq!(list.retry_after_ms, detail.request.retry_after_ms);
|
||||
assert_eq!(list.error_origin(), origin, "list: {body}");
|
||||
assert_eq!(detail.request.error_origin(), origin, "detail: {body}");
|
||||
}
|
||||
@@ -437,6 +444,12 @@ async fn usage_error_facts_preserve_recovery_and_validate_saved_close_frames() {
|
||||
.await
|
||||
.expect("detail with saved error facts");
|
||||
assert_eq!(detail.request.websocket_close_code, close_code);
|
||||
let close_reason = detail
|
||||
.request
|
||||
.upstream_error
|
||||
.as_ref()
|
||||
.and_then(|error| error.close_reason.as_deref());
|
||||
assert_eq!(record.upstream_error_message.as_deref(), close_reason);
|
||||
assert!(detail.request.recovered);
|
||||
assert_eq!(
|
||||
detail.request.continuation_unavailable_reason,
|
||||
@@ -2386,7 +2399,11 @@ async fn admin_observability_adapter_preserves_utc_queries_metrics_costs_and_det
|
||||
.expect("admin diagnostics")
|
||||
.items;
|
||||
assert_eq!(diagnostics[0].key, "acct_observe");
|
||||
assert_eq!(diagnostics[0].name, "account@example.invalid");
|
||||
assert_eq!(diagnostics[0].name, "primary");
|
||||
assert_eq!(
|
||||
diagnostics[0].account_email.as_deref(),
|
||||
Some("account@example.invalid")
|
||||
);
|
||||
assert_eq!(diagnostics[0].cost_coverage.provider_reported_count, 1);
|
||||
assert_eq!(diagnostics[0].costs[0].amount.as_str(), "1.25");
|
||||
|
||||
@@ -2914,7 +2931,11 @@ async fn observability_queries_preserve_request_account_cost_and_diagnostic_fact
|
||||
.expect("usage diagnostics")
|
||||
.items;
|
||||
assert_eq!(diagnostics[0].key, "acct_observe");
|
||||
assert_eq!(diagnostics[0].name, "account@example.invalid");
|
||||
assert_eq!(diagnostics[0].name, "primary");
|
||||
assert_eq!(
|
||||
diagnostics[0].account_email.as_deref(),
|
||||
Some("account@example.invalid")
|
||||
);
|
||||
assert_eq!(diagnostics[0].request_count, 3);
|
||||
assert_eq!(diagnostics[0].success_count, 2);
|
||||
assert_eq!(diagnostics[0].failure_count, 1);
|
||||
|
||||
@@ -715,14 +715,18 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
let now = Utc::now();
|
||||
|
||||
let mut alpha = account("acct_alpha", "user-alpha");
|
||||
alpha.name = "Zulu".to_owned();
|
||||
alpha.email = Some("alpha@example.invalid".to_owned());
|
||||
let mut beta = account("acct_beta", "user-beta");
|
||||
beta.provider_kind = "xai".to_owned();
|
||||
beta.name = "Team".to_owned();
|
||||
beta.email = Some("beta@example.invalid".to_owned());
|
||||
beta.credential_state = CredentialState::Banned;
|
||||
let mut charlie = account("acct_charlie", "user-charlie");
|
||||
charlie.name = "Team".to_owned();
|
||||
charlie.email = Some("charlie@example.invalid".to_owned());
|
||||
let mut invalid = account("acct_invalid", "user-invalid");
|
||||
invalid.name = " ".to_owned();
|
||||
invalid.email = Some("invalid@example.invalid".to_owned());
|
||||
invalid.credential_state = CredentialState::Invalid;
|
||||
let mut disabled = account("acct_disabled", "user-disabled");
|
||||
@@ -850,6 +854,33 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
["acct_charlie", "acct_beta"]
|
||||
);
|
||||
|
||||
let name_page = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(4).expect("page size"),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: None,
|
||||
sort: Some(AccountSort {
|
||||
field: AccountSortField::Name,
|
||||
direction: SortDirection::Desc,
|
||||
}),
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
.await
|
||||
.expect("sort accounts by display name");
|
||||
assert_eq!(
|
||||
name_page
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.account.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["acct_alpha", "acct_charlie", "acct_beta", "acct_invalid"]
|
||||
);
|
||||
|
||||
let last_used_page = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
|
||||
@@ -622,7 +622,7 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
.openai_request_settings()
|
||||
.residency
|
||||
.as_deref(),
|
||||
Some("us")
|
||||
None
|
||||
);
|
||||
assert!(
|
||||
initial
|
||||
@@ -632,7 +632,7 @@ async fn openai_request_settings_round_trip_into_snapshot() {
|
||||
);
|
||||
assert_eq!(
|
||||
initial.settings.openai_request_settings().request_country,
|
||||
OpenAiRequestCountry::FollowLocation {}
|
||||
OpenAiRequestCountry::Default {}
|
||||
);
|
||||
|
||||
for (enabled, country) in [
|
||||
|
||||
@@ -572,18 +572,17 @@ async fn diagnostics_should_group_same_email_accounts_by_stable_ref() {
|
||||
.await
|
||||
.expect("account diagnostics")
|
||||
.items;
|
||||
assert_eq!(diagnostics.len(), 2);
|
||||
assert_eq!(
|
||||
diagnostics
|
||||
.iter()
|
||||
.map(|item| item.key.as_str())
|
||||
.map(|item| (item.key.as_str(), item.name.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["acct_snap_a", "acct_snap_b"]
|
||||
[("acct_snap_a", "Alpha"), ("acct_snap_b", "Beta")]
|
||||
);
|
||||
assert!(
|
||||
diagnostics
|
||||
.iter()
|
||||
.all(|item| item.name == "same@example.invalid")
|
||||
.all(|item| item.account_email.as_deref() == Some("same@example.invalid"))
|
||||
);
|
||||
assert!(diagnostics.iter().all(|item| item.request_count == 1));
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::{AntigravityProvider, candidates::Project};
|
||||
use crate::transport::unsent;
|
||||
use futures::StreamExt;
|
||||
use gateway_core::{
|
||||
account::AccountEligibilityPolicy,
|
||||
engine::{
|
||||
AttemptContext,
|
||||
provider::{
|
||||
@@ -122,7 +123,13 @@ impl AntigravityProvider {
|
||||
if deadline.is_elapsed() {
|
||||
Err(unsent(Kind::Timeout))?;
|
||||
}
|
||||
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
|
||||
.then(|| selected.material.access_token.clone());
|
||||
let record_failure = async |error| {
|
||||
let error = match &probe_token {
|
||||
Some(token) => crate::transport::connection_test_error(error, token),
|
||||
None => error,
|
||||
};
|
||||
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
|
||||
};
|
||||
let response = tokio::select! {
|
||||
|
||||
@@ -235,7 +235,7 @@ impl CloudCodeClient {
|
||||
GenerateMode::Chat { .. } => None,
|
||||
GenerateMode::Json | GenerateMode::Stream => Some(self.system_instruction.as_ref()),
|
||||
};
|
||||
let request = super::request::request_body(body, instruction, false)?;
|
||||
let request = super::request::request_body(body, instruction, false, Some(model))?;
|
||||
let request = if matches!(mode, GenerateMode::Json | GenerateMode::Stream)
|
||||
&& model.starts_with("claude-")
|
||||
{
|
||||
@@ -289,7 +289,8 @@ impl CloudCodeClient {
|
||||
headers: &[MiddlewareHeader],
|
||||
) -> Result<Response, ProviderError> {
|
||||
// Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段
|
||||
let request = super::request::request_body(body, Some(&self.system_instruction), true)?;
|
||||
let request =
|
||||
super::request::request_body(body, Some(&self.system_instruction), true, None)?;
|
||||
#[derive(Serialize)]
|
||||
struct Envelope<'a> {
|
||||
request: &'a RawValue,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
//! 保留上游错误事实与本地来源,敏感凭据不得进入运维正文
|
||||
|
||||
use gateway_core::{
|
||||
error::{ProviderError, ProviderErrorKind as Kind, RawUpstreamError},
|
||||
error::{
|
||||
ClientVisibleUpstreamError, GatewayError, ProviderError, ProviderErrorKind as Kind,
|
||||
RawUpstreamError,
|
||||
},
|
||||
upstream::UpstreamSendState,
|
||||
};
|
||||
use reqwest::{Response, StatusCode};
|
||||
use serde_json::Value;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
const MAX_ERROR_BYTES: usize = 64 * 1024;
|
||||
@@ -73,15 +77,66 @@ fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError {
|
||||
error.with_raw_upstream_error(RawUpstreamError::new(text))
|
||||
}
|
||||
|
||||
fn retry_info(body: &str) -> Option<Duration> {
|
||||
let document: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
let error = document
|
||||
/// 连接测试只取 Google 的错误字段,验证链接和其他 metadata 留在受控详情中
|
||||
pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> ProviderError {
|
||||
let Some(document) = error
|
||||
.raw_upstream_error()
|
||||
.and_then(|raw| serde_json::from_str::<Value>(raw.as_str()).ok())
|
||||
else {
|
||||
return error;
|
||||
};
|
||||
let Some(failure) = google_error(&document) else {
|
||||
return error;
|
||||
};
|
||||
let info = google_error_detail(failure, "type.googleapis.com/google.rpc.ErrorInfo");
|
||||
let safe_text = |value: &Value| {
|
||||
value
|
||||
.as_str()
|
||||
.filter(|s| {
|
||||
!s.trim().is_empty()
|
||||
&& !s.contains("://")
|
||||
&& (token.is_empty() || !s.contains(token))
|
||||
})
|
||||
.map(str::to_owned)
|
||||
};
|
||||
let code = info.and_then(|detail| safe_text(&detail["reason"]));
|
||||
let error_type = safe_text(&failure["status"]);
|
||||
let message = info
|
||||
.and_then(|detail| safe_text(&detail["metadata"]["validation_error_message"]))
|
||||
.or_else(|| safe_text(&failure["message"]));
|
||||
if code.is_none() && error_type.is_none() && message.is_none() {
|
||||
return error;
|
||||
}
|
||||
let message = message.unwrap_or_else(|| {
|
||||
GatewayError::from_provider(&error)
|
||||
.safe_message()
|
||||
.to_owned()
|
||||
});
|
||||
error.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
message, code, error_type,
|
||||
))
|
||||
}
|
||||
|
||||
fn google_error(document: &Value) -> Option<&Value> {
|
||||
document
|
||||
.get("error")
|
||||
.or_else(|| document.pointer("/response/error"))?;
|
||||
let detail = error.get("details")?.as_array()?.iter().find(|detail| {
|
||||
detail.get("@type").and_then(serde_json::Value::as_str)
|
||||
== Some("type.googleapis.com/google.rpc.RetryInfo")
|
||||
})?;
|
||||
.or_else(|| document.pointer("/response/error"))
|
||||
}
|
||||
|
||||
fn google_error_detail<'a>(error: &'a Value, kind: &str) -> Option<&'a Value> {
|
||||
error
|
||||
.get("details")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|detail| detail["@type"] == kind)
|
||||
}
|
||||
|
||||
fn retry_info(body: &str) -> Option<Duration> {
|
||||
let document: Value = serde_json::from_str(body).ok()?;
|
||||
let detail = google_error_detail(
|
||||
google_error(&document)?,
|
||||
"type.googleapis.com/google.rpc.RetryInfo",
|
||||
)?;
|
||||
let delay = detail.get("retryDelay")?.as_str()?.strip_suffix('s')?;
|
||||
let (seconds, fraction) = delay.split_once('.').unwrap_or((delay, ""));
|
||||
if seconds.is_empty()
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! 在指定 JSON 对象字段上编辑原始字节,保留未知字段、顺序与数字表达
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{MapAccess, Visitor},
|
||||
};
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
pub(super) enum Edit {
|
||||
Keep,
|
||||
Remove,
|
||||
Replace(Box<RawValue>),
|
||||
}
|
||||
|
||||
pub(super) fn edit_object(
|
||||
body: &RawValue,
|
||||
mut edit: impl FnMut(&str, &RawValue) -> Result<Edit, serde_json::Error>,
|
||||
append: Option<(&str, &RawValue)>,
|
||||
) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
let json = body.get();
|
||||
let Fields(fields) = serde_json::from_str(json)?;
|
||||
let mut output = String::with_capacity(json.len());
|
||||
output.push('{');
|
||||
let mut cursor = 1;
|
||||
let mut retained = false;
|
||||
for (name, value) in fields {
|
||||
// RawValue 借自同一输入;位置由 serde JSON 解析器确定,不自行解析值或转码数字
|
||||
let start = value.get().as_ptr() as usize - json.as_ptr() as usize;
|
||||
let prefix = &json[cursor..start];
|
||||
cursor = start + value.get().len();
|
||||
let replacement = match edit(&name, value)? {
|
||||
Edit::Keep => None,
|
||||
Edit::Remove => continue,
|
||||
Edit::Replace(value) => Some(value),
|
||||
};
|
||||
let comma = (!retained)
|
||||
.then(|| prefix.bytes().position(|byte| !byte.is_ascii_whitespace()))
|
||||
.flatten()
|
||||
.filter(|&index| prefix.as_bytes()[index] == b',');
|
||||
if let Some(index) = comma {
|
||||
output.push_str(&prefix[..index]);
|
||||
output.push_str(&prefix[index + 1..]);
|
||||
} else {
|
||||
output.push_str(prefix);
|
||||
}
|
||||
output.push_str(replacement.as_deref().unwrap_or(value).get());
|
||||
retained = true;
|
||||
}
|
||||
if let Some((name, value)) = append {
|
||||
if retained {
|
||||
output.push(',');
|
||||
}
|
||||
output.push_str(&serde_json::to_string(name)?);
|
||||
output.push(':');
|
||||
output.push_str(value.get());
|
||||
}
|
||||
output.push_str(&json[cursor..]);
|
||||
RawValue::from_string(output)
|
||||
}
|
||||
|
||||
// 保留顺序和重复字段;身份字段的重复项也必须全部处理,不能被 Map 的最后值语义遗漏
|
||||
pub(super) struct Fields<'a>(pub(super) Vec<(String, &'a RawValue)>);
|
||||
|
||||
impl<'de> Deserialize<'de> for Fields<'de> {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct ObjectVisitor;
|
||||
impl<'de> Visitor<'de> for ObjectVisitor {
|
||||
type Value = Fields<'de>;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON object")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut fields = Vec::new();
|
||||
while let Some(name) = map.next_key()? {
|
||||
fields.push((name, map.next_value()?));
|
||||
}
|
||||
Ok(Fields(fields))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(ObjectVisitor)
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,15 @@ mod client;
|
||||
mod count;
|
||||
mod failure;
|
||||
mod headers;
|
||||
mod json;
|
||||
mod pool;
|
||||
mod request;
|
||||
mod response;
|
||||
mod signatures;
|
||||
mod tool_ids;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
pub(crate) use failure::{sent, unsent};
|
||||
pub(crate) use failure::{connection_test_error, sent, unsent};
|
||||
pub(crate) use headers::request_headers;
|
||||
pub(crate) use pool::ClientPool;
|
||||
pub(crate) use response::{ResponseContext, events};
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
//! 合成系统提示并改写 Cloud Code 身份字段,其他字段保留原始 JSON 字节
|
||||
//! 合成系统提示、处理思考签名并改写身份字段,其他字段保留原始 JSON 字节
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{MapAccess, Visitor},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
use super::unsent;
|
||||
use super::{
|
||||
json::{Edit, Fields, edit_object},
|
||||
unsent,
|
||||
};
|
||||
use gateway_core::error::{ProviderError, ProviderErrorKind};
|
||||
|
||||
pub(super) fn request_body(
|
||||
body: &[u8],
|
||||
instruction: Option<&RawValue>,
|
||||
count: bool,
|
||||
model: Option<&str>,
|
||||
) -> Result<Box<RawValue>, ProviderError> {
|
||||
let rewrite = || {
|
||||
let raw: &RawValue = serde_json::from_slice(body)?;
|
||||
@@ -22,6 +23,10 @@ pub(super) fn request_body(
|
||||
edit_object(
|
||||
raw,
|
||||
|name, value| {
|
||||
// 合并到已有的字段处理,避免为签名再解析、复制和校验整个请求
|
||||
if name == "contents" {
|
||||
return super::signatures::prepare_contents(value, model);
|
||||
}
|
||||
if (instruction.is_some()
|
||||
&& matches!(name, "systemInstruction" | "system_instruction"))
|
||||
|| (count
|
||||
@@ -109,80 +114,3 @@ fn prepend_system_prompt(
|
||||
Some(("parts", &parts)),
|
||||
)
|
||||
}
|
||||
|
||||
enum Edit {
|
||||
Keep,
|
||||
Remove,
|
||||
Replace(Box<RawValue>),
|
||||
}
|
||||
|
||||
fn edit_object(
|
||||
body: &RawValue,
|
||||
mut edit: impl FnMut(&str, &RawValue) -> Result<Edit, serde_json::Error>,
|
||||
append: Option<(&str, &RawValue)>,
|
||||
) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
let json = body.get();
|
||||
let Fields(fields) = serde_json::from_str(json)?;
|
||||
let mut output = String::with_capacity(json.len());
|
||||
output.push('{');
|
||||
let mut cursor = 1;
|
||||
let mut retained = false;
|
||||
for (name, value) in fields {
|
||||
// RawValue 借自同一输入;位置由 serde JSON 解析器确定,不自行解析值或转码数字
|
||||
let start = value.get().as_ptr() as usize - json.as_ptr() as usize;
|
||||
let prefix = &json[cursor..start];
|
||||
cursor = start + value.get().len();
|
||||
let replacement = match edit(&name, value)? {
|
||||
Edit::Keep => None,
|
||||
Edit::Remove => continue,
|
||||
Edit::Replace(value) => Some(value),
|
||||
};
|
||||
let comma = (!retained)
|
||||
.then(|| prefix.bytes().position(|byte| !byte.is_ascii_whitespace()))
|
||||
.flatten()
|
||||
.filter(|&index| prefix.as_bytes()[index] == b',');
|
||||
if let Some(index) = comma {
|
||||
output.push_str(&prefix[..index]);
|
||||
output.push_str(&prefix[index + 1..]);
|
||||
} else {
|
||||
output.push_str(prefix);
|
||||
}
|
||||
output.push_str(replacement.as_deref().unwrap_or(value).get());
|
||||
retained = true;
|
||||
}
|
||||
if let Some((name, value)) = append {
|
||||
if retained {
|
||||
output.push(',');
|
||||
}
|
||||
output.push_str(&serde_json::to_string(name)?);
|
||||
output.push(':');
|
||||
output.push_str(value.get());
|
||||
}
|
||||
output.push_str(&json[cursor..]);
|
||||
RawValue::from_string(output)
|
||||
}
|
||||
|
||||
// 保留顺序和重复字段;身份字段的重复项也必须全部处理,不能被 Map 的最后值语义遗漏
|
||||
struct Fields<'a>(Vec<(String, &'a RawValue)>);
|
||||
|
||||
impl<'de> Deserialize<'de> for Fields<'de> {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct ObjectVisitor;
|
||||
impl<'de> Visitor<'de> for ObjectVisitor {
|
||||
type Value = Fields<'de>;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON object")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut fields = Vec::new();
|
||||
while let Some(name) = map.next_key()? {
|
||||
fields.push((name, map.next_value()?));
|
||||
}
|
||||
Ok(Fields(fields))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(ObjectVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! 识别原生签名的已知封套,出站移除跨家族思考历史,兼容签名保持原样
|
||||
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use serde::Deserialize;
|
||||
use serde_json::value::{RawValue, to_raw_value};
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::json::{Edit, edit_object};
|
||||
|
||||
const SKIP: &str = "skip_thought_signature_validator";
|
||||
|
||||
fn family(model: &str) -> Option<&'static str> {
|
||||
["claude", "gemini"].into_iter().find(|family| {
|
||||
model
|
||||
.strip_prefix(family)
|
||||
.is_some_and(|rest| rest.starts_with('-'))
|
||||
})
|
||||
}
|
||||
|
||||
fn source(signature: &str) -> Option<&'static str> {
|
||||
// 预筛仅减少解码开销,来源由完整封套决定;不以首字母或密钥编号判定
|
||||
if !matches!(signature.as_bytes().first(), Some(b'C' | b'E' | b'Q')) {
|
||||
return None;
|
||||
}
|
||||
let mut decoded = STANDARD.decode(signature).ok()?;
|
||||
if decoded.first() == Some(&b'C') {
|
||||
decoded = STANDARD.decode(&decoded).ok()?;
|
||||
}
|
||||
// AGY CLI 1.5.18 实测:Claude 5.5 的 CAQS v4 封套包含 Google 通道、块类型和签名
|
||||
// 只读取封套元数据,不解密、校验或重编码其中的签名,不推断账号或项目兼容性
|
||||
if matches!(field(&decoded, 1), Some(Wire::Integer(4)))
|
||||
&& matches!(field(&decoded, 3), Some(Wire::Integer(1)))
|
||||
&& let Some(Wire::Bytes(container)) = field(&decoded, 2)
|
||||
&& let Some(Wire::Bytes(channel)) = field(container, 1)
|
||||
&& matches!(field(channel, 1), Some(Wire::Integer(_)))
|
||||
&& matches!(field(channel, 2), Some(Wire::Integer(2)))
|
||||
&& matches!(field(channel, 8), Some(Wire::Bytes(b"thinking")))
|
||||
&& matches!(field(container, 5), Some(Wire::Bytes(signature)) if !signature.is_empty())
|
||||
{
|
||||
return Some("claude");
|
||||
}
|
||||
// Gemini 样本为独占的 2 → 1 字节字段,内部为 Tink 前缀和不透明密文
|
||||
let container = sole_bytes(&decoded, 2)?;
|
||||
let opaque = sole_bytes(container, 1)?;
|
||||
(opaque.len() >= 21 && opaque[0] == 1).then_some("gemini")
|
||||
}
|
||||
|
||||
enum Wire<'a> {
|
||||
Integer(u64),
|
||||
Bytes(&'a [u8]),
|
||||
Fixed,
|
||||
}
|
||||
|
||||
fn varint(input: &mut &[u8]) -> Option<u64> {
|
||||
let mut result = 0;
|
||||
for shift in (0..70).step_by(7) {
|
||||
let (&byte, rest) = input.split_first()?;
|
||||
*input = rest;
|
||||
if shift == 63 && byte > 1 {
|
||||
return None;
|
||||
}
|
||||
result |= u64::from(byte & 0x7f) << shift;
|
||||
if byte < 0x80 {
|
||||
return Some(result);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn next_field<'a>(input: &mut &'a [u8]) -> Option<(u64, Wire<'a>)> {
|
||||
let tag = varint(input)?;
|
||||
let number = tag >> 3;
|
||||
if number == 0 || number > 0x1fff_ffff {
|
||||
return None;
|
||||
}
|
||||
let wire = tag & 7;
|
||||
if wire == 0 {
|
||||
return Some((number, Wire::Integer(varint(input)?)));
|
||||
}
|
||||
let len = match wire {
|
||||
1 => 8,
|
||||
2 => usize::try_from(varint(input)?).ok()?,
|
||||
5 => 4,
|
||||
_ => return None,
|
||||
};
|
||||
let value = input.get(..len)?;
|
||||
*input = &input[len..];
|
||||
Some((
|
||||
number,
|
||||
if wire == 2 {
|
||||
Wire::Bytes(value)
|
||||
} else {
|
||||
Wire::Fixed
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn field(mut input: &[u8], wanted: u64) -> Option<Wire<'_>> {
|
||||
let mut found = None;
|
||||
while !input.is_empty() {
|
||||
let (number, value) = next_field(&mut input)?;
|
||||
// 识别字段有歧义或封套截断时保持未知,交由上游处理
|
||||
if number == wanted && found.replace(value).is_some() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn sole_bytes(mut input: &[u8], wanted: u64) -> Option<&[u8]> {
|
||||
let (number, Wire::Bytes(value)) = next_field(&mut input)? else {
|
||||
return None;
|
||||
};
|
||||
(number == wanted && input.is_empty()).then_some(value)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Content<'a> {
|
||||
#[serde(default, borrow)]
|
||||
role: Cow<'a, str>,
|
||||
#[serde(default, borrow)]
|
||||
parts: Vec<&'a RawValue>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Part<'a> {
|
||||
#[serde(default)]
|
||||
thought: Option<bool>,
|
||||
#[serde(default, rename = "thoughtSignature", alias = "thought_signature")]
|
||||
signature: Option<Cow<'a, str>>,
|
||||
#[serde(default, borrow, rename = "functionCall", alias = "function_call")]
|
||||
call: Option<&'a RawValue>,
|
||||
}
|
||||
|
||||
pub(super) fn prepare_contents(
|
||||
contents: &RawValue,
|
||||
model: Option<&str>,
|
||||
) -> Result<Edit, serde_json::Error> {
|
||||
// AGY CLI 1.5.18 的 OAuth 路径在跨家族时去掉思考历史,Gateway GenAI 路径却保留签名
|
||||
// 只清理可识别的异家族签名;计数和未知模型无需扫描历史,不增加会话缓存
|
||||
let Some(target) = model.and_then(family) else {
|
||||
return Ok(Edit::Keep);
|
||||
};
|
||||
let Ok(contents) = serde_json::from_str::<Vec<&RawValue>>(contents.get()) else {
|
||||
return Ok(Edit::Keep);
|
||||
};
|
||||
let prepared = contents
|
||||
.iter()
|
||||
.map(|content| prepare_content(content, target))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
if prepared
|
||||
.iter()
|
||||
.all(|content| matches!(content, Some(Cow::Borrowed(_))))
|
||||
{
|
||||
return Ok(Edit::Keep);
|
||||
}
|
||||
let prepared: Vec<_> = prepared.into_iter().flatten().collect();
|
||||
to_raw_value(&prepared).map(Edit::Replace)
|
||||
}
|
||||
|
||||
fn prepare_content<'a>(
|
||||
raw: &'a RawValue,
|
||||
target: &str,
|
||||
) -> Result<Option<Cow<'a, RawValue>>, serde_json::Error> {
|
||||
let Ok(content) = serde_json::from_str::<Content<'_>>(raw.get()) else {
|
||||
return Ok(Some(Cow::Borrowed(raw)));
|
||||
};
|
||||
if content.role != "model" {
|
||||
return Ok(Some(Cow::Borrowed(raw)));
|
||||
}
|
||||
let Ok(parts) = content
|
||||
.parts
|
||||
.iter()
|
||||
.map(|part| serde_json::from_str::<Part<'_>>(part.get()))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
else {
|
||||
return Ok(Some(Cow::Borrowed(raw)));
|
||||
};
|
||||
let signatures: Vec<_> = parts
|
||||
.iter()
|
||||
.map(|part| part.signature.as_deref().and_then(source))
|
||||
.collect();
|
||||
let foreign = |source: &Option<&str>| source.is_some_and(|source| source != target);
|
||||
if !signatures.iter().any(foreign) {
|
||||
return Ok(Some(Cow::Borrowed(raw)));
|
||||
}
|
||||
let strip_thoughts = parts
|
||||
.iter()
|
||||
.zip(&signatures)
|
||||
.all(|(part, signature)| part.signature.is_none() || foreign(signature));
|
||||
let mut first_call = true;
|
||||
let mut output = Vec::new();
|
||||
for ((raw, part), signature) in content.parts.iter().zip(parts).zip(&signatures) {
|
||||
let foreign = foreign(signature);
|
||||
let strip_thought = part.thought == Some(true) && (foreign || strip_thoughts);
|
||||
if strip_thought && part.call.is_none() {
|
||||
continue;
|
||||
}
|
||||
// 对齐官方 CLI 1.5.18 的 ccpa.BuildRequest:导入历史缺少签名时只标记首个工具调用
|
||||
let placeholder = target == "gemini"
|
||||
&& first_call
|
||||
&& part.call.is_some()
|
||||
&& (part.signature.is_none() || foreign);
|
||||
if part.call.is_some() {
|
||||
first_call = false;
|
||||
}
|
||||
let replacement = placeholder.then(|| to_raw_value(SKIP)).transpose()?;
|
||||
if !foreign && !placeholder && !strip_thought {
|
||||
output.push(Cow::Borrowed(*raw));
|
||||
continue;
|
||||
}
|
||||
let part = edit_object(
|
||||
raw,
|
||||
|name, _| {
|
||||
Ok(
|
||||
if (matches!(name, "thoughtSignature" | "thought_signature") && foreign)
|
||||
|| (name == "thought" && strip_thought)
|
||||
{
|
||||
Edit::Remove
|
||||
} else {
|
||||
Edit::Keep
|
||||
},
|
||||
)
|
||||
},
|
||||
replacement
|
||||
.as_deref()
|
||||
.map(|signature| ("thoughtSignature", signature)),
|
||||
)?;
|
||||
// 只有签名的独立 part 在跨家族后不应变成无内容的对象
|
||||
if !foreign
|
||||
|| !serde_json::from_str::<super::json::Fields<'_>>(part.get())?
|
||||
.0
|
||||
.is_empty()
|
||||
{
|
||||
output.push(Cow::Owned(part));
|
||||
}
|
||||
}
|
||||
if output.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let parts = to_raw_value(&output)?;
|
||||
edit_object(
|
||||
raw,
|
||||
|name, _| {
|
||||
Ok(if name == "parts" {
|
||||
Edit::Replace(parts.clone())
|
||||
} else {
|
||||
Edit::Keep
|
||||
})
|
||||
},
|
||||
None,
|
||||
)
|
||||
.map(|content| Some(Cow::Owned(content)))
|
||||
}
|
||||
@@ -455,6 +455,75 @@ async fn disabled_account_probe_discovers_its_own_project_on_first_poll() {
|
||||
released(&fixture).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_probe_reports_google_rejection_without_verification_links() {
|
||||
let details = json!([{
|
||||
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
||||
"reason": "VALIDATION_REQUIRED",
|
||||
"metadata": {"validation_error_message": "Complete SMS verification.", "validation_url": "https://accounts.example.test/verify?nonce=private"}
|
||||
}]);
|
||||
for (status, body, reason, message) in [
|
||||
(401, json!({}), None, None),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"status":"PERMISSION_DENIED","message":"Access denied."}}),
|
||||
None,
|
||||
Some("Access denied."),
|
||||
),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"status":"PERMISSION_DENIED","message":"Verify your account to continue.","details":details}}),
|
||||
Some("VALIDATION_REQUIRED"),
|
||||
Some("Complete SMS verification."),
|
||||
),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"message":"fixture-access","details":details}}),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:loadCodeAssist"))
|
||||
.respond_with(ResponseTemplate::new(status).set_body_json(body))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let account = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.id()
|
||||
.clone();
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
diagnostic_context(AccountProbeTarget::ConnectionTest(account)),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.expect_err("Google rejected the project lookup");
|
||||
assert_eq!(error.upstream_status(), Some(status));
|
||||
let visible = error.client_visible_upstream_error();
|
||||
assert_eq!(visible.and_then(|e| e.code()), reason);
|
||||
assert_eq!(visible.map(|e| e.message()), message);
|
||||
assert_eq!(
|
||||
visible.and_then(|e| e.error_type()),
|
||||
message.map(|_| "PERMISSION_DENIED")
|
||||
);
|
||||
assert!(error.client_visible_upstream_response().is_none());
|
||||
released(&fixture).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feedback() {
|
||||
for (status, kind) in [
|
||||
|
||||
@@ -4,4 +4,5 @@ mod client;
|
||||
mod count;
|
||||
mod pool;
|
||||
mod request;
|
||||
mod signatures;
|
||||
mod tool_ids;
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! 原生签名透传、封套识别、模型互切清理和输入计数的历史保留
|
||||
|
||||
use crate::{
|
||||
profile,
|
||||
transport::{self, CloudCodeClient},
|
||||
};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use futures::TryStreamExt;
|
||||
use gateway_core::{
|
||||
lifecycle::{CancellationToken, Deadline},
|
||||
routing::UpstreamModelId,
|
||||
};
|
||||
use serde_json::{Value, json, value::RawValue};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
|
||||
// 按官方 CLI 样本的封套构造,密文使用测试字节,不包含真实账号签名
|
||||
fn bytes_field(number: u8, value: &[u8]) -> Vec<u8> {
|
||||
let mut output = vec![(number << 3) | 2];
|
||||
let mut len = value.len();
|
||||
while len >= 128 {
|
||||
output.push((len as u8 & 0x7f) | 0x80);
|
||||
len >>= 7;
|
||||
}
|
||||
output.push(len as u8);
|
||||
output.extend_from_slice(value);
|
||||
output
|
||||
}
|
||||
|
||||
fn claude_envelope(channel_id: u8) -> Vec<u8> {
|
||||
let mut channel = vec![8, channel_id, 16, 2, 24, 2, 56, 1];
|
||||
channel.extend(bytes_field(8, b"thinking"));
|
||||
let mut container = bytes_field(1, &channel);
|
||||
container.extend(bytes_field(5, &[0x42; 160]));
|
||||
let mut envelope = vec![8, 4];
|
||||
envelope.extend(bytes_field(2, &container));
|
||||
envelope.extend([24, 1]);
|
||||
envelope
|
||||
}
|
||||
|
||||
fn claude_signature() -> String {
|
||||
STANDARD.encode(STANDARD.encode(claude_envelope(20)))
|
||||
}
|
||||
|
||||
fn gemini_envelope() -> Vec<u8> {
|
||||
let mut opaque = vec![1, 2, 3, 4, 5];
|
||||
opaque.extend([0x42; 160]);
|
||||
bytes_field(2, &bytes_field(1, &opaque))
|
||||
}
|
||||
|
||||
fn gemini_signature() -> String {
|
||||
STANDARD.encode(gemini_envelope())
|
||||
}
|
||||
|
||||
async fn fixture(reply: &str) -> (MockServer, CloudCodeClient) {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_raw(format!(r#"{{"response":{reply}}}"#), "application/json"),
|
||||
)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(
|
||||
format!("id: signature-frame\ndata: {{\"response\":{reply}}}\n\n"),
|
||||
"text/event-stream",
|
||||
))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/v1internal:countTokens"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"totalTokens":42})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&profile::Selection::default().resolve("2.34.0"),
|
||||
)
|
||||
.unwrap();
|
||||
(server, client)
|
||||
}
|
||||
|
||||
async fn response(client: &CloudCodeClient, model: &str, stream: bool) -> (String, Value) {
|
||||
let response = client
|
||||
.generate(
|
||||
"project",
|
||||
model,
|
||||
"token",
|
||||
br#"{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}"#,
|
||||
stream.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let events = transport::events(
|
||||
response,
|
||||
transport::ResponseContext {
|
||||
stream,
|
||||
model: UpstreamModelId::new(model).unwrap(),
|
||||
deadline: Deadline::default(),
|
||||
cancel: CancellationToken::new(),
|
||||
token: "token".into(),
|
||||
pricing: None,
|
||||
started_at: std::time::Instant::now(),
|
||||
},
|
||||
)
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let wire = events[0].wire_event().unwrap();
|
||||
let raw = if stream {
|
||||
let sse = std::str::from_utf8(wire.raw_sse_frame().unwrap()).unwrap();
|
||||
assert!(sse.contains("id: signature-frame"));
|
||||
sse.lines()
|
||||
.find_map(|line| line.strip_prefix("data: "))
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
} else {
|
||||
std::str::from_utf8(wire.raw_json_body().unwrap())
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
};
|
||||
let value = serde_json::from_str(&raw).unwrap();
|
||||
(raw, value)
|
||||
}
|
||||
|
||||
async fn sent(server: &MockServer) -> Value {
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
serde_json::from_slice::<Value>(&requests.last().unwrap().body).unwrap()["request"].clone()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_signature_round_trip_preserves_own_thoughts_and_removes_foreign_thoughts() {
|
||||
// 官方 CLI Gateway 把 Claude 思考文本和末尾签名重排到同一 model 轮次的不同 part
|
||||
for (source, other, original) in [
|
||||
(
|
||||
"claude-opus-5-5-medium",
|
||||
"gemini-4-hydrogen-medium",
|
||||
claude_signature(),
|
||||
),
|
||||
(
|
||||
"gemini-4-hydrogen-medium",
|
||||
"claude-opus-5-5-medium",
|
||||
gemini_signature(),
|
||||
),
|
||||
] {
|
||||
let reply = format!(
|
||||
r#"{{ "responseId":"r","candidates":[{{"content":{{"role":"model","parts":[{{"thought":true,"text":"reasoning","thoughtSignature":"{original}"}}]}},"finishReason":"STOP"}}],"extension":1e+09,"extension":98765432109876543210987654 }}"#
|
||||
);
|
||||
let (server, client) = fixture(&reply).await;
|
||||
for stream in [false, true] {
|
||||
let (raw, value) = response(&client, source, stream).await;
|
||||
let signature = value["candidates"][0]["content"]["parts"][0]["thoughtSignature"]
|
||||
.as_str()
|
||||
.unwrap();
|
||||
assert_eq!(signature, original);
|
||||
assert_eq!(raw, reply);
|
||||
let history = json!({
|
||||
"systemInstruction":{"parts":[{"text":"client instruction"}]},
|
||||
"labels":{"client":"gateway","cascade_id":"conversation"},
|
||||
"contents":[
|
||||
{"role":"user","parts":[{"text":"first"}]},
|
||||
{"role":"model","parts":[{"thought":true,"text":"reasoning"},{"text":"answer","thoughtSignature":signature}]},
|
||||
{"role":"user","parts":[{"text":"next"}]}
|
||||
]});
|
||||
let body = serde_json::to_string(&history).unwrap();
|
||||
// 借用视图遇到转义字符串仍须识别同一来源,并与身份字段、系统提示处理共存
|
||||
let body = if stream {
|
||||
body.replace(r#""contents""#, r#""con\u0074ents""#)
|
||||
.replace(r#""model""#, r#""mo\u0064el""#)
|
||||
.replace(
|
||||
signature,
|
||||
&format!(r"\u{:04x}{}", signature.as_bytes()[0], &signature[1..]),
|
||||
)
|
||||
} else {
|
||||
body
|
||||
};
|
||||
for target in [source, other] {
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
target,
|
||||
"token",
|
||||
body.as_bytes(),
|
||||
stream.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let request = sent(&server).await;
|
||||
assert_eq!(request["labels"], json!({"cascade_id":"conversation"}));
|
||||
assert_eq!(
|
||||
request["systemInstruction"]["parts"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.last(),
|
||||
Some(&history["systemInstruction"]["parts"][0])
|
||||
);
|
||||
assert_eq!(request["contents"][0], history["contents"][0]);
|
||||
assert_eq!(request["contents"][2], history["contents"][2]);
|
||||
let parts = &request["contents"][1]["parts"];
|
||||
if target == source {
|
||||
assert_eq!(parts[0], history["contents"][1]["parts"][0]);
|
||||
assert_eq!(
|
||||
parts[1],
|
||||
json!({"text":"answer","thoughtSignature":original})
|
||||
);
|
||||
} else {
|
||||
assert_eq!(parts, &json!([{"text":"answer"}]));
|
||||
}
|
||||
}
|
||||
client
|
||||
.count_tokens("token", body.as_bytes(), &[])
|
||||
.await
|
||||
.unwrap();
|
||||
let request = sent(&server).await;
|
||||
assert!(request.get("labels").is_none());
|
||||
assert_eq!(
|
||||
request["contents"][1]["parts"][0],
|
||||
history["contents"][1]["parts"][0]
|
||||
);
|
||||
assert_eq!(
|
||||
request["contents"][1]["parts"][1]["thoughtSignature"],
|
||||
original
|
||||
);
|
||||
}
|
||||
assert_eq!(response(&client, "other-model", true).await.0, reply);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreign_tool_history_keeps_calls_results_and_valid_gemini_signatures() {
|
||||
let (server, client) = fixture("{}").await;
|
||||
let claude = claude_signature();
|
||||
let gemini = gemini_signature();
|
||||
let history = json!({"contents":[
|
||||
{"role":"model","parts":[{"thought":true,"text":"old reasoning","thoughtSignature":claude},{"thoughtSignature":claude}]},
|
||||
{"role":"model","parts":[{"thought":true,"text":"old reasoning"},
|
||||
{"text":"old answer","thoughtSignature":claude},
|
||||
{"functionCall":{"name":"first","args":{"thoughtSignature":"business data"}},"thought":true,"thoughtSignature":claude},
|
||||
{"functionCall":{"name":"second","args":{}}}]},
|
||||
{"role":"user","parts":[{"functionResponse":{"name":"first","response":{"ok":true}}},{"functionResponse":{"name":"second","response":{"ok":false}}}]},
|
||||
{"role":"model","parts":[{"thought":true,"text":"current reasoning"},{"functionCall":{"name":"third","args":{}},"thoughtSignature":gemini}]}
|
||||
]});
|
||||
let body = serde_json::to_string(&history).unwrap().replace(
|
||||
r#""args":{"thoughtSignature":"business data"}"#,
|
||||
r#""args":{ "thoughtSignature":"business data", "n":1e+09,"n":98765432109876543210987654 }"#,
|
||||
);
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
"gemini-4-hydrogen-medium",
|
||||
"token",
|
||||
body.as_bytes(),
|
||||
true.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let request = sent(&server).await;
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert!(std::str::from_utf8(&requests.last().unwrap().body).unwrap()
|
||||
.contains(r#"{ "thoughtSignature":"business data", "n":1e+09,"n":98765432109876543210987654 }"#));
|
||||
let contents = request["contents"].as_array().unwrap();
|
||||
assert_eq!(contents.len(), 3);
|
||||
assert_eq!(contents[0]["parts"][0], json!({"text":"old answer"}));
|
||||
assert_eq!(
|
||||
contents[0]["parts"][1]["thoughtSignature"],
|
||||
"skip_thought_signature_validator"
|
||||
);
|
||||
assert_eq!(contents[0]["parts"][1]["functionCall"]["name"], "first");
|
||||
assert!(contents[0]["parts"][1].get("thought").is_none());
|
||||
assert_eq!(contents[0]["parts"][2], history["contents"][1]["parts"][3]);
|
||||
assert_eq!(contents[1], history["contents"][2]);
|
||||
assert_eq!(contents[2]["parts"][0], history["contents"][3]["parts"][0]);
|
||||
assert_eq!(contents[2]["parts"][1]["thoughtSignature"], gemini);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_or_malformed_history_is_not_reinterpreted() {
|
||||
let (server, client) = fixture("{}").await;
|
||||
for body in [
|
||||
r#"{ "contents" : [ { "role":"model", "parts" : [{"thought":true,"text":"keep"},{"text":"answer","thoughtSignature":"b3BhcXVl"},{"functionCall":{"name":"x","args":{"n":1e+09,"n":98765432109876543210987654}}}] } ] }"#,
|
||||
r#"{"contents":[{"role":"model","parts":[{"thoughtSignature":123}]}]}"#,
|
||||
] {
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
"gemini-4-hydrogen",
|
||||
"token",
|
||||
body.as_bytes(),
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let envelope: std::collections::BTreeMap<String, &RawValue> =
|
||||
serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||||
let request: std::collections::BTreeMap<String, &RawValue> =
|
||||
serde_json::from_str(envelope["request"].get()).unwrap();
|
||||
let original: std::collections::BTreeMap<String, &RawValue> =
|
||||
serde_json::from_str(body).unwrap();
|
||||
assert_eq!(request["contents"].get(), original["contents"].get());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn envelope_recognition_preserves_unknown_truncated_and_ambiguous_signatures() {
|
||||
let (server, client) = fixture("{}").await;
|
||||
let mut duplicate_version = claude_envelope(20);
|
||||
duplicate_version.extend([8, 4]);
|
||||
let mut duplicate_container = claude_envelope(20);
|
||||
duplicate_container.extend(bytes_field(2, &[]));
|
||||
let mut future_version = claude_envelope(20);
|
||||
future_version[1] = 5;
|
||||
let mut truncated = claude_envelope(20);
|
||||
truncated.pop();
|
||||
let mut gemini_with_trailer = gemini_envelope();
|
||||
gemini_with_trailer.extend([24, 1]);
|
||||
let mut claude_with_extension = claude_envelope(21);
|
||||
claude_with_extension.extend([0x25, 1, 2, 3, 4]);
|
||||
let mut rotated_key = vec![1, 9, 8, 7, 6];
|
||||
rotated_key.extend([0x42; 32]);
|
||||
let double = |value: Vec<u8>| STANDARD.encode(STANDARD.encode(value));
|
||||
for (signature, source) in [
|
||||
(double(claude_with_extension), Some("claude")),
|
||||
(STANDARD.encode(claude_envelope(20)), Some("claude")),
|
||||
(
|
||||
STANDARD.encode(bytes_field(2, &bytes_field(1, &rotated_key))),
|
||||
Some("gemini"),
|
||||
),
|
||||
(double(duplicate_version), None),
|
||||
(double(duplicate_container), None),
|
||||
(double(future_version), None),
|
||||
(double(truncated), None),
|
||||
(STANDARD.encode(gemini_with_trailer), None),
|
||||
(
|
||||
STANDARD.encode(bytes_field(2, &bytes_field(1, &[0x42; 160]))),
|
||||
None,
|
||||
),
|
||||
(
|
||||
STANDARD.encode([
|
||||
0x12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 2,
|
||||
]),
|
||||
None,
|
||||
),
|
||||
(STANDARD.encode([8, 4, 0, 0]), None),
|
||||
("CA==".to_owned(), None),
|
||||
("not-base64".to_owned(), None),
|
||||
("skip_thought_signature_validator".to_owned(), None),
|
||||
] {
|
||||
let history = json!({"contents":[{"role":"model","parts":[
|
||||
{"thought":true,"text":"reasoning"},
|
||||
{"text":"answer","thought_signature":signature}
|
||||
]}]});
|
||||
let body = serde_json::to_vec(&history).unwrap();
|
||||
for target in ["claude", "gemini"] {
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
&format!("{target}-fixture"),
|
||||
"token",
|
||||
&body,
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let request = sent(&server).await;
|
||||
if source.is_some_and(|source| source != target) {
|
||||
assert_eq!(request["contents"][0]["parts"], json!([{"text":"answer"}]));
|
||||
} else {
|
||||
assert_eq!(request["contents"], history["contents"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mixed_sources_do_not_assign_unsigned_thoughts_to_a_foreign_signature() {
|
||||
let (server, client) = fixture("{}").await;
|
||||
let history = json!({"contents":[{"role":"model","parts":[
|
||||
{"thought":true,"text":"unsigned reasoning"},
|
||||
{"thought":true,"text":"foreign reasoning","thoughtSignature":claude_signature()},
|
||||
{"thought":true,"text":"unknown reasoning","thoughtSignature":"opaque"},
|
||||
{"text":"answer","thoughtSignature":gemini_signature()}
|
||||
]}]});
|
||||
client
|
||||
.generate(
|
||||
"project",
|
||||
"gemini-4-hydrogen",
|
||||
"token",
|
||||
&serde_json::to_vec(&history).unwrap(),
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
sent(&server).await["contents"][0]["parts"],
|
||||
json!([
|
||||
history["contents"][0]["parts"][0],
|
||||
history["contents"][0]["parts"][2],
|
||||
history["contents"][0]["parts"][3]
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 额度桶重置后的延迟预热、使用证据复核和持久化领取
|
||||
|
||||
use super::snapshot::BucketUseTime;
|
||||
use super::*;
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_core::account::QuotaWarmupStateUpdate;
|
||||
@@ -11,30 +12,49 @@ const RESET_WARMUP_DELAY_SECONDS: i64 = 5 * 60;
|
||||
struct BucketProgress {
|
||||
reset_at: Option<i64>,
|
||||
completed_reset_at: Option<i64>,
|
||||
last_warmup_at: Option<i64>,
|
||||
last_warmup_at: Option<BucketUseTime>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
credit_reset: Option<CreditReset>,
|
||||
retry_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct CreditReset {
|
||||
started_at: DateTime<Utc>,
|
||||
previous_window_end: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct LastRedemption {
|
||||
request_id: String,
|
||||
credit_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct WarmupProgress {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
last_redemption: Option<LastRedemption>,
|
||||
#[serde(default)]
|
||||
buckets: BTreeMap<String, BucketProgress>,
|
||||
}
|
||||
|
||||
fn enabled_windows<'a>(
|
||||
account: &'a ProviderAccount,
|
||||
snapshot: &'a CodexAccountQuotaSnapshot,
|
||||
) -> impl Iterator<Item = &'a CodexQuotaWindow> {
|
||||
snapshot.windows().iter().filter(|window| {
|
||||
window.is_account_wide()
|
||||
&& account
|
||||
.quota_settings()
|
||||
.iter()
|
||||
.any(|(key, settings)| key == window.key() && settings.warmup.is_some())
|
||||
})
|
||||
}
|
||||
|
||||
impl WarmupProgress {
|
||||
fn reconcile(&mut self, account: &ProviderAccount, snapshot: &CodexAccountQuotaSnapshot) {
|
||||
for (key, settings) in account.quota_settings().iter() {
|
||||
if settings.warmup.is_none() {
|
||||
continue;
|
||||
}
|
||||
let Some(window) = snapshot
|
||||
.windows()
|
||||
.iter()
|
||||
.find(|window| window.is_account_wide() && window.key() == key)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let progress = self.buckets.entry(key.to_owned()).or_default();
|
||||
for window in enabled_windows(account, snapshot) {
|
||||
let progress = self.buckets.entry(window.key().to_owned()).or_default();
|
||||
let observed_reset = window.reset_at().map(|at| at.timestamp());
|
||||
if let Some(reset) = progress.reset_at {
|
||||
let last_use = snapshot
|
||||
@@ -44,9 +64,19 @@ impl WarmupProgress {
|
||||
.into_iter()
|
||||
.chain(progress.last_warmup_at)
|
||||
.max();
|
||||
let newly_used = last_use.is_some_and(|used| used >= reset)
|
||||
|| (observed_reset.is_some_and(|next| next > reset)
|
||||
&& DateTime::<Utc>::from(snapshot.observed_at()).timestamp() >= reset
|
||||
let observed_at = DateTime::<Utc>::from(snapshot.observed_at());
|
||||
let used_after_reset = last_use.is_some_and(|used| match &progress.credit_reset {
|
||||
Some(credit) => used.0 >= credit.started_at,
|
||||
None => used.0.timestamp() >= reset,
|
||||
});
|
||||
let previous_end = progress
|
||||
.credit_reset
|
||||
.as_ref()
|
||||
.and_then(|credit| credit.previous_window_end)
|
||||
.unwrap_or(reset);
|
||||
let newly_used = used_after_reset
|
||||
|| (observed_reset.is_some_and(|next| next > previous_end)
|
||||
&& observed_at.timestamp() >= reset
|
||||
&& window.used_percent().is_some_and(|used| used > 0.0));
|
||||
if newly_used {
|
||||
progress.complete(reset);
|
||||
@@ -65,6 +95,29 @@ impl WarmupProgress {
|
||||
}
|
||||
}
|
||||
|
||||
fn register_weekly_reset(
|
||||
&mut self,
|
||||
account: &ProviderAccount,
|
||||
snapshot: &CodexAccountQuotaSnapshot,
|
||||
started_at: DateTime<Utc>,
|
||||
confirmed_at: i64,
|
||||
) -> bool {
|
||||
let mut registered = false;
|
||||
for window in
|
||||
enabled_windows(account, snapshot).filter(|w| w.kind() == CodexQuotaWindowKind::Weekly)
|
||||
{
|
||||
let bucket = self.buckets.entry(window.key().to_owned()).or_default();
|
||||
bucket.reset_at = Some(confirmed_at);
|
||||
bucket.retry_at = None;
|
||||
bucket.credit_reset = Some(CreditReset {
|
||||
started_at,
|
||||
previous_window_end: window.reset_at().map(|at| at.timestamp()),
|
||||
});
|
||||
registered = true;
|
||||
}
|
||||
registered
|
||||
}
|
||||
|
||||
fn due(&self, account: &ProviderAccount, now: DateTime<Utc>) -> Vec<(String, String, i64)> {
|
||||
account
|
||||
.quota_settings()
|
||||
@@ -88,6 +141,7 @@ impl BucketProgress {
|
||||
fn complete(&mut self, reset: i64) {
|
||||
self.completed_reset_at = Some(self.completed_reset_at.map_or(reset, |old| old.max(reset)));
|
||||
self.reset_at = None;
|
||||
self.credit_reset = None;
|
||||
self.retry_at = None;
|
||||
}
|
||||
}
|
||||
@@ -131,6 +185,56 @@ impl CodexCredentialQuotaService {
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub(super) async fn register_weekly_reset(
|
||||
&self,
|
||||
original: &ProviderAccount,
|
||||
started_at: DateTime<Utc>,
|
||||
request_id: Uuid,
|
||||
credit_id: Option<&str>,
|
||||
) -> Result<(), CodexCredentialQuotaError> {
|
||||
if !original.quota_settings().has_warmup() {
|
||||
return Ok(());
|
||||
}
|
||||
let request_id = request_id.to_string();
|
||||
let confirmed_at = Utc::now().timestamp();
|
||||
for _ in 0..QUOTA_MERGE_ATTEMPTS {
|
||||
let Some(account) = self.store.get_account(original.id()).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if account.revision() != original.revision()
|
||||
|| !warmup::warmup_account_is_available(&account)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let Some(snapshot) = self.read_snapshot_for(&account).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some((version, mut progress)) = self.read_warmup_progress(&account).await? else {
|
||||
return Ok(());
|
||||
};
|
||||
if progress.last_redemption.as_ref().is_some_and(|last| {
|
||||
last.request_id == request_id
|
||||
|| (credit_id.is_some() && last.credit_id.as_deref() == credit_id)
|
||||
}) {
|
||||
return Ok(());
|
||||
}
|
||||
if !progress.register_weekly_reset(&account, &snapshot, started_at, confirmed_at) {
|
||||
return Ok(());
|
||||
}
|
||||
progress.last_redemption = Some(LastRedemption {
|
||||
request_id: request_id.clone(),
|
||||
credit_id: credit_id.map(str::to_owned),
|
||||
});
|
||||
if self
|
||||
.write_warmup_progress(&account, &snapshot, version, &progress)
|
||||
.await?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(CodexCredentialQuotaError::RevisionConflict)
|
||||
}
|
||||
|
||||
/// 与 Cron 共用同一受租约保护的 worker,每次周期独立于全局 Cron 开关
|
||||
pub async fn execute_bucket_warmup_at(
|
||||
&self,
|
||||
@@ -192,7 +296,8 @@ impl CodexCredentialQuotaService {
|
||||
let Some(current) = self.store.get_account(account.id()).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !warmup::warmup_account_is_available(¤t)
|
||||
if account.revision() != current.revision()
|
||||
|| !warmup::warmup_account_is_available(¤t)
|
||||
|| current.quota().is_exhausted()
|
||||
|| current.quota_paused()
|
||||
|| !access_token_is_current(¤t, SystemTime::now())
|
||||
@@ -217,12 +322,16 @@ impl CodexCredentialQuotaService {
|
||||
.as_ref()
|
||||
.is_some_and(|warmup| warmup.model == *model)
|
||||
})
|
||||
&& progress
|
||||
.buckets
|
||||
.get(key)
|
||||
.is_some_and(|bucket| bucket.reset_at == Some(*reset))
|
||||
&& snapshot.windows().iter().any(|window| {
|
||||
window.is_account_wide() && window.key() == key && !window.limit_reached()
|
||||
&& progress.buckets.get(key).is_some_and(|bucket| {
|
||||
bucket.reset_at == Some(*reset)
|
||||
&& snapshot.windows().iter().any(|window| {
|
||||
window.is_account_wide()
|
||||
&& window.key() == key
|
||||
&& !window.limit_reached()
|
||||
&& (bucket.credit_reset.is_none()
|
||||
|| (window.reset_at().is_some()
|
||||
&& window.used_percent() == Some(0.0)))
|
||||
})
|
||||
})
|
||||
&& current.model_access().allows(model)
|
||||
});
|
||||
@@ -272,19 +381,12 @@ impl CodexCredentialQuotaService {
|
||||
return Ok(());
|
||||
};
|
||||
progress.reconcile(account, &snapshot);
|
||||
for (key, settings) in account.quota_settings().iter() {
|
||||
if settings.warmup.is_some()
|
||||
&& snapshot
|
||||
.windows()
|
||||
.iter()
|
||||
.any(|window| window.is_account_wide() && window.key() == key)
|
||||
{
|
||||
progress
|
||||
.buckets
|
||||
.entry(key.to_owned())
|
||||
.or_default()
|
||||
.last_warmup_at = Some(now.timestamp());
|
||||
}
|
||||
for window in enabled_windows(account, &snapshot) {
|
||||
progress
|
||||
.buckets
|
||||
.entry(window.key().to_owned())
|
||||
.or_default()
|
||||
.last_warmup_at = Some(BucketUseTime(now));
|
||||
}
|
||||
progress.reconcile(account, &snapshot);
|
||||
if self
|
||||
|
||||
@@ -208,9 +208,7 @@ fn merge_passive_quota(
|
||||
if let Some(usage) = usage.as_object_mut() {
|
||||
usage.insert(
|
||||
active_limit.clone(),
|
||||
serde_json::json!(
|
||||
chrono::DateTime::<chrono::Utc>::from(used_at).timestamp()
|
||||
),
|
||||
serde_json::json!(chrono::DateTime::<chrono::Utc>::from(used_at)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,7 +170,8 @@ impl CodexCredentialQuotaService {
|
||||
credential,
|
||||
};
|
||||
let request_id = format!("reset_credit_consume_{}", Uuid::now_v7().simple());
|
||||
consume_reset_credit_once(
|
||||
let started_at = chrono::Utc::now();
|
||||
let result = consume_reset_credit_once(
|
||||
&client,
|
||||
&prepared,
|
||||
&request_id,
|
||||
@@ -178,7 +179,28 @@ impl CodexCredentialQuotaService {
|
||||
redeem_request_id,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| map_reset_credit_attempt_error(error, true))
|
||||
.map_err(|error| map_reset_credit_attempt_error(error, true))?;
|
||||
if matches!(result.code.as_str(), "reset" | "already_redeemed")
|
||||
&& let Err(error) = self
|
||||
.register_weekly_reset(
|
||||
&prepared.account,
|
||||
started_at,
|
||||
redeem_request_id,
|
||||
result
|
||||
.credit
|
||||
.as_ref()
|
||||
.map(|card| card.id.as_str())
|
||||
.or(credit_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
account_id = %account_id,
|
||||
error = %error,
|
||||
"OpenAI quota bucket warmup after reset-credit consume failed"
|
||||
);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn reset_credit_account(
|
||||
|
||||
@@ -12,6 +12,7 @@ use gateway_core::account::{
|
||||
QuotaEvidence, QuotaObservation, QuotaResetPeriod, QuotaState,
|
||||
};
|
||||
use gateway_protocol::openai::events::{CreditsSnapshot, parse_credits_from_object};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::document::{
|
||||
@@ -110,6 +111,27 @@ impl CodexQuotaWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// 自然窗口按整秒划界,用卡操作还需区分同一秒内先后的使用
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
||||
pub(super) struct BucketUseTime(pub(super) DateTime<Utc>);
|
||||
|
||||
impl<'de> Deserialize<'de> for BucketUseTime {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Stored {
|
||||
Precise(DateTime<Utc>),
|
||||
Seconds(i64),
|
||||
}
|
||||
match Stored::deserialize(deserializer)? {
|
||||
Stored::Precise(at) => Ok(Self(at)),
|
||||
Stored::Seconds(at) => DateTime::from_timestamp(at, 0)
|
||||
.map(Self)
|
||||
.ok_or_else(|| serde::de::Error::custom("invalid bucket use timestamp")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CodexAccountQuotaSnapshot {
|
||||
account_id: ProviderAccountId,
|
||||
@@ -122,7 +144,7 @@ pub struct CodexAccountQuotaSnapshot {
|
||||
quota: QuotaState,
|
||||
windows: Vec<CodexQuotaWindow>,
|
||||
unconfirmed_limits: BTreeMap<String, f64>,
|
||||
pub(super) last_used_at: BTreeMap<String, i64>,
|
||||
pub(super) last_used_at: BTreeMap<String, BucketUseTime>,
|
||||
pub(super) recovery: Option<QuotaRecovery>,
|
||||
}
|
||||
|
||||
@@ -449,7 +471,9 @@ pub(crate) fn parse_account_quota_snapshot(
|
||||
.map(|usage| {
|
||||
usage
|
||||
.iter()
|
||||
.filter_map(|(source, at)| Some((source.clone(), at.as_i64()?)))
|
||||
.filter_map(|(source, at)| {
|
||||
Some((source.clone(), BucketUseTime::deserialize(at).ok()?))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
|
||||
@@ -8,6 +8,18 @@ async fn setup() -> (
|
||||
MockServer,
|
||||
chrono::DateTime<Utc>,
|
||||
i64,
|
||||
) {
|
||||
setup_window(-300, 0).await
|
||||
}
|
||||
|
||||
async fn setup_window(
|
||||
seconds_until_reset: i64,
|
||||
used: u64,
|
||||
) -> (
|
||||
Arc<MemoryAccountStore>,
|
||||
MockServer,
|
||||
chrono::DateTime<Utc>,
|
||||
i64,
|
||||
) {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_bucket_warmup").await;
|
||||
@@ -19,9 +31,12 @@ async fn setup() -> (
|
||||
.unwrap(),
|
||||
);
|
||||
let now = Utc::now();
|
||||
let reset = now.timestamp() - 300;
|
||||
let reset = now.timestamp() + seconds_until_reset;
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let observed_at = SystemTime::from(Utc.timestamp_opt(reset - 60, 0).unwrap());
|
||||
let observed_at = SystemTime::from(
|
||||
Utc.timestamp_opt(reset.min(now.timestamp()) - 60, 0)
|
||||
.unwrap(),
|
||||
);
|
||||
store
|
||||
.compare_and_swap_quota(QuotaObservation {
|
||||
quota_pause: None,
|
||||
@@ -29,7 +44,7 @@ async fn setup() -> (
|
||||
plan_type: None,
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
quota: OpaqueProviderData::new(usage(reset, 0).as_object().unwrap().clone()),
|
||||
quota: OpaqueProviderData::new(usage(reset, used).as_object().unwrap().clone()),
|
||||
observed_at,
|
||||
state: QuotaState::allowed(observed_at),
|
||||
})
|
||||
@@ -267,3 +282,243 @@ async fn pre_reset_usage_and_arbitrary_general_window_still_warm_up() {
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
async fn mount_consume(server: &MockServer, code: &str, card: Option<&str>) {
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/codex/rate-limit-reset-credits/consume"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"code": code,
|
||||
"credit": card.map(|id| json!({"id": id, "reset_type": "codex_rate_limits"}))
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(server)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rounded_request_in_idle_window_keeps_the_registered_boundary() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 0).await;
|
||||
let quota = service(&store, &server);
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap();
|
||||
observe_request("a, &store, now.timestamp() + 604800, false).await;
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rounded_request_in_the_natural_reset_second_skips_warmup() {
|
||||
let (store, server, now, reset) = setup().await;
|
||||
let quota = service(&store, &server);
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc.timestamp_opt(reset - 1, 0).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let mut document = usage(reset + 604800, 0);
|
||||
document["_cpr_bucket_last_used_at"] = json!({"codex": reset});
|
||||
let observed_at = SystemTime::from(Utc.timestamp_opt(reset, 500_000_000).unwrap());
|
||||
store
|
||||
.compare_and_swap_quota(QuotaObservation {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
quota: OpaqueProviderData::new(document.as_object().unwrap().clone()),
|
||||
observed_at,
|
||||
state: QuotaState::allowed(observed_at),
|
||||
quota_pause: None,
|
||||
expected_connection: None,
|
||||
plan_type: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap().warmed_up,
|
||||
0
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn confirmed_credit_retries_the_quota_check_after_restart() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
|
||||
let quota = service(&store, &server);
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap();
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let key = uuid::Uuid::new_v4();
|
||||
mount_consume(&server, "reset", None).await;
|
||||
quota
|
||||
.consume_reset_credit(account.id(), Some("credit_1"), key)
|
||||
.await
|
||||
.unwrap();
|
||||
let confirmed = Utc::now();
|
||||
quota
|
||||
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(4))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
|
||||
server.reset().await;
|
||||
let outage = Mock::given(method("GET"))
|
||||
.and(path("/api/codex/usage"))
|
||||
.respond_with(ResponseTemplate::new(400))
|
||||
.expect(1)
|
||||
.mount_as_scoped(&server)
|
||||
.await;
|
||||
let first = quota
|
||||
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first.failed, 1);
|
||||
drop(outage);
|
||||
let restarted = service(&store, &server);
|
||||
mount_usage(&server, now.timestamp() + 604800, 0, 1).await;
|
||||
mount_warmup(&server, 1).await;
|
||||
assert_eq!(
|
||||
restarted
|
||||
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(9))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
restarted
|
||||
.execute_bucket_warmup_at(confirmed + chrono::Duration::minutes(10))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn latest_credit_retries_keep_the_claim_and_new_credits_can_warm_up() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let first_key = uuid::Uuid::new_v4();
|
||||
for (code, key, requested_card, returned_card, expected) in [
|
||||
("reset", first_key, None, Some("first"), 1),
|
||||
("already_redeemed", first_key, None, None, 0),
|
||||
(
|
||||
"already_redeemed",
|
||||
uuid::Uuid::new_v4(),
|
||||
Some("first"),
|
||||
None,
|
||||
0,
|
||||
),
|
||||
("reset", uuid::Uuid::new_v4(), None, None, 1),
|
||||
("reset", uuid::Uuid::new_v4(), None, None, 1),
|
||||
] {
|
||||
let quota = service(&store, &server);
|
||||
mount_consume(&server, code, returned_card).await;
|
||||
mount_usage(&server, now.timestamp() + 604800, 0, expected).await;
|
||||
mount_warmup(&server, expected).await;
|
||||
quota
|
||||
.consume_reset_credit(account.id(), requested_card, key)
|
||||
.await
|
||||
.unwrap();
|
||||
let summary = quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(summary.warmed_up, expected);
|
||||
server.verify().await;
|
||||
server.reset().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rounded_request_after_credit_consume_skips_warmup() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 90).await;
|
||||
let quota = service(&store, &server);
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
mount_consume(&server, "reset", None).await;
|
||||
quota
|
||||
.consume_reset_credit(account.id(), None, uuid::Uuid::new_v4())
|
||||
.await
|
||||
.unwrap();
|
||||
observe_request("a, &store, now.timestamp() + 604800, false).await;
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reset_credit_consume_skips_warmup_when_new_cycle_already_has_usage() {
|
||||
let (store, server, now, _) = setup_window(3 * 86400, 80).await;
|
||||
let quota = service(&store, &server);
|
||||
assert_eq!(
|
||||
quota.execute_bucket_warmup_at(now).await.unwrap().warmed_up,
|
||||
0
|
||||
);
|
||||
mount_consume(&server, "reset", None).await;
|
||||
mount_usage(&server, now.timestamp() + 7 * 24 * 60 * 60, 1, 1).await;
|
||||
mount_warmup(&server, 0).await;
|
||||
quota
|
||||
.consume_reset_credit(
|
||||
&store.account("acct_bucket_warmup").unwrap().id().clone(),
|
||||
None,
|
||||
uuid::Uuid::new_v4(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reset_credit_consume_starts_warmup_after_previous_cycle_was_completed() {
|
||||
let (store, server, _, reset) = setup().await;
|
||||
let quota = service(&store, &server);
|
||||
// 先登记并完成本轮(窗口已到期且已有使用证据时跳过预热),再消费重置卡开启新窗口
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc.timestamp_opt(reset - 1, 0).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
observe_request("a, &store, reset + 604800, false).await;
|
||||
mount_consume(&server, "already_redeemed", None).await;
|
||||
mount_usage(&server, Utc::now().timestamp() + 7 * 24 * 60 * 60, 0, 1).await;
|
||||
mount_warmup(&server, 1).await;
|
||||
quota
|
||||
.consume_reset_credit(
|
||||
&store.account("acct_bucket_warmup").unwrap().id().clone(),
|
||||
None,
|
||||
uuid::Uuid::new_v4(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now())
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
quota
|
||||
.execute_bucket_warmup_at(Utc::now() + chrono::Duration::minutes(5))
|
||||
.await
|
||||
.unwrap()
|
||||
.warmed_up,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2030,7 +2030,7 @@ async fn provider_should_override_unclassified_time_contexts_over_websocket() {
|
||||
body.pointer("/input/1/content/0/text"),
|
||||
Some(&json!(desktop.replace("Asia/Shanghai", "Pacific/Auckland")))
|
||||
);
|
||||
assert_eq!(body.get("request_country"), Some(&json!("NZ")));
|
||||
assert_eq!(body.get("request_country"), Some(&Value::Null));
|
||||
assert_eq!(
|
||||
body.pointer("/input/0/content/0/text"),
|
||||
Some(&json!(
|
||||
@@ -6342,6 +6342,7 @@ async fn runtime_routing_headers_override_request_identity_and_clear_when_unset(
|
||||
{
|
||||
let settings = if index == 0 {
|
||||
gateway_core::settings::OpenAiRequestSettings {
|
||||
residency: Some("us".to_owned()),
|
||||
account_routing_override: Some("us_cr".to_owned()),
|
||||
..Default::default()
|
||||
}
|
||||
@@ -13770,10 +13771,7 @@ async fn downstream_client_markers_preserve_instruction_content() {
|
||||
let sent = capture_client_request(body.clone(), context, api_key).await;
|
||||
let mut expected = body;
|
||||
if !api_key {
|
||||
expected.insert(
|
||||
"request_country".to_owned(),
|
||||
json!(global_request_location().country),
|
||||
);
|
||||
expected.insert("request_country".to_owned(), Value::Null);
|
||||
}
|
||||
assert_eq!(sent, expected);
|
||||
}
|
||||
|
||||
@@ -92,13 +92,13 @@ async fn responses_options_follow_the_selected_upstream_on_both_transports() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_country_follows_the_selected_account_across_transports() {
|
||||
use OpenAiRequestCountry::{Custom, Default, FollowLocation, Passthrough};
|
||||
use OpenAiRequestCountry::{Custom, FollowLocation, Passthrough};
|
||||
let location = global_request_location();
|
||||
for (policy, location, input, oauth_country) in [
|
||||
(FollowLocation {}, None, None, Some(Value::Null)),
|
||||
(FollowLocation {}, Some(&location), None, Some(json!("NZ"))),
|
||||
(
|
||||
Default {},
|
||||
OpenAiRequestCountry::default(),
|
||||
Some(&location),
|
||||
Some(json!("CA")),
|
||||
Some(Value::Null),
|
||||
|
||||
@@ -150,7 +150,7 @@ async fn model_transports_apply_routing_settings_with_or_without_client_headers(
|
||||
"x-openai-account-routing-override",
|
||||
];
|
||||
for (document, expected) in [
|
||||
(r#"{}"#, [Some("us"), None]),
|
||||
(r#"{}"#, [None, None]),
|
||||
(
|
||||
r#"{"residency":null,"accountRoutingOverride":null}"#,
|
||||
[None, None],
|
||||
@@ -161,7 +161,7 @@ async fn model_transports_apply_routing_settings_with_or_without_client_headers(
|
||||
),
|
||||
(
|
||||
r#"{"accountRoutingOverride":"us_cr"}"#,
|
||||
[Some("us"), Some("us_cr")],
|
||||
[None, Some("us_cr")],
|
||||
),
|
||||
(
|
||||
r#"{"residency":"custom-region"}"#,
|
||||
@@ -173,7 +173,7 @@ async fn model_transports_apply_routing_settings_with_or_without_client_headers(
|
||||
),
|
||||
(
|
||||
r#"{"accountRoutingOverride":"NO_CONSTRAINT"}"#,
|
||||
[Some("us"), Some("NO_CONSTRAINT")],
|
||||
[None, Some("NO_CONSTRAINT")],
|
||||
),
|
||||
] {
|
||||
for (websocket, has_downstream_headers) in
|
||||
|
||||
@@ -50,3 +50,4 @@ e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_a
|
||||
c62495a0aff26b149381370fe1eea656091ab8d9d7d55aee27be4f56d5885fd3 0050_prompt_rewrite_rules.sql
|
||||
c4cc50c137deabae7895b97a8a8681c618f2b856276455d591475a02956ee373 0051_account_platform_icons.sql
|
||||
5911268734a4dddf099e747bdc684ef184b5861dd6fec0482c8da5f0eb35104c 0052_storage_write_efficiency.sql
|
||||
8118a6176c69ee64e5503f9d07043604679345e5e9e16f9dc606a58bfbc64442 0053_openai_request_defaults.sql
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
alter table runtime_settings
|
||||
alter column openai_request_settings_json set default '{"requestCountry":{"mode":"default"},"oauthGuardianReviewModel":true,"residency":null,"accountRoutingOverride":null}'::jsonb;
|
||||
|
||||
-- 仅调整旧默认值,保留自定义国家、透传模式及其他驻留和路由配置
|
||||
update runtime_settings
|
||||
set openai_request_settings_json = openai_request_settings_json
|
||||
|| case when openai_request_settings_json->'requestCountry' = '{"mode":"follow_location"}'::jsonb
|
||||
then '{"requestCountry":{"mode":"default"}}'::jsonb else '{}'::jsonb end
|
||||
|| case when openai_request_settings_json->'residency' = '"us"'::jsonb
|
||||
then '{"residency":null}'::jsonb else '{}'::jsonb end,
|
||||
settings_revision = config_revision + 1,
|
||||
config_revision = config_revision + 1,
|
||||
updated_at = now()
|
||||
where openai_request_settings_json->'requestCountry' = '{"mode":"follow_location"}'::jsonb
|
||||
or openai_request_settings_json->'residency' = '"us"'::jsonb;
|
||||
+4
-1
@@ -418,7 +418,7 @@ PostgreSQL/Redis 启动密码。日常校验使用 `config --quiet`
|
||||
| 并发与排队 | “系统设置 → 通用设置 → 并发与排队”分别配置 Key 与账号的排队容量和超时。账号排队失败后的处理在同页“重试与换号”中设置,见[排队规则](../docs/api.md#并发与排队) |
|
||||
| 账号错误保护 | “系统设置 → 通用设置 → 错误保护”默认关闭,按[自定义规则](../docs/api.md#账号错误保护)暂停账号调度 |
|
||||
| 全局请求位置 | “系统设置 → 平台设置 → OpenAI → 请求位置覆盖”,默认关闭 |
|
||||
| Codex OAuth 请求国家 | “系统设置 → 平台设置 → OpenAI → 请求国家”,默认跟随位置,也可选择“空值”“透传”或“自定义” |
|
||||
| Codex OAuth 请求国家 | “系统设置 → 平台设置 → OpenAI → 请求国家”,默认“空值”,也可选择“跟随位置”“透传”或“自定义” |
|
||||
| OpenAI OAuth 同步审核模型 | “系统设置 → 平台设置 → OpenAI → 自动审批”中的“专用审核模型”默认开启,关闭后沿用客户端模型。[适用条件](../docs/api.md#正文兼容) |
|
||||
| 代理位置 | “代理管理”;优先于全局位置,全局关闭时仍可独立生效 |
|
||||
|
||||
@@ -426,6 +426,9 @@ PostgreSQL/Redis 启动密码。日常校验使用 `config --quiet`
|
||||
数据驻留与账号路由在“系统设置 → 平台设置 → OpenAI → 请求设置”中填写,支持自定义值,留空删除对应请求头。
|
||||
保存后对新请求生效,无需重启。字段与适用范围见 [运行设置 API](../docs/api.md#数据驻留与路由)
|
||||
已有部署若在 `config.yaml` 中设置了 `openai.residency` 或 `openai.account_routing_override`,升级后须在平台设置中重新保存,并删除配置文件中的旧字段
|
||||
|
||||
升级迁移会一次性清空数据驻留 `us`,并将请求国家“跟随位置”改为“空值”,其他已配置值保持不变。需要这两项原值的部署,升级后在平台设置中重新保存
|
||||
|
||||
OAuth 续期和额度刷新等后台操作使用对应平台的全局客户端身份。发布资料刷新不改写用户选择或 `config.yaml`,见 [Provider 客户端身份](../docs/api.md#provider-客户端身份)
|
||||
|
||||
### CPR 互联
|
||||
|
||||
+22
-14
@@ -266,7 +266,7 @@ AGY 在 API Key 模式下使用 `gemini-3.1-flash-lite-preview` 发起同样的
|
||||
| GET | `/v1beta/models`、`/v1beta/models/{model}` | Gemini 格式的模型列表与详情,见[模型目录](#模型目录) |
|
||||
| POST | `/v1beta:{method}`(客户端后台指标) | 验证 Key 后返回 `{}`,不启动模型请求 |
|
||||
|
||||
普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 SSE 数据帧。等待首帧和后续帧时,网关保持静默。首帧前的失败保留 HTTP 错误状态。原生正文保留工具参数、结果、思考签名和未知字段。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content)
|
||||
普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 SSE 数据帧。等待首帧和后续帧时,网关保持静默。首帧前的失败保留 HTTP 错误状态。原生正文保留工具参数、结果和未知字段,思考签名按下述来源规则处理。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content)
|
||||
|
||||
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选 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)
|
||||
|
||||
@@ -274,6 +274,10 @@ Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agen
|
||||
|
||||
Claude 原生生成兼容缺失工具 ID 的历史:仅在相邻 `model`/`user` 轮次中,调用和结果的工具名各自唯一时补齐缺失的 `id`。一侧已有 ID 时沿用该 ID;两侧均缺失时生成确定性配对 ID,并避开正文已有 ID。已有字段、参数、结果和思考签名保持原样;同名并行调用、孤立结果、ID 冲突或格式错误不猜测配对,继续由上游校验。该兼容不作用于 Gemini、Chat 转换、独立搜索或输入计数
|
||||
|
||||
原生响应的思考签名保持上游原值,不添加网关标记。Claude/Gemini 生成根据已知原生封套识别来源,只移除可识别的异家族签名及对应思考内容,保留普通文本、工具调用和结果。导入 Gemini 的工具历史中,各轮首个工具调用缺少签名时使用官方 `skip_thought_signature_validator` 占位
|
||||
|
||||
签名处理不依赖服务端会话缓存。同家族、输入计数及无法识别的签名保持原样;封套识别不验证签名真伪,也不保证跨账号或项目复用。未知格式的旧历史切换模型仍可能被上游拒绝,此时需新建会话或 `/clear`
|
||||
|
||||
同账号及归属未知时保留追踪头;会话绑定或本次执行的已有账号归属明确发生切换时,CPR 清理入站或中间件带入的 `traceparent`、`tracestate`、`sentry-trace`、`baggage`。该清理作用于本次出站请求,不修改工具结果、思考签名或业务正文
|
||||
|
||||
原生生成依次使用 `X-Http-Session-Id`、`X-Session-Id`、正文 `sessionId`/`session_id` 识别会话,绑定按 Client Key、模型和入站协议隔离。会话识别只用于本地调度,保留客户端正文中的原值
|
||||
@@ -284,10 +288,10 @@ AGY 上游计数与生成响应的 `usageMetadata.promptTokenCount` 口径不完
|
||||
|
||||
Antigravity 模型也可通过 `/v1/chat/completions` 调用,支持 JSON 与 SSE;不接受 Responses 或 Messages 的内置跨协议调用。
|
||||
Chat 直接映射文本、图片/文档、函数与 custom 工具历史、生成参数和 JSON Schema。未知内容块或无法表达的语义返回请求错误,模型参数的实际支持范围由上游校验。
|
||||
原生入口保留工具结果和思考签名;常规生成与计数共用上述系统指令合成规则
|
||||
原生入口保留工具结果,思考签名按上述来源规则处理;常规生成与计数共用上述系统指令合成规则
|
||||
|
||||
Chat 工具多轮调用须携带完整助手输出和对应结果。Chat 只返回可读思考内容;对 Chat 历史中的工具调用使用 Google 的 `skip_thought_signature_validator` 标记,不增加服务端签名缓存。
|
||||
原生 GenAI 的真实签名仍原样回传,见 [Google 签名规则](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures)
|
||||
原生 GenAI 按上述来源规则保留真实签名,不以占位值替换同家族签名,见 [Google 签名规则](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures)
|
||||
|
||||
### Chat Completions 请求
|
||||
|
||||
@@ -914,8 +918,8 @@ OpenAI 仅在允许安全重放且尚未交付不可重放输出时执行下表
|
||||
投影为 `server_error`,HTTP 错误状态及 WS 包装错误的数字状态投影为 `503`,让客户端执行自己的
|
||||
有界重试。Provider 已确认容量不足的初始失败,即使没有这两个错误码,也返回 `503`。
|
||||
SSE/WS 的 `response.failed` 保留原消息、响应 ID 与其他业务字段;客户端无法消费的裸 `error`
|
||||
继续按现有规则投影为 `response.failed`。容量错误的 `Retry-After`、`retry-after-ms` 从响应头及错误事件的
|
||||
headers 中移除,避免客户端再次等待旧账号;关联 ID 等其他响应头保留,其他错误码不受影响。
|
||||
继续按现有规则投影为 `response.failed`。最终返回容量错误或因容量不足换号后要求客户端重放时,
|
||||
HTTP 响应头与 SSE/WS 错误事件保留上游提供的 `Retry-After` 和 `retry-after-ms`。
|
||||
内部上游状态、等待提示、错误码、原始事件及计量事实保持不变;已开始输出的请求由
|
||||
客户端决定如何恢复,代理不因此重放已提交的请求。
|
||||
`flex_unavailable` 是当前请求的终止拒绝,保留原始错误,不自动重试、切换传输或冷却账号
|
||||
@@ -1319,7 +1323,7 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
|
||||
- `provider`: `openai` 或 `xai`,省略或空值表示不过滤
|
||||
- `groupId`: 分组 ID、`ungrouped`,或省略以不过滤
|
||||
- `status`: `normal`、`quota_paused`、`quota_exhausted`、`rate_limited`、`disabled`、`error`
|
||||
- `sortBy`: `email`、`status`、`planType`、`usage`、`lastUsedAt`、`expiresAt`
|
||||
- `sortBy`: `name`(显示名称,缺失时依次使用邮箱、上游账号 ID、本地 ID)、`status`、`planType`、`usage`、`lastUsedAt`、`expiresAt`
|
||||
- `sortDirection`: `asc`、`desc`
|
||||
|
||||
账号列表的 `search` 仅按字面量包含匹配名称和邮箱,不区分大小写;`%`、`_` 和 `\` 按普通字符处理
|
||||
@@ -1362,6 +1366,7 @@ OpenAI OAuth 账号的 `capabilities.quotaSettingsSupported` 为真。通过 `PO
|
||||
该轮存在对应通用桶的请求使用证据或新窗口非零用量时跳过,不把重置前的使用或具名桶用量算入本轮。
|
||||
正常请求的额度反馈即使用量取整为 0% 也保留使用证据,主动额度刷新不会清除;成功的账号预热同样计入。
|
||||
无重置时间时等待后续观测,不通过空闲窗口滚动的倒计时推迟已登记的边界。
|
||||
手动或自动用卡确认成功后,已开启预热的通用周桶从确认时间起满 5 分钟复查。额度恢复且本轮空闲时才发送,重试最近一次用卡时沿用原预热进度。
|
||||
同批到期的通用窗口合并一次请求,领取进度跨重启保留;已领取请求发生超时或取消时不自动重放。
|
||||
账号停用、凭据不可用、额度耗尽或达到调度上限时不执行;复查失败最多每 5 分钟重查
|
||||
|
||||
@@ -1643,8 +1648,9 @@ OAuth 等待回调期间允许修改代理。提交时若代理已删除、停
|
||||
`unreachable` 表示无法连接代理端点,`tunnel_failed` 表示代理隧道协商失败。
|
||||
`check_proxy` 表示本次使用代理且建连失败,不能据此判定故障在代理;无提示时为 `null`
|
||||
- `sendState` 为 `not_sent`、`sent`、`ambiguous`,非 Provider 错误为 `null`
|
||||
- `error`、`providerErrorCode`、`providerErrorType`、`upstreamStatus`、`upstreamContentType` 和
|
||||
`upstreamBody` 是实际捕获的原始诊断字段;缺失时为 `null`,不会由本地猜测或翻译
|
||||
- `upstreamStatus` 可单独返回;`upstreamContentType` 和 `upstreamBody` 仅在有可展示的原始响应时返回
|
||||
- Antigravity 的 `providerErrorCode` 取 Google ErrorInfo 的 `reason`,`providerErrorType` 取 Google 的 `status`。
|
||||
`error` 优先展示可安全返回的上游消息,缺失时使用网关提示。验证链接不随连接测试返回
|
||||
|
||||
### 后台导入任务
|
||||
|
||||
@@ -2428,9 +2434,9 @@ Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请
|
||||
|
||||
```json
|
||||
{
|
||||
"requestCountry": { "mode": "follow_location" },
|
||||
"requestCountry": { "mode": "default" },
|
||||
"oauthGuardianReviewModel": true,
|
||||
"residency": "us",
|
||||
"residency": null,
|
||||
"accountRoutingOverride": null
|
||||
}
|
||||
```
|
||||
@@ -2441,14 +2447,14 @@ Antigravity 不应用这组国家、区域、城市和时区覆盖,原生请
|
||||
|
||||
| 管理端选项 | 设置值 | 发往上游的字段 |
|
||||
| --- | --- | --- |
|
||||
| 跟随位置 | `{"mode":"follow_location"}` | 默认选项。先取代理位置,再取已开启的全局位置。两者都没有时发送 `null` |
|
||||
| 空值 | `{"mode":"default"}` | 始终发送 `"request_country": null`,包括客户端传入国家、代理或全局位置已配置的情况 |
|
||||
| 跟随位置 | `{"mode":"follow_location"}` | 先取代理位置,再取已开启的全局位置。两者都没有时发送 `null` |
|
||||
| 空值 | `{"mode":"default"}` | 默认选项。始终发送 `"request_country": null`,包括客户端传入国家、代理或全局位置已配置的情况 |
|
||||
| 透传 | `{"mode":"passthrough"}` | 保留客户端原值,包括显式 `null`;客户端省略时也省略 |
|
||||
| 自定义 | `{"mode":"custom","country":"CA"}` | 始终发送指定的两位大写 ASCII 国家码,独立于城市、时区和全局位置开关 |
|
||||
|
||||
#### 数据驻留与路由
|
||||
|
||||
`openaiRequestSettings` 中的 `residency` 和 `accountRoutingOverride` 独立于客户端身份与请求位置,均为可选字符串,默认值分别为 `"us"` 和 `null`,分别设置 `x-openai-internal-codex-residency` 和
|
||||
`openaiRequestSettings` 中的 `residency` 和 `accountRoutingOverride` 独立于客户端身份与请求位置,均为可选字符串,默认 `null`,分别设置 `x-openai-internal-codex-residency` 和
|
||||
`x-openai-account-routing-override`。值必须能作为 HTTP/WebSocket 请求头发送(ASCII 文本),原样保留,不限制为固定选项。
|
||||
参考值分别为 `us` 和 `us`、`us_cr`。字段省略或为 `null` 时删除对应请求头,空字符串发送空头值;管理端留空保存为 `null`
|
||||
|
||||
@@ -3143,7 +3149,8 @@ Client Key 的频率、并发和费用预算限制分别为 `key_rate_limited`
|
||||
或 WS 关闭帧的 `closeReason`、`lastEventType`;不重新分类错误,也不包含原始请求、任意响应头或本地原因链。
|
||||
缺失、非 JSON 或未识别的结构返回 `null`,完整受控诊断通过诊断包获取。
|
||||
详情的 `message` 是网关摘要,不等同于上游 `upstreamError.message`;
|
||||
`retryAfterMs` 是已记录的重试等待毫秒数,未记录时为 `null`
|
||||
列表的 `upstreamErrorMessage` 优先取上游消息,其次取 WS 关闭原因,两者缺失时为 `null`。
|
||||
列表与详情的 `retryAfterMs` 是已记录的重试等待毫秒数,未记录时为 `null`
|
||||
|
||||
详情 `attempts[].downstreamCommitted` 为 `true` 时表示已开始客户端响应,为 `false` 时表示未开始。
|
||||
中间尝试的运维事件未保存交付边界,返回 `null`;不能据此推断客户端尚未收到响应
|
||||
@@ -3157,6 +3164,7 @@ Client Key 的频率、并发和费用预算限制分别为 `key_rate_limited`
|
||||
|
||||
使用记录列表和错误排查列表的 `accountPlanType` / `accountPlanTypeDisplay` 来自记录保存的账号订阅快照。
|
||||
Antigravity 的展示名取自请求时已观测到的 Google 套餐描述,快照缺少描述时为 `null`
|
||||
账号维度诊断按账号 ID 分组,`name` 依次取最近请求快照的账号名称、邮箱和账号 ID,`accountEmail` 返回快照邮箱,其他维度为 `null`。
|
||||
账号维度诊断使用该账号最近请求的订阅快照,并通过 `authenticationKind` 返回同一请求的认证类型快照;未保存的字段为 `null`,非账号维度的认证类型为 `null`
|
||||
|
||||
管理端请求列表及 Dashboard 最近请求中的 `accountNotes` 来自请求保存的账号备注快照,未保存时为 `null`
|
||||
|
||||
@@ -605,7 +605,7 @@ Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Message
|
||||
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
|
||||
原生生成与计数前置冻结画像的系统提示,普通 Chat 使用转换后的系统指令
|
||||
|
||||
Claude 原生生成的缺失工具 ID 兼容由 Antigravity `transport` 在出站副本上完成,只使用当前请求中可唯一配对的历史,不增加会话缓存或改变 Core 调度。配对边界见 [Antigravity 客户端原生生成](api.md#antigravity-客户端原生生成)
|
||||
Claude 原生生成的缺失工具 ID 配对,以及 Claude/Gemini 原生签名封套识别和跨家族思考历史清理由 Antigravity `transport` 持有。签名处理并入请求字段编辑,兼容或未知来源的历史复用原始内容,响应不改写签名;不增加会话缓存或改变 Core 调度。处理边界见 [Antigravity 客户端原生生成](api.md#antigravity-客户端原生生成)
|
||||
|
||||
Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属
|
||||
|
||||
@@ -811,7 +811,7 @@ Continuation 受原请求的 Client Key、账号范围、Provider 和发送/交
|
||||
正常 native 续接仍由连接池核对原连接及 response ID 是否可用
|
||||
- 原生续接的安全容量拒绝超过服务器建议等待上限时,Core 在换号预算内发起 `RotateForClientReplay`。
|
||||
OpenAI 仅通过既有选号器迁移会话绑定并释放租约,不发送当前增量输入;客户端收到完整历史重放指令后开启新链。
|
||||
无替代账号时保留原失败;API 移除容量错误的客户端等待提示,诊断仍保留原始错误与建议等待
|
||||
无替代账号时返回容量错误。两种客户端响应均保留上游的重试等待头
|
||||
- xAI 的续接状态只携带账号与 session ID;原生续接失效或进入重放阶段时返回 `ClientReplayRequired`,由客户端携带完整历史重发
|
||||
- scope 外账号与跨 Key 复用均拒绝;发送结果不明时,仅接受 Provider 明确给出的有界传输恢复意图
|
||||
|
||||
@@ -1150,6 +1150,7 @@ OpenAI 响应头的额度窗口按头名前缀归属,普通 Responses 的 `x-c
|
||||
按桶预热由 OpenAI Provider 解释重置时间、五分钟延迟和本轮使用证据,与 Cron 共用已有预热 worker 和单账号发送逻辑。
|
||||
请求使用时间按额度来源保留在 Provider 额度正文,未产生实际输出的失败响应只更新额度事实;刷新 `/usage` 保留本地使用证据。
|
||||
Store 在账号行独立保存不透明预热进度,通过凭据版本、配置、额度快照版本及账号状态原子领取,不推进配置版本。
|
||||
用卡确认后,OpenAI Provider 将最近一次消费的请求 ID 和可用的卡片 ID 随周桶预热进度一起保存,用于识别本次消费的重试。
|
||||
已领取的请求不因超时、取消或重启重放;普通凭据续期保留进度,身份替换或额度事实失效时同步失效进度
|
||||
|
||||
OpenAI Provider 统一解释点数可用性,主动查询、耗尽恢复与失败回读复用同一规则。
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"build:source": "vue-tsc -p tsconfig.source.json --noEmit && vite build --mode source"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#6ae11ac8b3509307a7efd54e6e4c2fc8fae98b89",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#09de193d1f1ff785b07713e0ccea98d35ebb0222",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lobehub/icons-vue": "1.2.0",
|
||||
|
||||
Generated
+5
-5
@@ -192,8 +192,8 @@ importers:
|
||||
.:
|
||||
dependencies:
|
||||
'@codex-proxy/ui':
|
||||
specifier: github:zyycn/codex-proxy-ui#6ae11ac8b3509307a7efd54e6e4c2fc8fae98b89
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/6ae11ac8b3509307a7efd54e6e4c2fc8fae98b89(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
specifier: github:zyycn/codex-proxy-ui#09de193d1f1ff785b07713e0ccea98d35ebb0222
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/09de193d1f1ff785b07713e0ccea98d35ebb0222(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
'@fontsource-variable/inter':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
@@ -451,8 +451,8 @@ packages:
|
||||
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
|
||||
engines: {node: '>= 20.12.0'}
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/6ae11ac8b3509307a7efd54e6e4c2fc8fae98b89':
|
||||
resolution: {gitHosted: true, integrity: sha512-HpFUCs+1qvcOtMrt8uoRdF/nABwnMeT2ziObJr3r+SMulIS9JKdMSQc3f+ZfsEn0iPR2Fmh6xXg/5QgWx8KNqA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/6ae11ac8b3509307a7efd54e6e4c2fc8fae98b89}
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/09de193d1f1ff785b07713e0ccea98d35ebb0222':
|
||||
resolution: {gitHosted: true, integrity: sha512-LQmVPnJgE6dHwQcKRpcJ3lS5uzyEVvugcfr4+kwbBU2VnoMcMII27oi/ukYXMUil73gvjX42OFwwCA16Y1HMyg==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/09de193d1f1ff785b07713e0ccea98d35ebb0222}
|
||||
version: 0.14.0
|
||||
engines: {node: '>=24'}
|
||||
peerDependencies:
|
||||
@@ -3559,7 +3559,7 @@ snapshots:
|
||||
fast-wrap-ansi: 0.2.2
|
||||
sisteransi: 1.0.5
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/6ae11ac8b3509307a7efd54e6e4c2fc8fae98b89(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/09de193d1f1ff785b07713e0ccea98d35ebb0222(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
dependencies:
|
||||
'@ant-design/colors': 8.0.1
|
||||
'@ant-design/fast-color': 3.0.1
|
||||
|
||||
@@ -87,6 +87,7 @@ export interface UsageErrorFacts {
|
||||
errorCode: string | null
|
||||
errorKind: string | null
|
||||
websocketCloseCode: number | null
|
||||
retryAfterMs: number | null
|
||||
continuationUnavailableReason: string | null
|
||||
upstreamConnectionExitReason: string | null
|
||||
recovered: boolean
|
||||
@@ -98,6 +99,7 @@ export interface UsageListRecord extends UsageErrorFacts {
|
||||
clientStatusCode: number | null
|
||||
upstreamStatusCode: number | null
|
||||
errorMessage: string | null
|
||||
upstreamErrorMessage: string | null
|
||||
clientApiKeyName: string | null
|
||||
id: string
|
||||
provider: string | null
|
||||
@@ -140,7 +142,6 @@ export interface UsageRecord extends UsageErrorFacts {
|
||||
closeReason: string | null
|
||||
lastEventType: string | null
|
||||
} | null
|
||||
retryAfterMs: number | null
|
||||
id: string
|
||||
requestId: string
|
||||
clientApiKeyId: string | null
|
||||
@@ -387,6 +388,7 @@ export interface UsageDiagnosticItem {
|
||||
platformIcon: string | null
|
||||
key: string
|
||||
name: string
|
||||
accountEmail: string | null
|
||||
authenticationKind: string | null
|
||||
accountPlanType: string | null
|
||||
accountPlanTypeDisplay: string | null
|
||||
|
||||
@@ -11,7 +11,7 @@ const canHover = useMediaQuery('(hover: hover)')
|
||||
<template>
|
||||
<ZPopover class="h-4 items-center" :trigger="canHover ? 'hover-click' : 'click'" placement="top-start" :hover-delay="240">
|
||||
<template #reference="{ open }">
|
||||
<ZIconButton variant="link" size="small" class="w-4!" :aria-label="label" :aria-expanded="open" aria-haspopup="dialog">
|
||||
<ZIconButton variant="link" size="small" class="size-6!" :aria-label="label" :aria-expanded="open" aria-haspopup="dialog">
|
||||
<CircleAlert class="size-3" aria-hidden="true" />
|
||||
</ZIconButton>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import type { UsageAccountIdentity } from './presenter'
|
||||
import { computed } from 'vue'
|
||||
import { usageAccountDisplay } from './presenter'
|
||||
|
||||
const props = defineProps<{ record: UsageAccountIdentity }>()
|
||||
const display = computed(() => usageAccountDisplay(props.record))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="block max-w-full truncate text-z-sm leading-none font-bold text-z-text">
|
||||
{{ display.primary }}
|
||||
</span>
|
||||
<span v-if="display.secondary" class="mt-1 block max-w-full truncate font-mono text-z-xs text-z-text-secondary">
|
||||
{{ display.secondary }}
|
||||
</span>
|
||||
</template>
|
||||
@@ -4,7 +4,8 @@ import { ZPopover, ZScrollbar } from '@codex-proxy/ui'
|
||||
import { CheckCheck, CircleHelp, Network, Server, Unplug } from '@lucide/vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { usageErrorOrigin, usageErrorSummary, usageErrorTitle } from './errors'
|
||||
import { formatDuration } from '@/utils/format'
|
||||
import { usageErrorMessage, usageErrorOrigin, usageErrorSummary, usageErrorTitle } from './errors'
|
||||
|
||||
const props = defineProps<{ record: UsageListRecord }>()
|
||||
|
||||
@@ -16,11 +17,12 @@ const originIcons = {
|
||||
}
|
||||
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const code = computed(() => props.record.errorCode || props.record.errorKind)
|
||||
const errorType = computed(() => props.record.errorKind || props.record.errorCode)
|
||||
const origin = computed(() => usageErrorOrigin(props.record))
|
||||
const outcome = computed(() => usageErrorTitle(props.record))
|
||||
const summary = computed(() => usageErrorSummary(props.record))
|
||||
|
||||
const message = computed(() => usageErrorMessage(props.record, props.record.errorMessage, props.record.upstreamErrorMessage))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -65,14 +67,19 @@ const summary = computed(() => usageErrorSummary(props.record))
|
||||
</template>
|
||||
<ZScrollbar class="w-max max-w-[min(26rem,calc(100vw-2rem))]" max-height="min(18rem, 60dvh)">
|
||||
<div class="grid gap-1 px-3 py-2 text-z-sm leading-relaxed whitespace-pre-wrap select-text wrap-anywhere" translate="no">
|
||||
<code v-if="code" class="font-mono font-emphasis">{{ code }}</code>
|
||||
<span v-if="record.errorKind && record.errorKind !== code">
|
||||
{{ t('usage.error.failureClassification') }} · <code>{{ record.errorKind }}</code>
|
||||
<span v-if="record.errorKind">
|
||||
{{ t('usage.error.failureClassification') }} · <code class="font-emphasis">{{ record.errorKind }}</code>
|
||||
</span>
|
||||
<span v-if="record.errorCode && record.errorCode !== record.errorKind">
|
||||
{{ t('usage.error.errorCode') }} · <code>{{ record.errorCode }}</code>
|
||||
</span>
|
||||
<span v-if="record.websocketCloseCode != null">
|
||||
{{ t('usage.error.websocketCloseCode') }} · <code>{{ record.websocketCloseCode }}</code>
|
||||
</span>
|
||||
<span>{{ record.errorMessage || t('usage.error.noDetails') }}</span>
|
||||
<span v-if="record.retryAfterMs != null">
|
||||
{{ t('usage.error.retryAfter') }} · <code>{{ formatDuration(record.retryAfterMs) }}</code>
|
||||
</span>
|
||||
<span>{{ t('usage.error.errorMessage') }} · {{ message }}</span>
|
||||
</div>
|
||||
</ZScrollbar>
|
||||
</ZPopover>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { UsageErrorFacts, UsageListRecord } from '@/api'
|
||||
import type { UsageErrorFacts, UsageListRecord, UsageRecord } from '@/api'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
export type UsageErrorRecord = UsageErrorFacts & {
|
||||
@@ -56,6 +56,29 @@ export function usageSendStateText(state: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function gatewayErrorMessage(kind: string | null, message: string | null) {
|
||||
if (kind === 'process_interrupted') {
|
||||
if (message === 'request did not reach a terminal state')
|
||||
return t('usage.error.processInterrupted')
|
||||
if (message === 'request recovery lease is missing')
|
||||
return t('usage.error.requestTrackingLost')
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
export function usageErrorMessage(
|
||||
record: Pick<UsageRecord, 'errorKind' | 'logicalOutcome'>,
|
||||
message: string | null,
|
||||
upstreamMessage: string | null | undefined,
|
||||
) {
|
||||
if (upstreamMessage)
|
||||
return upstreamMessage
|
||||
const saved = message?.trim()
|
||||
return saved && saved !== record.logicalOutcome
|
||||
? gatewayErrorMessage(record.errorKind, saved.replace(/^OpenAI upstream failure: /, ''))
|
||||
: t('usage.error.noDetails')
|
||||
}
|
||||
|
||||
export function usageErrorSummary(record: UsageListRecord): string {
|
||||
const reason = usageErrorReason(record.errorKind) || usageErrorReason(record.errorCode)
|
||||
if (reason)
|
||||
@@ -71,7 +94,7 @@ export function usageErrorSummary(record: UsageListRecord): string {
|
||||
if (record.errorKind === 'upstream_unavailable' && upstreamClosed)
|
||||
return t('usage.error.upstreamConnectionClosed')
|
||||
|
||||
return record.errorMessage || record.errorCode || record.errorKind
|
||||
return gatewayErrorMessage(record.errorKind, record.errorMessage) || record.errorCode || record.errorKind
|
||||
|| (record.websocketCloseCode != null
|
||||
? `WS ${record.websocketCloseCode}`
|
||||
: t('usage.error.noDetails'))
|
||||
|
||||
@@ -7,10 +7,8 @@ import { ZTable } from '@codex-proxy/ui'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import AccountPlanBadge from '@/components/account-plan-badge/index.vue'
|
||||
import ProviderIconGroup from '@/components/ProviderIconGroup.vue'
|
||||
import {
|
||||
usageAccountText,
|
||||
usageUserAgent,
|
||||
} from './presenter'
|
||||
import { usageUserAgent } from './presenter'
|
||||
import UsageAccountCell from './UsageAccountCell.vue'
|
||||
import UsageBillingCell from './UsageBillingCell.vue'
|
||||
import UsageClientIpCell from './UsageClientIpCell.vue'
|
||||
import UsageErrorCell from './UsageErrorCell.vue'
|
||||
@@ -63,11 +61,7 @@ const { t } = useI18n({ useScope: 'global' })
|
||||
</template>
|
||||
|
||||
<template #accountEmail="{ row }">
|
||||
<span
|
||||
class="block max-w-full truncate font-mono text-z-sm leading-none font-bold text-z-text"
|
||||
>
|
||||
{{ usageAccountText(row) }}
|
||||
</span>
|
||||
<UsageAccountCell :record="row" />
|
||||
<span
|
||||
v-if="row.accountNotes?.trim()"
|
||||
class="mt-1 block max-w-full truncate text-z-xs font-emphasis text-z-text-quaternary"
|
||||
|
||||
@@ -64,8 +64,24 @@ export function usageTransportTypeClass(transport?: string | null) {
|
||||
return 'bg-z-fill-tertiary text-z-text-secondary'
|
||||
}
|
||||
|
||||
export function usageAccountText(record: Pick<UsageCommonRecord, 'accountEmail' | 'accountName' | 'accountId'>) {
|
||||
return record.accountEmail || record.accountName || record.accountId || '—'
|
||||
export type UsageAccountIdentity = Pick<UsageCommonRecord, 'accountName' | 'accountEmail' | 'accountId'>
|
||||
|
||||
export function usageAccountDisplay(record: UsageAccountIdentity) {
|
||||
const email = record.accountEmail?.trim()
|
||||
const primary = record.accountName?.trim() || email || record.accountId || '—'
|
||||
return {
|
||||
primary,
|
||||
secondary: email && email !== primary
|
||||
? email
|
||||
: '',
|
||||
}
|
||||
}
|
||||
|
||||
export function usageAccountText(record: UsageAccountIdentity) {
|
||||
const { primary, secondary } = usageAccountDisplay(record)
|
||||
return secondary
|
||||
? `${primary} (${secondary})`
|
||||
: primary
|
||||
}
|
||||
|
||||
export function usageClientIp(record: { clientIp?: string | null }) {
|
||||
|
||||
@@ -111,6 +111,9 @@
|
||||
"proxyUnreachable": "Could not connect to the account proxy — test it in Proxies",
|
||||
"proxyTunnelFailed": "Could not establish a tunnel through the account proxy — check its settings",
|
||||
"checkProxy": "The request could not be sent upstream — test the account proxy in Proxies",
|
||||
"googleCredentials": "Google rejected the credentials for this account (401)",
|
||||
"googleAccessDenied": "Google denied this account access to Antigravity (403)",
|
||||
"googleVerification": "Sign in to Google and verify this account, then test again (403)",
|
||||
"upstreamUnavailable": "Upstream service temporarily unavailable",
|
||||
"timeout": "Upstream request timed out",
|
||||
"canceled": "Test canceled",
|
||||
|
||||
@@ -816,7 +816,7 @@
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "Account routing",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "Defaults to us, sends the residency header as entered, clearing the field removes the header",
|
||||
"residencyHelp": "Blank by default, sends the residency header as entered, clearing the field removes the header",
|
||||
"accountRoutingOverrideHelp": "Defaults to blank, reference values are us and us_cr, sends the routing header as entered, clearing the field removes the header",
|
||||
"description": "Configure parameters sent to the upstream provider"
|
||||
},
|
||||
|
||||
@@ -257,6 +257,8 @@
|
||||
"error": {
|
||||
"noDetails": "No detailed error message was recorded",
|
||||
"noAvailableProvider": "No upstream provider is available for this request.",
|
||||
"processInterrupted": "The gateway did not record how the request ended",
|
||||
"requestTrackingLost": "The gateway lost track of the request before its outcome was recorded",
|
||||
"requestLimited": "Request limited",
|
||||
"upstreamCapacityUnavailable": "Upstream model is at capacity",
|
||||
"upstreamConnectionClosed": "Upstream connection closed",
|
||||
@@ -273,6 +275,7 @@
|
||||
"responseId": "Response ID",
|
||||
"clientKeyId": "Client key ID",
|
||||
"errorCode": "Error code",
|
||||
"errorMessage": "Error message",
|
||||
"failureClassification": "Failure classification",
|
||||
"duration": "Duration",
|
||||
"triggerMode": "Trigger mode",
|
||||
|
||||
@@ -111,6 +111,9 @@
|
||||
"proxyUnreachable": "无法连接账号代理,请在「代理管理」中测试该代理",
|
||||
"proxyTunnelFailed": "未能通过账号代理建立隧道,请检查代理设置",
|
||||
"checkProxy": "请求未能发往上游,可在「代理管理」中测试账号代理",
|
||||
"googleCredentials": "Google 未接受此账号的登录凭据(401)",
|
||||
"googleAccessDenied": "Google 拒绝此账号访问 Antigravity(403)",
|
||||
"googleVerification": "请登录 Google 完成账号验证后再测试(403)",
|
||||
"upstreamUnavailable": "上游服务暂不可用",
|
||||
"timeout": "上游请求超时",
|
||||
"canceled": "测试请求已取消",
|
||||
|
||||
@@ -816,7 +816,7 @@
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "账号路由",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "默认 us,按填写值发送数据驻留请求头,留空则删除此请求头",
|
||||
"residencyHelp": "默认留空,按填写值发送数据驻留请求头,留空则删除此请求头",
|
||||
"accountRoutingOverrideHelp": "默认留空,可填写 us 或 us_cr,按填写值发送账号路由请求头,留空则删除此请求头",
|
||||
"description": "配置发往上游的请求参数"
|
||||
},
|
||||
|
||||
@@ -257,6 +257,8 @@
|
||||
"error": {
|
||||
"noDetails": "未记录具体错误消息",
|
||||
"noAvailableProvider": "此请求没有可用的上游服务",
|
||||
"processInterrupted": "网关未记录到请求结束",
|
||||
"requestTrackingLost": "网关已失去对这次请求的跟踪,最终结果未知",
|
||||
"requestLimited": "请求受限",
|
||||
"upstreamCapacityUnavailable": "上游模型容量不足",
|
||||
"upstreamConnectionClosed": "上游连接已关闭",
|
||||
@@ -273,6 +275,7 @@
|
||||
"responseId": "响应 ID",
|
||||
"clientKeyId": "API密钥 ID",
|
||||
"errorCode": "错误码",
|
||||
"errorMessage": "错误信息",
|
||||
"failureClassification": "失败分类",
|
||||
"duration": "耗时",
|
||||
"triggerMode": "触发方式",
|
||||
|
||||
@@ -111,6 +111,9 @@
|
||||
"proxyUnreachable": "無法連線至帳號代理,請在「代理管理」中測試該代理",
|
||||
"proxyTunnelFailed": "無法透過帳號代理建立通道,請檢查代理設定",
|
||||
"checkProxy": "請求未能送往上游,可在「代理管理」中測試帳號代理",
|
||||
"googleCredentials": "Google 未接受此帳號的登入憑證(401)",
|
||||
"googleAccessDenied": "Google 拒絕此帳號存取 Antigravity(403)",
|
||||
"googleVerification": "請登入 Google 完成帳號驗證後再測試(403)",
|
||||
"upstreamUnavailable": "上游服務暫不可用",
|
||||
"timeout": "上游請求超時",
|
||||
"canceled": "測試請求已取消",
|
||||
|
||||
@@ -816,7 +816,7 @@
|
||||
"residencyPlaceholder": "us",
|
||||
"accountRoutingOverride": "帳號路由",
|
||||
"accountRoutingPlaceholder": "us / us_cr",
|
||||
"residencyHelp": "預設 us,依填寫值傳送資料駐留請求標頭,留空則刪除此標頭",
|
||||
"residencyHelp": "預設留空,依填寫值傳送資料駐留請求標頭,留空則刪除此標頭",
|
||||
"accountRoutingOverrideHelp": "預設留空,可填寫 us 或 us_cr,依填寫值傳送帳號路由請求標頭,留空則刪除此標頭",
|
||||
"description": "配置發往上游的請求參數"
|
||||
},
|
||||
|
||||
@@ -257,6 +257,8 @@
|
||||
"error": {
|
||||
"noDetails": "未記錄具體錯誤消息",
|
||||
"noAvailableProvider": "此請求沒有可用的上游服務",
|
||||
"processInterrupted": "閘道未記錄到請求結束",
|
||||
"requestTrackingLost": "閘道已失去對這次請求的追蹤,最終結果未知",
|
||||
"requestLimited": "請求受限",
|
||||
"upstreamCapacityUnavailable": "上游模型容量不足",
|
||||
"upstreamConnectionClosed": "上游連線已關閉",
|
||||
@@ -273,6 +275,7 @@
|
||||
"responseId": "響應 ID",
|
||||
"clientKeyId": "API密鑰 ID",
|
||||
"errorCode": "錯誤碼",
|
||||
"errorMessage": "錯誤訊息",
|
||||
"failureClassification": "失敗分類",
|
||||
"duration": "耗時",
|
||||
"triggerMode": "觸發方式",
|
||||
|
||||
@@ -85,7 +85,7 @@ watch(hasPersonalInfo, (available) => {
|
||||
v-if="(account.capabilities.quota || quotaEntries.length > 0 || account.upstream?.discovered) && (hasPlanBadge || lastRefreshed)"
|
||||
class="col-span-2 row-start-2 m-0 flex min-w-0 items-center gap-1.5 text-z-xs font-emphasis text-z-text-secondary"
|
||||
>
|
||||
<AccountPlanBadge v-if="hasPlanBadge" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="sm" class="shrink-0" />
|
||||
<AccountPlanBadge v-if="hasPlanBadge" :upstream="account.upstream" :authentication-kind="account.authenticationKind" :plan-type="account.planType" :plan-type-display="account.planTypeDisplay" size="sm" class="shrink-0 rounded-md!" />
|
||||
<span v-if="lastRefreshed" class="min-w-0 truncate">{{ lastRefreshed }}</span>
|
||||
</p>
|
||||
<div v-if="hasActions" class="col-start-2 row-start-1 flex items-center gap-0.5 [&_svg]:size-3.5 [&_svg]:stroke-2">
|
||||
|
||||
@@ -123,7 +123,16 @@ function parseConnectionTestEvent(raw: string): ConnectionTestEvent | null {
|
||||
return value as ConnectionTestEvent
|
||||
}
|
||||
|
||||
function connectionTestFailureText(event: ConnectionTestFailureEvent) {
|
||||
function connectionTestFailureText(event: ConnectionTestFailureEvent, provider?: string) {
|
||||
if (provider === 'antigravity' && event.source === 'upstream') {
|
||||
if (event.upstreamStatus === 401)
|
||||
return t('accounts.connectionTest.errors.googleCredentials')
|
||||
if (event.upstreamStatus === 403) {
|
||||
return event.providerErrorCode === 'VALIDATION_REQUIRED'
|
||||
? t('accounts.connectionTest.errors.googleVerification')
|
||||
: t('accounts.connectionTest.errors.googleAccessDenied')
|
||||
}
|
||||
}
|
||||
if (event.source === 'provider' && event.sendState === 'not_sent') {
|
||||
switch (event.proxyHint) {
|
||||
case 'invalid_configuration': return t('accounts.connectionTest.errors.proxyInvalid')
|
||||
@@ -394,7 +403,7 @@ export function useAccountConnectionTest(options: { reload: () => Promise<unknow
|
||||
recordConnectionTestFailure(
|
||||
`failure-${event.source || 'unknown'}`,
|
||||
connectionTestFailureLabel(event),
|
||||
connectionTestFailureText(event),
|
||||
connectionTestFailureText(event, testingAccount.value?.provider),
|
||||
connectionTestFailureDiagnostics(event),
|
||||
event,
|
||||
)
|
||||
|
||||
@@ -35,7 +35,7 @@ export const accountColumns = computed(() => (defineTableColumns<Account>([
|
||||
label: t('accounts.account'),
|
||||
kind: 'identity',
|
||||
size: '2xl',
|
||||
sortable: 'email',
|
||||
sortable: 'name',
|
||||
},
|
||||
{
|
||||
key: 'provider',
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ZCard, ZFormItem, ZIconButton, ZInput, ZPopover, ZSwitch } from '@codex-proxy/ui'
|
||||
import { CircleAlert } from '@lucide/vue'
|
||||
import { ZCard, ZFormItem, ZInput, ZSwitch } from '@codex-proxy/ui'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
|
||||
@@ -34,17 +33,12 @@ const reservedConcurrency = defineModel<string>('reservedConcurrency', { require
|
||||
</ZFormItem>
|
||||
<ZFormItem :show-message="Boolean(reservedConcurrency.trim())" prop="openaiGuardianReservedConcurrency" :label="t('settings.concurrency.autoReview.label')" :description="t('settings.concurrency.autoReview.description')">
|
||||
<template #label-extra>
|
||||
<ZPopover class="-my-1" trigger="hover-click" placement="top-start">
|
||||
<template #reference="{ open }">
|
||||
<ZIconButton variant="link" :aria-label="t('settings.concurrency.autoReview.helpTitle')" :aria-expanded="open" class="size-6!">
|
||||
<CircleAlert class="size-3.5" aria-hidden="true" />
|
||||
</ZIconButton>
|
||||
</template>
|
||||
<div class="max-w-72 space-y-2 px-3 py-2 text-z-sm leading-relaxed text-z-text-secondary">
|
||||
<HelpPopover :label="t('settings.concurrency.autoReview.helpTitle')">
|
||||
<div class="space-y-2">
|
||||
<p>{{ t('settings.scheduling.autoReviewSlotsHelp') }}</p>
|
||||
<p>{{ t('settings.scheduling.autoReviewQueueHelp') }}</p>
|
||||
</div>
|
||||
</ZPopover>
|
||||
</HelpPopover>
|
||||
</template>
|
||||
<ZInput v-model="reservedConcurrency" :aria-label="t('settings.concurrency.autoReview.label')" :disabled="disabled" type="number" min="0" max="4294967295" step="1" />
|
||||
</ZFormItem>
|
||||
|
||||
@@ -42,7 +42,7 @@ export function useSettingsForm() {
|
||||
streamIdleTimeoutMs: null as number | null,
|
||||
},
|
||||
openaiRequestSettings: {
|
||||
requestCountry: { mode: 'follow_location' } as OpenAiRequestCountry,
|
||||
requestCountry: { mode: 'default' } as OpenAiRequestCountry,
|
||||
oauthGuardianReviewModel: true,
|
||||
residency: '',
|
||||
accountRoutingOverride: '',
|
||||
|
||||
@@ -118,6 +118,8 @@ function previewUsageRecord(options: PreviewUsageRecordOptions): UsageListRecord
|
||||
upstreamConnectionExitReason: null,
|
||||
recovered: false,
|
||||
errorMessage: null,
|
||||
upstreamErrorMessage: null,
|
||||
retryAfterMs: null,
|
||||
clientApiKeyName: t('appearance.preview.dashboard.demoKey'),
|
||||
provider: options.provider,
|
||||
authenticationKind: options.authenticationKind,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import AccountPlanBadge from '@/components/account-plan-badge/index.vue'
|
||||
import ProviderIconGroup from '@/components/ProviderIconGroup.vue'
|
||||
import { usageAccountDisplay } from '@/components/usage-records-table/presenter'
|
||||
import { formatLocalizedCompactNumber as formatCompactNumber, formatDuration, formatPercent, formatUsd } from '@/utils/format'
|
||||
|
||||
const props = withDefaults(
|
||||
@@ -123,26 +124,28 @@ type DiagnosticDisplayItem = Diagnostics['items'][number] & {
|
||||
const displayItems = computed<DiagnosticDisplayItem[]>(() =>
|
||||
(props.diagnostics?.items ?? []).map(item => ({
|
||||
...item,
|
||||
nameDisplay: diagnosticNameDisplay(item.name),
|
||||
nameDisplay: diagnosticNameDisplay(item),
|
||||
})),
|
||||
)
|
||||
const hasData = computed(() => !props.loading && displayItems.value.length > 0)
|
||||
|
||||
function diagnosticNameDisplay(name: string) {
|
||||
const raw = name.trim() || t('common.values.unknown')
|
||||
function diagnosticNameDisplay(item: Diagnostics['items'][number]) {
|
||||
if (resultDimension.value === 'account')
|
||||
return usageAccountDisplay({ accountName: item.name, accountEmail: item.accountEmail, accountId: item.key })
|
||||
|
||||
const raw = item.name.trim() || t('common.values.unknown')
|
||||
const full
|
||||
= resultDimension.value === 'transport'
|
||||
? ({ websocket: 'WS', http_sse: 'SSE' }[raw] ?? raw)
|
||||
: raw
|
||||
if (resultDimension.value !== 'model' && resultDimension.value !== 'account') {
|
||||
return { primary: full, secondary: '', full }
|
||||
if (resultDimension.value !== 'model') {
|
||||
return { primary: full, secondary: '' }
|
||||
}
|
||||
|
||||
const [primary, secondary = ''] = full.split(/\s+(?:→|->)\s+/, 2)
|
||||
return {
|
||||
primary: primary || full,
|
||||
secondary,
|
||||
full,
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -139,6 +139,7 @@ const attempts = computed(() => (props.record?.attempts ?? []).map(attempt => ({
|
||||
label: t('accounts.account'),
|
||||
value: usageAccountText(attempt),
|
||||
mono: true,
|
||||
wrap: true,
|
||||
},
|
||||
{
|
||||
label: t('usage.error.platform'),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import type { UsageRecordDetail } from '@/api'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { usageErrorOrigin, usageErrorTitle } from '@/components/usage-records-table/errors'
|
||||
import { usageErrorMessage, usageErrorOrigin, usageErrorTitle } from '@/components/usage-records-table/errors'
|
||||
import { usageTransportType } from '@/components/usage-records-table/presenter'
|
||||
import { formatDuration } from '@/utils/format'
|
||||
import UsageDetailFieldGrid from './UsageDetailFieldGrid.vue'
|
||||
@@ -12,15 +12,7 @@ const props = defineProps<{ record: UsageRecordDetail }>()
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const origin = computed(() => usageErrorOrigin(props.record))
|
||||
const title = computed(() => usageErrorTitle(props.record))
|
||||
const errorMessage = computed(() => {
|
||||
const upstream = props.record.upstreamError
|
||||
if (upstream?.message || upstream?.closeReason)
|
||||
return upstream.message || upstream.closeReason
|
||||
const message = props.record.message.trim()
|
||||
return message && message !== props.record.logicalOutcome
|
||||
? message.replace(/^OpenAI upstream failure: /, '')
|
||||
: t('usage.error.noDetails')
|
||||
})
|
||||
const errorMessage = computed(() => usageErrorMessage(props.record, props.record.message, props.record.upstreamError?.message || props.record.upstreamError?.closeReason))
|
||||
const errorItems = computed(() => [
|
||||
{ label: 'Code', value: props.record.upstreamError?.code ?? props.record.errorCode },
|
||||
{ label: 'Type', value: props.record.upstreamError?.errorType },
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import type { EChartsOption } from 'echarts'
|
||||
|
||||
import type { UsageRecordDetail } from '@/api'
|
||||
import type { UsageAttempt, UsageRecordDetail } from '@/api'
|
||||
import { defineTableColumns, ZButton, ZDialog, ZTable } from '@codex-proxy/ui'
|
||||
|
||||
import { computed } from 'vue'
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
usageTransportType,
|
||||
usageUserAgent,
|
||||
} from '@/components/usage-records-table/presenter'
|
||||
import UsageAccountCell from '@/components/usage-records-table/UsageAccountCell.vue'
|
||||
import { useChartPalette } from '@/composables/useChartPalette'
|
||||
|
||||
import { formatDuration, formatInteger } from '@/utils/format'
|
||||
@@ -74,6 +75,7 @@ const requestItems = computed(() => [
|
||||
label: t('accounts.account'),
|
||||
value: accountDisplay.value,
|
||||
mono: true,
|
||||
wrap: true,
|
||||
fullWidth: true,
|
||||
},
|
||||
{
|
||||
@@ -240,8 +242,7 @@ interface AttemptRow {
|
||||
model: string | null
|
||||
transport: string
|
||||
statusCode: number | null
|
||||
accountLabel: string
|
||||
accountId: string | null
|
||||
account: UsageAttempt
|
||||
latencyMs: number | null
|
||||
}
|
||||
|
||||
@@ -282,7 +283,7 @@ const attemptColumns = computed(() => (defineTableColumns<AttemptRow>([
|
||||
size: 'sm',
|
||||
},
|
||||
{
|
||||
key: 'accountLabel',
|
||||
key: 'account',
|
||||
label: t('accounts.account'),
|
||||
kind: 'mono',
|
||||
size: '2xl',
|
||||
@@ -304,8 +305,7 @@ const attemptRows = computed<AttemptRow[]>(() =>
|
||||
model: attempt.model,
|
||||
transport: attempt.transport,
|
||||
statusCode: attempt.statusCode,
|
||||
accountLabel: attempt.accountEmail || attempt.accountName || attempt.accountId || '—',
|
||||
accountId: attempt.accountId,
|
||||
account: attempt,
|
||||
latencyMs: attempt.latencyMs,
|
||||
})),
|
||||
)
|
||||
@@ -685,12 +685,8 @@ const tokenDonutOption = computed<EChartsOption>(() => {
|
||||
:status-code="typeof row.statusCode === 'number' ? row.statusCode : null"
|
||||
/>
|
||||
</template>
|
||||
<template #accountLabel="{ row }">
|
||||
<span
|
||||
class="block max-w-full truncate font-mono text-z-sm font-bold text-z-text"
|
||||
>
|
||||
{{ row.accountLabel }}
|
||||
</span>
|
||||
<template #account="{ row }">
|
||||
<UsageAccountCell :record="row.account" />
|
||||
</template>
|
||||
<template #latencyMs="{ row }">
|
||||
<span class="font-mono font-bold tabular-nums text-z-text">
|
||||
|
||||
+1
-1
Submodule modules/ui updated: 6ae11ac8b3...09de193d1f
+8
-6
@@ -1,15 +1,17 @@
|
||||
# v3.60.3
|
||||
# v3.60.5
|
||||
|
||||
## 优化改进
|
||||
|
||||
- Codex 出站 HTTP/2 使用与官方客户端一致的 h2 0.4.19
|
||||
- 请求错误浮层直接展示上游错误信息和重试等待时间,无需额外加载完整详情,并补充请求中断的本地化提示
|
||||
- Antigravity 连接测试区分 Google 登录凭据无效、访问被拒和需要账号验证,展示可安全返回的上游错误原因
|
||||
|
||||
## 问题修复
|
||||
|
||||
- 修复 Antigravity 原生调用 Claude 时因历史缺少工具 ID 导致的请求失败,自动补齐可唯一配对的工具调用和结果 ID
|
||||
- 插件取消发送与确认等待分别使用宿主排队期限(默认各 30 秒),避免批量取消时误关正常会话
|
||||
- 对齐 xAI 与 Grok CLI 的连接行为,原生 Responses 保留上游 SSE 帧,并过滤来自下游的代理和客户端环境头
|
||||
- 上游容量不足时,客户端收到的错误会保留上游建议的重试等待时间,换号后要求重发完整历史时也能看到
|
||||
- 修复手动或自动用卡后周额度桶仍等待原重置时间的问题,已启用预热的周桶在确认用卡 5 分钟后复查,本轮已有使用或重试同次消费时避免重复预热
|
||||
- 修复账号列表按邮箱而非显示名称排序的问题,请求记录、尝试明细和账号诊断统一优先展示名称并附邮箱
|
||||
- 修复图标选择器异步加载时的图标稳定性和网格响应式布局
|
||||
|
||||
## 升级须知
|
||||
|
||||
- xAI 原生续接失效时返回 `previous_response_not_found`,由客户端携带完整历史重发
|
||||
- 直接调用管理 API 的账号列表排序时,需将 `sortBy=email` 改为 `sortBy=name`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.60.3
|
||||
version: 3.60.5
|
||||
published:
|
||||
'3':
|
||||
stable: 3.60.2
|
||||
rc: 3.60.2
|
||||
beta: 3.60.2
|
||||
alpha: 3.60.2
|
||||
stable: 3.60.4
|
||||
rc: 3.60.4
|
||||
beta: 3.60.4
|
||||
alpha: 3.60.4
|
||||
|
||||
Reference in New Issue
Block a user