Compare commits

..
21 Commits
Author SHA1 Message Date
ZyyandCodex 95c35d0a67 chore: bump version to 3.62.0
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 01:07:04 +08:00
ZyyandCodex 259a2e1ba0 fix(backend): enforce body limits and simplify contracts
Reject subsequent reads after outbound bodies exceed capacity, reuse Client Key cursor wire types, and simplify protocol fixtures.

Clarify current API contracts, module ownership, and local test setup.

Co-authored-by: Codex <noreply@openai.com>
2026-12-05 00:45:03 +08:00
ZyyandCodex 2f51412625 fix(openai): align continuation history with Codex wire items
Project known response items and nested content for history matching without changing forwarded payloads. Preserve client tool-result metadata and compare unknown variants verbatim.

Add version-pinned replay fixtures and multi-turn outbound regression coverage.

Co-authored-by: Codex <noreply@openai.com>
2026-12-05 00:21:17 +08:00
PINGBOZHOUandClaude Opus 5.5 32f3b11ddf fix(openai): price gpt-image-2.6 models (#850)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 00:19:59 +08:00
github-actions[bot] c2891e14ce chore(release): update release channels to 3.61.1-rc.6 2026-12-04 13:53:03 +00:00
ZyyandCodex b28eee6e18 chore: bump version to 3.61.1-rc.6
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 21:29:59 +08:00
6bf182677a fix(antigravity): repair IDs for same-name parallel tools (#849)
Pair ID-less calls and results by tool name and GenAI ordering when
counts match. Preserve ambiguous groups and existing raw JSON fields.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 21:21:02 +08:00
ZyyandCodex 8d4b0496e2 fix(openai): map unsupported none reasoning effort to low when available
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 20:40:14 +08:00
github-actions[bot] 9b08c3a50d chore(release): update release channels to 3.61.1-rc.5 2026-12-04 10:14:06 +00:00
ZyyandCodex f43e1f95c3 chore: bump version to 3.61.1-rc.5
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:57:14 +08:00
21cf139c96 fix(openai): keep slow model catalog refreshes alive (#846)
Use a 30-second idle timeout for account retries and manual refreshes while keeping ordinary discovery bounded. Let the admin UI wait for these refreshes until completion or cancellation.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:49:30 +08:00
ZyyandCodex 7d6e4cc4e7 fix(openai): limit model retry hints to scoped rate limits
Keep ordinary account cooldowns on their existing selection path, including peer accounts after quota synchronization.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:40:15 +08:00
ZyyandCodex 2ddcd7c936 feat(openai): track turn rate limits per account and model
Preserve session scheduling and retry hints while a model cools down. Show active model limits and their recovery times in the account list.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 17:17:10 +08:00
ZyyandCodex c71e6176c5 fix(web): add a subtle surface to client import options
Give the tool row a persistent muted background and light shadow, and
increase the inset around the GitHub link.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:54:47 +08:00
ZyyandCodex 28d3e3c2cb fix(web): centralize page sizing and preserve PWA bottom spacing
Keep long pages naturally sized and share the available page height across
viewport-bound panels. Let list cards fill the remaining space while
preserving internal scrolling and pagination in short windows.

Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:54:46 +08:00
dd793a84ab fix(protocol): preserve tool semantics across Chat and Codex (#844)
Support named independent tool outputs and flatten custom grammar formats.
Adapt Codex search aliases, long call IDs and tool names while preserving
history pairing and restoring client-visible names in JSON and SSE.

Refs #843

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 14:13:31 +08:00
ZyyandCodex 5ed8b626d7 docs(skills): ground safeguards in expected behavior
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 13:33:50 +08:00
ZyyandCodex 96d8b25d0b fix(store): skip nested requests in key recovery and accept large limits
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 13:25:44 +08:00
Zyy a193de4eba fix(providers): align SSE history reuse with Codex and use disk for Antigravity artifacts 2026-12-04 13:07:26 +08:00
github-actions[bot] e296bef65e chore(release): update release channels to 3.61.1-rc.4 2026-12-04 04:09:54 +00:00
ZyyandCodex 89092272a1 docs(readme): add the Telegram community invite
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:49:02 +08:00
121 changed files with 4043 additions and 758 deletions

No files matched your search

+3 -1
View File
@@ -16,6 +16,8 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
评估功能建议、排障、开发和审查时,先按[问题与方案依据](../../../CONTRIBUTING.md#问题与方案依据)核实使用者要完成什么、当前行为造成了什么影响。反馈直接给出改法时,先弄清提出这个改法的原因
先确定正常使用时应得到的结果。设计校验、回退或故障恢复时,同时看它防住的具体风险和它可能挡住的正常用法。按协议、隔离要求和实际部署条件选择对正常路径影响最小的做法。只在假设的部署场景下才需要的处理,留到有相应需求时再做
排查故障时,从症状沿实际调用链回溯,定位行为最早偏离预期的环节,用源码、诊断或对照复现说明触发条件如何导致结果。原因尚未确定时,区分已知事实与假设,指出哪项证据能区分可能原因。确认根因后,在负责该行为的模块修复,用原触发场景验证
涉及 Codex 时,以对应版本的官方源码核实客户端行为,默认透明转发,只做必要适配。建议宿主接管已有决定时,指出需要它介入的网关职责或实际约束。若只是个别部署希望采用不同策略,说明不建议内置的原因。实现可行性不能证明宿主应当承担这项需求
@@ -56,7 +58,7 @@ description: Codex Proxy RS 的需求评估、排障、开发、代码审查与
- 移动或重命名测试时,核对受影响的场景覆盖是否保留;涉及子进程调用或名称过滤时,同步更新调用入口并实际运行,确认目标用例确实执行且行为断言通过
- 清理只证明旧字段、旧路由或旧实现已经消失的用例与附带断言;未知字段校验使用合法请求基线加无业务含义的未知字段,避免因缺少必填项等其他错误而误通过
- 同一层对同一行为的重复覆盖合并为清晰的场景矩阵,复用相邻测试夹具;跨层测试确有不同职责或失败路径时保留,不为统一而扩大测试辅助抽象
- 断言可观察的行为与业务不变量,避免复述结构体赋值、罗列表列或字段清单、匹配 SQL 文本与源码布局
- 断言可观察的行为与业务不变量,避免复述实现细节。验收上游兼容行为时,先从对应版本的上游实现确定预期,再核对网关对同一输入的处理。例如历史应增量续接时,要看出站请求是否只含预期的增量,因为回退全量也可能返回成功
- 维护项目明确要求的架构边界检查;发现漏检时,对照规则核实扫描范围、排除项与被检查的依赖关系,优先补齐现有检查中能稳定判定的缺口
- 当前协议兼容、数据读取兼容、安全边界、并发和资源生命周期仍需覆盖,不按 `old`、`legacy` 等名称机械删除,也不能用改名代替无效用例清理
- 不在仓库中新增或保留迁移 SQL 专项测试,包括迁移文本、schema 演变与指定版本升级用例;需要验证迁移执行、数据保留或回滚时,在临时目录编写一次性验证并使用隔离数据库,测试通过即可,临时脚本不纳入维护测试集
+13 -7
View File
@@ -12,7 +12,7 @@
[![GHCR](https://img.shields.io/badge/GHCR-codex--proxy--rs-2496ED?logo=docker&logoColor=white&style=flat-square)](https://github.com/zyycn/codex-proxy-rs/pkgs/container/codex-proxy-rs)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](LICENSE)
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [社区](#社区) · [贡献者](#贡献者) · [Star History](#star-history) · [支持项目](#支持项目) · [许可证](#许可证)
[快速预览](#快速预览) · [快速开始](#快速开始) · [文档](#文档) · [贡献者](#贡献者) · [Star History](#star-history) · [社区](#社区) · [支持项目](#支持项目) · [许可证](#许可证)
</div>
@@ -49,12 +49,6 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
| 开发宿主 | [开发与源码联调](docs/development.md) · [系统架构](docs/architecture.md) · [管理端主题](docs/theme.md) · [数据库迁移](backend/migrations/README.md) |
| 参与协作 | [贡献、审查与验证](CONTRIBUTING.md) |
## 社区
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
## 贡献者
[<img src="https://contrib.rocks/image?repo=zyycn/codex-proxy-rs&amp;columns=10" alt="查看 GitHub 贡献者列表" width="480">](https://github.com/zyycn/codex-proxy-rs/graphs/contributors)
@@ -68,6 +62,18 @@ curl -fsSL https://raw.githubusercontent.com/zyycn/codex-proxy-rs/main/deploy/in
</picture>
</a>
## 社区
点击或扫码加入 Telegram 群 [小酒馆][telegram-group]
[<img src="docs/community/telegram-qr.png" alt="扫码加入小酒馆 Telegram 群" width="138">][telegram-group]
[telegram-group]: https://t.me/+9tk761zbNAMyNWY9
问题反馈与功能建议请使用 [GitHub Issues](https://github.com/zyycn/codex-proxy-rs/issues),填写要求见 [贡献说明](CONTRIBUTING.md#提交-issue)
感谢 [LINUX DO](https://linux.do) 社区提供开放、友善的技术交流平台
## 支持项目
如果 Codex Proxy RS 帮助到你了,欢迎请我喝杯咖啡 ☕
@@ -79,7 +79,11 @@ impl Providers {
)
.await?;
environment.host.report_startup_ready("OpenAI Provider");
let antigravity = provider_antigravity::initialize(ports.clone()).await?;
let antigravity = provider_antigravity::initialize(
ports.clone(),
environment.host.runtime_data_dir().join("antigravity"),
)
.await?;
environment
.host
.report_startup_ready("Antigravity Provider");
@@ -92,6 +92,9 @@ pub struct AccountListQuery {
/// Admin query service 从运行态存储取得的当前账号冷却快照
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AccountRuntimeSnapshot {
/// 模型维度冷却独立于整账号冷却,不能据此阻断其他模型
pub model_cooldowns:
BTreeMap<String, Vec<gateway_core::provider_ports::ProviderScopedCooldown>>,
pub protection_rules: BTreeMap<String, Vec<gateway_core::account::AccountProtectionMatch>>,
pub cooldown: BTreeMap<String, gateway_core::account::AccountCooldown>,
/// `None` 表示实时 lease 存储不可用;`Some` 中未出现的账号当前使用量为零
@@ -223,6 +226,7 @@ pub struct AccountPage {
/// 同一状态快照下的账号事实与唯一状态投影
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountPageItem {
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
pub platform_icon: Option<String>,
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
pub account: AccountRecord,
@@ -1319,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
/// 统一账号目录的一行完整结果
#[derive(Debug, Clone, PartialEq)]
pub struct AccountDirectoryItem {
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
pub platform_icon: Option<String>,
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
pub account: AccountRecord,
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
lookback,
);
Ok(AccountDirectoryItem {
model_cooldowns: stored.model_cooldowns,
platform_icon: stored.platform_icon,
protection_rules: stored.protection_rules,
capacity: super::peer_link::upstream::account_capacity(
@@ -648,6 +649,7 @@ impl AccountsService for DefaultAccountsService {
lookback,
);
Ok(AccountDirectoryItem {
model_cooldowns: item.model_cooldowns,
platform_icon: item.platform_icon,
protection_rules: item.protection_rules,
capacity: crate::model::accounts::AccountCapacity {
@@ -315,6 +315,7 @@ impl AccountRuntimeStore for FakeRuntimeStore {
) -> AdminStoreResult<AccountRuntimeSnapshot> {
*self.requested_accounts.lock().expect("requested accounts") = account_ids.to_vec();
Ok(AccountRuntimeSnapshot {
model_cooldowns: BTreeMap::new(),
protection_rules: std::collections::BTreeMap::new(),
cooldown: BTreeMap::from([(
"acct_limited".to_owned(),
@@ -740,6 +740,7 @@ impl FakeAccountStore {
last_error_message: account.last_error_message.clone(),
};
AccountPageItem {
model_cooldowns: Vec::new(),
platform_icon: None,
protection_rules: Vec::new(),
capacity: gateway_admin::model::accounts::AccountCapacity {
@@ -67,6 +67,7 @@ pub(super) fn account_view(
time: crate::time::TimePresenter,
) -> AccountView {
let AccountDirectoryItem {
model_cooldowns,
platform_icon,
account,
capacity,
@@ -111,6 +112,17 @@ pub(super) fn account_view(
.map(|value| super::upstream_info::view(value, now, time));
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
quota.protection_rules = protection_rules;
quota.model_rate_limits = model_cooldowns
.into_iter()
.map(|cooldown| {
let until: DateTime<Utc> = cooldown.until().into();
AccountModelRateLimitView {
model: cooldown.scope().value().to_owned(),
until: time.rfc3339(&until),
until_display: time.datetime(&until),
}
})
.collect();
AccountView {
platform_icon,
quota_settings: account.quota_settings,
@@ -271,6 +283,7 @@ pub(super) fn account_quota_view(
let recovery_probe_required = cooldown.is_some_and(|value| value.kind.requires_probe());
(
AccountQuotaView {
model_rate_limits: Vec::new(),
paused_windows: quota.paused_windows,
refreshed_at: quota.observed_at.map(|value| time.rfc3339(&value)),
refreshed_at_relative: quota
@@ -382,6 +382,7 @@ pub use crate::admin::account_groups::AccountGroupRefView;
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountQuotaView {
pub model_rate_limits: Vec<AccountModelRateLimitView>,
pub paused_windows: Vec<String>,
pub refreshed_at: Option<String>,
pub refreshed_at_relative: Option<crate::time::RelativeTimeView>,
@@ -397,6 +398,14 @@ pub struct AccountQuotaView {
pub credits: Option<AccountQuotaCreditsView>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountModelRateLimitView {
pub model: String,
pub until: String,
pub until_display: String,
}
/// 上游点数安全视图,不透出额度响应中的其他 Provider 字段
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -484,7 +484,6 @@ impl TryFrom<(ClientKeyPage, crate::time::TimePresenter)> for ClientKeyListData
let next_cursor = page
.next_cursor
.map(wire_cursor)
.transpose()?
.as_ref()
.map(encode_client_key_cursor)
.transpose()?;
@@ -597,7 +596,8 @@ impl From<ClientKeyMutation> for MutatedClientKeyData {
}
/// 解码后的 Client Key 游标字段
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ClientKeyCursorData {
pub sort: ClientKeySort,
pub value: ClientKeyCursorValue,
@@ -614,25 +614,12 @@ pub enum ClientKeyCursorValue {
LastUsedAt(Option<DateTime<Utc>>),
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct CursorWire {
sort: ClientKeySort,
value: ClientKeyCursorValue,
id: String,
}
/// 把 owner 游标编码为不透明 wire 值
pub fn encode_client_key_cursor(
cursor: &ClientKeyCursorData,
) -> Result<String, WireValidationError> {
validate_client_key_cursor(cursor)?;
let bytes = serde_json::to_vec(&CursorWire {
sort: cursor.sort,
value: cursor.value.clone(),
id: cursor.id.clone(),
})
.map_err(|_| WireValidationError::new("cursor"))?;
let bytes = serde_json::to_vec(cursor).map_err(|_| WireValidationError::new("cursor"))?;
Ok(URL_SAFE_NO_PAD.encode(bytes))
}
@@ -644,13 +631,8 @@ pub fn decode_client_key_cursor(encoded: &str) -> Result<ClientKeyCursorData, Wi
let bytes = URL_SAFE_NO_PAD
.decode(encoded)
.map_err(|_| WireValidationError::new("cursor"))?;
let cursor: CursorWire =
let cursor: ClientKeyCursorData =
serde_json::from_slice(&bytes).map_err(|_| WireValidationError::new("cursor"))?;
let cursor = ClientKeyCursorData {
sort: cursor.sort,
value: cursor.value,
id: cursor.id,
};
validate_client_key_cursor(&cursor)?;
Ok(cursor)
}
@@ -724,20 +706,18 @@ fn domain_cursor(cursor: ClientKeyCursorData) -> Result<ClientKeyCursor, WireVal
})
}
fn wire_cursor(cursor: ClientKeyCursor) -> Result<ClientKeyCursorData, WireValidationError> {
fn wire_cursor(cursor: ClientKeyCursor) -> ClientKeyCursorData {
let value = match cursor.value {
DomainCursorValue::Name(value) => ClientKeyCursorValue::Name(value),
DomainCursorValue::Enabled(value) => ClientKeyCursorValue::Enabled(value),
DomainCursorValue::CreatedAt(value) => ClientKeyCursorValue::CreatedAt(value),
DomainCursorValue::LastUsedAt(value) => ClientKeyCursorValue::LastUsedAt(value),
};
let cursor = ClientKeyCursorData {
ClientKeyCursorData {
sort: wire_sort(cursor.sort),
value,
id: cursor.id.to_string(),
};
validate_client_key_cursor(&cursor)?;
Ok(cursor)
}
}
fn client_key_id(
+12 -10
View File
@@ -119,22 +119,24 @@ pub fn gateway_error_response(error: &GatewayError) -> Response {
}
let mut response = (status, Json(body)).into_response();
response.extensions_mut().insert(error.clone());
if let Some(delay) = error.retry_after()
&& let Ok(value) = HeaderValue::from_str(
&delay
.as_secs()
.saturating_add(u64::from(delay.subsec_nanos() > 0))
.max(1)
.to_string(),
)
{
if let Some(seconds) = retry_after_seconds(error) {
response
.headers_mut()
.insert(axum::http::header::RETRY_AFTER, value);
.insert(axum::http::header::RETRY_AFTER, HeaderValue::from(seconds));
}
response
}
/// HTTP 和 WS 的等待秒数均向上取整,避免客户端在冷却到期前重新发起请求
pub(crate) fn retry_after_seconds(error: &GatewayError) -> Option<u64> {
error.retry_after().map(|delay| {
delay
.as_secs()
.saturating_add(u64::from(delay.subsec_nanos() > 0))
.max(1)
})
}
/// Gateway 错误稳定映射,供 HTTP、SSE 和 WebSocket 共用
#[must_use]
pub const fn gateway_error_contract(
@@ -185,6 +185,9 @@ pub(super) fn initial_engine_error_event(
response_event_headers(response_headers)
};
if upstream.is_none() {
if let Some(seconds) = crate::client_error::retry_after_seconds(&gateway) {
headers.insert("retry-after".to_owned(), Value::String(seconds.to_string()));
}
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
for name in RESPONSE_REQUEST_ID_HEADERS {
headers.remove(name);
@@ -255,6 +255,18 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
last_error_message: None,
};
let mut item = account_page_item(facts, now, "oauth");
let model_until = now + Duration::seconds(8);
item.model_cooldowns = vec![gateway_core::provider_ports::ProviderScopedCooldown::new(
gateway_core::account::ProviderAccountId::new(item.account.id.clone()).unwrap(),
gateway_core::account::CredentialRevision::new(
item.account.credential_revision.get(),
)
.unwrap(),
gateway_core::provider_ports::ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
),
model_until.into(),
)];
if kind.is_error_protection() {
item.protection_rules = vec![gateway_core::account::AccountProtectionMatch {
id: "removed-rule".to_owned(),
@@ -278,6 +290,14 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
let body = to_bytes(response.into_body(), 32768).await.unwrap();
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
let quota = &value["data"]["items"][0]["quota"];
assert_eq!(
quota["modelRateLimits"],
serde_json::json!([{
"model": "gpt-5.4",
"until": zone.local(model_until).to_rfc3339(),
"untilDisplay": zone.local(model_until).format("%Y-%m-%d %H:%M:%S").to_string(),
}])
);
if kind.is_error_protection() {
assert_eq!(quota["rateLimitReason"], "error_protection");
assert_eq!(
@@ -411,6 +431,7 @@ fn account_page_item(
use gateway_core::account::resolve_account_status;
AccountPageItem {
model_cooldowns: Vec::new(),
platform_icon: None,
protection_rules: Vec::new(),
account: AccountRecord {
@@ -1,5 +1,6 @@
//! 验证 Client Key 管理接口的预算、密钥输入与查询合同
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{DateTime, TimeZone as _, Utc};
use gateway_api::admin::client_keys::{
self, ClientKeyCursorData, ClientKeyCursorValue, ClientKeyListData, ClientKeyMutationRequest,
@@ -475,12 +476,41 @@ fn client_key_cursor_should_round_trip_and_reject_noncanonical_input() {
};
let encoded = encode_client_key_cursor(&cursor).expect("encode cursor");
let decoded = decode_client_key_cursor(&encoded).expect("decode cursor");
let wire = json!({
"sort": { "field": "createdAt", "direction": "desc" },
"value": { "kind": "createdAt", "value": "2026-07-18T08:00:00Z" },
"id": "key_cursor"
});
assert_eq!(decoded, cursor);
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&URL_SAFE_NO_PAD.decode(&encoded).unwrap())
.unwrap(),
wire
);
assert!(!encoded.contains("key_cursor"));
for invalid in ["", "not-base64!", "e30"] {
assert!(decode_client_key_cursor(invalid).is_err());
}
for (field, value) in [
("unknownField", json!(true)),
("id", json!(" ")),
("value", json!({ "kind": "enabled", "value": true })),
(
"sort",
json!({ "field": "createdAt", "direction": "desc", "unknownField": true }),
),
] {
let mut invalid = wire.clone();
invalid[field] = value;
let encoded = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&invalid).unwrap());
assert_eq!(
decode_client_key_cursor(&encoded)
.expect_err("reject invalid cursor fields")
.field(),
"cursor"
);
}
}
#[test]
@@ -564,6 +564,7 @@ mod provider {
last_error_message: None,
};
AccountPageItem {
model_cooldowns: Vec::new(),
platform_icon: None,
protection_rules: Vec::new(),
capacity: gateway_admin::model::accounts::AccountCapacity {
@@ -1484,6 +1484,7 @@ impl AccountRuntimeStore for UnusedStore {
async fn active_rate_limits(&self) -> AdminStoreResult<AccountRuntimeSnapshot> {
Ok(AccountRuntimeSnapshot {
model_cooldowns: BTreeMap::new(),
cooldown: BTreeMap::new(),
protection_rules: BTreeMap::new(),
in_flight: Some(BTreeMap::new()),
@@ -1492,6 +1493,7 @@ impl AccountRuntimeStore for UnusedStore {
async fn account_runtime(&self, _: &[String]) -> AdminStoreResult<AccountRuntimeSnapshot> {
Ok(AccountRuntimeSnapshot {
model_cooldowns: BTreeMap::new(),
cooldown: BTreeMap::new(),
protection_rules: BTreeMap::new(),
in_flight: Some(BTreeMap::new()),
@@ -262,7 +262,8 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
{"role":"developer","content":"brief"},
{"role":"system","content":null},
{"role":"assistant","tool_calls":[]},
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]},
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
]);
let response = fixture.post(request.clone()).await;
assert_eq!(response.status(), StatusCode::OK);
@@ -384,10 +384,14 @@ fn engine_provider_error_should_preserve_retry_classification() {
#[test]
fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
let error = EngineError::Provider(ProviderError::new(
ProviderErrorKind::AccountCapacityUnavailable,
UpstreamSendState::NotSent,
));
let error = EngineError::Provider(
ProviderError::new(
ProviderErrorKind::AccountCapacityUnavailable,
UpstreamSendState::NotSent,
)
.with_retry_after(std::time::Duration::from_millis(7100)),
);
assert_eq!(engine_error_response(&error).headers()["retry-after"], "8");
let projected = gateway_error_from_engine(&error);
assert_eq!(
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
last_error_message: None,
};
*fixture.account.lock().unwrap() = Some(AccountPageItem {
model_cooldowns: Vec::new(),
platform_icon: None,
protection_rules: Vec::new(),
capacity: AccountCapacity {
@@ -1586,6 +1586,11 @@ impl GatewayError {
),
};
let mut gateway = gateway;
if gateway.kind() == GatewayErrorKind::AccountCapacityUnavailable
&& let Some(delay) = error.retry_after()
{
gateway = gateway.with_retry_after(delay);
}
if gateway.kind() == GatewayErrorKind::InvalidRequest
&& let Some(details) = error
.failure_observation
@@ -113,6 +113,7 @@ pub struct ProviderScopedCooldown {
credential_revision: CredentialRevision,
scope: ProviderCooldownScope,
until: SystemTime,
rate_limited_until: Option<SystemTime>,
}
impl ProviderScopedCooldown {
@@ -128,6 +129,7 @@ impl ProviderScopedCooldown {
credential_revision,
scope,
until,
rate_limited_until: None,
}
}
@@ -141,6 +143,18 @@ impl ProviderScopedCooldown {
self.credential_revision
}
/// 选号冷却可能还包含模型拒绝;目录只展示实际限流期限
#[must_use]
pub fn with_rate_limited_until(mut self, until: Option<SystemTime>) -> Self {
self.rate_limited_until = until.map(|until| until.min(self.until));
self
}
#[must_use]
pub const fn rate_limited_until(&self) -> Option<SystemTime> {
self.rate_limited_until
}
#[must_use]
pub const fn scope(&self) -> &ProviderCooldownScope {
&self.scope
+5
View File
@@ -117,6 +117,11 @@ pub async fn initialize_command_line(mut config: HostConfig) -> Result<HostBundl
}
impl HostBundle {
/// 宿主配置解析后的运行数据目录,供需要磁盘空间的内置服务使用。
pub fn runtime_data_dir(&self) -> &std::path::Path {
self.config.runtime_data_dir()
}
/// 向启动控制台报告一个组装阶段已就绪
pub fn report_startup_ready(&self, service: &'static str) {
tracing::info!(target: "gateway_startup", service, "服务启动正常");
@@ -416,6 +416,11 @@ impl HttpBody {
return Err(HttpError::sent("read size"));
}
loop {
if self.received > 32 * 1024 * 1024 {
// 累计量封存超限结果,后续读取不能交付已拒绝的缓冲
self.pending = Bytes::new();
return Err(HttpError::sent("response size"));
}
// 已缓冲的数据和就绪帧也受本次期限约束,不能绕过 owner 的读取预算
if Instant::now() >= deadline {
return Err(HttpError::sent("response deadline").with_kind(HttpErrorKind::Timeout));
@@ -445,9 +450,6 @@ impl HttpBody {
}
};
self.received = self.received.saturating_add(self.pending.len());
if self.received > 32 * 1024 * 1024 {
return Err(HttpError::sent("response size"));
}
}
}
}
@@ -158,6 +158,60 @@ async fn managed_http_caps_chunks_and_recovers_capacity_after_body_drop() {
);
}
#[tokio::test]
async fn managed_http_body_limit_rejects_all_reads_after_exceeding_capacity() {
let limit = 32 * 1024 * 1024;
let server = MockServer::start().await;
let client = HttpClient::new().unwrap();
for size in [limit, limit + 1] {
server.reset().await;
Mock::given(any())
.respond_with(ResponseTemplate::new(200).set_body_bytes(vec![42; size]))
.expect(1)
.mount(&server)
.await;
let mut response = client
.open(
request(server.uri()),
None,
&local_network(),
Duration::from_secs(10),
)
.await
.unwrap();
let mut received = 0;
let result = loop {
match response.body.read(64 * 1024).await {
Ok(Some(chunk)) => received += chunk.len(),
result => break result,
}
};
if size == limit {
assert!(result.unwrap().is_none());
assert_eq!(received, limit);
} else {
assert!(received <= limit);
let error = result.unwrap_err();
assert_eq!(error.kind(), HttpErrorKind::Response);
assert_eq!(error.send_state, UpstreamSendState::Sent);
assert_eq!(error.reason(), "response size");
assert_eq!(
response.body.read(1).await.unwrap_err().reason(),
"response size"
);
assert_eq!(
response
.body
.read_with_timeout(1, Duration::from_secs(1))
.await
.unwrap_err()
.reason(),
"response size"
);
}
}
}
#[tokio::test]
async fn managed_http_deadline_and_invalid_headers_preserve_send_facts() {
let server = MockServer::start().await;
@@ -59,11 +59,13 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
}
}
if role == "tool" {
string(
message.get("tool_call_id"),
&format!("{path}.tool_call_id"),
false,
)?;
// Responses 的独立工具输出通过名称标识,不依赖前序调用
let field = if message.get("tool_call_id").is_none_or(Value::is_null) {
"name"
} else {
"tool_call_id"
};
string(message.get(field), &format!("{path}.{field}"), false)?;
} else if message
.get("tool_call_id")
.is_some_and(|v| !v.is_null() && v != "")
@@ -166,12 +166,7 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
let mut message = object(value, &path)?;
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
if role == "tool" {
let call_id = required_string(
&mut message,
"tool_call_id",
&format!("{path}.tool_call_id"),
false,
)?;
let call_id = optional(&mut message, "tool_call_id");
let content_path = format!("{path}.content");
let content = required(&mut message, "content", &content_path)?;
let output = if content.is_string() {
@@ -179,15 +174,24 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
} else {
content_parts(content, &role, &content_path, false)?.into()
};
let kind = if custom_calls.contains(&call_id) {
let kind = if call_id
.as_ref()
.and_then(Value::as_str)
.is_some_and(|id| custom_calls.contains(id))
{
"custom_tool_call_output"
} else {
"function_call_output"
};
let mut item = json!({"type": kind, "call_id": call_id, "output": output});
if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
string(&name, &format!("{path}.name"), true)?;
item["name"] = name;
let mut item = json!({"type": kind, "output": output});
if let Some(call_id) = call_id {
item["call_id"] = call_id;
}
for field in ["name", "namespace"] {
if let Some(value) = optional(&mut message, field).filter(|value| value != "") {
string(&value, &format!("{path}.{field}"), true)?;
item[field] = value;
}
}
input.push(item);
continue;
@@ -377,12 +381,13 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
.into_iter()
.enumerate()
.map(|(index, value)| {
let path = format!("tools[{index}]");
let mut path = format!("tools[{index}]");
let mut tool = object(value, &path)?;
let kind = required_string(&mut tool, "type", &format!("{path}.type"), false)?;
if matches!(kind.as_str(), "function" | "custom") {
if let Some(nested) = optional(&mut tool, &kind) {
tool = object(nested, &format!("{path}.{kind}"))?;
path = format!("{path}.{kind}");
tool = object(nested, &path)?;
}
if tool.get("description") == Some(&Value::Null) {
tool.remove("description");
@@ -395,6 +400,14 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
tool.insert("strict".into(), false.into());
}
} else if let Some(format) = tool.get_mut("format").and_then(Value::as_object_mut)
&& format.get("type").and_then(Value::as_str) == Some("grammar")
&& let Some(grammar) = optional(format, "grammar")
{
// Chat 将语法嵌套在 grammar,Responses 使用同层的 syntax 和 definition
let grammar = object(grammar, &format!("{path}.format.grammar"))?;
format.extend(grammar);
format.insert("type".into(), "grammar".into());
}
}
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
@@ -63,14 +63,48 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
#[test]
fn invalid_tool_history_reports_source_path() {
let request = json!({"model":"m","messages":[{"role":"tool","content":"ok"}]});
assert_eq!(
parse_request(&serde_json::to_vec(&request).unwrap())
.err()
for (identity, parameter) in [
(json!({}), "messages[0].name"),
(json!({"name":null}), "messages[0].name"),
(json!({"name":" "}), "messages[0].name"),
(json!({"name":17}), "messages[0].name"),
(
json!({"name":"notifications","tool_call_id":""}),
"messages[0].tool_call_id",
),
(
json!({"name":"notifications","tool_call_id":17}),
"messages[0].tool_call_id",
),
] {
let mut message = json!({"role":"tool","content":"ok"});
message
.as_object_mut()
.unwrap()
.parameter(),
Some("messages[0].tool_call_id")
);
.extend(identity.as_object().unwrap().clone());
let request = json!({"model":"m","messages":[message]});
let error = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap_err();
assert_eq!(error.parameter(), Some(parameter));
}
}
#[test]
fn named_tool_outputs_preserve_the_original_request_and_target_requirements() {
let request = json!({"model":"m","messages":[
{"role":"tool","name":"notifications","namespace":"agent","content":"notice"}
]});
let parsed = parse_request(&serde_json::to_vec(&request).unwrap()).unwrap();
assert_eq!(&parsed, request.as_object().unwrap());
assert!(responses::convert_request(&parsed).is_ok());
for result in [
messages::convert_request(&parsed, &Default::default()),
genai::convert_request(&parsed),
] {
assert_eq!(
result.unwrap_err().parameter(),
Some("messages[0].tool_call_id")
);
}
}
#[test]
@@ -472,11 +506,14 @@ fn all_targets_apply_the_same_common_request_validation() {
#[test]
fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
for format in [
json!(null),
json!({"type":"text"}),
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
json!(17),
for (format, expected) in [
(json!(null), json!(null)),
(json!({"type":"text"}), json!({"type":"text"})),
(
json!({"type":"grammar","grammar":{"syntax":"lark","definition":"PRIVATE_GRAMMAR"}}),
json!({"type":"grammar","syntax":"lark","definition":"PRIVATE_GRAMMAR"}),
),
(json!(17), json!(17)),
] {
let mut body = super::request();
body.insert(
@@ -484,7 +521,7 @@ fn custom_format_constraints_are_preserved_or_rejected_by_the_target() {
json!([{"type":"custom","custom":{"name":"run","format":format}}]),
);
let responses = responses::convert_request(&body).unwrap();
assert_eq!(responses["tools"][0]["format"], format);
assert_eq!(responses["tools"][0]["format"], expected);
for result in [
messages::convert_request(&body, &Default::default()),
genai::convert_request(&body),
@@ -1,4 +1,4 @@
//! Chat 到 Responses 的字段、媒体和工具映射回归
//! Chat 到 Responses 的字段、媒体和工具映射
use gateway_protocol::chat_completions::responses::convert_request;
use serde_json::{Value, json};
@@ -53,6 +53,31 @@ fn preserves_ordered_roles_images_and_modern_tool_round_trip() {
assert!(converted.get("previous_response_id").is_none());
}
#[test]
fn named_tool_outputs_preserve_unpaired_identity_and_order() {
for call_id in [None, Some(Value::Null)] {
let mut notice = json!({"role":"tool","name":"lookup","namespace":"agent","content":[{"type":"text","text":"independent notice"}]});
if let Some(call_id) = call_id {
notice["tool_call_id"] = call_id;
}
let converted = convert(json!({"model":"model-a","messages":[
{"role":"assistant","tool_calls":[{"id":"call_lookup","type":"custom","custom":{"name":"lookup","input":"query"}}]},
notice,
{"role":"tool","tool_call_id":"call_lookup","content":"matched result"},
{"role":"tool","name":"notifications","content":"another notice"}
]}));
assert_eq!(
converted["input"],
json!([
{"type":"custom_tool_call","call_id":"call_lookup","name":"lookup","input":"query"},
{"type":"function_call_output","name":"lookup","namespace":"agent","output":[{"type":"input_text","text":"independent notice"}]},
{"type":"custom_tool_call_output","call_id":"call_lookup","output":"matched result"},
{"type":"function_call_output","name":"notifications","output":"another notice"}
])
);
}
}
#[test]
fn web_search_options_require_a_hosted_search_and_flatten_location() {
for (options, expected) in [
@@ -278,7 +303,7 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
]}));
assert_eq!(
converted["tools"][0],
json!({"type":"custom", "name":"patch", "format":schema})
json!({"type":"custom", "name":"patch", "format":{"type":"grammar","syntax":"lark","definition":"start: /.+/"}})
);
assert_eq!(
converted["tool_choice"],
@@ -293,6 +318,40 @@ fn custom_tools_keep_native_input_and_mixed_call_families_through_history() {
assert_eq!(converted["input"][5]["type"], "function_call_output");
}
#[test]
fn custom_grammar_formats_keep_their_constraints_and_source_paths() {
for nested in [false, true] {
for syntax in ["lark", "regex"] {
let format =
json!({"type":"grammar","syntax":syntax,"definition":"OK","future_field":true});
let definition = json!({"name":"probe","format":format});
let tool = if nested {
json!({"type":"custom","custom":definition})
} else {
json!({"type":"custom","name":"probe","format":format})
};
let mut body =
json!({"model":"m","messages":[{"role":"user","content":"hello"}],"tools":[tool]});
assert_eq!(convert(body.clone())["tools"][0]["format"], format);
let declaration = if nested {
&mut body["tools"][0]["custom"]
} else {
&mut body["tools"][0]
};
declaration["format"] = json!({"type":"grammar","grammar":false});
let error = convert_request(body.as_object().unwrap()).unwrap_err();
assert_eq!(
error.parameter(),
Some(if nested {
"tools[0].custom.format.grammar"
} else {
"tools[0].format.grammar"
})
);
}
}
}
#[test]
fn files_and_audio_are_preserved_as_inputs_instead_of_losing_the_user_turn() {
for file in [
@@ -1,4 +1,4 @@
//! Responses 到 Chat 的完整响应、SSE增量及历史字段回归
//! Responses 到 Chat 的完整响应、流式增量、用量与错误投影
use gateway_protocol::chat_completions::{
ChatAccumulator, ChatError, ChatIdentity,
@@ -7,86 +7,67 @@ use gateway_protocol::chat_completions::{
use serde_json::{Value, json};
use std::collections::BTreeMap;
struct Session(Vec<Value>);
impl Session {
fn new(events: Vec<Value>) -> Self {
Self(events)
}
fn with_batch(mut self, events: Vec<Value>) -> Self {
self.0.extend(events);
self
}
}
struct Fixture(Session);
struct Projection {
json: Option<Value>,
chunks: Vec<Value>,
error: Option<ChatError>,
}
impl Fixture {
fn new(events: Session) -> Self {
Self(events)
}
fn post(&self, request: Value) -> Projection {
let identity = chat_identity();
let mut result = Projection {
json: None,
chunks: Vec::new(),
error: None,
};
if request["stream"] == true {
let mut encoder = ChatStreamEncoder::new(
identity,
request["stream_options"]["include_usage"] == true,
);
for event in &self.0.0 {
match encoder.push_event(event["type"].as_str(), event) {
Ok(chunks) => result.chunks.extend(chunks),
Err(error) => {
result.error = Some(error);
return result;
}
fn project_events(events: &[Value], streaming: bool, include_usage: bool) -> Projection {
let identity = chat_identity();
let mut result = Projection {
json: None,
chunks: Vec::new(),
error: None,
};
if streaming {
let mut encoder = ChatStreamEncoder::new(identity, include_usage);
for event in events {
match encoder.push_event(event["type"].as_str(), event) {
Ok(chunks) => result.chunks.extend(chunks),
Err(error) => {
result.error = Some(error);
return result;
}
}
match encoder.finish() {
Ok(chunks) => result.chunks.extend(chunks),
Err(error) => result.error = Some(error),
}
}
match encoder.finish() {
Ok(chunks) => result.chunks.extend(chunks),
Err(error) => result.error = Some(error),
}
} else {
let projected = if events.len() == 1 {
events[0]
.get("response")
.ok_or(ChatError::IncompleteStream)
.and_then(|value| project_response(value, &identity))
} else {
let projected = if self.0.0.len() == 1 {
self.0.0[0]
.get("response")
.ok_or(ChatError::IncompleteStream)
.and_then(|value| project_response(value, &identity))
} else {
let mut encoder = ChatStreamEncoder::new(identity, true);
let mut accumulator = ChatAccumulator::default();
let mut collect = || {
for event in &self.0.0 {
for chunk in encoder.push_event(event["type"].as_str(), event)? {
accumulator.push(&chunk)?;
}
}
for chunk in encoder.finish()? {
let mut encoder = ChatStreamEncoder::new(identity, true);
let mut accumulator = ChatAccumulator::default();
let mut collect = || {
for event in events {
for chunk in encoder.push_event(event["type"].as_str(), event)? {
accumulator.push(&chunk)?;
}
Ok::<_, ChatError>(())
};
collect().and_then(|()| accumulator.finish())
}
for chunk in encoder.finish()? {
accumulator.push(&chunk)?;
}
Ok::<_, ChatError>(())
};
match projected {
Ok(value) => result.json = Some(value),
Err(error) => result.error = Some(error),
}
collect().and_then(|()| accumulator.finish())
};
match projected {
Ok(value) => result.json = Some(value),
Err(error) => result.error = Some(error),
}
result
}
result
}
fn json_body(response: Projection) -> Value {
assert!(response.error.is_none(), "{:?}", response.error);
response.json.unwrap()
}
fn sse_body(response: Projection) -> (String, Vec<Value>) {
fn stream_chunks(response: Projection) -> (String, Vec<Value>) {
assert!(response.error.is_none(), "{:?}", response.error);
(
serde_json::to_string(&response.chunks).unwrap(),
@@ -100,9 +81,6 @@ fn chat_identity() -> ChatIdentity {
model: "model-a".to_owned(),
}
}
fn chat_request(stream: bool) -> Value {
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
}
fn wire(kind: &str, mut value: Value) -> Value {
value["type"] = json!(kind);
value
@@ -135,8 +113,8 @@ fn tool(id: &str, call_id: &str, name: &str, arguments: &str) -> Value {
#[test]
fn json_projects_public_identity_text_and_actual_usage() {
let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))]));
let response = fixture.post(chat_request(false));
let events = vec![completed(json!([message("你好 🌍")]))];
let response = project_events(&events, false, false);
let body = json_body(response);
assert_eq!(body["object"], "chat.completion");
assert!(body["id"].as_str().unwrap().starts_with("chatcmpl-"));
@@ -164,7 +142,7 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() {
let mut answer = message(&text);
answer["content"][0]["annotations"] = json!([citation]);
for stream in [false, true] {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.done",
@@ -189,13 +167,11 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() {
json!({"output_index":2,"item":answer}),
),
completed(json!([])),
]));
let mut request = chat_request(stream);
request["web_search_options"] = json!({});
let response = fixture.post(request);
];
let response = project_events(&events, stream, false);
let expected = format!("🌍 {text}");
if stream {
let (_, chunks) = sse_body(response);
let (_, chunks) = stream_chunks(response);
assert_eq!(combined(&chunks, "content"), expected);
assert_eq!(
chunks.last().unwrap()["choices"][0]["finish_reason"],
@@ -223,8 +199,8 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
{"type":"message","id":"refusal1","role":"assistant","status":"completed",
"content":[{"type":"refusal","refusal":"cannot help"}]}]),
] {
let fixture = Fixture::new(Session::new(vec![completed(output.clone())]));
let response = fixture.post(chat_request(false));
let events = vec![completed(output.clone())];
let response = project_events(&events, false, false);
let body = json_body(response);
let choice = &body["choices"][0];
assert_eq!(choice["message"]["content"], Value::Null);
@@ -245,7 +221,7 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
}
#[test]
fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
fn stream_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
for include_usage in [false, true] {
let terminal = completed(json!([message("你好 🌍")]));
let events = [
@@ -316,7 +292,7 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
}
#[test]
fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
fn stream_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
let first = tool(
"fc_first",
"call_first",
@@ -324,7 +300,7 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
"{ \"city\": \"北京\" }",
);
let second = tool("fc_second", "call_second", "search", "{\"query\":\"Rust\"}");
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.added",
@@ -355,8 +331,8 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
json!({"output_index":2,"item":first}),
),
completed(json!([second, first])),
]));
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
];
let (_, chunks) = stream_chunks(project_events(&events, true, false));
let mut tools = BTreeMap::<u64, (String, String, String)>::new();
for chunk in &chunks {
if let Some(calls) = chunk["choices"][0]["delta"]["tool_calls"].as_array() {
@@ -406,7 +382,7 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
let mut text = message("preserved");
text["future_optional"] = json!({"opaque":true});
text["content"][0]["future_attribute"] = json!([1, 2, 3]);
let fixture = Fixture::new(Session::new(vec![
let events = vec![
wire("response.future_auxiliary", json!({"future":true})),
wire(
"response.future_reasoning.delta",
@@ -414,8 +390,8 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
),
created(),
completed(json!([text])),
]));
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
];
let (_, chunks) = stream_chunks(project_events(&events, true, false));
assert_eq!(combined(&chunks, "content"), "preserved");
assert!(
!chunks
@@ -430,7 +406,7 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
for streaming in [false, true] {
let state =
json!({"type":kind,"id":"ctx_1","encrypted_content":"opaque-private-state"});
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.added",
@@ -441,10 +417,10 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
json!({"output_index":0,"item":state}),
),
completed(json!([state, message("preserved")])),
]));
let response = fixture.post(chat_request(streaming));
];
let response = project_events(&events, streaming, false);
if streaming {
let (text, chunks) = sse_body(response);
let (text, chunks) = stream_chunks(response);
assert_eq!(combined(&chunks, "content"), "preserved");
assert!(!text.contains("opaque-private-state"));
assert_eq!(
@@ -474,10 +450,10 @@ fn incomplete_projects_only_supported_finish_reasons() {
"id":"resp_chat_test","status":"incomplete","output":[message("partial")],
"incomplete_details":{"reason":reason}}}),
);
let fixture = Fixture::new(Session::new(vec![created(), event]));
let response = fixture.post(chat_request(streaming));
let events = vec![created(), event];
let response = project_events(&events, streaming, false);
if streaming {
let (_, chunks) = sse_body(response);
let (_, chunks) = stream_chunks(response);
assert_eq!(
chunks.last().unwrap()["choices"][0]["finish_reason"],
expected
@@ -497,7 +473,7 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected()
"encrypted_content":"OPAQUE_ENCRYPTED_REASONING_MARKER"
});
for streaming in [false, true] {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.added",
@@ -525,14 +501,10 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected()
"output_tokens_details":{"reasoning_tokens":2,"accepted_prediction_tokens":1}}
}}),
),
]));
let mut request = chat_request(streaming);
if streaming {
request["stream_options"] = json!({"include_usage":true});
}
let response = fixture.post(request);
];
let response = project_events(&events, streaming, true);
let (body, content, usage) = if streaming {
let (body, chunks) = sse_body(response);
let (body, chunks) = stream_chunks(response);
let usage = chunks
.iter()
.find(|chunk| chunk["choices"] == json!([]))
@@ -572,12 +544,8 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() {
json!({"id":"action_native","type":"computer_call","status":"completed","call_id":"call_action","action":{"type":"click","x":1,"y":2}}),
] {
for streaming in [false, true] {
let fixture = Fixture::new(Session::new(vec![created(), completed(json!([output]))]));
let mut request = chat_request(streaming);
if streaming {
request["stream_options"] = json!({"include_usage":true});
}
let response = fixture.post(request);
let events = vec![created(), completed(json!([output]))];
let response = project_events(&events, streaming, true);
assert_eq!(response.error, Some(ChatError::InvalidResponse));
assert!(
!response
@@ -592,16 +560,15 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() {
#[test]
fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_text.delta",
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"partial"}),
),
]));
let mut body = chat_request(true);
body["stream_options"] = json!({"include_usage":true});
let response = fixture.post(body);
];
let response = project_events(&events, true, true);
assert_eq!(response.error, Some(ChatError::IncompleteStream));
assert!(
!response
@@ -618,16 +585,15 @@ fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
}
#[test]
fn first_batch_terminal_can_finish_without_creating_usage_facts() {
let fixture = Fixture::new(Session::new(vec![wire(
fn completed_event_without_usage_does_not_invent_usage() {
let events = vec![wire(
"response.completed",
json!({"response":{
"id":"resp_chat_test","status":"completed","output":[message("done only")]
}}),
)]));
let mut body = chat_request(true);
body["stream_options"] = json!({"include_usage":true});
let (_, chunks) = sse_body(fixture.post(body));
)];
let (_, chunks) = stream_chunks(project_events(&events, true, true));
assert_eq!(combined(&chunks, "content"), "done only");
assert_eq!(
chunks
@@ -643,7 +609,7 @@ fn first_batch_terminal_can_finish_without_creating_usage_facts() {
fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
let output = json!({"id":"msg_refusal","type":"message","role":"assistant","status":"completed",
"content":[{"type":"refusal","refusal":"cannot help"}]});
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.refusal.delta",
@@ -654,8 +620,8 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"refusal":"cannot help"}),
),
completed(json!([output])),
]));
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
];
let (_, chunks) = stream_chunks(project_events(&events, true, false));
assert_eq!(combined(&chunks, "refusal"), "cannot help");
assert_eq!(combined(&chunks, "content"), "");
assert_eq!(
@@ -667,23 +633,20 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
#[test]
fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage() {
for with_created in [false, true] {
// 终态与辅助事件同属一批 Core 交付 不构造已终结会话继续产出事件的另一种异常
let session = Session::new(if with_created {
let mut events = if with_created {
vec![created()]
} else {
Vec::new()
})
.with_batch(vec![
};
events.extend([
completed(json!([message("completed text")])),
wire(
"response.future_metadata",
json!({"response_id":"resp_chat_test","future":{"kept":true}}),
),
]);
let fixture = Fixture::new(session);
let mut body = chat_request(true);
body["stream_options"] = json!({"include_usage":true});
let (_, chunks) = sse_body(fixture.post(body));
let (_, chunks) = stream_chunks(project_events(&events, true, true));
assert_eq!(combined(&chunks, "content"), "completed text");
assert_eq!(
chunks
@@ -727,10 +690,9 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
failure
}
};
let fixture = Fixture::new(Session::new(vec![created(), failure]));
let mut body = chat_request(true);
body["stream_options"] = json!({"include_usage":true});
let (_, chunks) = sse_body(fixture.post(body));
let events = vec![created(), failure];
let (_, chunks) = stream_chunks(project_events(&events, true, true));
let errors = chunks
.iter()
.filter_map(|chunk| chunk.get("error"))
@@ -749,15 +711,15 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
#[test]
fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_text.delta",
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"already sent"}),
),
completed(json!([message("different result")])),
]));
let response = fixture.post(chat_request(true));
];
let response = project_events(&events, true, false);
assert_eq!(response.error, Some(ChatError::InvalidResponse));
assert_eq!(combined(&response.chunks, "content"), "already sent");
assert!(
@@ -795,7 +757,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
initial_custom["input"] = json!("");
let mut initial_function = function.clone();
initial_function["arguments"] = json!("");
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_item.added",
@@ -818,10 +780,10 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
json!({"output_index":0,"item_id":"ct_1","input":"first\nsecond"}),
),
completed(output.clone()),
]));
let response = fixture.post(chat_request(streaming));
];
let response = project_events(&events, streaming, false);
if streaming {
let (body, chunks) = sse_body(response);
let (body, chunks) = stream_chunks(response);
assert_eq!(combined(&chunks, "refusal"), "no");
assert_eq!(combined(&chunks, "reasoning_content"), "thought");
assert!(!body.contains("PRIVATE_REASONING"));
@@ -870,7 +832,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
let image = json!({"id":"ig_one","type":"image_generation_call","status":"completed","result":"ZmluYWw=","output_format":"webp"});
for streaming in [false, true] {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.image_generation_call.partial_image",
@@ -881,10 +843,10 @@ fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
json!({"output_index":0,"item":image}),
),
completed(json!([image, message("created")])),
]));
let response = fixture.post(chat_request(streaming));
];
let response = project_events(&events, streaming, false);
if streaming {
let (_, chunks) = sse_body(response);
let (_, chunks) = stream_chunks(response);
let images = chunks
.iter()
.filter_map(|chunk| chunk["choices"][0]["delta"]["images"].as_array())
@@ -913,7 +875,7 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
let mut output = message("hello");
output["content"][0]["logprobs"] = probabilities.clone();
for streaming in [false, true] {
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_text.delta",
@@ -924,10 +886,10 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","text":"hello","logprobs":probabilities}),
),
completed(json!([output])),
]));
let response = fixture.post(chat_request(streaming));
];
let response = project_events(&events, streaming, false);
if streaming {
let (_, chunks) = sse_body(response);
let (_, chunks) = stream_chunks(response);
let values = chunks
.iter()
.filter_map(|chunk| chunk["choices"][0]["logprobs"]["content"].as_array())
@@ -951,7 +913,7 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
first["content"][0]["annotations"] = json!([citation]);
let mut second = message("xy");
second["id"] = json!("msg_second");
let fixture = Fixture::new(Session::new(vec![
let events = vec![
created(),
wire(
"response.output_text.delta",
@@ -970,8 +932,8 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","annotation_index":0,"annotation":citation}),
),
completed(json!([first, second])),
]));
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
];
let (_, chunks) = stream_chunks(project_events(&events, true, false));
assert_eq!(combined(&chunks, "content"), "abxycd");
let annotations = chunks
.iter()
@@ -69,7 +69,9 @@ impl ClientAdmissionRecoveryRepository for PgClientAdmissionRecoveryRepository {
lease.lease_expires_at, request.outcome
from model_requests request
left join model_request_leases lease on lease.request_id = request.id
where request.started_at >= $1 or request.outcome = 'running'
where (request.started_at >= $1 or request.outcome = 'running')
and (request.client_transport, request.request_kind)
is distinct from ('internal_plugin', 'plugin_child_model')
order by request.client_api_key_ref, request.started_at, request.id",
)
.bind(window_started_at)
@@ -325,19 +325,36 @@ impl AccountStore for PgAdminAccountStore {
));
}
let now = Utc::now();
let cooldown = runtime.cooldown;
let now_system_time = std::time::SystemTime::from(now);
let active_rate_limited_ids = cooldown
let active_rate_limited_ids = runtime
.cooldown
.iter()
.filter(|(_, cooldown)| cooldown.is_active(now_system_time))
.map(|(account_id, _)| account_id.clone())
.collect::<Vec<_>>();
let active_model_revisions = runtime
.model_cooldowns
.iter()
.flat_map(|(account, models)| {
models
.iter()
.filter(|model| model.until() > now_system_time)
.filter_map(|model| {
i64::try_from(model.credential_revision().get())
.ok()
.map(|revision| (account.clone(), revision))
})
})
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
let page = load_admin_account_page(
&self.pool,
&self.query_budget,
&query,
now,
active_rate_limited_ids,
active_model_revisions,
)
.await?;
let item_ids = page
@@ -351,14 +368,12 @@ impl AccountStore for PgAdminAccountStore {
.into_iter()
.map(|(summary, platform_icon)| {
let account_id = summary.id.clone();
let projection = account_status_projection(
&summary,
now.into(),
cooldown.get(&account_id).copied(),
);
let (projection, model_cooldowns) =
super::runtime::account_directory_projection(&summary, now.into(), &runtime);
let mut account = admin_account_record(summary)?;
account.groups = groups_by_account.remove(&account_id).unwrap_or_default();
Ok(AccountPageItem {
model_cooldowns,
platform_icon,
protection_rules: runtime
.protection_rules
@@ -397,8 +412,8 @@ impl AccountStore for PgAdminAccountStore {
return Ok(None);
};
let now = Utc::now();
let cooldown = runtime.cooldown.get(account_id).copied();
let projection = account_status_projection(&record.summary, now.into(), cooldown);
let (projection, model_cooldowns) =
super::runtime::account_directory_projection(&record.summary, now.into(), &runtime);
let account_id = record.summary.id.clone();
let mut groups = self
.account_groups_by_account(std::slice::from_ref(&account_id))
@@ -424,6 +439,7 @@ impl AccountStore for PgAdminAccountStore {
)
})?;
Ok(Some(AccountPageItem {
model_cooldowns,
platform_icon,
protection_rules: runtime
.protection_rules
@@ -16,7 +16,10 @@ pub(crate) async fn load_admin_account_page(
query: &AdminAccountListQuery,
now: DateTime<Utc>,
active_rate_limited_ids: Vec<String>,
active_model_revisions: Vec<(String, i64)>,
) -> AdminStoreResult<AdminAccountPageRows> {
let (model_account_ids, model_revisions): (Vec<_>, Vec<_>) =
active_model_revisions.into_iter().unzip();
validate_group_filter(pool, query.group_filter.as_ref()).await?;
let provider_kind = query
@@ -56,7 +59,10 @@ pub(crate) async fn load_admin_account_page(
when a.credential_state <> 'ready'
or a.access_token_expires_at <= $2 then 'error'
when a.quota_access_state = 'exhausted' then 'quota_exhausted'
when a.id = any($1::text[]) then 'rate_limited'
when a.id = any($1::text[]) or exists (
select 1 from unnest($13::text[], $14::bigint[]) as limits(account_id, revision)
where limits.account_id = a.id and limits.revision = a.credential_revision
) then 'rate_limited'
when a.quota_paused then 'quota_paused'
else 'normal'
end as admin_status
@@ -165,6 +171,8 @@ pub(crate) async fn load_admin_account_page(
.bind(usage_ids)
.bind(usage_tokens)
.bind(usage_latest)
.bind(model_account_ids)
.bind(model_revisions)
.fetch_all(&mut *snapshot.tx)
.await
.map_err(|source| postgres_unavailable("load admin account page", source))?;
@@ -12,6 +12,40 @@ use gateway_core::{
use super::ProviderAccountSummary;
pub(crate) fn account_directory_projection(
account: &ProviderAccountSummary,
now: SystemTime,
runtime: &gateway_admin::model::accounts::AccountRuntimeSnapshot,
) -> (
AccountStatusProjection,
Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
) {
let models = runtime
.model_cooldowns
.get(&account.id)
.into_iter()
.flatten()
.filter(|cooldown| {
cooldown.credential_revision().get() == account.credential_revision.get()
&& cooldown.until() > now
})
.cloned()
.collect::<Vec<_>>();
let mut projection =
account_status_projection(account, now, runtime.cooldown.get(&account.id).copied());
// 目录汇总展示部分模型受限,不将其写入整账号 cooldown 或用于其他模型的调度
if !models.is_empty()
&& matches!(
projection.status,
gateway_core::account::AccountStatus::Normal
| gateway_core::account::AccountStatus::QuotaPaused
)
{
projection.status = gateway_core::account::AccountStatus::RateLimited;
}
(projection, models)
}
#[must_use]
pub(crate) fn account_status_projection(
account: &ProviderAccountSummary,
@@ -155,8 +155,6 @@ impl ClientAdmissionRequest {
return Err(invalid("lease TTL must be positive"));
}
redis_duration_millis(self.lease_ttl)?;
redis_integer(self.limits.max_concurrency, "maximum concurrency")?;
redis_integer(self.limits.requests_per_minute, "requests per minute")?;
Ok(())
}
}
@@ -287,6 +285,7 @@ impl ClientAdmissionRepository for RedisClientAdmissionRepository {
.key(&keys[1])
.arg(&request.model_request_id)
.arg(lease_ttl_ms)
// ZCARD 的取值都能精确表示,超过 Lua 精确范围的限额始终大于实际计数
.arg(request.limits.max_concurrency)
.arg(request.limits.requests_per_minute)
.arg(MAX_REDIS_EXACT_INTEGER)
@@ -11,7 +11,7 @@ use gateway_core::{
},
};
use redis::{Script, aio::ConnectionManager};
use std::{collections::BTreeMap, sync::LazyLock};
use std::{collections::BTreeMap, sync::LazyLock, time::SystemTime};
use crate::{Revision, StoreError, StoreResult, redis_unavailable, require_nonempty};
@@ -55,6 +55,42 @@ static WRITE_ACCOUNT: LazyLock<Script> = LazyLock::new(|| {
)
});
// 模型事实与目录索引同次写入;普通成功只清整账号冷却,不触碰这里的期限
const WRITE_SCOPED: &str = r#"
local current = tonumber(redis.call('HGET', KEYS[1], 'revision') or '0')
local incoming = tonumber(ARGV[1])
local until_ms = tonumber(ARGV[2])
local limited_ms = tonumber(ARGV[4])
local clock = redis.call('TIME')
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
if current > incoming or until_ms <= now_ms then return 0 end
if current == incoming then
local previous = tonumber(redis.call('HGET', KEYS[1], 'until_ms') or '0')
local limited = tonumber(redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0')
if previous >= until_ms and limited >= limited_ms then return 0 end
until_ms = math.max(previous, until_ms)
limited_ms = math.max(limited, limited_ms)
end
redis.call('HSET', KEYS[1], 'revision', incoming, 'until_ms', until_ms, 'rate_limited_until_ms', limited_ms)
redis.call('PEXPIREAT', KEYS[1], until_ms + 60000)
if limited_ms > now_ms then
redis.call('ZADD', KEYS[2], limited_ms, ARGV[3])
local latest = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES')
redis.call('PEXPIREAT', KEYS[2], tonumber(latest[2]) + 60000)
redis.call('ZADD', KEYS[3], 'GT', latest[2], ARGV[5])
else
redis.call('ZREM', KEYS[2], ARGV[3])
end
return 1
"#;
const ACTIVE_SCOPES: &str = r#"
local clock = redis.call('TIME')
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now_ms)
return redis.call('ZRANGE', KEYS[1], 0, -1)
"#;
const READ_SCOPED: &str = r#"
local revision = redis.call('HGET', KEYS[1], 'revision')
local until_ms = redis.call('HGET', KEYS[1], 'until_ms')
@@ -62,9 +98,9 @@ local clock = redis.call('TIME')
local now_ms = (tonumber(clock[1]) * 1000) + math.floor(tonumber(clock[2]) / 1000)
if not revision or not until_ms or tonumber(until_ms) <= now_ms then
redis.call('DEL', KEYS[1])
return {0, '0', '0'}
return {0, '0', '0', '0'}
end
return {1, revision, until_ms}
return {1, revision, until_ms, redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0'}
"#;
const INVALIDATE_SCRIPT: &str = r#"
@@ -132,6 +168,73 @@ impl RedisCredentialCooldownRepository {
format!("{}:account:active-cooldowns", self.namespace)
}
fn model_index_key(&self, account: &str) -> StoreResult<String> {
Ok(format!("{}:models", self.key(account)?))
}
fn active_model_index_key(&self) -> String {
format!("{}:account:active-model-cooldowns", self.namespace)
}
async fn read_model_cooldowns(
&self,
account: &str,
) -> StoreResult<Vec<ProviderScopedCooldown>> {
let models: Vec<String> = Script::new(ACTIVE_SCOPES)
.key(self.model_index_key(account)?)
.invoke_async(&mut self.connection.clone())
.await
.map_err(|source| redis_unavailable("list account model cooldowns", source))?;
let account =
ProviderAccountId::new(account).map_err(|_| invalid("invalid cooldown account"))?;
let scopes = models
.into_iter()
.map(|model| {
gateway_core::routing::UpstreamModelId::new(model)
.map(ProviderCooldownScope::upstream_model)
.map_err(|_| invalid("invalid cooldown model"))
})
.collect::<StoreResult<Vec<_>>>()?;
let mut cooldowns = Vec::new();
for scopes in scopes.chunks(COOLDOWN_READ_BATCH_SIZE) {
let script = Script::new(READ_SCOPED);
let commands = scopes
.iter()
.map(|scope| {
let mut command = redis::cmd("EVALSHA");
command
.arg(script.get_hash())
.arg(1)
.arg(self.scoped_key(account.as_str(), scope)?);
Ok(command)
})
.collect();
for (scope, value) in scopes
.iter()
.zip(self.read_script_batch(&script, commands).await)
{
let value = redis::from_redis_value(value?)
.map_err(|source| redis_unavailable("decode model cooldown", source))?;
if let Some(cooldown) = parse_scoped_cooldown(value, &account, scope)?
&& let Some(until) = cooldown
.rate_limited_until()
.filter(|until| *until > SystemTime::now())
{
cooldowns.push(
ProviderScopedCooldown::new(
account.clone(),
cooldown.credential_revision(),
scope.clone(),
until,
)
.with_rate_limited_until(Some(until)),
);
}
}
}
Ok(cooldowns)
}
fn capacity_failures_key(&self, provider_account_id: &str) -> StoreResult<String> {
let fingerprint = resource_fingerprint("credential cooldown", provider_account_id)?;
Ok(format!(
@@ -168,49 +271,27 @@ impl RedisCredentialCooldownRepository {
credential_revision: Revision,
cooldown_until: DateTime<Utc>,
kind: ProviderCooldownKind,
index_member: Option<&str>,
index_member: &str,
) -> StoreResult<bool> {
let until_ms = cooldown_until.timestamp_millis();
if until_ms <= 0 {
return Err(invalid("cooldown expiry must be positive"));
}
let mut connection = self.connection.clone();
let written = if let Some(index_member) = index_member {
WRITE_ACCOUNT
.key(key)
.key(self.active_index_key())
.key(self.protection_key(index_member)?)
.key(self.protection_index_key())
.arg(credential_revision.get())
.arg(until_ms)
.arg(index_member)
.arg(kind.as_str())
.arg(uuid::Uuid::new_v4().to_string())
.invoke_async::<i64>(&mut connection)
.await
} else {
Script::new(WRITE_SCRIPT)
.key(key)
.arg(credential_revision.get())
.arg(until_ms)
.arg("")
.arg(kind.as_str())
.arg(uuid::Uuid::new_v4().to_string())
.invoke_async::<i64>(&mut connection)
.await
}
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
Ok(written == 1)
}
async fn read_scoped_key(&self, key: String) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
let result = Script::new(READ_SCOPED)
let written = WRITE_ACCOUNT
.key(key)
.invoke_async(&mut self.connection.clone())
.await;
parse_scoped_cooldown(
result.map_err(|source| redis_unavailable("read credential cooldown", source))?,
)
.key(self.active_index_key())
.key(self.protection_key(index_member)?)
.key(self.protection_index_key())
.arg(credential_revision.get())
.arg(until_ms)
.arg(index_member)
.arg(kind.as_str())
.arg(uuid::Uuid::new_v4().to_string())
.invoke_async::<i64>(&mut connection)
.await
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
Ok(written == 1)
}
/// 保留每条命令的错误,脚本失效时只补发尚未执行的 NOSCRIPT 项
@@ -294,26 +375,18 @@ impl RedisCredentialCooldownRepository {
&self,
key: String,
through_revision: Revision,
index_member: Option<&str>,
index_key: String,
index_member: &str,
) -> StoreResult<bool> {
let mut connection = self.connection.clone();
let removed = if let Some(index_member) = index_member {
Script::new(INVALIDATE_SCRIPT)
.key(key)
.key(self.active_index_key())
.arg(through_revision.get())
.arg(index_member)
.invoke_async::<i64>(&mut connection)
.await
} else {
Script::new(INVALIDATE_SCRIPT)
.key(key)
.arg(through_revision.get())
.arg("")
.invoke_async::<i64>(&mut connection)
.await
}
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
let removed = Script::new(INVALIDATE_SCRIPT)
.key(key)
.key(index_key)
.arg(through_revision.get())
.arg(index_member)
.invoke_async::<i64>(&mut connection)
.await
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
Ok(removed == 1)
}
@@ -337,8 +410,16 @@ impl RedisCredentialCooldownRepository {
}
pub(crate) async fn active_cooldowns(&self) -> StoreResult<AccountRuntimeSnapshot> {
self.read_cooldown_accounts(self.all_cooldown_accounts().await?)
let mut accounts = self.all_cooldown_accounts().await?;
let model_accounts: Vec<String> = Script::new(ACTIVE_SCOPES)
.key(self.active_model_index_key())
.invoke_async(&mut self.connection.clone())
.await
.map_err(|source| redis_unavailable("list model cooldown accounts", source))?;
accounts.extend(model_accounts);
accounts.sort_unstable();
accounts.dedup();
self.read_cooldown_accounts(accounts).await
}
pub(crate) async fn account_cooldowns(
@@ -349,13 +430,16 @@ impl RedisCredentialCooldownRepository {
return Ok(AccountRuntimeSnapshot::default());
}
// 索引与冷却事实由 Lua 原子维护,只读取范围内实际有状态的账号
let (cooldowns, protections): (Vec<Option<f64>>, Vec<Option<f64>>) = redis::pipe()
let [cooldowns, protections, models]: [Vec<Option<f64>>; 3] = redis::pipe()
.cmd("ZMSCORE")
.arg(self.active_index_key())
.arg(accounts)
.cmd("ZMSCORE")
.arg(self.protection_index_key())
.arg(accounts)
.cmd("ZMSCORE")
.arg(self.active_model_index_key())
.arg(accounts)
.query_async(&mut self.connection.clone())
.await
.map_err(|error| redis_unavailable("read scoped account cooldown index", error))?;
@@ -363,8 +447,11 @@ impl RedisCredentialCooldownRepository {
.iter()
.zip(cooldowns)
.zip(protections)
.filter(|((_, cooldown), protection)| cooldown.is_some() || protection.is_some())
.map(|((account, _), _)| account.clone())
.zip(models)
.filter(|(((_, cooldown), protection), model)| {
cooldown.is_some() || protection.is_some() || model.is_some()
})
.map(|(((account, _), _), _)| account.clone())
.collect();
self.read_cooldown_accounts(active).await
}
@@ -376,15 +463,20 @@ impl RedisCredentialCooldownRepository {
use futures::{StreamExt as _, TryStreamExt as _};
let reads = futures::stream::iter(accounts)
.map(|account| async move {
self.read_account_runtime(&account)
.await
.map(|runtime| (account, runtime))
let (runtime, models) = tokio::try_join!(
self.read_account_runtime(&account),
self.read_model_cooldowns(&account),
)?;
Ok((account, runtime, models))
})
.buffer_unordered(32)
.try_collect::<Vec<_>>()
.await?;
let mut snapshot = AccountRuntimeSnapshot::default();
for (account, (cooldown, freeze)) in reads {
for (account, (cooldown, freeze), models) in reads {
if !models.is_empty() {
snapshot.model_cooldowns.insert(account.clone(), models);
}
if let Some(cooldown) = cooldown {
snapshot.cooldown.insert(
account.clone(),
@@ -446,7 +538,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
cooldown.credential_revision,
cooldown.cooldown_until,
cooldown.kind,
Some(&cooldown.provider_account_id),
&cooldown.provider_account_id,
)
.await
}
@@ -480,7 +572,8 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
.invalidate_at_key(
self.key(provider_account_id)?,
through_revision,
Some(provider_account_id),
self.active_index_key(),
provider_account_id,
)
.await?;
Ok(protection_cleared || cooldown_cleared)
@@ -530,6 +623,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
local removed = 0
for i = 2, #KEYS do removed = removed + redis.call('DEL', KEYS[i]) end
redis.call('ZREM', ARGV[2], ARGV[1])
redis.call('ZREM', ARGV[3], ARGV[1])
return removed + redis.call('ZREM', KEYS[1], ARGV[1])
"#,
)
@@ -537,6 +631,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
.key(keys)
.arg(provider_account_id)
.arg(self.protection_index_key())
.arg(self.active_model_index_key())
.invoke_async(&mut connection)
.await
.map_err(|source| redis_unavailable("delete account cooldowns and index", source))?;
@@ -686,18 +781,37 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
Box::pin(async move {
let revision = Revision::new(cooldown.credential_revision().get())
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
self.cache_at_key(
self.scoped_key(cooldown.account_id().as_str(), cooldown.scope())
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
revision,
cooldown.until().into(),
ProviderCooldownKind::RateLimit,
None,
)
.await
.map_err(|source| {
crate::provider_unavailable("cache scoped credential cooldown", source)
})
let account = cooldown.account_id().as_str();
let key = self
.scoped_key(account, cooldown.scope())
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
let index = self
.model_index_key(account)
.map_err(|_| provider_invalid("encode model cooldown index"))?;
let until: DateTime<Utc> = cooldown.until().into();
let written: i64 = Script::new(WRITE_SCOPED)
.key(key)
.key(index)
.key(self.active_model_index_key())
.arg(revision.get())
.arg(until.timestamp_millis())
.arg(cooldown.scope().value())
.arg(
cooldown
.rate_limited_until()
.map(DateTime::<Utc>::from)
.map_or(0, |time| time.timestamp_millis()),
)
.arg(account)
.invoke_async(&mut self.connection.clone())
.await
.map_err(|source| {
crate::provider_unavailable(
"cache scoped credential cooldown",
redis_unavailable("write model cooldown", source),
)
})?;
Ok(written == 1)
})
}
@@ -708,24 +822,18 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
) -> futures::future::BoxFuture<'a, Result<Option<ProviderScopedCooldown>, ProviderStoreError>>
{
Box::pin(async move {
self.read_scoped_key(
self.scoped_key(account_id.as_str(), scope)
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
)
.await
.map_err(|source| {
let key = self
.scoped_key(account_id.as_str(), scope)
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
let value = Script::new(READ_SCOPED)
.key(key)
.invoke_async(&mut self.connection.clone())
.await
.map_err(|source| redis_unavailable("read scoped cooldown", source))
.and_then(|value| parse_scoped_cooldown(value, account_id, scope));
value.map_err(|source| {
crate::provider_unavailable("read scoped credential cooldown", source)
})?
.map(|(revision, until)| {
Ok(ProviderScopedCooldown::new(
account_id.clone(),
CredentialRevision::new(revision.get())
.map_err(|_| provider_invalid("decode scoped credential cooldown"))?,
scope.clone(),
until.into(),
))
})
.transpose()
})
}
@@ -754,28 +862,16 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
.collect();
let values = self.read_script_batch(&script, commands).await;
results.extend(batch.iter().zip(values).map(|(account, value)| {
let value = value
value
.and_then(|value| {
redis::from_redis_value(value).map_err(|source| {
redis_unavailable("decode scoped cooldown", source)
})
})
.and_then(parse_scoped_cooldown)
.and_then(|value| parse_scoped_cooldown(value, account, scope))
.map_err(|source| {
crate::provider_unavailable("read scoped credential cooldown", source)
})?;
value
.map(|(revision, until)| {
Ok(ProviderScopedCooldown::new(
account.clone(),
CredentialRevision::new(revision.get()).map_err(|_| {
provider_invalid("decode scoped credential cooldown")
})?,
scope.clone(),
until.into(),
))
})
.transpose()
}));
}
results
@@ -795,7 +891,9 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
self.scoped_key(account_id.as_str(), scope)
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
revision,
None,
self.model_index_key(account_id.as_str())
.map_err(|_| provider_invalid("encode model cooldown index"))?,
scope.value(),
)
.await
.map_err(|source| {
@@ -858,21 +956,35 @@ pub(super) fn invalid(message: &str) -> StoreError {
}
}
type ScopedCooldownReply = (i64, String, i64, i64);
fn parse_scoped_cooldown(
(present, revision, until_ms): (i64, String, String),
) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
(present, revision, until_ms, limited_ms): ScopedCooldownReply,
account: &ProviderAccountId,
scope: &ProviderCooldownScope,
) -> StoreResult<Option<ProviderScopedCooldown>> {
if present == 0 {
return Ok(None);
}
let revision = revision
.parse::<u64>()
.map_err(|source| invalid("cached cooldown revision is invalid").with_source(source))?;
let until_ms = until_ms
.parse::<i64>()
.map_err(|source| invalid("cached cooldown expiry is invalid").with_source(source))?;
let cooldown_until = DateTime::from_timestamp_millis(until_ms)
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))?;
Ok(Some((Revision::new(revision)?, cooldown_until)))
let revision =
CredentialRevision::new(revision).map_err(|_| invalid("invalid cooldown revision"))?;
let deadline = |ms| {
DateTime::from_timestamp_millis(ms)
.map(SystemTime::from)
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))
};
Ok(Some(
ProviderScopedCooldown::new(
account.clone(),
revision,
scope.clone(),
deadline(until_ms)?,
)
.with_rate_limited_until((limited_ms > 0).then(|| deadline(limited_ms)).transpose()?),
))
}
fn provider_cooldown(record: CredentialCooldown) -> Result<ProviderCooldown, ProviderStoreError> {
@@ -62,6 +62,23 @@ async fn recovery_loads_precise_window_and_running_request_facts() {
.await
.expect("remove missing lease fixture");
seed_request(
&database.pool,
"nested-child",
now - Duration::seconds(8),
now + Duration::seconds(30),
"running",
)
.await;
sqlx::query(
"update model_requests set client_transport = 'internal_plugin',
request_kind = case id when 'recent-running' then 'plugin_bound_model' else 'plugin_child_model' end
where id in ('nested-child', 'recent-running')",
)
.execute(&database.pool)
.await
.unwrap();
let repository = PgClientAdmissionRecoveryRepository::new(database.pool.clone());
let actual = repository
.load_client_admission_recovery(window_started_at)
@@ -2,6 +2,76 @@
use super::*;
#[tokio::test]
async fn model_cooldown_status_filter_and_details_share_revision_and_expiry_rules() {
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
let Some(database) = TestDatabase::create("account_model_cooldown").await else {
return;
};
let repository = PgProviderAccountRepository::new(database.pool.clone());
let ids = ["acct_active", "acct_stale", "acct_expired", "acct_disabled"];
for id in ids {
let mut record = account(id, id);
record.enabled = id != "acct_disabled";
repository.insert_provider_account(record).await.unwrap();
}
let mut runtime = AccountRuntimeSnapshot::default();
for id in ids {
let stored = repository.load_provider_account(id).await.unwrap().unwrap();
let revision = stored.summary.credential_revision.get();
let revision = if id == "acct_stale" {
revision + 1
} else {
revision
};
let until = Utc::now() + TimeDelta::seconds(if id == "acct_expired" { -1 } else { 60 });
runtime.model_cooldowns.insert(
id.into(),
vec![ProviderScopedCooldown::new(
ProviderAccountId::new(id).unwrap(),
gateway_core::account::CredentialRevision::new(revision).unwrap(),
ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
),
until.into(),
)],
);
}
let store = admin_account_store(&database.pool);
let page = store
.list_accounts(
AccountListQuery {
page: 1,
page_size: PageSize::new(20).unwrap(),
provider_kind: None,
group_filter: None,
search: None,
status: Some(AccountStatus::RateLimited),
sort: None,
},
runtime.clone(),
)
.await
.unwrap();
assert_eq!(page.total, 1);
assert_eq!(page.summary.rate_limited, 1);
assert_eq!(page.summary.normal, 2);
assert_eq!(page.summary.disabled, 1);
let item = &page.items[0];
assert_eq!(item.account.id, "acct_active");
assert_eq!(item.projection.status, AccountStatus::RateLimited);
assert!(item.projection.cooldown.is_none());
assert_eq!(item.model_cooldowns.len(), 1);
let detail = store
.load_account("acct_active", runtime)
.await
.unwrap()
.unwrap();
assert_eq!(detail.projection, item.projection);
assert_eq!(detail.model_cooldowns, item.model_cooldowns);
database.close().await;
}
#[tokio::test]
async fn import_name_only_overrides_a_single_account_and_keeps_batch_names() {
use gateway_admin::model::accounts::AccountImportSettings;
@@ -940,6 +940,7 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
sort: None,
},
AccountRuntimeSnapshot {
model_cooldowns: BTreeMap::new(),
protection_rules: std::collections::BTreeMap::new(),
cooldown: BTreeMap::from([(
"acct_alpha".to_owned(),
@@ -18,11 +18,19 @@ fn client_admission_rejects_zero_ttl() {
assert!(request.validate().is_err());
}
#[test]
fn client_admission_rejects_values_outside_redis_exact_integer_range() {
let mut request = admission_request("request-1", "key-1", Duration::from_secs(30));
#[tokio::test]
async fn configured_limits_above_lua_integer_precision_allow_requests() {
let Some((repository, mut connection, namespace)) = repository().await else {
return;
};
let mut request = admission_request("req_large_limits", "key-1", Duration::from_secs(30));
request.limits.max_concurrency = 1_u64 << 53;
assert!(request.validate().is_err());
request.limits.requests_per_minute = i64::MAX as u64;
assert_eq!(
repository.admit_client_request(&request).await.unwrap(),
ClientAdmissionDecision::Granted
);
delete_namespace_keys(&mut connection, &namespace).await;
}
#[test]
@@ -313,7 +313,12 @@ async fn scoped_cooldown_isolated_by_model_and_revision_fenced() {
.is_some()
);
let keys = namespace_keys(&mut connection, &namespace).await;
assert_eq!(keys.len(), 1);
assert_eq!(
keys.iter()
.filter(|key| key.contains(":cooldown:model:"))
.count(),
1
);
assert!(!keys[0].contains(account_id.as_str()));
assert!(!keys[0].contains(model_b.value()));
}
@@ -516,6 +521,142 @@ fn runtime_store(
)
}
#[tokio::test]
async fn model_cooldowns_are_visible_in_runtime_without_blocking_the_entire_account() {
use gateway_admin::ports::store::AccountRuntimeStore as _;
let Some((repository, connection, namespace)) = repository().await else {
return;
};
let runtime = runtime_store(&repository, connection, &namespace);
let id = ProviderAccountId::new("acct_model_limit").unwrap();
let revision = CredentialRevision::new(1).unwrap();
let models = ["gpt-5.4", "gpt-5.5"].map(|model| {
ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new(model).unwrap(),
)
});
let until: SystemTime = millisecond_precision(Utc::now() + Duration::seconds(60)).into();
// 不支持的模型仍影响选号,但不能让目录误报限流;两种期限可重叠
let unsupported_until = until + std::time::Duration::from_secs(1800);
repository
.put_scoped_if_later(ProviderScopedCooldown::new(
id.clone(),
revision,
models[0].clone(),
unsupported_until,
))
.await
.unwrap();
assert!(
runtime
.active_rate_limits()
.await
.unwrap()
.model_cooldowns
.is_empty()
);
for scope in &models {
repository
.put_scoped_if_later(
ProviderScopedCooldown::new(id.clone(), revision, scope.clone(), until)
.with_rate_limited_until(Some(until)),
)
.await
.unwrap();
}
repository.clear_after_success(&id, revision).await.unwrap();
let snapshot = runtime.active_rate_limits().await.unwrap();
assert!(snapshot.cooldown.is_empty());
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 2);
assert!(
snapshot.model_cooldowns[id.as_str()]
.iter()
.all(|model| model.until() == until)
);
assert_eq!(
repository
.read_scoped(&id, &models[0])
.await
.unwrap()
.unwrap()
.until(),
unsupported_until
);
let scoped = runtime
.account_rate_limits(&[id.to_string()])
.await
.unwrap();
assert_eq!(scoped.model_cooldowns, snapshot.model_cooldowns);
repository
.clear_scoped(&id, &models[0], revision)
.await
.unwrap();
let snapshot = runtime.active_rate_limits().await.unwrap();
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 1);
assert_eq!(snapshot.model_cooldowns[id.as_str()][0].scope(), &models[1]);
repository
.delete_account_cooldowns(id.as_str())
.await
.unwrap();
assert!(
runtime
.active_rate_limits()
.await
.unwrap()
.model_cooldowns
.is_empty()
);
}
#[tokio::test]
async fn expired_model_cooldown_disappears_from_the_directory_even_during_redis_grace() {
use gateway_admin::ports::store::AccountRuntimeStore as _;
let Some((repository, mut connection, namespace)) = repository().await else {
return;
};
let runtime = runtime_store(&repository, connection.clone(), &namespace);
let id = ProviderAccountId::new("acct_model_expired").unwrap();
let until = (Utc::now() + Duration::minutes(1)).into();
repository
.put_scoped_if_later(
ProviderScopedCooldown::new(
id.clone(),
CredentialRevision::new(1).unwrap(),
ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
),
until,
)
.with_rate_limited_until(Some(until)),
)
.await
.unwrap();
let key = namespace_keys(&mut connection, &namespace)
.await
.into_iter()
.find(|key| key.contains(":cooldown:model:"))
.unwrap();
redis::cmd("HSET")
.arg(key)
.arg("until_ms")
.arg(Utc::now().timestamp_millis() - 1000)
.query_async::<i64>(&mut connection)
.await
.unwrap();
assert!(
runtime
.active_rate_limits()
.await
.unwrap()
.model_cooldowns
.is_empty()
);
repository
.delete_account_cooldowns(id.as_str())
.await
.unwrap();
}
#[tokio::test]
async fn capacity_freeze_survives_due_time_and_runtime_restart_until_probe_succeeds() {
use gateway_admin::ports::store::AccountRuntimeStore as _;
@@ -9,17 +9,23 @@ mod transport;
use gateway_admin::ports::provider::ProviderBundle;
use gateway_core::{provider_ports::ProviderStorePorts, routing::ProviderKind};
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};
#[derive(Debug, thiserror::Error)]
#[error("Antigravity Provider 初始化失败")]
pub struct ConfigError;
pub async fn initialize(ports: ProviderStorePorts) -> Result<ProviderBundle, ConfigError> {
pub async fn initialize(
ports: ProviderStorePorts,
artifact_dir: PathBuf,
) -> Result<ProviderBundle, ConfigError> {
let kind = ProviderKind::new("antigravity").map_err(|_| ConfigError)?;
let oauth = Arc::new(credential::GoogleOAuth::for_provider()?);
let origin = oauth.resource_origin().clone();
let release = Arc::new(profile::ReleaseService::new(ports.artifact_profiles())?);
let release = Arc::new(profile::ReleaseService::new(
ports.artifact_profiles(),
artifact_dir,
)?);
release.restore().await;
let credentials = Arc::new(credential::CredentialService::new(
kind.clone(),
@@ -308,6 +308,7 @@ pub(crate) async fn download(
client: &Client,
url: &str,
sha512: Option<&str>,
artifact_dir: &std::path::Path,
) -> Result<std::fs::File, WorkerTaskError> {
let mut response = client
.get(url)
@@ -323,7 +324,11 @@ pub(crate) async fn download(
{
return Err(invalid());
}
let file = tempfile::tempfile().map_err(|e| invalid().with_source(e))?;
// 官方包可能大于容器的 /tmp;匿名文件随句柄释放,失败和取消也不会留下半包。
tokio::fs::create_dir_all(artifact_dir)
.await
.map_err(|e| invalid().with_source(e))?;
let file = tempfile::tempfile_in(artifact_dir).map_err(|e| invalid().with_source(e))?;
let mut file = tokio::fs::File::from_std(file);
let mut count = 0u64;
let mut digest = Sha512::new();
@@ -23,6 +23,7 @@ pub(crate) async fn verify(
version: &str,
url: &str,
sha512: Option<&str>,
artifact_dir: &std::path::Path,
) -> Result<u64, WorkerTaskError> {
match (target.client, target.platform) {
(ClientKind::Desktop, Platform::Macos) => {
@@ -50,7 +51,7 @@ pub(crate) async fn verify(
.await
}
_ => {
let file = download(client, url, sha512).await?;
let file = download(client, url, sha512, artifact_dir).await?;
// 取消 worker 时同步中止阻塞解包,临时文件由解析任务退出时关闭
let (file, _guard) = CancellableFile::new(file);
let version = version.to_owned();
@@ -13,6 +13,7 @@ use gateway_core::{provider_ports::ProviderArtifactProfileCachePort, routing::Pr
use serde::Deserialize;
use std::{
collections::{BTreeMap, BTreeSet},
path::PathBuf,
sync::{Arc, Mutex, RwLock},
time::Duration,
};
@@ -74,6 +75,7 @@ pub(crate) struct ReleaseService {
impl ReleaseService {
pub(crate) fn new(
cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
) -> Result<Self, ConfigError> {
let client = gateway_egress::http_client(None)
.map_err(|_| ConfigError)?
@@ -89,6 +91,7 @@ impl ReleaseService {
verification: VerificationCache::new(
ProviderKind::new("antigravity").map_err(|_| ConfigError)?,
cache,
artifact_dir,
),
})
}
@@ -13,6 +13,7 @@ use gateway_core::{
};
use serde::{Deserialize, Serialize};
use std::{
path::PathBuf,
sync::Arc,
time::{Duration, Instant},
};
@@ -39,13 +40,19 @@ struct Payload {
pub(crate) struct VerificationCache {
provider: ProviderKind,
cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
}
impl VerificationCache {
pub(crate) fn new(
provider: ProviderKind,
cache: Arc<dyn ProviderArtifactProfileCachePort>,
artifact_dir: PathBuf,
) -> Self {
Self { provider, cache }
Self {
provider,
cache,
artifact_dir,
}
}
pub(crate) async fn load(
@@ -117,6 +124,7 @@ impl VerificationCache {
&release.version,
&release.url,
release.sha512.as_deref(),
&self.artifact_dir,
)
.await?;
(Utc::now(), changelist)
@@ -1,4 +1,4 @@
//! 为 Claude 原生生成补齐能唯一配对的工具 ID,保留其余原始 JSON 字节
//! 按 GenAI 工具关联规则为 Claude 原生生成补齐 ID,保留其余原始 JSON 字节
use std::{borrow::Cow, collections::BTreeMap};
@@ -83,15 +83,14 @@ fn tools<'a>(content: &Content<'a>) -> Option<Vec<Tool<'a>>> {
}
#[derive(Default)]
struct Pair {
call: Option<usize>,
response: Option<usize>,
ambiguous: bool,
struct ToolGroup<'a> {
calls: Vec<&'a Tool<'a>>,
responses: Vec<&'a Tool<'a>>,
}
pub(super) fn repair(body: Box<RawValue>) -> Result<Box<RawValue>, serde_json::Error> {
// AGY CLI 1.5.20 的 convertToVertexV1 清空两侧 ID,见 #807
// https://github.com/zyycn/codex-proxy-rs/issues/807
// AGY CLI / ACP 1.5.24 的 Gateway/GenAI 路径仍清空两侧 ID,见 #807、#848
// https://github.com/zyycn/codex-proxy-rs/issues/848
// 客户端恢复保留 ID 后移除此补偿;不为格式错误或有歧义的历史猜测关联
let Ok(request) = serde_json::from_str::<Request<'_>>(body.get()) else {
return Ok(body);
@@ -118,48 +117,62 @@ pub(super) fn repair(body: Box<RawValue>) -> Result<Box<RawValue>, serde_json::E
}
let calls = &turns[turn];
let responses = &turns[turn + 1];
let mut pairs = BTreeMap::<&str, Pair>::new();
for (index, call) in calls.iter().enumerate() {
let pair = pairs.entry(&call.name).or_default();
pair.ambiguous |= pair.call.replace(index).is_some();
let mut groups = BTreeMap::<&str, ToolGroup<'_>>::new();
for call in calls {
groups.entry(&call.name).or_default().calls.push(call);
}
for (index, response) in responses.iter().enumerate() {
let pair = pairs.entry(&response.name).or_default();
pair.ambiguous |= pair.response.replace(index).is_some();
for response in responses {
groups
.entry(&response.name)
.or_default()
.responses
.push(response);
}
for pair in pairs.values().filter(|pair| !pair.ambiguous) {
let (Some(call), Some(response)) = (pair.call, pair.response) else {
for group in groups.values() {
if group.calls.len() != group.responses.len() {
continue;
};
let (call, response) = (&calls[call], &responses[response]);
let id = match (call.id.as_deref(), response.id.as_deref()) {
(Some(_), Some(_)) => continue,
(Some(id), None) | (None, Some(id)) => {
if ids.get(id) != Some(&1) {
continue;
}
id.to_owned()
}
(None, None) => {
// 轮次与 part 位置使追加历史和重试保持稳定;同时避开客户端已有 ID
let mut id = format!("toolu_cpr_{turn}_{}", call.part);
while ids.contains_key(id.as_str()) {
id.push('_');
}
id
}
};
ids.insert(Cow::Owned(id.clone()), 2);
let insertion = format!(",\"id\":{}", serde_json::to_string(&id)?);
for tool in [call, response]
.into_iter()
.filter(|tool| tool.id.is_none())
}
// GenAI 无 ID 时按同名出现顺序配对;混有 ID 时可能按 ID 重排,不能套用顺序
// https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/tools/function-calling#parallel_function_calling
if group.calls.len() > 1
&& group
.calls
.iter()
.chain(&group.responses)
.any(|tool| tool.id.is_some())
{
// RawValue 来自同一正文,插入点由解析器确定,不重编码参数、结果或签名
let end = tool.raw.get().as_ptr() as usize - body.get().as_ptr() as usize
+ tool.raw.get().len()
- 1;
insertions.insert(end, insertion.clone());
continue;
}
for (call, response) in group.calls.iter().zip(&group.responses) {
let id = match (call.id.as_deref(), response.id.as_deref()) {
(Some(_), Some(_)) => continue,
(Some(id), None) | (None, Some(id)) => {
if ids.get(id) != Some(&1) {
continue;
}
id.to_owned()
}
(None, None) => {
// 轮次与 part 位置使追加历史和重试保持稳定;同时避开客户端已有 ID
let mut id = format!("toolu_cpr_{turn}_{}", call.part);
while ids.contains_key(id.as_str()) {
id.push('_');
}
id
}
};
ids.insert(Cow::Owned(id.clone()), 2);
let insertion = format!(",\"id\":{}", serde_json::to_string(&id)?);
for tool in [call, response]
.into_iter()
.filter(|tool| tool.id.is_none())
{
// RawValue 来自同一正文,插入点由解析器确定,不重编码参数、结果或签名
let end = tool.raw.get().as_ptr() as usize - body.get().as_ptr() as usize
+ tool.raw.get().len()
- 1;
insertions.insert(end, insertion.clone());
}
}
}
}
@@ -46,7 +46,11 @@ pub(super) async fn fixture() -> (MockServer, CredentialService, Arc<MemoryPorts
runtime_policy: store.clone(),
credential_state: store.clone(),
release: Arc::new(
crate::profile::ReleaseService::new(crate::support::profile::cache()).unwrap(),
crate::profile::ReleaseService::new(
crate::support::profile::cache(),
std::env::temp_dir(),
)
.unwrap(),
),
oauth: Arc::new(GoogleOAuth::with_endpoints(
config,
@@ -103,15 +103,31 @@ async fn complete_download_requires_the_manifest_digest() {
let server = serve(body.to_vec(), "").await;
let client = reqwest::Client::new();
let digest = hex::encode(Sha512::digest(body));
let file = download(&client, &server.uri(), Some(&digest))
let root = tempfile::tempdir().unwrap();
let artifact_dir = root.path().join("antigravity");
let file = download(&client, &server.uri(), Some(&digest), &artifact_dir)
.await
.unwrap();
assert_eq!(file.metadata().unwrap().len(), body.len() as u64);
drop(file);
assert_eq!(std::fs::read_dir(&artifact_dir).unwrap().count(), 0);
let blocked = root.path().join("file");
std::fs::write(&blocked, b"").unwrap();
assert!(
download(&client, &server.uri(), Some(&"0".repeat(128)))
download(&client, &server.uri(), Some(&digest), &blocked)
.await
.is_err()
);
assert!(
download(
&client,
&server.uri(),
Some(&"0".repeat(128)),
&artifact_dir
)
.await
.is_err()
);
}
#[test]
@@ -27,7 +27,7 @@ fn fixture_release(server: &wiremock::MockServer, version: &str) -> Release {
async fn cache_restore_and_renewal_preserve_verification_without_downloading_again() {
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
let cache = cache();
let service = VerificationCache::new(provider(), cache.clone());
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
let client = reqwest::Client::new();
let target = Selection::default().target();
let release = fixture_release(&server, "2.35.1");
@@ -42,7 +42,7 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
.unwrap();
assert_eq!(same.verified_at, first.verified_at);
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
let restarted = VerificationCache::new(provider(), cache.clone());
let restarted = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
let restored = restarted.load(target).await.unwrap().unwrap();
assert_eq!(restored.verified_at, first.verified_at);
assert_eq!(first.changelist, 1_234_567_890);
@@ -50,7 +50,7 @@ async fn cache_restore_and_renewal_preserve_verification_without_downloading_aga
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
assert_eq!(server.received_requests().await.unwrap().len(), requests);
let releases = ReleaseService::new(cache.clone()).unwrap();
let releases = ReleaseService::new(cache.clone(), std::env::temp_dir()).unwrap();
releases.restore().await;
let restored = dashboard(&Selection::default(), &releases);
assert_eq!(restored.version, release.version);
@@ -79,7 +79,7 @@ async fn latest_profile_switches_version_and_changelist_only_after_verified_publ
)
.await;
let cache = cache();
let service = VerificationCache::new(provider(), cache.clone());
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
let target = Selection::default().target();
let client = reqwest::Client::new();
let old = service
@@ -92,7 +92,7 @@ async fn latest_profile_switches_version_and_changelist_only_after_verified_publ
.await
.unwrap();
let new_release = fixture_release(&new_server, "2.36.0");
let releases = ReleaseService::new(cache.clone()).unwrap();
let releases = ReleaseService::new(cache.clone(), std::env::temp_dir()).unwrap();
releases.restore().await;
let before = dashboard(&Selection::default(), &releases);
let frozen = default_profile(&releases).frozen();
@@ -131,7 +131,7 @@ async fn latest_profile_switches_version_and_changelist_only_after_verified_publ
async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification() {
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
let cache = cache();
let service = VerificationCache::new(provider(), cache.clone());
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
let client = reqwest::Client::new();
let target = Selection::default().target();
let release = fixture_release(&server, "2.35.1");
@@ -189,7 +189,7 @@ async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification
async fn version_disagreement_leaves_the_previous_cache_intact() {
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
let cache = cache();
let service = VerificationCache::new(provider(), cache.clone());
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
let client = reqwest::Client::new();
let target = Selection::default().target();
let release = fixture_release(&server, "2.35.1");
@@ -67,7 +67,7 @@ async fn middleware_business_headers_survive_without_overriding_frozen_authentic
let fixture = Fixture::new(&upstream.uri());
let profile = profile::resolve(
&Selection::default().configuration(),
&ReleaseService::new(crate::support::profile::cache()).unwrap(),
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
)
.unwrap();
Mock::given(path("/v1internal:generateContent"))
@@ -247,7 +247,9 @@ impl Fixture {
store.clone(),
store.clone(),
);
let release = Arc::new(ReleaseService::new(crate::support::profile::cache()).unwrap());
let release = Arc::new(
ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let credentials = Arc::new(CredentialService::new(
kind.clone(),
&ports,
@@ -21,8 +21,9 @@ use wiremock::{
async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_payload() {
let server = MockServer::start().await;
let (origin, access_token) = refreshed_credential(&server).await;
let profile =
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
let profile = profile::default_profile(
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let user_agent = "antigravity/hub/2.37.0 (aidev_client; os_type=darwin; arch=arm64)";
let client = CloudCodeClient::new(&origin, None, &profile).unwrap();
let post = |p| {
@@ -171,8 +172,9 @@ async fn oauth_refresh_and_native_generate_preserve_grant_profile_and_wire_paylo
#[tokio::test]
async fn streamed_text_is_projected_once_across_native_frames() {
let server = MockServer::start().await;
let profile =
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
let profile = profile::default_profile(
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
let frames = [
json!({"candidates":[{"content":{"parts":[{"text":""}]}}]}),
@@ -249,8 +251,9 @@ async fn streamed_text_is_projected_once_across_native_frames() {
#[tokio::test]
async fn incomplete_native_stream_and_redirect_are_rejected() {
let server = MockServer::start().await;
let profile =
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
let profile = profile::default_profile(
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
Mock::given(path("/v1internal:streamGenerateContent")).respond_with(ResponseTemplate::new(200).set_body_raw("data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}}\n\n","text/event-stream")).mount(&server).await;
let res = client
@@ -350,8 +353,9 @@ async fn compressed_response(status: u16, body: &[u8], media: &str) -> ResponseT
async fn compressed_control_responses_keep_errors_and_decoded_size_limits() {
use gateway_core::error::ProviderErrorKind;
let server = MockServer::start().await;
let profile =
profile::default_profile(&ReleaseService::new(crate::support::profile::cache()).unwrap());
let profile = profile::default_profile(
&ReleaseService::new(crate::support::profile::cache(), std::env::temp_dir()).unwrap(),
);
let client = CloudCodeClient::new(&server.uri().parse().unwrap(), None, &profile).unwrap();
Mock::given(path("/v1internal:loadCodeAssist"))
.respond_with(
@@ -71,9 +71,9 @@ fn history(calls: Vec<Value>, responses: Vec<Value>) -> Value {
}
#[tokio::test]
async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
async fn missing_ids_pair_by_name_and_parallel_order_without_reencoding_business_fields() {
let (server, client) = client().await;
let contents = r#"[{"role":"model","parts":[{"thought":true,"text":"reason","thoughtSignature":"opaque=="},{"functionCall":{"name":"look\u0075p","args":{"large":98765432109876543210987654,"n":1e+09,"n":2}}},{"function_call":{"name":"read","args":{}}}]},{"role":"user","parts":[{"function_response":{"name":"read","response":{"output":"second"}}},{"functionResponse":{"name":"lookup","response":{"output":"first","functionCall":{"name":"nested"}}}}]}]"#;
let contents = r#"[{"role":"model","parts":[{"thought":true,"text":"reason","thoughtSignature":"opaque=="},{"functionCall":{"name":"look\u0075p","args":{"large":98765432109876543210987654,"n":1e+09,"n":2}}},{"function_call":{"name":"read","args":{}}},{"text":"next"},{"functionCall":{"name":"lookup","args":{"key":"third"}}}]},{"role":"user","parts":[{"function_response":{"name":"read","response":{"output":"second"}}},{"functionResponse":{"name":"lookup","response":{"output":"first","functionCall":{"name":"nested"}}}},{"text":"next"},{"function_response":{"name":"lookup","response":{"output":"third"}}}]}]"#;
let body = format!(r#"{{"contents":{contents},"unknown":1e+09,"unknown":2}}"#);
for mode in [GenerateMode::Json, GenerateMode::Stream] {
let outgoing = generate(&server, &client, &body, "claude-opus-5-5-medium", mode).await;
@@ -84,8 +84,17 @@ async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
let second = value["contents"][0]["parts"][2]["function_call"]["id"]
.as_str()
.unwrap();
let third = value["contents"][0]["parts"][4]["functionCall"]["id"]
.as_str()
.unwrap();
assert!(!first.is_empty());
assert_ne!(first, second);
assert_ne!(first, third);
assert_ne!(second, third);
assert_eq!(
value["contents"][1]["parts"][3]["function_response"]["id"],
third
);
assert_eq!(
value["contents"][1]["parts"][1]["functionResponse"]["id"],
first
@@ -97,7 +106,8 @@ async fn missing_ids_pair_by_unique_name_without_reencoding_business_fields() {
let restored = outgoing
.get()
.replace(&format!(",\"id\":\"{first}\""), "")
.replace(&format!(",\"id\":\"{second}\""), "");
.replace(&format!(",\"id\":\"{second}\""), "")
.replace(&format!(",\"id\":\"{third}\""), "");
assert!(restored.contains(contents));
assert!(restored.contains(r#""unknown":1e+09,"unknown":2"#));
assert!(
@@ -116,11 +126,13 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
call("run", None),
call("read", Some("existing-call")),
call("lookup", None),
call("run", None),
],
vec![
response("lookup", Some("existing-result")),
response("read", None),
response("run", None),
response("run", None),
],
);
let first = generate(
@@ -147,6 +159,13 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
first_value["contents"][0]["parts"][2]["functionCall"]["id"],
"existing-result"
);
let parallel_id = &first_value["contents"][0]["parts"][3]["functionCall"]["id"];
assert!(parallel_id.as_str().is_some_and(|id| !id.is_empty()));
assert_ne!(parallel_id, id);
assert_eq!(
first_value["contents"][1]["parts"][3]["functionResponse"]["id"],
*parallel_id
);
let retry = generate(
&server,
&client,
@@ -185,8 +204,12 @@ async fn existing_ids_are_reused_and_generated_ids_survive_retries_and_appended_
// 客户端已有的 ID 即使占用补偿命名空间,也不能和新配对共用
let collision = history(
vec![call("run", None), call("read", Some(id))],
vec![response("run", None), response("read", Some(id))],
vec![call("run", None), call("read", Some(id)), call("run", None)],
vec![
response("run", None),
response("read", Some(id)),
response("run", None),
],
);
let collision = generate(
&server,
@@ -213,12 +236,28 @@ async fn ambiguous_or_invalid_history_and_existing_ids_remain_unchanged() {
let mut cases = vec![
history(
vec![call("run", None), call("run", None)],
vec![response("run", None), response("run", None)],
vec![response("run", None)],
),
history(
vec![call("run", None)],
vec![response("run", None), response("run", None)],
),
history(
vec![call("run", Some("a")), call("run", None)],
vec![response("run", None), response("run", None)],
),
history(
vec![call("run", None), call("run", None)],
vec![response("run", None), response("run", Some("b"))],
),
history(
vec![call("run", Some("a")), call("run", None)],
vec![response("run", None), response("run", Some("a"))],
),
history(
vec![call("run", Some("a")), call("run", Some("b"))],
vec![response("run", Some("b")), response("run", Some("a"))],
),
history(vec![call("run", None)], vec![response("other", None)]),
history(
vec![call("run", Some("a"))],
@@ -257,7 +296,10 @@ async fn ambiguous_or_invalid_history_and_existing_ids_remain_unchanged() {
#[tokio::test]
async fn compatibility_is_limited_to_native_claude_generation() {
let (server, client) = client().await;
let body = history(vec![call("run", None)], vec![response("run", None)]);
let body = history(
vec![call("run", None), call("run", None)],
vec![response("run", None), response("run", None)],
);
for (model, mode) in [
("gemini-4-hydrogen", GenerateMode::Json),
(
@@ -458,6 +458,8 @@ pub(super) const IMAGE_MODELS: &[&str] = &[
"gpt-image-2.5-sunburst-2026-09-08",
"gpt-image-2.5-flare",
"gpt-image-2.5-flare-2026-09-08",
"gpt-image-2.6-sunburst",
"gpt-image-2.6-flare",
];
pub(super) const IMAGE_TEXT_RATES: TokenRates = TokenRates::new(50_000, 0, 12_500);
pub(super) const IMAGE_TOKEN_RATES: TokenRates = TokenRates::new(80_000, 300_000, 20_000);
@@ -1,9 +1,147 @@
//! Chat 转换的目标档位与 fast 协议头适配
//! Chat 转换的目标档位、工具标识与 fast 协议头适配
use std::collections::{HashMap, HashSet};
use bytes::Bytes;
use gateway_core::engine::middleware::MiddlewareHeader;
use reqwest::header::HeaderMap;
use serde_json::{Map, Value};
use sha2::{Digest as _, Sha256};
/// 名称映射只属于本次 Chat 响应,历史调用 ID 在出站副本中保持成对关联
pub(crate) fn normalize_translated_codex_tools(
body: &mut Map<String, Value>,
) -> HashMap<String, String> {
let mut fields = Vec::new();
for (field, value) in body.iter_mut() {
match field.as_str() {
"tools" | "input" => {
if let Some(items) = value.as_array_mut() {
for item in items {
collect_tool_names(item, &mut fields);
}
}
}
"tool_choice" => collect_tool_names(value, &mut fields),
_ => {}
}
}
// 先预留所有原名,避免别名抢占后面声明的合法名称
let mut used = fields
.iter()
.filter_map(|value| value.as_str())
.map(str::to_owned)
.collect();
let mut names = HashMap::new();
for field in fields {
let Some(name) = field.as_str() else { continue };
if name.is_empty()
|| name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
{
continue;
}
let alias = names.entry(name.to_owned()).or_insert_with(|| {
let base: String = name
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-') {
ch
} else {
'_'
}
})
.collect();
unique_tool_alias(&base, &mut used)
});
*field = Value::String(alias.clone());
}
if let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) {
let mut used = input
.iter()
.filter_map(|item| item.get("call_id").and_then(Value::as_str))
.map(str::to_owned)
.collect();
let mut ids = HashMap::new();
for item in input.iter().filter(|item| {
matches!(
item.get("type").and_then(Value::as_str),
Some("function_call" | "custom_tool_call")
)
}) {
let Some(id) = item
.get("call_id")
.and_then(Value::as_str)
.filter(|id| id.chars().count() > 64)
else {
continue;
};
ids.entry(id.to_owned()).or_insert_with(|| {
let digest = hex::encode(Sha256::digest(id.as_bytes()));
unique_tool_alias(&format!("call_{digest}"), &mut used)
});
}
for item in input {
if matches!(
item.get("type").and_then(Value::as_str),
Some(
"function_call"
| "custom_tool_call"
| "function_call_output"
| "custom_tool_call_output"
)
) && let Some(alias) = item
.get("call_id")
.and_then(Value::as_str)
.and_then(|id| ids.get(id))
{
item["call_id"] = alias.clone().into();
}
}
}
names
.into_iter()
.map(|(name, alias)| (alias, name))
.collect()
}
fn collect_tool_names<'a>(tool: &'a mut Value, names: &mut Vec<&'a mut Value>) {
match tool.get("type").and_then(Value::as_str) {
Some(
"function"
| "custom"
| "function_call"
| "custom_tool_call"
| "function_call_output"
| "custom_tool_call_output",
) => {
if let Some(name) = tool.get_mut("name") {
names.push(name);
}
}
Some("namespace" | "allowed_tools" | "additional_tools" | "tool_search_output") => {
if let Some(tools) = tool.get_mut("tools").and_then(Value::as_array_mut) {
for tool in tools {
collect_tool_names(tool, names);
}
}
}
_ => {}
}
}
fn unique_tool_alias(base: &str, used: &mut HashSet<String>) -> String {
// 调用方只传入 ASCII 名称或十六进制摘要,可按字节截取 Codex 标识上限
let mut candidate = base[..base.len().min(64)].to_owned();
let mut index = 0;
while !used.insert(candidate.clone()) {
index += 1;
let suffix = format!("_{index}");
candidate = format!("{}{suffix}", &base[..base.len().min(64 - suffix.len())]);
}
candidate
}
pub(crate) fn normalize_translated_codex_service_tier(body: &mut Map<String, Value>) {
// 转换生成的默认档位沿用 Codex 客户端的省略表达,原生 Responses 保留调用方声明
@@ -10,7 +10,10 @@ mod search_tools;
use gateway_core::engine::middleware::MiddlewareHeader;
use serde_json::{Map, Value};
pub(crate) use chat::{add_translated_fast_beta, normalize_translated_codex_service_tier};
pub(crate) use chat::{
add_translated_fast_beta, normalize_translated_codex_service_tier,
normalize_translated_codex_tools,
};
pub(crate) use headers::is_non_codex_request_header;
pub(crate) use request::normalize_codex_request_body;
pub(crate) use search_tools::declares_hosted_search;
@@ -8,6 +8,7 @@ use serde_json::{Map, Value, json};
/// 只处理已验证被拒绝的字段,不根据客户端品牌推断整份历史是否合法
pub(super) fn normalize_non_codex_request_body(body: &mut Map<String, Value>) {
normalize_codex_oauth_options(body);
super::search_tools::normalize_search_tool_aliases(body);
let Some(input) = body.get_mut("input").and_then(Value::as_array_mut) else {
return;
};
@@ -132,7 +133,23 @@ fn normalize_codex_oauth_options(body: &mut Map<String, Value>) {
///
/// 兼容基准是 Codex Core/Desktop 的模型请求,不是公开 OpenAI Responses API
/// 未知字段继续透传,不能因官方请求结构中没有某个字段就将其列入过滤规则
pub(crate) fn normalize_codex_request_body(body: &mut Map<String, Value>) {
pub(crate) fn normalize_codex_request_body(
body: &mut Map<String, Value>,
should_replace_none_with_low: impl FnOnce() -> bool,
) {
// 整个请求共用所选账号的目录判断,首次遇到显式 none 才读取快照
let replace_none = std::cell::LazyCell::new(should_replace_none_with_low);
let normalize_effort = |fields: &mut Map<String, Value>| {
if let Some(effort) = fields
.get_mut("reasoning")
.and_then(|reasoning| reasoning.get_mut("effort"))
&& effort.as_str() == Some("none")
&& *replace_none
{
*effort = Value::from("low");
}
};
normalize_effort(body);
// 官方 Core/Desktop 显式发送 store=false;仅为缺字段的下游请求补齐,保留显式值
body.entry("store").or_insert(Value::Bool(false));
@@ -158,10 +175,12 @@ pub(crate) fn normalize_codex_request_body(body: &mut Map<String, Value>) {
let Some(item) = item.as_object_mut() else {
continue;
};
if item.get("type").and_then(Value::as_str) == Some("message")
&& item.get("role").and_then(Value::as_str) == Some("system")
{
item.insert("role".to_owned(), Value::String("developer".to_owned()));
match item.get("type").and_then(Value::as_str) {
Some("configuration_update") => normalize_effort(item),
Some("message") if item.get("role").and_then(Value::as_str) == Some("system") => {
item.insert("role".to_owned(), Value::String("developer".to_owned()));
}
_ => {}
}
}
}
@@ -1,7 +1,39 @@
//! 识别普通与 Responses Lite 请求中的托管搜索声明,不改写工具配置
//! 识别托管搜索声明并适配 Codex 的搜索工具名称
use serde_json::{Map, Value};
pub(super) fn normalize_search_tool_aliases(body: &mut Map<String, Value>) {
for (field, value) in body {
match field.as_str() {
"tools" | "input" => {
if let Some(items) = value.as_array_mut() {
for item in items {
normalize_search_tool(item);
}
}
}
"tool_choice" => normalize_search_tool(value),
_ => {}
}
}
}
fn normalize_search_tool(tool: &mut Value) {
match tool.get("type").and_then(Value::as_str) {
Some("web_search_preview" | "web_search_preview_2025_03_11") => {
tool["type"] = "web_search".into();
}
Some("allowed_tools" | "additional_tools" | "tool_search_output" | "namespace") => {
if let Some(tools) = tool.get_mut("tools").and_then(Value::as_array_mut) {
for tool in tools {
normalize_search_tool(tool);
}
}
}
_ => {}
}
}
pub(crate) fn declares_hosted_search(body: &Map<String, Value>) -> bool {
body.get("tools")
.and_then(Value::as_array)
@@ -308,6 +308,12 @@ struct CatalogRetry {
delay: Duration,
}
#[derive(Clone, Copy)]
enum CatalogFetchMode {
Discovery,
Recovery,
}
#[derive(Default)]
struct CatalogCacheState {
restored: bool,
@@ -497,6 +503,20 @@ impl CodexCredentialCatalogService {
})
}
pub(crate) fn should_replace_none_with_low(
&self,
account: &ProviderAccount,
model: &UpstreamModelId,
) -> bool {
self.cached().ok().flatten().is_some_and(|snapshot| {
snapshot.account_model(account, model).is_some_and(|entry| {
let levels = entry.capabilities().reasoning_efforts();
levels.iter().any(|level| level == "low")
&& !levels.iter().any(|level| level == "none")
})
})
}
pub(crate) fn messages_model_capabilities(
&self,
account: &ProviderAccount,
@@ -576,13 +596,23 @@ impl CodexCredentialCatalogService {
if let Some(catalog) = self.read_account_catalog(account).await? {
return Ok(catalog);
}
self.refresh_account_catalog(account.id()).await
self.query_account_catalog(account.id(), CatalogFetchMode::Discovery)
.await
}
/// 实时刷新指定账号的模型集合,包括管理员显式查询的停用账号
pub async fn refresh_account_catalog(
&self,
account_id: &ProviderAccountId,
) -> Result<CodexAccountCatalog, CodexCredentialCatalogError> {
self.query_account_catalog(account_id, CatalogFetchMode::Recovery)
.await
}
async fn query_account_catalog(
&self,
account_id: &ProviderAccountId,
mode: CatalogFetchMode,
) -> Result<CodexAccountCatalog, CodexCredentialCatalogError> {
let account = self
.repository
@@ -596,7 +626,7 @@ impl CodexCredentialCatalogService {
let client = self.discovery_client().await?;
let revision = self.state_revision()?;
let (catalog, entry) = self
.fetch_observation(&client, &account, &scope, None)
.fetch_observation(&client, &account, &scope, None, mode)
.await?;
if eligible_catalog_account(&account, SystemTime::now())
&& let Err(error) = self.merge_observations(revision, vec![(scope, entry)])
@@ -615,9 +645,10 @@ impl CodexCredentialCatalogService {
account: &ProviderAccount,
scope: &CodexCatalogScope,
etag: Option<String>,
mode: CatalogFetchMode,
) -> Result<(CodexAccountCatalog, AccountEntry), CodexCredentialCatalogError> {
let observed_at = SystemTime::now();
let mut fetched = self.fetch_account_models(client, account).await?;
let mut fetched = self.fetch_account_models(client, account, mode).await?;
let observed = AccountCatalogObservation {
account_id: account.id().clone(),
revision: account.revision(),
@@ -664,7 +695,9 @@ impl CodexCredentialCatalogService {
account: &ProviderAccount,
) -> Result<(Vec<CodexCatalogModel>, SystemTime), CodexCredentialCatalogError> {
let client = self.discovery_client().await?;
let fetched = self.fetch_account_models(&client, account).await?;
let fetched = self
.fetch_account_models(&client, account, CatalogFetchMode::Discovery)
.await?;
if fetched.models.is_empty() {
return Err(CodexCredentialCatalogError::NoEligibleCredential);
}
@@ -728,6 +761,7 @@ impl CodexCredentialCatalogService {
&self,
client: &CodexBackendClient,
account: &ProviderAccount,
mode: CatalogFetchMode,
) -> Result<CodexModelCatalogSnapshot, CodexCredentialCatalogError> {
let deadline = tokio::time::Instant::now() + MODEL_CATALOG_TIMEOUT;
let credential =
@@ -755,22 +789,25 @@ impl CodexCredentialCatalogService {
{
client = client.with_messages_api_base_url(&auth.configuration.base_url);
}
tokio::time::timeout_at(
deadline,
client.fetch_models_with_context(
CodexRequestContext::auxiliary(
authorization.expose_secret(),
account.upstream_account_id(),
&request_id,
None,
),
let fetch = client.fetch_models_with_context(
CodexRequestContext::auxiliary(
authorization.expose_secret(),
account.upstream_account_id(),
&request_id,
None,
),
)
.await
.map_err(|_| CodexCredentialCatalogError::Upstream {
detail: "model catalog timed out".to_owned(),
})?
None,
);
match mode {
CatalogFetchMode::Discovery => {
tokio::time::timeout_at(deadline, fetch)
.await
.map_err(|_| CodexCredentialCatalogError::Upstream {
detail: "model catalog timed out".to_owned(),
})?
}
CatalogFetchMode::Recovery => fetch.await,
}
.map_err(|error| CodexCredentialCatalogError::Upstream {
detail: error.to_string(),
})
@@ -325,11 +325,17 @@ impl CodexCredentialCatalogService {
.into_iter()
.filter_map(|(scope, account)| {
let work = cache.refreshes.get(&scope);
let due = match work {
Some(work) => work.retry.as_ref().is_none_or(|retry| retry.at <= instant),
None => !entries.get(&scope).is_some_and(|entry| entry.is_fresh(now)),
let mode = match work {
Some(AccountCatalogRefresh {
retry: Some(retry), ..
}) => (retry.at <= instant).then_some(CatalogFetchMode::Recovery)?,
None if entries.get(&scope).is_some_and(|entry| entry.is_fresh(now)) => {
return None;
}
_ => CatalogFetchMode::Discovery,
};
due.then(|| (scope, account, work.and_then(|work| work.etag.clone())))
let etag = work.and_then(|work| work.etag.clone());
Some((scope, account, etag, mode))
})
.collect::<Vec<_>>()
};
@@ -345,10 +351,12 @@ impl CodexCredentialCatalogService {
});
let fetches = stream::iter(due)
.zip(starts)
.map(|((scope, account, etag), ())| {
.map(|((scope, account, etag, mode), ())| {
let client = &client;
async move {
let result = self.fetch_observation(client, &account, &scope, etag).await;
let result = self
.fetch_observation(client, &account, &scope, etag, mode)
.await;
(scope, result)
}
})
@@ -60,13 +60,13 @@ pub use oauth::{
pub use profile_statistics::{
CodexCredentialProfileService, CodexProfileAvatarError, CodexProfileStatisticsError,
};
pub(crate) use quota::observed_quota_window;
pub use quota::{
CodexAccountQuotaSnapshot, CodexCredentialQuotaError, CodexCredentialQuotaService,
CodexInitialSyncDelays, CodexQuotaFact, CodexQuotaRefreshPolicy, CodexQuotaSyncSummary,
CodexQuotaWindow, CodexQuotaWindowKind, CodexQuotaWindowRole, CodexResetCreditsError,
parse_codex_quota_usage,
};
pub(crate) use quota::{DEFAULT_RATE_LIMIT_COOLDOWN, observed_quota_window};
pub use refresh::{
CodexCredentialRefreshError, CodexCredentialRefreshOutcome, CodexCredentialRefreshService,
DueCodexCredential,
@@ -75,7 +75,7 @@ use snapshot::{
// 同一份上游观测只重做本地合并,高并发时不无限争抢写入
const QUOTA_MERGE_ATTEMPTS: usize = 3;
const LIMIT_EVIDENCE_FIELD: &str = "_cpr_quota_limit_evidence";
const DEFAULT_RATE_LIMIT_COOLDOWN: Duration = Duration::from_secs(60);
pub(crate) const DEFAULT_RATE_LIMIT_COOLDOWN: Duration = Duration::from_secs(60);
pub(crate) const QUOTA_SCHEDULING_TTL: Duration = Duration::from_secs(10 * 60);
const QUOTA_HYDRATION_FAILURE_TTL: Duration = Duration::from_secs(5);
const PERIODIC_QUOTA_REFRESH_RETRY_INTERVAL: Duration = Duration::from_secs(30 * 60);
@@ -62,8 +62,6 @@ const SESSION_AFFINITY_TIMEOUT: Duration = Duration::from_millis(500);
const CYBER_POLICY_TIMEOUT: Duration = Duration::from_millis(100);
const CYBER_POLICY_SESSION_TTL: Duration = Duration::from_secs(60 * 60);
const MAX_ACCOUNT_SNAPSHOT_RETRIES: u32 = 3;
// 套餐权限可能变化,明确拒绝只作有界的账号模型排除,不冻结整个账号
const MODEL_UNSUPPORTED_COOLDOWN: Duration = Duration::from_secs(30 * 60);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexAccountFailure {
@@ -665,7 +663,10 @@ impl CodexCredentialSelector {
account_ids: &[ProviderAccountId],
native_accounts: &BTreeSet<ProviderAccountId>,
model: CodexSelectionModel<'_>,
) -> HashMap<ProviderAccountId, AccountCooldown> {
) -> (
HashMap<ProviderAccountId, AccountCooldown>,
BTreeSet<ProviderAccountId>,
) {
let native = accounts
.iter()
.filter(|account| native_accounts.contains(account.id()));
@@ -693,11 +694,15 @@ impl CodexCredentialSelector {
.then(|| (id.clone(), state))
})
.collect();
let mut model_rate_limited_accounts = BTreeSet::new();
for (account, cooldown) in native.zip(model_cooldowns) {
if let Some(cooldown) = cooldown.ok().flatten().filter(|cooldown| {
cooldown.credential_revision() == account.revision()
&& cooldown.until() > SystemTime::now()
}) {
if cooldown.rate_limited_until() == Some(cooldown.until()) {
model_rate_limited_accounts.insert(account.id().clone());
}
// 两种冷却取较晚期限,保留账号级冷却的恢复探测语义
active
.entry(account.id().clone())
@@ -708,7 +713,7 @@ impl CodexCredentialSelector {
});
}
}
active
(active, model_rate_limited_accounts)
}
async fn select_inner_loop(
@@ -1093,8 +1098,8 @@ impl CodexCredentialSelector {
continue 'capacity;
}
let follow_only = follow_only && image_primary_to_keep.is_none();
let rate_limits = if diagnostic {
HashMap::new()
let (rate_limits, model_rate_limited_accounts) = if diagnostic {
Default::default()
} else {
self.load_candidate_cooldowns(&accounts, &account_ids, &native_accounts, model)
.await
@@ -1468,6 +1473,33 @@ impl CodexCredentialSelector {
}
// 只判断本次账号范围;空池、认证失效和租约失败不能伪装成额度耗尽
// 策略排除与临时容量阻塞分开,保留繁忙账号的可恢复语义
// 只有本轮可选账号的原生模型限流才提供等待提示
let cooldown_retry = candidates
.iter()
.filter(|candidate| {
model_rate_limited_accounts.contains(candidate.account.id())
})
.filter(|candidate| {
!context.excluded_accounts.contains(candidate.account.id())
})
.filter(|candidate| {
context
.account_scope
.as_ref()
.is_none_or(|scope| scope.allows(candidate.account.id()))
})
.filter(|candidate| {
candidate
.account
.status_projection(context.now, candidate.signals.cooldown)
.status
== AccountStatus::RateLimited
})
.filter_map(|candidate| candidate.signals.cooldown)
.filter(|cooldown| cooldown.kind == AccountCooldownKind::RateLimit)
.filter_map(|cooldown| cooldown.until.duration_since(context.now).ok())
.min();
shortest_retry = minimum_duration(shortest_retry, cooldown_retry);
let mut statuses = candidates
.iter()
.filter(|candidate| {
@@ -1690,20 +1722,11 @@ impl CodexCredentialSelector {
}
}
pub(crate) async fn record_model_unsupported(
pub(crate) async fn record_model_cooldown(
&self,
account: &ProviderAccount,
model: &gateway_core::routing::UpstreamModelId,
cooldown: ProviderScopedCooldown,
) -> Result<(), ProviderStoreError> {
let now = SystemTime::now();
self.cooldowns
.put_scoped_if_later(ProviderScopedCooldown::new(
account.id().clone(),
account.revision(),
ProviderCooldownScope::upstream_model(model.clone()),
now.checked_add(MODEL_UNSUPPORTED_COOLDOWN).unwrap_or(now),
))
.await?;
self.cooldowns.put_scoped_if_later(cooldown).await?;
Ok(())
}
@@ -38,7 +38,7 @@ impl CodexProvider {
};
let mut source_context = generate.protocol_payload().context().clone();
let target = selected.lease.authentication().api_protocol();
let translator = response::ChatResponseTranslator::new(target, identity, original);
let mut translator = response::ChatResponseTranslator::new(target, identity, original);
match target {
ApiKeyProtocol::Messages => {
let capabilities = self
@@ -82,6 +82,8 @@ impl CodexProvider {
CodexRuntimeAuthentication::OAuth(_)
) {
crate::compat::normalize_translated_codex_service_tier(&mut body);
translator.tool_names =
crate::compat::normalize_translated_codex_tools(&mut body);
}
let body = serde_json::to_vec(&body).map_err(|_| request_error())?;
let operation = operation
@@ -1,5 +1,7 @@
//! 单次响应直接映射为 Chat wire,原生观测与资源释放归现有执行链
use std::collections::HashMap;
use super::*;
use gateway_core::engine::provider::NativeResponseTranslator;
use gateway_protocol::{
@@ -20,6 +22,7 @@ pub(super) struct ChatResponseTranslator {
complete_json: bool,
streaming: bool,
include_usage: bool,
pub(super) tool_names: HashMap<String, String>,
}
impl ChatResponseTranslator {
@@ -54,6 +57,7 @@ impl ChatResponseTranslator {
complete_json: false,
streaming: request.get("stream").and_then(Value::as_bool) == Some(true),
include_usage,
tool_names: Default::default(),
}
}
}
@@ -79,7 +83,7 @@ impl NativeResponseTranslator for ChatResponseTranslator {
}
if let Some(raw) = event.raw_json_body() {
let body = serde_json::from_slice(raw).map_err(|_| response_error())?;
let response = match self.encoder {
let mut response = match self.encoder {
Encoder::Responses(_) => responses::project_response(&body, &self.identity),
Encoder::Messages(_) => {
messages::project_response_with_request(&body, &self.identity, &self.request)
@@ -94,8 +98,10 @@ impl NativeResponseTranslator for ChatResponseTranslator {
self.include_usage,
)
.map_err(map_error)?,
&self.tool_names,
);
}
restore_tool_names(&mut response, &self.tool_names);
return ProtocolWireEvent::raw_json(
CHAT_PROTOCOL,
serde_json::to_vec(&response)
@@ -113,7 +119,7 @@ impl NativeResponseTranslator for ChatResponseTranslator {
Encoder::Messages(encoder) => encoder.push_event(event.event_type(), event.data()),
}
.map_err(map_error)?;
wire_events(chunks)
wire_events(chunks, &self.tool_names)
}
fn finish(&mut self) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
@@ -125,19 +131,52 @@ impl NativeResponseTranslator for ChatResponseTranslator {
Encoder::Messages(encoder) => encoder.finish(),
}
.map_err(map_error)?;
wire_events(chunks)
wire_events(chunks, &self.tool_names)
}
}
fn wire_events(chunks: Vec<Value>) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
fn wire_events(
chunks: Vec<Value>,
names: &HashMap<String, String>,
) -> Result<Vec<ProtocolWireEvent>, ProviderError> {
chunks
.into_iter()
.map(|chunk| {
.map(|mut chunk| {
restore_tool_names(&mut chunk, names);
ProtocolWireEvent::json(CHAT_PROTOCOL, None, chunk).map_err(|_| response_error())
})
.collect()
}
fn restore_tool_names(response: &mut Value, names: &HashMap<String, String>) {
if names.is_empty() {
return;
}
let Some(choices) = response.get_mut("choices").and_then(Value::as_array_mut) else {
return;
};
for choice in choices {
for field in ["message", "delta"] {
let Some(calls) = choice
.get_mut(field)
.and_then(|message| message.get_mut("tool_calls"))
.and_then(Value::as_array_mut)
else {
continue;
};
for call in calls {
for kind in ["function", "custom"] {
if let Some(name) = call.get_mut(kind).and_then(|tool| tool.get_mut("name"))
&& let Some(original) = name.as_str().and_then(|name| names.get(name))
{
*name = original.clone().into();
}
}
}
}
}
}
fn map_error(error: ChatError) -> ProviderError {
response_error().with_source(error)
}
@@ -3,6 +3,7 @@
use super::*;
use crate::transport::protocol::responses::is_replaceable_response_prelude;
use gateway_core::error::{ProxyConnectionHint, TransientRetryPolicy};
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
use gateway_protocol::http::preferred_response_request_id;
/// OpenAI 失败对 Smart 账号分数的结构化 reason 闭集
@@ -41,6 +42,34 @@ pub fn openai_failure_affects_account_score(error: &ProviderError) -> bool {
openai_account_score_failure_reason(error).is_some_and(is_openai_account_score_failure_reason)
}
pub(super) enum ModelCooldown {
Unsupported,
RateLimited(std::time::SystemTime),
}
impl ModelCooldown {
fn for_account(
&self,
account: &ProviderAccount,
model: &UpstreamModelId,
) -> ProviderScopedCooldown {
let (until, rate_limit) = match self {
Self::Unsupported => (
std::time::SystemTime::now() + Duration::from_secs(30 * 60),
None,
),
Self::RateLimited(until) => (*until, Some(*until)),
};
ProviderScopedCooldown::new(
account.id().clone(),
account.revision(),
ProviderCooldownScope::upstream_model(model.clone()),
until,
)
.with_rate_limited_until(rate_limit)
}
}
pub(super) struct MappedProviderFailure {
pub(super) error: ProviderError,
pub(super) websocket_transport_retryable: bool,
@@ -48,7 +77,7 @@ pub(super) struct MappedProviderFailure {
/// 原始上游错误描述,仅在凭据错误状态下持久化
pub(super) error_message: Option<String>,
pub(super) cyber_policy_failure: bool,
pub(super) model_unsupported: bool,
pub(super) model_cooldown: Option<ModelCooldown>,
pub(super) set_cookie_headers: Vec<String>,
pub(super) response_origin: Option<Url>,
pub(super) rate_limit_headers: Vec<(String, String)>,
@@ -65,7 +94,7 @@ impl MappedProviderFailure {
account_failure: None,
error_message: None,
cyber_policy_failure: false,
model_unsupported: false,
model_cooldown: None,
set_cookie_headers: Vec::new(),
response_origin: None,
rate_limit_headers: Vec::new(),
@@ -350,11 +379,11 @@ pub(super) async fn apply_failure(
false,
)
.await;
if failure.model_unsupported
if let Some(model_cooldown) = &failure.model_cooldown
&& let Some(model) = context.upstream_model
&& let Err(error) = context
.selector
.record_model_unsupported(account, model)
.record_model_cooldown(model_cooldown.for_account(account, model))
.await
{
tracing::warn!(account_id = %account.id(), error = %error,
@@ -554,7 +583,7 @@ pub(super) fn apply_websocket_recovery_policy(
return;
}
// 明确账号拒绝走已有换号路径,业务瞬态失败走请求内退避,不消耗 WS 传输预算
if failure.model_unsupported
if matches!(failure.model_cooldown, Some(ModelCooldown::Unsupported))
|| (failure.error.replay_is_safe()
&& (failure.account_failure.is_some()
|| matches!(
@@ -1629,7 +1658,21 @@ pub(super) fn map_upstream_failure(
account_failure: account_failure(&failure),
error_message: failure.client_message,
cyber_policy_failure,
model_unsupported: category == CodexFailureCategory::ModelUnsupported,
model_cooldown: match category {
CodexFailureCategory::ModelUnsupported => Some(ModelCooldown::Unsupported),
CodexFailureCategory::TurnRateLimited => {
// 流内错误的 Retry-After 从错误发生时计时,不能使用早先的连接响应头时间
let now = std::time::SystemTime::now();
let duration = failure
.retry_after_seconds
.map(Duration::from_secs)
.unwrap_or(crate::credential::DEFAULT_RATE_LIMIT_COOLDOWN);
Some(ModelCooldown::RateLimited(
now.checked_add(duration).unwrap_or(now),
))
}
_ => None,
},
// 普通 5xx 与未知流内错误不足以证明容量拒绝,不能用于冻结账号
set_cookie_headers: failure.set_cookie_headers,
response_origin: failure.response_origin,
@@ -1689,7 +1732,7 @@ fn upstream_failure_summary(
}
CodexFailureCategory::RateLimited => (ProviderErrorKind::RateLimited, "上游请求频率受限"),
CodexFailureCategory::TurnRateLimited => {
(ProviderErrorKind::RateLimited, "当前对话轮次受到限流")
(ProviderErrorKind::RateLimited, "当前账号的模型请求频率受限")
}
CodexFailureCategory::CloudflareChallenge => {
(ProviderErrorKind::Unavailable, "Cloudflare 要求验证请求")
@@ -553,7 +553,7 @@ impl Provider for CodexProvider {
..Default::default()
};
};
let Ok(encoded) = encode_generate_payload(request, "observability") else {
let Ok(encoded) = encode_generate_payload(request, "observability", || false) else {
return ProviderRequestObservation::default();
};
let previous_reasoning_effort_override = request
@@ -694,7 +694,7 @@ impl Provider for CodexProvider {
}
// 跨协议转换必须在选号后执行;选号前只按各自协议读取明确会话身份
let upstream = (generate.protocol_payload().protocol() == OPENAI_PROTOCOL)
.then(|| encode_generate_payload(generate, upstream_model.as_str()))
.then(|| encode_generate_payload(generate, upstream_model.as_str(), || false))
.transpose()
.map_err(map_request_error)?;
// 固定调度约束:Guardian 分类先于选号,不能随原生/适配器发送路径改变
@@ -976,8 +976,11 @@ impl CodexProvider {
"provider_input",
None,
);
let mut upstream = encode_generate_payload(&generate, upstream_model.as_str())
.map_err(map_request_error)?;
let mut upstream = encode_generate_payload(&generate, upstream_model.as_str(), || {
self.catalog
.should_replace_none_with_low(lease.account(), &upstream_model)
})
.map_err(map_request_error)?;
upstream.client_account_follow_only = crate::request_identity::follows_session_with_headers(
generate.protocol_payload().body(),
generate.protocol_payload().context(),
@@ -1,7 +1,12 @@
//! 上游模型目录读取;Codex 版本协商与 Messages 分页各自遵循原生合同
use crate::profile::CodexWireProfile;
use std::time::Duration;
use bytes::BytesMut;
use gateway_protocol::openai::events::retry_after_seconds_from_body;
use tokio::time::{Instant, timeout, timeout_at};
use crate::profile::CodexWireProfile;
use super::backend::{
CodexBackendClient, CodexBackendTransport, CodexClientError, CodexClientResult,
@@ -15,6 +20,8 @@ use super::super::{
response_meta,
};
const CATALOG_READ_IDLE: Duration = Duration::from_secs(30);
impl CodexBackendClient {
/// 目录优先使用显式协商版本,否则沿用调用方冻结的画像版本
pub async fn fetch_models_with_context(
@@ -112,7 +119,12 @@ impl CodexBackendClient {
.headers_mut()
.insert(gateway_protocol::peer::ROUTE_HEADER, route.clone());
}
let response = self.client.execute(request).await?;
let idle_timeout = |_| CodexClientError::StreamIdleTimeout {
timeout: CATALOG_READ_IDLE,
};
let mut response = timeout(CATALOG_READ_IDLE, self.client.execute(request))
.await
.map_err(idle_timeout)??;
let status = response.status();
let diagnostics = response_meta::diagnostics(Some(status.as_u16()), response.headers())
.with_response_origin(Some(response.url().clone()));
@@ -123,7 +135,17 @@ impl CodexBackendClient {
.then(|| catalog_etag(response.headers()))
.transpose()?
.flatten();
let body = response.bytes().await?;
let mut body = BytesMut::new();
let mut deadline = Instant::now() + CATALOG_READ_IDLE;
while let Some(chunk) = timeout_at(deadline, response.chunk())
.await
.map_err(idle_timeout)??
{
if !chunk.is_empty() {
body.extend_from_slice(&chunk);
deadline = Instant::now() + CATALOG_READ_IDLE;
}
}
if !status.is_success() {
let body = String::from_utf8_lossy(&body).into_owned();
return Err(CodexClientError::Upstream {
@@ -140,7 +162,7 @@ impl CodexBackendClient {
send_phase: CodexUpstreamSendPhase::AfterPayload,
});
}
Ok((body, etag))
Ok((body.freeze(), etag))
}
}
@@ -107,7 +107,7 @@ pub fn encode_generate_request(
upstream_model: &str,
location: Option<&CodexRequestLocation>,
) -> Result<CodexResponsesRequest, CodexRequestEncodeError> {
let mut encoded = encode_generate_payload(request, upstream_model)?;
let mut encoded = encode_generate_payload(request, upstream_model, || false)?;
apply_codex_request_country(
encoded.body_mut(),
location,
@@ -121,6 +121,7 @@ pub fn encode_generate_request(
pub(crate) fn encode_generate_payload(
request: &GenerateRequest,
upstream_model: &str,
should_replace_none_with_low: impl FnOnce() -> bool,
) -> Result<CodexResponsesRequest, CodexRequestEncodeError> {
let payload = request.protocol_payload();
if payload.protocol() != OPENAI_PROTOCOL {
@@ -128,7 +129,7 @@ pub(crate) fn encode_generate_payload(
}
let mut body = payload.body().clone();
body.insert("model".to_owned(), Value::String(upstream_model.to_owned()));
normalize_codex_request_body(&mut body);
normalize_codex_request_body(&mut body, should_replace_none_with_low);
let mut encoded = CodexResponsesRequest::from_body(body);
encoded.explicit_prompt_cache_key = encoded.prompt_cache_key().is_some();
extract_request_context(&mut encoded);
@@ -1,17 +1,13 @@
//! 物理 WS 的响应归属与 HTTP 全量输入的增量续接
use std::{
collections::BTreeMap,
hash::{Hash, Hasher},
};
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::transport::protocol::{
responses::CodexResponsesRequest, websocket::websocket_response_completed_id,
};
use super::history::{HistoryItem, fingerprint};
#[derive(Default)]
pub(super) struct WebSocketContinuationState {
latest_response_id: Option<String>,
@@ -31,11 +27,22 @@ impl WebSocketContinuationState {
if request.store() || !request.generate() || body.contains_key("previous_response_id") {
return Self::default();
}
// 每轮元数据随当前帧照常发送,模型、工具及未知正文属性均参与前缀校验
let properties: BTreeMap<_, _> = body
.iter()
.filter(|(key, _)| !matches!(key.as_str(), "input" | "client_metadata"))
.collect();
// 对齐 Codex 的 responses_request_properties_mismatch,仅比较它用来判定续接的属性
let properties = [
"model",
"tools",
"tool_choice",
"parallel_tool_calls",
"reasoning",
"store",
"stream",
"include",
"service_tier",
"prompt_cache_key",
"prompt_cache_options",
"text",
]
.map(|field| body.get(field).unwrap_or(&Value::Null));
let mut input = Prefix {
count: 0,
digest: fingerprint((owner, properties)),
@@ -47,9 +54,9 @@ impl WebSocketContinuationState {
.history
.as_ref()
.map_or(0, |last| last.total.count.min(items.len()));
input.extend(&items[..cut]);
let reuse = self.history.is_some_and(|last| last.total == input) && cut < items.len();
input.extend(&items[cut..]);
input.extend(items[..cut].iter().map(HistoryItem::Input));
let reuse = self.history.is_some_and(|last| last.total == input);
input.extend(items[cut..].iter().map(HistoryItem::Input));
if reuse && let Some(id) = self.latest_response_id.filter(|id| !id.is_empty()) {
items.drain(..cut);
request.set_previous_response_id(Some(id));
@@ -73,7 +80,7 @@ impl WebSocketContinuationState {
if let Some(item) = value.get("item").filter(|i| i.is_object())
&& value["output_index"].as_u64() == Some(index as u64)
{
history.total.push(item);
history.total.push(HistoryItem::Output(item));
} else {
self.history = None;
}
@@ -89,11 +96,9 @@ impl WebSocketContinuationState {
self.history = None;
} else {
history.total = history.input;
history.total.extend(output);
history.total.extend(output.iter().map(HistoryItem::Output));
}
} else if history.total.count == history.input.count
|| history.total.count - history.input.count < history.added
{
} else if history.total.count - history.input.count < history.added {
self.history = None;
}
}
@@ -120,33 +125,14 @@ struct Prefix {
}
impl Prefix {
fn extend(&mut self, items: &[Value]) {
fn extend<'a>(&mut self, items: impl IntoIterator<Item = HistoryItem<'a>>) {
for item in items {
self.push(item);
}
}
fn push(&mut self, item: &Value) {
fn push(&mut self, item: HistoryItem<'_>) {
self.digest = fingerprint((self.digest, item));
self.count += 1;
}
}
// Value 的 Hash 忽略对象键顺序、保留数组顺序;摘要只在当前进程的连接租约内比较
fn fingerprint(value: impl Hash) -> [u8; 32] {
struct DigestHasher(Sha256);
impl Hasher for DigestHasher {
fn write(&mut self, bytes: &[u8]) {
self.0.update(bytes);
}
fn finish(&self) -> u64 {
u64::from_be_bytes(self.0.clone().finalize().as_chunks::<8>().0[0])
}
}
let mut hasher = DigestHasher(Sha256::new());
value.hash(&mut hasher);
hasher.0.finalize().into()
}
@@ -0,0 +1,234 @@
//! Codex 历史项回传形状的只读摘要投影,不改写或留存业务正文
use std::hash::{Hash, Hasher};
use serde_json::Value;
use sha2::{Digest, Sha256};
// 基准:openai/codex rust-v0.174.0,models.rs 的 ResponseItem 及嵌套线协议
// https://github.com/openai/codex/blob/2d42293d1d32079068f1e4ed8aa70fdbf146ec01/codex-rs/protocol/src/models.rs
// 官方先解析类型再回传,不能直接比较上游 JSON 中未被客户端保留的字段
#[derive(Clone, Copy)]
enum Shape {
Item,
Content,
AgentContent,
ToolOutput,
Summary,
ReasoningContent,
WebSearchAction,
ShellAction,
ConfigurationReasoning,
}
pub(super) enum HistoryItem<'a> {
Input(&'a Value),
Output(&'a Value),
}
impl Hash for HistoryItem<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
let (Self::Input(value) | Self::Output(value)) = self;
hash_value(value, Shape::Item, state);
let kind = value["type"].as_str().unwrap_or_default();
if fields(Shape::Item, kind, value).is_some()
&& !matches!(
kind,
"additional_tools" | "configuration_update" | "compaction_trigger"
)
{
// 上游 JSON 的结果元数据被官方 skip_deserializing,客户端回传的宿主结果则必须比较
if matches!(self, Self::Input(_)) {
hash_tool_results(value, state);
} else {
false.hash(state);
}
}
}
}
fn hash_value<H: Hasher>(value: &Value, shape: Shape, state: &mut H) {
if let Some(items) = value.as_array()
&& !matches!(shape, Shape::Item)
{
0_u8.hash(state);
items.len().hash(state);
for item in items {
hash_value(item, shape, state);
}
return;
}
let kind = value
.get("type")
.and_then(Value::as_str)
.unwrap_or_default();
let kind = match (shape, kind) {
(Shape::Item, "compaction_summary") => "compaction",
(Shape::ConfigurationReasoning, _) => "",
_ => kind,
};
let Some(fields) = value.as_object().and_then(|_| fields(shape, kind, value)) else {
// 未知类型和非对象值仍按原值比较,不能像客户端 Other 一样合并不同正文
1_u8.hash(state);
value.hash(state);
return;
};
2_u8.hash(state);
kind.hash(state);
for field in fields {
let child = &value[*field];
match (shape, kind, *field) {
// 空 reasoning.content 在官方序列化时省略,其他空数组仍是有意义的值
(Shape::Item, "reasoning", "content") if child.is_null() => {
hash_value(&Value::Array(Vec::new()), Shape::ReasoningContent, state);
}
(Shape::Item, "message", "content") => hash_value(child, Shape::Content, state),
(Shape::Item, "agent_message", "content") => {
hash_value(child, Shape::AgentContent, state);
}
(Shape::Item, "reasoning", "summary") => hash_value(child, Shape::Summary, state),
(Shape::Item, "reasoning", "content") => {
hash_value(child, Shape::ReasoningContent, state);
}
(Shape::Item, "function_call_output" | "custom_tool_call_output", "output") => {
hash_value(child, Shape::ToolOutput, state);
}
(Shape::Item, "web_search_call", "action") => {
hash_value(child, Shape::WebSearchAction, state);
}
(Shape::Item, "local_shell_call", "action") => {
hash_value(child, Shape::ShellAction, state);
}
(Shape::Item, "configuration_update", "reasoning") => {
hash_value(child, Shape::ConfigurationReasoning, state);
}
// arguments、工具定义、schema、annotations 和 logprobs 都保留完整 JSON
_ => child.hash(state),
}
}
}
fn fields(shape: Shape, kind: &str, value: &Value) -> Option<&'static [&'static str]> {
Some(match (shape, kind) {
(Shape::Item, "additional_tools") => &["id", "role", "tools"],
(Shape::Item, "message") => &[
"encrypted_content",
"status",
"id",
"role",
"content",
"phase",
],
(Shape::Item, "agent_message") => &["id", "author", "recipient", "content"],
(Shape::Item, "reasoning") => &["id", "summary", "content", "encrypted_content"],
(Shape::Item, "local_shell_call") => {
&["encrypted_content", "id", "call_id", "status", "action"]
}
(Shape::Item, "function_call") => &[
"encrypted_content",
"status",
"id",
"name",
"namespace",
"arguments",
"encrypted_function_args",
"call_id",
],
(Shape::Item, "tool_search_call") => &[
"encrypted_content",
"id",
"call_id",
"status",
"execution",
"arguments",
],
(Shape::Item, "function_call_output") => &["id", "call_id", "name", "namespace", "output"],
(Shape::Item, "custom_tool_call") => &[
"encrypted_content",
"id",
"status",
"call_id",
"name",
"namespace",
"input",
],
(Shape::Item, "custom_tool_call_output") => &["id", "call_id", "name", "output"],
(Shape::Item, "tool_search_output") => &["id", "call_id", "status", "execution", "tools"],
(Shape::Item, "web_search_call") => &["encrypted_content", "id", "status", "action"],
(Shape::Item, "image_generation_call") => &[
"encrypted_content",
"id",
"status",
"revised_prompt",
"result",
],
(Shape::Item, "compaction" | "compaction_summary" | "context_compaction") => {
&["id", "encrypted_content"]
}
(Shape::Item, "configuration_update") => &["reasoning"],
(Shape::Item, "compaction_trigger") => &[],
(Shape::Content | Shape::AgentContent | Shape::ToolOutput, "input_text")
| (Shape::Summary, "summary_text")
| (Shape::ReasoningContent, "reasoning_text" | "text") => &["text"],
(Shape::Content, "output_text") => &["text", "annotations", "logprobs"],
(Shape::AgentContent | Shape::ToolOutput, "encrypted_content") => &["encrypted_content"],
(Shape::Content | Shape::ToolOutput, "input_image") => {
if value.get("image_url").is_some_and(Value::is_string) {
&["image_url", "detail"]
} else {
&["file_id", "detail"]
}
}
(Shape::Content | Shape::ToolOutput, "input_audio") => {
if value.get("audio_url").is_some_and(Value::is_string) {
&["audio_url"]
} else {
&["file_id"]
}
}
(Shape::WebSearchAction, "search") => &["query", "queries"],
(Shape::WebSearchAction, "open_page") => &["url"],
(Shape::WebSearchAction, "find_in_page") => &["url", "pattern"],
(Shape::ShellAction, "exec") => {
&["command", "timeout_ms", "working_directory", "env", "user"]
}
(Shape::ConfigurationReasoning, "") => &["effort"],
_ => return None,
})
}
fn hash_tool_results<H: Hasher>(item: &Value, state: &mut H) {
// 官方比较宿主已记录的结果及调用绑定;反序列化会丢掉这些可信字段,不能借此忽略更新
// result ID 只存在于客户端内存,线上可比较的事实是原始 metadata、调用位置、名称和参数
for (index, call) in item["internal_chat_message_metadata_passthrough"]["executed_tool_calls"]
.as_array()
.into_iter()
.flatten()
.enumerate()
{
if let Some(result) = call.get("tool_result_metadata") {
true.hash(state);
(index, call.get("name"), call.get("arguments"), result).hash(state);
}
}
false.hash(state);
}
// Value 的 Hash 忽略对象键顺序、保留数组顺序;摘要只在当前进程的连接租约内比较
pub(super) fn fingerprint(value: impl Hash) -> [u8; 32] {
struct DigestHasher(Sha256);
impl Hasher for DigestHasher {
fn write(&mut self, bytes: &[u8]) {
self.0.update(bytes);
}
fn finish(&self) -> u64 {
u64::from_be_bytes(self.0.clone().finalize().as_chunks::<8>().0[0])
}
}
let mut hasher = DigestHasher(Sha256::new());
value.hash(&mut hasher);
hasher.0.finalize().into()
}
@@ -8,6 +8,7 @@ mod coordinator;
mod error;
mod exchange;
mod handshake;
mod history;
mod live;
mod model;
mod pool;
@@ -603,7 +603,7 @@ async fn openai_admin_provider_exposes_live_wire_profile_and_validated_billing()
}
#[tokio::test]
async fn openai_legacy_billing_should_not_infer_long_context_flag() {
async fn openai_billing_reconstruction_does_not_infer_long_context_flag() {
let config = valid_config();
let bundle = provider_openai::initialize(
config.config.clone(),
@@ -626,7 +626,7 @@ async fn openai_legacy_billing_should_not_infer_long_context_flag() {
amount: "1.5".parse().expect("stored total"),
},
})
.expect("legacy billing")
.expect("reconstructed billing")
.expect("matching billing breakdown");
assert_eq!(billing.total_amount.amount.as_str(), "1.5");
@@ -2,6 +2,9 @@
use super::*;
use gateway_protocol::openai::OPENAI_PROTOCOL;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
#[tokio::test]
async fn invalidation_queues_background_refresh_without_an_upstream_etag() {
@@ -363,3 +366,131 @@ async fn periodic_failure_arms_an_idle_catalog_worker_without_an_etag() {
assert!(service.cached_account_models(&account).unwrap().is_some());
server.verify().await;
}
async fn accept_catalog_request(listener: &TcpListener) -> TcpStream {
let (socket, _) = tokio::time::timeout(Duration::from_secs(5), listener.accept())
.await
.expect("expected an upstream catalog request")
.unwrap();
let mut reader = BufReader::new(socket);
let mut line = String::new();
reader.read_line(&mut line).await.unwrap();
assert!(line.starts_with("GET /codex/models?"));
loop {
line.clear();
assert_ne!(reader.read_line(&mut line).await.unwrap(), 0);
if line == "\r\n" {
return reader.into_inner();
}
}
}
const PARTIAL_CATALOG: &[u8] = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{";
async fn stalled_catalog<T>(
listener: &TcpListener,
request: impl Future<Output = T>,
partial_body: bool,
) -> (T, u64) {
tokio::pin!(request);
let mut socket = tokio::select! {
_ = &mut request => panic!("catalog request ended before reaching the upstream"),
socket = accept_catalog_request(listener) => socket,
};
if partial_body {
socket.write_all(PARTIAL_CATALOG).await.unwrap();
}
tokio::time::pause();
let start = tokio::time::Instant::now();
let result = tokio::time::timeout(Duration::from_secs(35), request)
.await
.expect("stalled catalog request must release the connection");
let elapsed = start.elapsed().as_secs();
tokio::time::resume();
(result, elapsed)
}
async fn send_slow_catalog(listener: &TcpListener) {
let mut socket = accept_catalog_request(listener).await;
socket.write_all(PARTIAL_CATALOG).await.unwrap();
for chunk in [
br#""models":"#.as_slice(),
b"[",
br#"{"slug":"#,
br#""slow","#,
br#""display_name":"#,
br#""Slow"}"#,
b"]}",
] {
tokio::time::pause();
tokio::time::sleep(Duration::from_secs(20)).await;
tokio::time::resume();
socket.write_all(chunk).await.unwrap();
}
}
#[tokio::test]
async fn discovery_times_out_but_a_due_retry_can_publish_a_slow_catalog() {
let store = Arc::new(MemoryAccountStore::default());
let account = seed_account(&store, "acct_slow_retry").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let service = service_with_catalog_cache(&store, url, catalog_cache());
let (scan, elapsed) = stalled_catalog(&listener, service.refresh_catalogs(), true).await;
scan.unwrap();
assert!((14..=15).contains(&elapsed));
assert!(service.cached_account_models(&account).unwrap().is_none());
tokio::time::pause();
tokio::time::advance(Duration::from_secs(61)).await;
tokio::time::resume();
let (retry, ()) = tokio::join!(service.refresh_catalogs(), send_slow_catalog(&listener));
retry.unwrap();
assert_eq!(
service.cached_account_models(&account).unwrap().unwrap(),
["slow"]
);
}
#[tokio::test]
async fn manual_refresh_tracks_body_progress_and_keeps_the_catalog_on_stall() {
let store = Arc::new(MemoryAccountStore::default());
let account = seed_account(&store, "acct_slow_manual").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let service = service_with_catalog_cache(&store, url, catalog_cache());
let (miss, elapsed) = stalled_catalog(
&listener,
service.cached_or_refresh_account_catalog(&account),
true,
)
.await;
assert!(matches!(
miss,
Err(CodexCredentialCatalogError::Upstream { .. })
));
assert!((14..=15).contains(&elapsed));
let (refresh, ()) = tokio::join!(
service.refresh_account_catalog(account.id()),
send_slow_catalog(&listener)
);
assert_eq!(refresh.unwrap().models(), ["slow"]);
for partial_body in [false, true] {
let (refresh, elapsed) = stalled_catalog(
&listener,
service.refresh_account_catalog(account.id()),
partial_body,
)
.await;
assert!(matches!(
refresh,
Err(CodexCredentialCatalogError::Upstream { .. })
));
assert!((29..=30).contains(&elapsed));
assert_eq!(
service.cached_account_models(&account).unwrap().unwrap(),
["slow"]
);
}
}
@@ -326,3 +326,129 @@ async fn shorter_account_cooldown_cannot_unmask_an_active_model_cooldown_during_
assert!(cooldowns.cooldowns.lock().unwrap()[account.id()].until() < SystemTime::now());
assert_eq!(selected.account_id().as_str(), "acct_second");
}
#[tokio::test]
async fn model_cooldown_survives_success_and_only_blocks_the_matching_account_and_model() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_first", "test-first");
create_account(&store, "acct_second", "test-second");
let account = store.account("acct_first").unwrap();
let cooldowns = Arc::new(MemoryCooldownPort::new());
let scope = ProviderCooldownScope::upstream_model(UpstreamModelId::new("gpt-5.4").unwrap());
let until = SystemTime::now() + Duration::from_secs(60);
cooldowns
.put_scoped_if_later(
ProviderScopedCooldown::new(
account.id().clone(),
account.revision(),
scope.clone(),
until,
)
.with_rate_limited_until(Some(until)),
)
.await
.unwrap();
let selector = selector_with_runtime(
&store,
Arc::new(TestLeaseCoordinator::default()),
Arc::new(MemorySessionAffinity::default()),
Arc::new(AccountFeedbackStats::default()),
cooldowns.clone(),
);
selector.record_success(&account).await;
let request_url = Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap();
let new_session = attempt(BTreeSet::new());
let request = SelectCodexCredential {
protocol: gateway_protocol::openai::OPENAI_PROTOCOL,
upstream_model: "gpt-5.4",
request_url: &request_url,
attempt: &new_session,
session_affinity_key: None,
};
let selected = selector.select(&request).await.unwrap();
assert_eq!(selected.account_id().as_str(), "acct_second");
drop(selected);
let same_account = attempt_with_required(BTreeSet::new(), Some(account.id().clone()));
let other_model = selector
.select(&SelectCodexCredential {
upstream_model: "gpt-5.5",
attempt: &same_account,
..request
})
.await
.unwrap();
assert_eq!(other_model.account_id(), account.id());
assert!(
cooldowns
.read_scoped(account.id(), &scope)
.await
.unwrap()
.is_some()
);
}
#[tokio::test]
async fn pinned_model_cooldown_returns_retry_after_without_rotating_or_entering_capacity_queue() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_original", "test-original");
create_account(&store, "acct_primary", "test-free");
let account = store.account("acct_original").unwrap();
let cooldowns = Arc::new(MemoryCooldownPort::new());
let scope = ProviderCooldownScope::upstream_model(UpstreamModelId::new("gpt-5.4").unwrap());
let until = SystemTime::now() + Duration::from_secs(60);
cooldowns
.put_scoped_if_later(
ProviderScopedCooldown::new(
account.id().clone(),
account.revision(),
scope.clone(),
until,
)
.with_rate_limited_until(Some(until)),
)
.await
.unwrap();
let selector = selector_with_runtime(
&store,
Arc::new(TestLeaseCoordinator::default()),
Arc::new(MemorySessionAffinity::default()),
Arc::new(AccountFeedbackStats::default()),
cooldowns.clone(),
);
let attempt = AttemptContext::new(
RequestAttemptContext::new(
ModelRequestId::new("req_model_wait").unwrap(),
ClientApiKeyId::new("key_codex_contract").unwrap(),
),
NonZeroU32::new(1).unwrap(),
SystemTime::now() + Duration::from_secs(5),
account_policy().with_queue(gateway_core::concurrency::ConcurrencyQueuePolicy {
max_waiting: 1,
timeout: Duration::from_secs(2),
}),
AccountAttemptContext::new(BTreeSet::new(), Some(account.id().clone()), None)
.with_account_scope(contract_account_scope()),
None,
CancellationToken::new(),
);
let request_url = Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap();
let request = SelectCodexCredential {
protocol: gateway_protocol::openai::OPENAI_PROTOCOL,
upstream_model: "gpt-5.4",
request_url: &request_url,
attempt: &attempt,
session_affinity_key: None,
};
selector.record_success(&account).await;
let error = selector.select(&request).await.unwrap_err();
assert!(
matches!(error, CredentialSelectionError::CapacityUnavailable { retry_after: Some(duration) } if duration > Duration::from_secs(55) && duration <= Duration::from_secs(60)),
"{error:?}"
);
cooldowns
.clear_scoped(account.id(), &scope, account.revision())
.await
.unwrap();
let selected = selector.select(&request).await.unwrap();
assert_eq!(selected.account_id(), account.id());
}
@@ -112,7 +112,7 @@ async fn mount_warmup(server: &MockServer, expected: u64) {
}
#[tokio::test]
async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart() {
async fn second_precision_progress_waits_five_minutes_and_claim_survives_restart() {
let (store, server, now, reset) = setup().await;
let quota = service(&store, &server);
mount_usage(&server, reset + 604800, 0, 1).await;
@@ -128,13 +128,13 @@ async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart()
);
assert!(server.received_requests().await.unwrap().is_empty());
let account = store.account("acct_bucket_warmup").unwrap();
let mut legacy = store
let mut stored = store
.load_quota_warmup_state(&account)
.await
.unwrap()
.unwrap();
// 升级前的进度以整秒持久化,新读取器仍须沿用该边界与并发领取约束。
legacy.data.get_mut("buckets").unwrap()["codex:604800s"]["reset_at"] = json!(reset);
// 整秒时间戳沿用同一预热边界与并发领取约束
stored.data.get_mut("buckets").unwrap()["codex:604800s"]["reset_at"] = json!(reset);
let observed_at = store
.get_quotas(std::slice::from_ref(account.id()))
.await
@@ -144,9 +144,9 @@ async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart()
store
.compare_and_swap_quota_warmup_state(QuotaWarmupStateUpdate {
account: &account,
expected_version: legacy.version,
expected_version: stored.version,
expected_quota_observed_at: Some(observed_at),
data: legacy.data,
data: stored.data,
})
.await
.unwrap()
@@ -486,13 +486,13 @@ async fn a_new_exhaustion_cannot_reuse_partial_recovery_from_the_previous_failur
}
#[tokio::test]
async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() {
async fn stored_weekly_exhaustion_uses_window_evidence_over_account_reset() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_old_weekly").await;
let account = store.account("acct_old_weekly").expect("account");
create_account(&store, "acct_weekly_reset").await;
let account = store.account("acct_weekly_reset").expect("account");
let observed_at = SystemTime::now();
let mut old = usage((88, SHORT_RESET), (100, WEEK_RESET));
old["rate_limit"]["allowed"] = json!(false);
let mut stored = usage((88, SHORT_RESET), (100, WEEK_RESET));
stored["rate_limit"]["allowed"] = json!(false);
store
.compare_and_swap_quota(gateway_core::account::QuotaObservation {
quota_pause: None,
@@ -501,7 +501,7 @@ async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() {
account_id: account.id().clone(),
expected_revision: account.revision(),
quota: gateway_core::account::OpaqueProviderData::new(
old.as_object().expect("document").clone(),
stored.as_object().expect("document").clone(),
),
observed_at,
state: QuotaState::exhausted(
@@ -511,7 +511,7 @@ async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() {
),
})
.await
.expect("seed old persisted quota");
.expect("seed stored quota");
let server = MockServer::start().await;
let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri());
mount_usage(&server, usage((88, SHORT_RESET), (0, WEEK_RESET + 604_800))).await;
@@ -565,7 +565,7 @@ async fn an_unknown_slot_establishes_a_baseline_before_it_can_recover() {
}
#[tokio::test]
async fn legacy_exhaustion_recovers_after_two_nonfull_observations_despite_reset_drift() {
async fn exhaustion_without_reset_recovers_after_two_nonfull_observations_despite_reset_drift() {
for (first, second) in [(0, 1), (1, 1), (2, 2), (2, 60), (3600, 7200)] {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_drifting_reset";
@@ -579,7 +579,7 @@ async fn legacy_exhaustion_recovers_after_two_nonfull_observations_despite_reset
old["rate_limit"]["allowed"] = json!(true);
mount_usage(&server, old).await;
service.refresh_account(account.id()).await.unwrap();
// 旧版流内拒绝保留最近的用量,但未记录错误 reset,两个窗口都需复核
// 拒绝状态缺少重置时间时,两个窗口都需复核
persist_quota_state(&store, &account, exhausted_quota(None)).await;
for (offset, exhausted) in [(first, true), (second, false)] {
let mut fresh = usage((0, now + 18_000), (16, week + offset));
@@ -0,0 +1,207 @@
//! 验证 Chat 工具别名经实际出站、流式与 JSON 响应保持名称和调用关联
use super::*;
use gateway_core::event::{ProtocolWireEvent, ProviderEvent};
use gateway_protocol::chat_completions::ChatAccumulator;
use sha2::{Digest as _, Sha256};
#[tokio::test]
async fn chat_tool_aliases_preserve_pairing_names_and_account_boundaries() {
let long_id = format!("call_{}", "x".repeat(80));
let mut collision_id = format!("call_{}", hex::encode(Sha256::digest(long_id.as_bytes())));
collision_id.truncate(64);
let long_custom_id = "调用".repeat(40);
let long_name = format!("tool_{}", "x".repeat(80));
let arguments = json!({"tool_name":"mcp.server/tool","call_id":long_id}).to_string();
let schema = json!({"type":"object","properties":{"mcp.server/tool":{"type":"string"}}});
for api_key in [false, true] {
for streaming in [false, true] {
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
if api_key {
store
.seed_api_key(
"acct_provider_contract",
server.uri(),
provider_openai::credential::ResponsesTransport::Http,
)
.await;
} else {
create_account(&store, "acct_provider_contract").await;
}
Mock::given(method("POST"))
.and(path(if api_key { "/responses" } else { "/codex/responses" }))
.respond_with(|request: &wiremock::Request| {
let body = captured_request_body(request);
let output = json!([
{"type":"function_call","id":"fc_new","call_id":"call_new","name":body["tools"][0]["name"],"arguments":"{}","status":"completed"},
{"type":"custom_tool_call","id":"ctc_new","call_id":"custom_new","name":body["tools"][2]["name"],"input":"raw input","status":"completed"}
]);
let mut events = vec![json!({"type":"response.created","response":{"id":"r_tools","model":"gpt-5.4","status":"in_progress"}})];
for (index, item) in output.as_array().unwrap().iter().enumerate() {
events.push(json!({"type":"response.output_item.added","output_index":index,"item":item}));
events.push(json!({"type":"response.output_item.done","output_index":index,"item":item}));
}
events.push(json!({"type":"response.completed","response":{
"id":"r_tools","model":"gpt-5.4","status":"completed","output":output,
"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}
}}));
let sse = events.iter().map(|event| format!("data: {event}\n\n")).collect::<String>();
ResponseTemplate::new(200).set_body_raw(sse, "text/event-stream")
})
.expect(1)
.mount(&server).await;
let body = json!({
"model":"gpt-5.4","stream":streaming,
"tools":[
{"type":"function","function":{"name":"mcp.server/tool","parameters":schema}},
{"type":"function","function":{"name":"mcp_server_tool"}},
{"type":"custom","custom":{"name":"mcp/server/tool"}},
{"type":"function","function":{"name":long_name}}
],
"tool_choice":{"type":"allowed_tools","allowed_tools":{"mode":"auto","tools":[
{"type":"function","function":{"name":"mcp.server/tool"}},
{"type":"custom","custom":{"name":"mcp/server/tool"}}
]}},
"messages":[
{"role":"assistant","tool_calls":[
{"type":"function","id":long_id,"function":{"name":"mcp.server/tool","arguments":arguments}},
{"type":"function","id":collision_id,"function":{"name":"mcp_server_tool","arguments":"{}"}},
{"type":"custom","id":long_custom_id,"custom":{"name":"mcp/server/tool","input":"raw history"}}
]},
{"role":"tool","tool_call_id":long_id,"content":"first"},
{"role":"tool","tool_call_id":collision_id,"content":"second"},
{"role":"tool","tool_call_id":long_custom_id,"content":"third"},
{"role":"tool","name":"mcp.server/tool","namespace":"agent","content":"independent"},
{"role":"user","content":"continue"}
]
});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
.unwrap()
.with_context(Map::from_iter([("use_websocket".into(), json!(false))])),
));
let mut stream = provider_with_base_url(&store, server.uri())
.execute(
planned_request("openai", operation),
context("req_chat_tools", CancellationToken::new()),
)
.await
.unwrap();
let mut accumulator = ChatAccumulator::default();
while let Some(event) = stream.next().await {
let event = event.unwrap();
let terminal = event
.canonical_facts()
.iter()
.any(|fact| matches!(fact, GatewayEvent::Completed(_)));
for event in stream.translate_native_response(event, terminal).unwrap() {
if let Some(wire) = event.wire_event() {
accumulator.push(wire.data()).unwrap();
}
}
}
let result = accumulator.finish().unwrap();
assert_eq!(
result["choices"][0]["message"]["tool_calls"][0]["function"]["name"],
"mcp.server/tool"
);
assert_eq!(
result["choices"][0]["message"]["tool_calls"][1]["custom"]["name"],
"mcp/server/tool"
);
assert_eq!(
result["choices"][0]["message"]["tool_calls"][1]["custom"]["input"],
"raw input"
);
let requests = server.received_requests().await.unwrap();
let sent = captured_request_body(&requests[0]);
assert_eq!(sent["tools"][0]["parameters"], schema);
assert_eq!(sent["input"][0]["arguments"], arguments);
assert_eq!(sent["input"][6]["namespace"], "agent");
assert!(sent["input"][6].get("call_id").is_none());
let ids = [&long_id, &collision_id, &long_custom_id];
let mut distinct_ids = BTreeSet::new();
let mut distinct_names = BTreeSet::new();
for (index, original_id) in ids.into_iter().enumerate() {
let id = sent["input"][index]["call_id"].as_str().unwrap();
assert_eq!(id, sent["input"][index + 3]["call_id"]);
assert!(distinct_ids.insert(id));
let name = sent["tools"][index]["name"].as_str().unwrap();
assert_eq!(name, sent["input"][index]["name"]);
assert!(distinct_names.insert(name));
if api_key || index == 1 {
assert_eq!(id, original_id);
} else {
assert!(id.len() <= 64);
assert_ne!(id, original_id);
}
if !api_key {
assert!(name.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')));
}
}
assert_eq!(sent["input"][6]["name"], sent["tools"][0]["name"]);
assert_eq!(
sent["tool_choice"]["tools"][0]["name"],
sent["tools"][0]["name"]
);
assert_eq!(
sent["tool_choice"]["tools"][1]["name"],
sent["tools"][2]["name"]
);
assert_eq!(sent["tools"][1]["name"], "mcp_server_tool");
assert_eq!(sent["tools"][3]["name"], long_name);
server.verify().await;
}
}
}
#[tokio::test]
async fn complete_json_restores_oauth_tool_names_for_each_chat_delivery() {
for streaming in [false, true] {
let server = MockServer::start().await;
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_provider_contract").await;
let request = json!({"model":"gpt-5.4","stream":streaming,"messages":[{"role":"user","content":"hello"}],
"tools":[{"type":"function","function":{"name":"工具.lookup"}}]});
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("chat_completions", request.as_object().unwrap().clone())
.unwrap(),
));
let mut stream = provider_with_base_url(&store, server.uri())
.execute(
planned_request("openai", operation),
context("req_tool_json", CancellationToken::new()),
)
.await
.unwrap();
let response = json!({"id":"r","object":"response","model":"gpt-5.4","status":"completed",
"output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"___lookup","arguments":"{}"}],
"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}});
let wire =
ProtocolWireEvent::raw_json("openai", serde_json::to_vec(&response).unwrap().into())
.unwrap();
let events = stream
.translate_native_response(ProviderEvent::wire(wire), true)
.unwrap();
let mut accumulator = ChatAccumulator::default();
for wire in events.iter().filter_map(|event| event.wire_event()) {
if let Some(raw) = wire.raw_json_body() {
let result: Value = serde_json::from_slice(raw).unwrap();
assert_eq!(
result["choices"][0]["message"]["tool_calls"][0]["function"]["name"],
"工具.lookup"
);
} else {
accumulator.push(wire.data()).unwrap();
}
}
if streaming {
let result = accumulator.finish().unwrap();
assert_eq!(
result["choices"][0]["message"]["tool_calls"][0]["function"]["name"],
"工具.lookup"
);
}
}
}
@@ -5,6 +5,7 @@ mod account_isolation;
mod cache_preference;
mod capacity;
mod catalog_startup;
mod chat_tools;
mod cookies;
mod correlation;
mod error_details;
@@ -936,17 +937,26 @@ async fn capture_downstream_request(
websocket: bool,
lite: bool,
) -> Value {
capture_downstream_with_country(original, api_key, websocket, lite, None, Default::default())
.await
capture_downstream_with_settings(
original,
api_key,
websocket,
lite,
None,
Default::default(),
None,
)
.await
}
async fn capture_downstream_with_country(
async fn capture_downstream_with_settings(
original: Value,
api_key: bool,
websocket: bool,
lite: bool,
location: Option<gateway_core::account::RequestLocation>,
country: OpenAiRequestCountry,
catalog: Option<Value>,
) -> Value {
let http = MockServer::start().await;
let (base_url, websocket_server) = if websocket {
@@ -1009,7 +1019,12 @@ async fn capture_downstream_with_country(
),
])),
));
let provider = provider_with_base_url(&store, base_url);
let provider = if let Some(catalog) = catalog {
seed_account_catalog(&store, "acct_provider_contract", u8::from(api_key), catalog).await;
provider_with_catalog_and_base_url(&store, base_url).await
} else {
provider_with_base_url(&store, base_url)
};
let mut stream = provider
.execute(
planned_request("openai", operation),
@@ -3203,6 +3218,8 @@ async fn image_prices_should_use_modality_rates_and_precede_delivery() {
(ImageRequestKind::Edit, "gpt-image-2.5-sunburst-2026-09-08"),
(ImageRequestKind::Generation, "gpt-image-2.5-flare"),
(ImageRequestKind::Edit, "gpt-image-2.5-flare-2026-09-08"),
(ImageRequestKind::Generation, "gpt-image-2.6-sunburst"),
(ImageRequestKind::Edit, "gpt-image-2.6-flare"),
] {
let events = image_metering_events(kind, &response, model).await;
let costs = events
@@ -3257,6 +3274,8 @@ async fn image_prices_should_remain_unknown_when_modality_or_model_is_uncertain(
("gpt-image-2.5", valid.clone()),
("gpt-image-2.5-sunburst-future", valid.clone()),
("gpt-image-2.5-flare-future", valid.clone()),
("gpt-image-2.6", valid.clone()),
("gpt-image-2.6-flare-future", valid.clone()),
("gpt-image-2", json!(null)),
(
"gpt-image-2",
@@ -8355,20 +8374,26 @@ async fn completed_response_persists_session_affinity_before_stream_consumer_sto
}
async fn seed_service_tiers(store: &MemoryAccountStore, id: &str, model: &str, tiers: &[&str]) {
use gateway_core::account::AccountCatalogObservation;
let account = store.account(id).unwrap();
let tiers: Vec<_> = tiers
.iter()
.map(|id| json!({"id":id,"name":id,"description":""}))
.collect();
let mut document = vec![0];
serde_json::to_writer(
&mut document,
&json!({"models":[{
seed_account_catalog(
store,
id,
0,
json!({"models":[{
"slug":model, "display_name":model, "service_tiers":tiers,
}]}),
)
.unwrap();
.await;
}
async fn seed_account_catalog(store: &MemoryAccountStore, id: &str, protocol: u8, catalog: Value) {
use gateway_core::account::AccountCatalogObservation;
let account = store.account(id).unwrap();
let mut document = vec![protocol];
serde_json::to_writer(&mut document, &catalog).unwrap();
assert!(
store
.save_account_catalog(
@@ -9371,7 +9396,7 @@ async fn capacity_http_and_websocket_opening_rejections_use_bounded_business_ret
}
#[tokio::test]
async fn request_rejections_should_not_retry_or_cool_down_accounts() {
async fn request_rejections_should_not_retry_or_cool_down_entire_accounts() {
use gateway_core::provider_ports::ProviderCooldownPort as _;
use provider_openai::credential::ResponsesTransport;
for (use_websocket, (code, error_type, expected_kind)) in
@@ -9485,6 +9510,16 @@ async fn request_rejections_should_not_retry_or_cool_down_accounts() {
}
);
assert!(cooldowns.read(account.id()).await.unwrap().is_none());
let scope = gateway_core::provider_ports::ProviderCooldownScope::upstream_model(
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
);
let model_cooldown = cooldowns.read_scoped(account.id(), &scope).await.unwrap();
assert_eq!(model_cooldown.is_some(), code == "turn_rate_limit_exceeded");
if let Some(cooldown) = model_cooldown {
assert_eq!(cooldown.rate_limited_until(), Some(cooldown.until()));
let remaining = cooldown.until().duration_since(SystemTime::now()).unwrap();
assert!(remaining > Duration::from_secs(295) && remaining <= Duration::from_secs(300));
}
}
}
@@ -9907,6 +9942,15 @@ async fn stream_failures_preserve_error_fields_independent_of_retry_classificati
assert!(error.retry_is_prohibited());
assert_eq!(error.retry_after(), Some(Duration::from_secs(7)));
}
if code == "turn_rate_limit_exceeded" {
use gateway_core::provider_ports::{ProviderCooldownPort as _, ProviderCooldownScope};
let account = store.account("acct_provider_contract").unwrap();
let scope = ProviderCooldownScope::upstream_model(gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap());
let cooldown = cooldowns.read_scoped(account.id(), &scope).await.unwrap().expect("model cooldown");
let remaining = cooldown.until().duration_since(SystemTime::now()).unwrap();
assert!(remaining > Duration::from_secs(5) && remaining <= Duration::from_secs(7));
assert!(cooldowns.read(account.id()).await.unwrap().is_none());
}
if expected_kind == ProviderErrorKind::QuotaExhausted {
assert_eq!(store.account("acct_provider_contract").unwrap().quota().access(), QuotaAccessState::Exhausted);
}
@@ -708,6 +708,7 @@ async fn upstream_model_rejection_cools_only_that_model_across_requests_and_tran
.err()
.expect("model cooldown must survive the first request");
assert_eq!(blocked.kind(), ProviderErrorKind::NoEligibleAccount);
assert!(blocked.retry_after().is_none());
assert!(cooldowns.cooldowns.lock().unwrap().is_empty());
server.reset().await;
Mock::given(method("POST"))
@@ -130,13 +130,14 @@ async fn request_country_follows_the_selected_account_across_transports() {
for api_key in [false, true] {
let expected = if api_key { &input } else { &oauth_country };
for websocket in [false, true] {
let sent = capture_downstream_with_country(
let sent = capture_downstream_with_settings(
body.clone(),
api_key,
websocket,
false,
location.cloned(),
policy.clone(),
None,
)
.await;
assert_eq!(
@@ -411,6 +412,59 @@ async fn websocket_messages_preserve_text_and_metadata_despite_unrecognized_json
assert_eq!(&delivered[1..delivered.len() - 1], messages);
}
#[tokio::test]
async fn none_effort_follows_the_selected_models_catalog_on_both_transports() {
for (levels, expected) in [
(&["high", "minimal", "low"][..], "low"),
(&["high", "medium"], "none"),
(&["low", "none"], "none"),
(&[], "none"),
] {
let levels: Vec<_> = levels
.iter()
.map(|effort| json!({"effort": effort}))
.collect();
let catalog = json!({"models":[
{"slug":"client-alias","display_name":"alias","supported_reasoning_levels":[{"effort":"minimal"}]},
{"slug":"gpt-5.4","display_name":"target","supported_reasoning_levels":levels}
]});
let body = json!({
"model":"client-alias", "reasoning":{"effort":"none","summary":"auto"},
"input":[
{"type":"configuration_update","reasoning":{"effort":"none","other":1}},
{"type":"configuration_update","reasoning":{"effort":"high"}},
{"type":"configuration_update","reasoning":{"effort":"none"}},
{"type":"configuration_update","reasoning":{"summary":"auto"}},
{"type":"future","reasoning":{"effort":"none"}}
]
});
let mut expected_input = body["input"].clone();
for index in [0, 2] {
expected_input[index]["reasoning"]["effort"] = json!(expected);
}
for api_key in [false, true] {
for websocket in [false, true] {
let sent = capture_downstream_with_settings(
body.clone(),
api_key,
websocket,
false,
None,
Default::default(),
Some(catalog.clone()),
)
.await;
assert_eq!(sent["model"], "gpt-5.4");
assert_eq!(
sent["reasoning"],
json!({"effort":expected,"summary":"auto"})
);
assert_eq!(sent["input"], expected_input);
}
}
}
}
#[tokio::test]
async fn responses_service_tiers_reach_each_upstream_on_both_transports() {
for tier in [
@@ -222,7 +222,8 @@ async fn privacy_workspace_alias_matches_websocket_opening_and_reused_frames() {
let body: Value = serde_json::from_str(&frame).unwrap();
aliases.push(assert_workspace_alias(&metadata, &body));
let completed = json!({"type":"response.completed","response":{
"id":format!("resp_workspace_{n}"),"model":"gpt-5.4","status":"completed","output":[]
"id":format!("resp_workspace_{n}"),"model":"gpt-5.4","status":"completed",
"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}]
}});
socket
.send(Message::Text(completed.to_string().into()))
@@ -667,7 +668,14 @@ async fn privacy_header_change_isolates_websocket_then_reuses_stable_headers() {
let body: Value = serde_json::from_str(&frame).unwrap();
assert_eq!(body["input"][0]["content"][0]["text"], "hellohello");
cache_keys.push(body["prompt_cache_key"].as_str().unwrap().to_owned());
socket.send(Message::Text(json!({"type":"response.completed","response":{"id":format!("resp_privacy_pool_{}",cache_keys.len()),"model":"gpt-5.4","status":"completed","output":[]}}).to_string().into())).await.unwrap();
let completed = json!({"type":"response.completed","response":{
"id":format!("resp_privacy_pool_{}", cache_keys.len()),"model":"gpt-5.4","status":"completed",
"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}]
}});
socket
.send(Message::Text(completed.to_string().into()))
.await
.unwrap();
}
// 保留第一条连接,确保下一次握手是池隔离的结果而非断线重连
sockets.push(socket);
@@ -112,8 +112,13 @@ async fn search_history_preserves_existing_tools_and_explicit_choices() {
}
#[tokio::test]
async fn search_history_keeps_existing_search_declarations_in_all_supported_locations() {
for kind in ["web_search", "web_search_preview"] {
async fn search_history_preserves_options_and_adapts_known_search_aliases() {
for (kind, codex_kind) in [
("web_search", "web_search"),
("web_search_preview", "web_search"),
("web_search_preview_2025_03_11", "web_search"),
("web_search_preview_future", "web_search_preview_future"),
] {
for location in ["top", "additional_tools", "tool_search_output"] {
let mut original = search_request();
let tool = json!({"type":kind,"external_web_access":true,"search_context_size":"high"});
@@ -127,8 +132,25 @@ async fn search_history_keeps_existing_search_declarations_in_all_supported_loca
}),
);
}
let actual = capture_downstream_request(original.clone(), false, false, true).await;
assert_request_fields(&actual, &original);
original["tool_choice"] =
json!({"type":"allowed_tools","mode":"auto","tools":[{"type":kind}]});
for api_key in [false, true] {
for websocket in [false, true] {
let mut expected = original.clone();
if !api_key {
if location == "top" {
expected["tools"][0]["type"] = codex_kind.into();
} else {
expected["input"][0]["tools"][0]["type"] = codex_kind.into();
}
expected["tool_choice"]["tools"][0]["type"] = codex_kind.into();
}
let actual =
capture_downstream_request(original.clone(), api_key, websocket, true)
.await;
assert_request_fields(&actual, &expected);
}
}
}
}
}
@@ -1688,11 +1688,21 @@ impl ProviderCooldownPort for MemoryCooldownPort {
fn clear_scoped<'a>(
&'a self,
_account_id: &'a ProviderAccountId,
_scope: &'a ProviderCooldownScope,
_through_revision: CredentialRevision,
account_id: &'a ProviderAccountId,
scope: &'a ProviderCooldownScope,
through_revision: CredentialRevision,
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
Box::pin(async { Ok(false) })
Box::pin(async move {
let mut scoped = self.scoped.lock().unwrap();
let key = (account_id.clone(), scope.clone());
if scoped
.get(&key)
.is_some_and(|cooldown| cooldown.credential_revision() > through_revision)
{
return Ok(false);
}
Ok(scoped.remove(&key).is_some())
})
}
fn clear_all<'a>(
@@ -6,15 +6,22 @@ use super::*;
async fn http_history_follows_completed_output_on_its_own_connection() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let tool = json!({"type":"function_call","name":"lookup","call_id":"c","arguments":"{}"});
let message = json!({"type":"message","role":"assistant","content":"ok"});
let tool = json!({"type":"function_call","id":"fc","status":"completed","name":"lookup","call_id":"c","arguments":"{}"});
let message = json!({"type":"message","id":"msg","role":"assistant","content":[{"type":"output_text","text":"ok","annotations":[],"logprobs":[]}]});
let reasoning =
json!({"type":"reasoning","id":"rs","encrypted_content":"ciphertext","summary":[]});
let (frames, mut seen) = tokio::sync::mpsc::unbounded_channel();
let server = tokio::spawn({
let tool = tool.clone();
let message = message.clone();
let mut tool = tool.clone();
tool["metadata"] = json!({"turn_id":"turn"});
tool["internal_chat_message_metadata_passthrough"] = json!({"turn_id":"turn"});
let mut message = message.clone();
message["metadata"] = json!({"turn_id":"turn"});
let mut reasoning = reasoning.clone();
reasoning["content"] = json!([]);
async move {
// 更换会话池键后在另一条连接上从全量重新开始
for turns in [0..6, 6..9] {
for turns in [0..6, 6..16] {
let (socket, _) = listener.accept().await.unwrap();
let mut ws = accept_codex_test_websocket(socket).await;
for turn in turns {
@@ -23,13 +30,18 @@ async fn http_history_follows_completed_output_on_its_own_connection() {
.send(serde_json::from_str::<Value>(&frame).unwrap())
.unwrap();
let output = if turn == 0 {
for event in ["response.output_item.added", "response.output_item.done"] {
let event = json!({"type":event,"item":tool,"output_index":0});
ws.send(Message::Text(event.to_string().into()))
.await
.unwrap();
for (index, item) in [&reasoning, &tool].into_iter().enumerate() {
for event in ["response.output_item.added", "response.output_item.done"]
{
let event = json!({"type":event,"item":item,"output_index":index});
ws.send(Message::Text(event.to_string().into()))
.await
.unwrap();
}
}
json!([])
} else if turn == 14 {
json!([])
} else {
json!([message])
};
@@ -60,24 +72,53 @@ async fn http_history_follows_completed_output_on_its_own_connection() {
.with_websocket_pool(Arc::new(CodexWebSocketPool::default()));
let mut history = vec![json!({"role":"user","content":"start"})];
for turn in 0..9 {
for turn in 0..16 {
let next = json!({"role":"user","content":format!("turn {turn}")});
match turn {
0 => {}
1 => {
history.push(reasoning.clone());
history.push(tool.clone());
history.push(json!({"type":"function_call_output","call_id":"c","output":"found"}));
history.push(json!({"type":"function_call_output","call_id":"c","output":"found",
"internal_chat_message_metadata_passthrough":{"turn_id":"one","executed_tool_calls":[
{"name":"lookup","arguments":{},"tool_result_metadata":{"revision":1}}
]}
}));
}
_ => {
history.push(message.clone());
history.push(next);
let mut replay = message.clone();
match turn {
// 采样输出可带回服务端元数据,正文变化则属于历史分支
9 => replay["metadata"] = json!({"turn_id":"turn"}),
10 => replay["metadata"] = json!({"turn_id":"edited"}),
11 => replay["content"][0]["text"] = json!("edited"),
_ => {}
}
if turn != 15 {
history.push(replay);
}
if turn != 12 {
history.push(next);
}
}
}
if turn == 2 {
history[3]["internal_chat_message_metadata_passthrough"]["turn_id"] = json!("two");
}
if turn == 13 {
history[3]["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]["tool_result_metadata"]
["revision"] = json!(2);
}
if turn == 3 {
history[0]["content"] = json!("edited");
}
let instructions = if turn < 4 { "original" } else { "changed" };
let mut request = codex_request("model", instructions, history.clone());
let mut body = codex_request_body("model", instructions, history.clone());
body.insert("client_extension".into(), json!(turn));
if turn >= 14 {
body.insert("tools".into(), json!([{"type":"function","name":"other"}]));
}
let mut request = CodexResponsesRequest::from_body(body);
request.client_api_key_id = Some(if turn < 5 { "key-a" } else { "key-b" }.into());
request.local_conversation_id = Some(if turn < 6 { "session" } else { "other" }.into());
backend
@@ -85,9 +126,14 @@ async fn http_history_follows_completed_output_on_its_own_connection() {
.await
.unwrap();
let sent = seen.recv().await.unwrap();
if matches!(turn, 1 | 2 | 8) {
if matches!(turn, 1 | 2 | 4 | 8 | 9 | 10 | 12 | 15) {
assert_eq!(sent["previous_response_id"], format!("resp_{}", turn - 1));
assert_eq!(sent["input"], json!([history.last().unwrap()]));
let delta = if turn == 12 {
json!([])
} else {
json!([history.last().unwrap()])
};
assert_eq!(sent["input"], delta, "turn {turn}");
} else {
assert!(sent.get("previous_response_id").is_none(), "turn {turn}");
assert_eq!(sent["input"], json!(history));
@@ -0,0 +1,311 @@
//! 官方历史项回传、业务变更与可信工具结果的多轮出站验证
use super::*;
struct Exchange {
name: String,
input: Vec<Value>,
output: Vec<Value>,
previous: Option<usize>,
expected: Vec<Value>,
request_fields: Map<String, Value>,
}
impl Exchange {
fn full(name: String, input: Vec<Value>, output: Vec<Value>) -> Self {
Self {
name,
expected: input.clone(),
input,
output,
previous: None,
request_fields: Map::new(),
}
}
}
#[tokio::test]
async fn http_history_matches_official_item_replay_and_preserves_business_changes() {
// replay 由固定官方源码的 serde 声明独立生成,不调用网关投影生成预期
let fixture: Value = serde_json::from_str(include_str!("history_items.json")).unwrap();
let mut exchanges = Vec::new();
for case in fixture["cases"].as_array().unwrap() {
let name = case["name"].as_str().unwrap();
let upstream = &case["upstream"];
let replay = &case["replay"];
let is_output = case["output"].as_bool().unwrap();
// 同一基线分别验证等价回传及每个业务字段变化,错误信息直接给出类型和字段
for (field, change) in std::iter::once(("", &Value::Null)).chain(
case["changes"]
.as_object()
.unwrap()
.iter()
.map(|(field, value)| (field.as_str(), value)),
) {
let user = json!({"type":"message","role":"user","content":[{"type":"input_text","text":format!("{name}:{field}")}]});
let next = json!({"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]});
let first = exchanges.len();
let input = if is_output {
vec![user.clone()]
} else {
vec![user.clone(), upstream.clone()]
};
let output = if is_output {
vec![upstream.clone()]
} else {
vec![]
};
exchanges.push(Exchange::full(
format!("{name}:{field}:baseline"),
input,
output,
));
let mut replay = replay.clone();
if !field.is_empty() {
let (parent, key) = field.rsplit_once('/').unwrap();
let target = replay.pointer_mut(parent).unwrap();
if let Some(object) = target.as_object_mut() {
object.insert(key.to_owned(), change.clone());
} else {
target[key.parse::<usize>().unwrap()] = change.clone();
}
}
let input = vec![user, replay, next.clone()];
let expected = if field.is_empty() {
vec![next]
} else {
input.clone()
};
exchanges.push(Exchange {
name: format!("{name}:{field}:replay"),
input,
output: vec![],
previous: field.is_empty().then_some(first),
expected,
request_fields: Map::new(),
});
}
}
assert_exchanges(exchanges).await;
}
#[tokio::test]
async fn http_history_keeps_unknown_items_and_late_tool_results_distinct() {
let result = json!({"type":"function_call_output","call_id":"call","output":"result",
"internal_chat_message_metadata_passthrough":{"turn_id":"one","executed_tool_calls":[
{"name":"lookup","arguments":{"q":1},"tool_result_metadata":{"revision":1}}
]}});
let mut metadata_only = result.clone();
metadata_only["internal_chat_message_metadata_passthrough"]["turn_id"] = json!("two");
metadata_only["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]["tool_result_sources"] =
json!([{"type":"mcp","id":"source"}]);
let mut cases = vec![("analytics", result.clone(), metadata_only, true)];
for (field, value) in [
("tool_result_metadata", json!({"revision":2})),
("tool_result_metadata", Value::Null),
(
"tool_result_metadata",
json!("omitted_due_to_size_limit (overage_bytes=128)"),
),
("name", json!("other")),
("arguments", json!({"q":2})),
] {
let mut changed = result.clone();
changed["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0][field] =
value;
cases.push((field, result.clone(), changed, false));
}
let mut removed = result.clone();
removed["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]
.as_object_mut()
.unwrap()
.shift_remove("tool_result_metadata");
cases.push(("removed_result", result.clone(), removed, false));
let mut reordered = result.clone();
reordered["internal_chat_message_metadata_passthrough"]["executed_tool_calls"]
.as_array_mut()
.unwrap()
.insert(0, json!({"name":"unobserved","arguments":{}}));
cases.push(("call_order", result, reordered, false));
cases.push((
"unknown_item",
json!({"type":"future_item","content":"one"}),
json!({"type":"future_item","content":"two"}),
false,
));
cases.push((
"unknown_metadata",
json!({"type":"future_item","metadata":1}),
json!({"type":"future_item","metadata":2}),
false,
));
cases.push((
"unknown_content",
json!({"type":"message","role":"assistant","content":[{"type":"future_content","data":1}]}),
json!({"type":"message","role":"assistant","content":[{"type":"future_content","data":2}]}),
false,
));
let mut exchanges = Vec::new();
for (index, (name, previous, current, reuse)) in cases.into_iter().enumerate() {
let user = json!({"role":"user","content":format!("case {index}")});
let next = json!({"role":"user","content":"next"});
let first = exchanges.len();
exchanges.push(Exchange::full(
name.to_owned(),
vec![user.clone(), previous],
vec![],
));
let input = vec![user, current, next.clone()];
exchanges.push(Exchange {
name: name.to_owned(),
expected: if reuse { vec![next] } else { input.clone() },
input,
output: vec![],
previous: reuse.then_some(first),
request_fields: Map::new(),
});
}
assert_exchanges(exchanges).await;
}
#[tokio::test]
async fn http_history_compares_codex_properties_and_forwards_per_response_fields() {
// core/src/client.rs::responses_request_properties_mismatch 的全部字段
let baseline = json!({
"model":"model", "tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}],
"tool_choice":"auto", "parallel_tool_calls":true,
"reasoning":{"effort":"high","summary":"auto"}, "store":false,"stream":true,
"include":["reasoning.encrypted_content"], "service_tier":"auto", "prompt_cache_key":"cache",
"prompt_cache_options":{"ttl":"30m"}, "text":{"verbosity":"medium"}
});
let changes = [
("model", json!("other"), false),
("tools", json!([{"type":"function","name":"other"}]), false),
("tool_choice", json!("required"), false),
("parallel_tool_calls", json!(false), false),
("reasoning", json!({"effort":"low","summary":"auto"}), false),
("store", json!(true), false),
("stream", json!(false), false),
("include", json!([]), false),
("service_tier", json!("priority"), false),
("prompt_cache_key", json!("other"), false),
("prompt_cache_options", json!({"ttl":"12h"}), false),
("text", json!({"verbosity":"high"}), false),
("generate", json!(false), false),
("client_metadata", json!({"turn_id":"next"}), true),
(
"stream_options",
json!({"reasoning_summary_delivery":"sequential_cutoff"}),
true,
),
("access_programs", json!({"cyber":"standard"}), true),
("request_country", json!("US"), true),
("instructions", json!("current instructions"), true),
("client_extension", json!({"turn":2}), true),
];
let mut exchanges = Vec::new();
for (field, value, reuse) in changes {
let user = json!({"role":"user","content":field});
let next = json!({"role":"user","content":"next"});
let first = exchanges.len();
let mut initial = Exchange::full(field.to_owned(), vec![user.clone()], vec![]);
initial.request_fields = baseline.as_object().unwrap().clone();
exchanges.push(initial);
let input = vec![user, next.clone()];
let mut request_fields = baseline.as_object().unwrap().clone();
request_fields.insert(field.to_owned(), value);
exchanges.push(Exchange {
name: field.to_owned(),
expected: if reuse { vec![next] } else { input.clone() },
input,
output: vec![],
previous: reuse.then_some(first),
request_fields,
});
}
assert_exchanges(exchanges).await;
}
async fn assert_exchanges(exchanges: Vec<Exchange>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let outputs: Vec<_> = exchanges
.iter()
.map(|exchange| exchange.output.clone())
.collect();
let (frames, mut seen) = tokio::sync::mpsc::unbounded_channel();
let server = tokio::spawn(async move {
let (socket, _) = listener.accept().await.unwrap();
let mut ws = accept_codex_test_websocket(socket).await;
for (turn, output) in outputs.into_iter().enumerate() {
let frame = ws.next().await.unwrap().unwrap().into_text().unwrap();
frames
.send(serde_json::from_str::<Value>(&frame).unwrap())
.unwrap();
for (index, item) in output.iter().enumerate() {
for event in ["response.output_item.added", "response.output_item.done"] {
ws.send(Message::Text(
json!({"type":event,"output_index":index,"item":item})
.to_string()
.into(),
))
.await
.unwrap();
}
}
// 分别覆盖只提供流式完成项和终态同时携带完整 output 的上游
let output = if turn % 4 == 0 { output } else { vec![] };
ws.send(Message::Text(json!({"type":"response.completed","response":{"id":format!("resp_{turn}"),"output":output}}).to_string().into())).await.unwrap();
}
});
let backend = CodexBackendClient::new(
reqwest::Client::builder().no_proxy().build().unwrap(),
format!("http://{addr}"),
test_wire_profile(),
)
.with_websocket_pool(Arc::new(CodexWebSocketPool::default()));
for exchange in exchanges {
let mut body = codex_request_body("model", "instructions", exchange.input);
body.extend(exchange.request_fields.clone());
let mut request = CodexResponsesRequest::from_body(body);
request.client_api_key_id = Some("key".into());
request.local_conversation_id = Some("session".into());
timeout(
Duration::from_secs(10),
backend.create_response(&request, request_context("req", Some("acct"))),
)
.await
.unwrap()
.unwrap();
let sent = seen.recv().await.unwrap();
assert_eq!(
sent.get("previous_response_id"),
exchange
.previous
.map(|turn| json!(format!("resp_{turn}")))
.as_ref(),
"{}",
exchange.name
);
assert_eq!(sent["input"], json!(exchange.expected), "{}", exchange.name);
for (field, value) in exchange.request_fields {
let mut actual = sent[&field].clone();
if field == "client_metadata" {
// 每轮出站补入请求时间戳,客户端提供的其余字段仍须原样保留
actual
.as_object_mut()
.unwrap()
.remove("x-codex-ws-stream-request-start-ms")
.expect("upstream request timestamp");
}
// 非流式客户端由网关聚合,WS 上游始终流式;客户端 stream 变化仍须使本轮完整重放
let expected = if field == "stream" {
Value::Bool(true)
} else {
value
};
assert_eq!(actual, expected, "{}:{field}", exchange.name);
}
}
server.await.unwrap();
}
@@ -0,0 +1,818 @@
{
"source": "openai/codex rust-v0.174.0 (2d42293d1d32079068f1e4ed8aa70fdbf146ec01), protocol/src/models.rs serde wire replay; internal analytics removed; host tool results tested separately",
"cases": [
{
"changes": {
"/content/0/annotations": [
{
"url": "https://example.com"
}
],
"/content/0/logprobs": [
{
"logprob": -1,
"token": "hello"
}
],
"/content/0/text": "changed",
"/id": "other",
"/phase": "final_answer",
"/status": "incomplete"
},
"name": "message",
"output": true,
"replay": {
"content": [
{
"annotations": [],
"logprobs": [],
"text": "hello",
"type": "output_text"
}
],
"id": "msg",
"phase": "commentary",
"role": "assistant",
"status": "completed",
"type": "message"
},
"upstream": {
"content": [
{
"annotations": [],
"logprobs": [],
"text": "hello",
"type": "output_text"
}
],
"encrypted_content": null,
"id": "msg",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"phase": "commentary",
"role": "assistant",
"status": "completed",
"type": "message"
}
},
{
"changes": {
"/encrypted_content": "different",
"/summary/0/text": "changed"
},
"name": "reasoning_empty_content",
"output": true,
"replay": {
"encrypted_content": "cipher",
"id": "rs",
"summary": [
{
"text": "thinking",
"type": "summary_text"
}
],
"type": "reasoning"
},
"upstream": {
"content": [],
"encrypted_content": "cipher",
"id": "rs",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"summary": [
{
"text": "thinking",
"type": "summary_text"
}
],
"type": "reasoning"
}
},
{
"changes": {
"/content/0/text": "changed",
"/content/1/text": "changed"
},
"name": "reasoning_content",
"output": true,
"replay": {
"content": [
{
"text": "first",
"type": "reasoning_text"
},
{
"text": "second",
"type": "text"
}
],
"encrypted_content": null,
"id": "rs",
"summary": [],
"type": "reasoning"
},
"upstream": {
"content": [
{
"text": "first",
"type": "reasoning_text"
},
{
"text": "second",
"type": "text"
}
],
"id": "rs",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"summary": [],
"type": "reasoning"
}
},
{
"changes": {
"/arguments": "{\"q\":1}",
"/call_id": "other",
"/encrypted_function_args": [
"cipher"
],
"/name": "other",
"/namespace": "namespace"
},
"name": "function_call",
"output": true,
"replay": {
"arguments": "{}",
"call_id": "call",
"id": "fc",
"name": "lookup",
"status": "completed",
"type": "function_call"
},
"upstream": {
"arguments": "{}",
"call_id": "call",
"encrypted_content": null,
"encrypted_function_args": null,
"id": "fc",
"internal_chat_message_metadata_passthrough": {
"executed_tool_calls": [
{
"arguments": {},
"name": "lookup",
"tool_result_metadata": {
"untrusted_server_value": 1
}
}
],
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"name": "lookup",
"namespace": null,
"status": "completed",
"type": "function_call"
}
},
{
"changes": {
"/call_id": "other",
"/input": "echo changed",
"/name": "other",
"/namespace": "namespace"
},
"name": "custom_tool_call",
"output": true,
"replay": {
"call_id": "call",
"id": "ct",
"input": "echo test",
"name": "exec",
"status": "completed",
"type": "custom_tool_call"
},
"upstream": {
"call_id": "call",
"encrypted_content": null,
"id": "ct",
"input": "echo test",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"name": "exec",
"namespace": null,
"status": "completed",
"type": "custom_tool_call"
}
},
{
"changes": {
"/action/queries": [
"other"
],
"/action/query": "changed",
"/id": "changed"
},
"name": "web_search_search",
"output": true,
"replay": {
"action": {
"query": "test",
"type": "search"
},
"id": "ws",
"status": "completed",
"type": "web_search_call"
},
"upstream": {
"action": {
"queries": null,
"query": "test",
"type": "search"
},
"encrypted_content": null,
"id": "ws",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"status": "completed",
"type": "web_search_call"
}
},
{
"changes": {
"/action/url": "https://example.org"
},
"name": "web_search_open_page",
"output": true,
"replay": {
"action": {
"type": "open_page",
"url": "https://example.com"
},
"id": "ws",
"status": "completed",
"type": "web_search_call"
},
"upstream": {
"action": {
"type": "open_page",
"url": "https://example.com"
},
"id": "ws",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"status": "completed",
"type": "web_search_call"
}
},
{
"changes": {
"/action/pattern": "other",
"/action/url": "https://example.org"
},
"name": "web_search_find",
"output": true,
"replay": {
"action": {
"pattern": "test",
"type": "find_in_page",
"url": "https://example.com"
},
"id": "ws",
"status": "completed",
"type": "web_search_call"
},
"upstream": {
"action": {
"pattern": "test",
"type": "find_in_page",
"url": "https://example.com"
},
"id": "ws",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"status": "completed",
"type": "web_search_call"
}
},
{
"changes": {
"/action/command": [
"echo",
"changed"
],
"/action/env": {
"X": "one"
},
"/action/timeout_ms": 5,
"/action/user": "example",
"/action/working_directory": "/example"
},
"name": "local_shell_call",
"output": true,
"replay": {
"action": {
"command": [
"echo",
"test"
],
"env": null,
"timeout_ms": null,
"type": "exec",
"user": null,
"working_directory": null
},
"call_id": null,
"id": "shell",
"status": "completed",
"type": "local_shell_call"
},
"upstream": {
"action": {
"command": [
"echo",
"test"
],
"type": "exec"
},
"id": "shell",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"status": "completed",
"type": "local_shell_call"
}
},
{
"changes": {
"/arguments/query": "changed",
"/call_id": "other",
"/execution": "client"
},
"name": "tool_search_call",
"output": true,
"replay": {
"arguments": {
"query": "test"
},
"call_id": null,
"execution": "server",
"id": "ts",
"status": "completed",
"type": "tool_search_call"
},
"upstream": {
"arguments": {
"query": "test"
},
"execution": "server",
"id": "ts",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"status": "completed",
"type": "tool_search_call"
}
},
{
"changes": {
"/result": "different",
"/revised_prompt": "changed"
},
"name": "image_generation_call",
"output": true,
"replay": {
"id": "ig",
"result": "image-data",
"status": "completed",
"type": "image_generation_call"
},
"upstream": {
"encrypted_content": null,
"id": "ig",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"result": "image-data",
"revised_prompt": null,
"status": "completed",
"type": "image_generation_call"
}
},
{
"changes": {
"/encrypted_content": "cipher"
},
"name": "context_compaction",
"output": true,
"replay": {
"id": "ctx",
"type": "context_compaction"
},
"upstream": {
"encrypted_content": null,
"id": "ctx",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"metadata": {
"turn_id": "sampled-turn"
},
"type": "context_compaction"
}
},
{
"changes": {
"/tools/0/name": "other",
"/tools/0/parameters": {
"type": "string"
}
},
"name": "additional_tools",
"output": false,
"replay": {
"role": "developer",
"tools": [
{
"name": "test",
"parameters": {
"type": "object"
},
"type": "function"
}
],
"type": "additional_tools"
},
"upstream": {
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"role": "developer",
"tools": [
{
"name": "test",
"parameters": {
"type": "object"
},
"type": "function"
}
],
"type": "additional_tools"
}
},
{
"changes": {
"/author": "other",
"/content/0/text": "changed",
"/content/1/encrypted_content": "changed",
"/recipient": "other"
},
"name": "agent_message",
"output": false,
"replay": {
"author": "worker",
"content": [
{
"text": "hello",
"type": "input_text"
},
{
"encrypted_content": "cipher",
"type": "encrypted_content"
}
],
"recipient": "parent",
"type": "agent_message"
},
"upstream": {
"author": "worker",
"content": [
{
"text": "hello",
"type": "input_text"
},
{
"encrypted_content": "cipher",
"type": "encrypted_content"
}
],
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"recipient": "parent",
"type": "agent_message"
}
},
{
"changes": {
"/call_id": "other",
"/name": "other",
"/namespace": "other",
"/output": "changed"
},
"name": "function_call_output_text",
"output": false,
"replay": {
"call_id": "call",
"output": "result",
"type": "function_call_output"
},
"upstream": {
"call_id": "call",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"name": null,
"namespace": null,
"output": "result",
"type": "function_call_output"
}
},
{
"changes": {
"/output/0/text": "changed",
"/output/1/detail": "high",
"/output/1/image_url": "different",
"/output/2/file_id": "other",
"/output/3/audio_url": "other",
"/output/4/file_id": "other",
"/output/5/encrypted_content": "other"
},
"name": "function_call_output_content",
"output": false,
"replay": {
"call_id": "call",
"output": [
{
"text": "result",
"type": "input_text"
},
{
"image_url": "data:image/png;base64,dGVzdA==",
"type": "input_image"
},
{
"detail": "original",
"file_id": "image-file",
"type": "input_image"
},
{
"audio_url": "data:audio/wav;base64,dGVzdA==",
"type": "input_audio"
},
{
"file_id": "audio-file",
"type": "input_audio"
},
{
"encrypted_content": "cipher",
"type": "encrypted_content"
}
],
"type": "function_call_output"
},
"upstream": {
"call_id": "call",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"output": [
{
"text": "result",
"type": "input_text"
},
{
"detail": null,
"image_url": "data:image/png;base64,dGVzdA==",
"type": "input_image"
},
{
"detail": "original",
"file_id": "image-file",
"type": "input_image"
},
{
"audio_url": "data:audio/wav;base64,dGVzdA==",
"type": "input_audio"
},
{
"file_id": "audio-file",
"type": "input_audio"
},
{
"encrypted_content": "cipher",
"type": "encrypted_content"
}
],
"type": "function_call_output"
}
},
{
"changes": {
"/call_id": "other",
"/name": "other",
"/output": "changed"
},
"name": "custom_tool_call_output",
"output": false,
"replay": {
"call_id": "call",
"output": "result",
"type": "custom_tool_call_output"
},
"upstream": {
"call_id": "call",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"name": null,
"output": "result",
"type": "custom_tool_call_output"
}
},
{
"changes": {
"/call_id": "other",
"/execution": "client",
"/status": "in_progress",
"/tools/0/name": "other"
},
"name": "tool_search_output",
"output": false,
"replay": {
"call_id": "call",
"execution": "server",
"status": "completed",
"tools": [
{
"name": "test",
"type": "function"
}
],
"type": "tool_search_output"
},
"upstream": {
"call_id": "call",
"execution": "server",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"status": "completed",
"tools": [
{
"name": "test",
"type": "function"
}
],
"type": "tool_search_output"
}
},
{
"changes": {
"/encrypted_content": "changed"
},
"name": "compaction_alias",
"output": false,
"replay": {
"encrypted_content": "cipher",
"id": "compact",
"type": "compaction"
},
"upstream": {
"encrypted_content": "cipher",
"id": "compact",
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"type": "compaction_summary"
}
},
{
"changes": {
"/reasoning/effort": "low"
},
"name": "configuration_update",
"output": false,
"replay": {
"reasoning": {
"effort": "high"
},
"type": "configuration_update"
},
"upstream": {
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"reasoning": {
"effort": "high"
},
"type": "configuration_update"
}
},
{
"changes": {
"/type": "context_compaction"
},
"name": "compaction_trigger",
"output": false,
"replay": {
"type": "compaction_trigger"
},
"upstream": {
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"type": "compaction_trigger"
}
},
{
"changes": {
"/content/0/text": "other",
"/content/1/detail": "low",
"/content/1/file_id": "other",
"/content/2/audio_url": "other"
},
"name": "message_multimodal",
"output": false,
"replay": {
"content": [
{
"text": "test",
"type": "input_text"
},
{
"detail": "high",
"file_id": "image-file",
"type": "input_image"
},
{
"audio_url": "audio-data",
"type": "input_audio"
}
],
"role": "user",
"type": "message"
},
"upstream": {
"content": [
{
"text": "test",
"type": "input_text"
},
{
"detail": "high",
"file_id": "image-file",
"type": "input_image"
},
{
"audio_url": "audio-data",
"type": "input_audio"
}
],
"internal_chat_message_metadata_passthrough": {
"turn_id": "old-turn"
},
"role": "user",
"type": "message"
}
}
]
}
@@ -11,6 +11,7 @@ mod cleanup;
mod continuation;
mod diagnostics;
mod fingerprint;
mod history;
mod metadata;
mod pool;
@@ -261,7 +261,7 @@ async fn xai_admin_provider_validates_known_billing_breakdown() {
}
#[tokio::test]
async fn xai_legacy_billing_should_not_infer_long_context_flag() {
async fn xai_billing_reconstruction_does_not_infer_long_context_flag() {
let bundle = provider_xai::initialize(provider_ports())
.await
.expect("xAI bundle");
@@ -279,7 +279,7 @@ async fn xai_legacy_billing_should_not_infer_long_context_flag() {
amount: "0.8".parse().expect("stored total"),
},
})
.expect("legacy billing")
.expect("reconstructed billing")
.expect("matching billing breakdown");
assert_eq!(billing.total_amount.amount.as_str(), "0.8");
+15 -8
View File
@@ -32,20 +32,27 @@ sha256sum --check --strict .frozen-sha256
## 本地测试库
`gateway-store` 的 PostgreSQL/Redis 集成测试使用以下环境变量;所需测试服务未配置时,本地相关测试跳过,CI 直接失败:
为集成测试准备专用 PostgreSQL 与 Redis 实例,服务启动方式见[开发指南](../../docs/development.md#启动宿主)。测试会创建随机 schema、Redis key 和临时认证用户,不能连接生产实例
- PostgreSQL 测试用户需要创建、删除 schema 和角色的权限
- Redis 测试用户需要读写测试键、执行脚本及创建、删除 ACL 用户的权限
- 备份恢复测试需要在测试进程的 `PATH` 中提供与 PostgreSQL 服务端版本匹配的 `pg_dump` 和 `psql`
在运行测试的终端设置连接信息,两条 URL 都须包含符合 [Store 密码要求](../../deploy/README.md#手动安装)的密码。测试凭据可使用 `openssl rand -hex 24` 生成的十六进制值,避免 URL 转义
```bash
export CPR_TEST_DATABASE_URL='postgres://<user>:<password>@127.0.0.1:5432/<db>'
export CPR_TEST_REDIS_URL='redis://:<password>@127.0.0.1:6379'
unset CPR_DATABASE_URL CPR_REDIS_URL CPR_DATABASE_PASSWORD CPR_REDIS_PASSWORD
```
插件 Runtime 的真实子进程与持久化测试可使用专用的 `CPR_PLUGIN_TEST_DATABASE_URL`,此时须同时设置 `CPR_PLUGIN_TEST_REDIS_URL`。省略插件数据库 URL 时使用上面的测试服务
将占位值替换为测试服务的实际用户、密码和数据库名。测试 URL 携带密码;部署配置仍将 URL 与密码分开,清除上述部署环境变量可避免它们覆盖测试配置
使用专用开发或测试实例,测试通过随机 schema 和 Redis key 前缀隔离数据。凭据取自部署配置或 CI Secret,不要分享未脱敏的 `docker inspect` 输出
插件 Runtime 的真实子进程与持久化测试默认复用这组服务。需要单独实例时,同时设置 `CPR_PLUGIN_TEST_DATABASE_URL` 与 `CPR_PLUGIN_TEST_REDIS_URL`,密码要求相同
PostgreSQL 的临时 schema 测试连接使用异步提交,保留事务可见性、回滚和完整迁移检查
需要验证数据库崩溃后的持久性时,使用独立数据库与生产连接配置,不复用这类 fixture
按[后端验证命令](../../docs/architecture.md#验证命令)运行测试。Store 用例在所需 URL 缺失时本地提前返回;插件 Runtime 用例在两组数据库 URL 均未设置时本地提前返回,选定数据库后缺少对应 Redis URL 会失败。CI 要求配置测试服务
运行包含 `StoreBundle` 初始化的完整集成测试时,两条测试 URL 都须包含密码,原始密码须满足
[Store 密码要求](../../deploy/README.md#手动安装),在测试 URL 中按 URL 规则编码。
在测试进程中清除 `CPR_DATABASE_URL`、`CPR_REDIS_URL`、`CPR_DATABASE_PASSWORD` 和 `CPR_REDIS_PASSWORD`,避免部署环境覆盖测试配置
提前返回的用例可能仍显示通过,不能据此认定 PostgreSQL / Redis 行为已验证。URL 已设置但连接失败时,用例会失败,不按未配置处理
Store 的 PostgreSQL 临时 schema 夹具执行完整迁移集,并为这些测试连接设置异步提交,验证现行读写、事务可见性与回滚。
验证数据库崩溃后的持久性须使用独立数据库与生产连接配置,不复用这类夹具
+66 -30
View File
@@ -276,7 +276,9 @@ CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保
Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文在 `systemInstruction.parts` 前添加画像提示词。普通 Chat 转换只发送调用方系统指令及其配置的改写结果。网关移除 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。系统指令也接受 `system_instruction`,两者同时提供时以 `systemInstruction` 为准,出站统一使用驼峰名称。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建
Claude 原生生成兼容缺失工具 ID 的历史:仅在相邻 `model`/`user` 轮次中,调用和结果的工具名各自唯一时补齐缺失的 `id`。一侧已有 ID 时沿用该 ID;两侧均缺失时生成确定性配对 ID,并避开正文已有 ID。已有字段、参数、结果和思考签名保持原样;同名并行调用、孤立结果、ID 冲突或格式错误不猜测配对,继续由上游校验。该兼容不作用于 Gemini、Chat 转换、独立搜索或输入计数
Claude 原生生成在相邻 `model`/`user` 轮次中补齐缺失的工具 `id`,按工具名配对。同名调用和结果各只有一个时,一侧已有 ID 就沿用,两侧均缺失时生成确定性配对 ID。同名并行调用要求调用与结果数量一致、两侧全部缺失 ID,按各自的出现顺序配对,遵循 [GenAI 并行函数调用规则](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/tools/function-calling#parallel_function_calling)
生成的 ID 避开正文已有 ID,工具参数、结果、思考签名及已有字段保留原始表达。同名并行历史混有 ID、数量不匹配、孤立结果、ID 冲突或格式错误时保留原样,由上游校验。该兼容只适用于 Claude 原生生成
原生响应的思考签名保持上游原值,不添加网关标记。Claude/Gemini 生成根据已知原生封套识别来源,只移除可识别的异家族签名及对应思考内容,保留普通文本、工具调用和结果。导入 Gemini 的工具历史中,各轮首个工具调用缺少签名时使用官方 `skip_thought_signature_validator` 占位
@@ -336,9 +338,9 @@ print(completion.choices[0].message.content)
| `file` 内容块 | `file.file_id`、`file.file_data`、`file.file_url` 至少提供一种,保留可选 `filename`;URL 和非 PDF 文件为网关的 Responses 扩展,实际支持由上游判断 |
| `input_audio` 内容块 | Chat 的 `data` 和 `format` 转为 Responses `audio_url` data URL;原生音频引用与 `input_text`、`input_image`、`input_file` 内容块也可携带 |
| `messages[].refusal`、assistant 的 `refusal` 内容块 | 保留 assistant 拒绝历史,各角色消息的 `refusal: ""` 按缺省处理 |
| `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果,保留 ID、参数或输入字符串。空调用列表按缺省处理。tool 必须携带调用 ID 和结果,其他角色忽略空 ID。custom 结果须携带前序调用历史 |
| `messages[].name` | Responses 将 tool 消息的非空字符串名称随结果携带。Messages 和 GenAI 通过调用 ID 匹配历史。其他角色的名称作为辅助信息忽略 |
| `tools` | 展开 function/custom 定义,保留 schema、format 及原生工具对象。function 的 `parameters: null` 按省略处理,`strict` 省略或为 `null` 时使用 `false` |
| `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果,保留 ID、参数或输入字符串。空调用列表按缺省处理。tool 必须携带结果;Responses 目标允许调用 ID 缺省或为 `null` 的独立工具输出,此时必须提供非空 `name`,不推断配对或丢弃内容。显式空 ID 仍返回 `400`,其他角色忽略空 ID。custom 结果须携带前序调用历史 |
| `messages[].name`、`messages[].namespace` | Responses 将 tool 消息的非空字符串名称和命名空间随结果携带。Messages 和 GenAI 仍要求调用 ID 并匹配历史,不支持无 ID 的独立输出。其他角色的名称和命名空间作为辅助信息忽略 |
| `tools` | 展开 function/custom 定义,保留 schema 及原生工具对象。custom 的 `format.grammar` 展开为 Responses 的 `format.syntax` 和 `format.definition`。function 的 `parameters: null` 按省略处理,`strict` 省略或为 `null` 时使用 `false` |
| `tool_choice`、`parallel_tool_calls` | 展开指定 function/custom 和 `allowed_tools` 选择;原生选择与并行布尔值交给上游 |
| `web_search_options` | `{}` 即要求上游执行 `web_search`;支持 `search_context_size` 与 `user_location.approximate` |
| `response_format` | 非 `null` 时优先于 `text.format`,保留 JSON Schema;未知格式交给 Responses 上游 |
@@ -355,6 +357,11 @@ print(completion.choices[0].message.content)
`seed`、`frequency_penalty`、`presence_penalty`、`logit_bias` 和 `prediction` 没有对应的 Responses 控制语义,接受后忽略,不保证生效。
消息的 `reasoning_content` 和 `reasoning` 作为辅助历史忽略,不转为用户正文
Chat 发往 Codex/OAuth 时,包含 `[A-Za-z0-9_-]` 以外字符的工具名称转换为无冲突别名,
工具声明、选择和历史使用同一映射,JSON 与 SSE 响应还原客户端名称。
历史调用 ID 超过 64 字符时,调用和对应结果使用同一短 ID;名称与 ID 映射仅限当前请求,
工具参数和结果正文保持原值
`n`、`store`、`background`、`modalities` 和 `functions` 可省略或为 `null`。非空值仅接受 `n: 1`、`store: false`、`background: false`、`modalities: ["text"]` 和 `functions: []`。
网关拒绝 `function_call`、`function` 消息角色、音频输出和无法映射的内容类型。
入口不接收 `input`、`previous_response_id` 或 `conversation`;需要服务端续接时使用 `/v1/responses`
@@ -605,6 +612,8 @@ WS 握手的轮次元数据头只随首次请求转发,后续帧在正文中
不删除工具参数 schema、输入内容或 `client_metadata` 内的同名业务字段;其他未知字段继续透传。
`prompt_cache_key` 不用于补造会话或线程请求头;客户端未提供缓存键、会话或线程身份时保持缺省
顶层和 `input` 中每条 `configuration_update` 的 `reasoning.effort` 显式为 `"none"` 时,仅当所选账号的上游模型目录列出 `low` 且未列出 `none` 时,网关才将该值改为 `"low"`。其他情况保留原值
发往 Codex/OAuth 的 Responses 请求另按下表处理;API Key 上游保留这些字段。规则只匹配表中列出的位置
| 请求字段 | Codex/OAuth 出站行为 |
@@ -612,6 +621,7 @@ WS 握手的轮次元数据头只随首次请求转发,后续帧在正文中
| `top_p`、`frequency_penalty`、`presence_penalty`、`chat_template_kwargs`、`user`、`metadata`、`safety_identifier` | 省略;采样参数取默认值时也省略 |
| `stream_options.include_usage` | 省略该成员,保留其他流式选项 |
| `truncation`、`stop_sequences`、`prompt_cache_options` | 分别仅在值为 `"disabled"`、`[]`、`{}` 时省略;显式策略交给上游校验 |
| 搜索工具声明与 `tool_choice` | `web_search_preview`、`web_search_preview_2025_03_11` 映射为 `web_search`,保留搜索选项;同样适用于 `additional_tools`、`tool_search_output` 和 `allowed_tools` 中的声明 |
选定 Codex/OAuth 上游后,HTTP 和 WebSocket 按相同规则处理 `input` 中的回放条目,适用于所有 User-Agent。API Key 上游保留这些历史字段
@@ -669,7 +679,7 @@ Responses WebSocket 接受文本消息,`response.create` 在同一连接串行
| WS → SSE | 通常保留下游 WS。需要完整重放的 OpenAI 大包回退按下述规则重连 |
| WS → WS | 保留当前绑定的上游 WS,支持下一轮续接 |
Codex OAuth 的 SSE 客户端可以每轮提交完整历史。网关先执行隐私规则,再用处理后的内容匹配历史。复用同一上游 WS 时,若同一 Client Key 的请求配置和历史前缀匹配上一轮已完成的输入、输出,网关使用 `previous_response_id` 和新增输入续接。换连接或历史不匹配时发送本次完整输入。此优化用于 `store=false` 的生成请求;显式续接和出站插件接管的帧沿用各自的传输合同
Codex OAuth 的 SSE 客户端可以每轮提交完整历史。网关先执行隐私规则,再用处理后的内容匹配历史。复用同一上游 WS 时,若同一 Client Key 的模型、工具、推理等 Codex 续接配置相同,且历史前缀匹配上一轮已完成的输入、输出,网关使用 `previous_response_id` 和剩余输入续接。剩余输入可以为空,每轮元数据及额外的请求属性随本轮转发。换连接或历史不匹配时发送本次完整输入。此优化用于 `store=false` 的生成请求;显式续接和出站插件接管的帧沿用各自的传输合同
活跃客户端 WS 的绑定不受普通空闲回收期限约束;上游 Close(不限关闭码)、EOF、传输读写失败、总寿命到期或连接被回收仍可能使连接内续接失效,
网关在收到绑定上游的失效通知且下游空闲时,以关闭码 1000 要求客户端重连并发送完整输入。
@@ -872,8 +882,10 @@ HTTP 瞬时建连失败(含 TLS 握手 EOF),或 WebSocket 新请求在发
再次失败刷新有效期,成功结束后解除限制。其他重试策略不受影响,缺少有效身份、状态过期或状态存储不可用时沿用原策略。
这是一项轮次重试预算控制,不是客户端重试意图的精确检测;状态与交付顺序见[数据面请求生命周期](architecture.md#4-数据面请求生命周期)
`turn_rate_limit_exceeded` 保留原始错误和 `Retry-After`,由客户端按自身重试预算等待。
代理不因此写入账号冷却、换号或透明重试,其他会话仍可使用该账号
OpenAI 原生链路的 `turn_rate_limit_exceeded` 按账号与上游模型记录临时冷却,期限采用 `Retry-After`,缺失时使用 60 秒。
新请求选号避开受限组合,其他模型和已在输出的请求不受影响;并发请求的成功反馈不会提前清除此冷却。
已有会话沿用亲和、固定归属与排队策略:允许重选时可换号,后代线程跟随主会话等待,固定账号的普通冷却请求返回剩余等待时间。
本次错误保留原始错误和 `Retry-After`,不因记录冷却而透明重放,由客户端按自身重试预算等待
`/v1/responses` 流式请求尚未发出数据或心跳时,若上游 WS `error` 明确返回 400,
且网关判定为普通请求参数错误,客户端收到 HTTP 400 和原始 `error` 对象。
@@ -1266,7 +1278,7 @@ call 与账号的绑定保存在网关进程内,未连接时一小时过期;
| `GET` | `/api/key-usage/overview` | `period?`、`asOf?` 或 `startTime?`、`endTime?`,另含 `model?` | 用量汇总、趋势、当前额度和锚点所在日期的健康时间线 |
| `GET` | `/api/key-usage/records` | 同上,另含 `kind?`、`currentPage?`、`pageSize?` | 当前 Key 的请求记录 |
| `GET` | `/api/key-usage/config` | 无 | 当前 Key 的客户端配置凭据 |
| `GET` | `/api/key-usage/version` | 无 | “关于”弹窗使用的当前版本号和提交号 |
| `GET` | `/api/key-usage/version` | 无 | 当前版本号和提交号 |
用量查询支持[页面时间合同](#页面时间合同),默认 `period=7d`,一次最多 31 天。模型按字面量包含匹配,区分大小写,通配符按普通字符处理
不接受 Key ID、账号、Provider 等范围参数或其他未知字段。页码默认 1,每页默认 20,允许 1–100 条;
@@ -1371,6 +1383,10 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
未要求探测时,该字段表示冷却结束时间。`protectionRules` 返回触发时的规则快照 `[{ id, name }]`,
没有保护原因时为空数组,修改或删除当前规则不改写此快照。错误保护与上游限流独立恢复,解除保护不保证其他限制已经解除
`quota.modelRateLimits` 只列出有效的模型限流,每项包含上游 `model`、RFC 3339 格式的 `until` 和按部署时区格式化的 `untilDisplay`。
存在模型限流时,账号列表、状态筛选和统计归入 `rate_limited`,停用、凭据错误和额度耗尽仍优先显示;仅模型受限时整账号的 `rateLimitedUntil` 与 `rateLimitReason` 保持 `null`。
管理端状态详情展示受限模型、剩余秒数与恢复时间,到期回读列表。模型不受支持时不显示限流;该汇总状态不阻断其他模型
OpenAI OAuth 账号的 `capabilities.quotaSettingsSupported` 为真。通过 `POST /api/admin/accounts/batch-update`
提交 `{"accountIds":["acct_1"],"quotaSettings":{"codex:18000s":{"limitPercent":99,"warmup":null},"codex:604800s":{"limitPercent":95,"warmup":{"model":"gpt-5.5"}}}}`。
键取自该账号 `quota.windows` 中 `accountWide: true` 的窗口 `key`,这里只配置通用额度桶。
@@ -1496,11 +1512,7 @@ Key 预算及其访问状态随互联默认公开,不要求开启 `shareQuota`
最多 256 项,每个 ID 最多 256 字节;重复 ID 去重,不接受空白、控制字符、`__` 前缀或 `*` 通配符。
允许保存当前上游目录尚未返回的 ID。限制按全局模型映射后的上游 ID 判断,不扩大账号本身的上游权限。
管理端刷新目录只更新目录,不修改模型限制。全选与取消全选只作用于上游目录中符合当前搜索条件的模型。
账号和分组白名单均可一键勾选 `gpt-image-2` 和 `gpt-image-1.5`。
自定义模型取消勾选后在本次编辑期间保留,可再次勾选。保存时以最终选中项更新限制,关闭或取消编辑会丢弃草稿。
白名单的清理按钮列出当前目录未返回的已选 ID,默认不选中任何项,
由管理员确认后从当前表单移除,保存账号后生效。目录未就绪、刷新失败或返回空目录时不能清理,清理也不能将白名单置空。
刷新模型目录不修改已保存的模型限制。
图像、搜索、插件适配模型和映射目标可能不在目录中,目录缺失本身不代表模型失效。
例如 Plus 设置 `allowlist` 并选中 luna 的实际 ID,Pro 设置 `denylist` 并选中同一 ID,即可严格分流;
Pro 使用 `all` 时也能参与 luna 调度。套餐名称不自动生成或修改规则
@@ -2255,12 +2267,51 @@ HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.c
| `POST` | `/api/admin/client-keys/disable` | `{ id }` | 禁用 |
| `POST` | `/api/admin/client-keys/delete` | `{ id }` | 删除 |
### 列表查询
`GET /api/admin/client-keys` 接受以下可选参数:
| 参数 | 默认值 | 约束 |
| --- | --- | --- |
| `limit` | `50` | 每页数量,整数 `1`–`65535` |
| `search` | 不筛选 | 去除首尾空白后最多 256 字节,不能包含控制字符;空字符串等同于未提供 |
| `sortBy` | `createdAt` | `name`、`enabled`、`createdAt` 或 `lastUsedAt` |
| `sortDirection` | `desc` | `asc` 或 `desc` |
| `cursor` | 从第一页开始 | 原样传入上次返回的 `nextCursor`;非空且最多 512 字节,不自行构造或解析 |
响应 `data` 为 `{ items, nextCursor, total }`。`total` 为满足搜索条件的总数,`nextCursor: null` 表示已到末尾。
翻页时保持搜索和排序条件,`limit` 可调整;切换搜索或排序时省略 `cursor`,重新读取第一页。
游标绑定排序字段和方向;非法参数、未知查询字段、无效游标或排序不匹配均返回 `400` / `40001`
搜索仅匹配名称和标签,不匹配密钥值或可见前缀;不区分大小写,使用字面量包含匹配,`%`、`_` 和 `\` 按普通字符处理。
名称排序不区分大小写,`lastUsedAt` 为空的记录始终排在最后;排序值相同时按 Key ID 同方向排序
### 统计与窗口对齐
两个统计接口按部署时区和请求开始时间统计近 7 天(`7d`,默认)或 30 天(`30d`)。概览返回截止时间 `asOf`(Unix 毫秒),切换指标与读取明细时可用其固定统计区间。趋势按 `metric`(`costUsd`、`tokens`、`requests`)返回周期排名前五的模型,其余合为一条曲线(`model: null`)。模型优先取上游实际模型,缺失时回退到请求模型,两者都缺失时为空字符串
模型和周期合计包含请求数、已知 Token、已知 USD 费用,以及费用是否含本地估算或存在缺失。无已知数值时对应金额或 Token 为 `null`,费用占比以该 Key 周期内的已知 USD 总额为分母
手动对齐使用密钥可访问分组内账号的当前整账号 24 小时或七天窗口。确认时复核预览边界和密钥窗口版本,按完成时间重算本期消费。窗口到期后密钥恢复原生日历规则。已失效的预览或不足以重算的费用历史返回冲突
### 创建与更新密钥
创建字段为 `name`、可选 `label`、`groupIds`、`maxConcurrency`、`requestsPerMinute`、可选
`dailyLimitUsd`、`weeklyLimitUsd`、`customKey`、`providerRequestProfileOverrides`、`peerSharing` 和 `validity`。更新请求携带 `id`,不接受 `customKey`。
`groupIds` 必须显式提交:空数组派生 `routingScope: "all"`,非空数组派生
`routingScope: "groups"`。列表项返回分组引用 `groups`,以及从当前有效账号池派生、仅供展示的 `providerKinds`
创建成功返回 `201`,`data` 为 `{ id, prefix, plaintextKey }`;reveal 返回 `{ id, plaintextKey }`。
这两个响应包含完整明文 Key,调用方须安全保存。单个 Key 的更新、启用、禁用和删除返回 `{ id }`,完整配置通过列表查询读取
`peerSharing` 为 `{ enabled, sharePool, shareQuota, sharePlans }`,各项均为布尔值且默认 `false`。
创建时省略保持关闭;更新时省略或 `null` 保留整个配置,提交对象时替换完整配置,对象内省略项为 `false`。
列表项返回完整对象。`sharePlans` 需要 `sharePool`;开启 `enabled` 必须提交非空 `groupIds`,
推理允许使用这些组内的 OAuth 和 API Key 账号,[CPR 互联导出](#cpr-互联只读协议) 仅公开本地直连账号的观测。
账号池、原生额度窗口、套餐分布分别按对应开关公开;关闭共享不改变已保存的其他开关值
### 批量更新
批量更新只提交要修改的字段,各密钥保留其余配置。任一密钥或分组不存在、任一密钥的最终配置无效时,整批回滚
- `enabled` 设置启用状态。`groupIds` 替换全部分组,显式传空数组授权全部当前及未来账号
@@ -2268,19 +2319,6 @@ HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.c
- `peerSharing` 可单独修改 `enabled`、`sharePool`、`shareQuota`、`sharePlans`。开启互联需要绑定分组,共享套餐构成需要开启账号池概览
- `providerRequestProfileOverrides` 按 Provider 更新,显式传入某个 Provider 为 `null` 时恢复其全局配置。`installationSeed` 单独接受 UUID;仅修改身份配置时保留各密钥原有种子,仅修改种子时保留各自的身份配置
创建字段为 `name`、可选 `label`、`groupIds`、`maxConcurrency`、`requestsPerMinute`、可选
`dailyLimitUsd`、`weeklyLimitUsd`、`customKey`、`providerRequestProfileOverrides` 和 `peerSharing`。更新请求携带 `id`,不接受 `customKey`。
`groupIds` 必须显式提交:空数组派生 `routingScope: "all"`,非空数组派生
`routingScope: "groups"`。响应同时返回分组引用 `groups`,以及从当前有效账号池派生、仅供展示的
`providerKinds`。创建和 reveal 响应会返回完整明文 Key,调用方
必须立即安全保存
`peerSharing` 为 `{ enabled, sharePool, shareQuota, sharePlans }`,各项均为布尔值且默认 `false`。
创建时省略保持关闭;更新时省略或 `null` 保留整个配置,提交对象时替换完整配置,对象内省略项为 `false`。
列表、创建及更新响应均返回完整对象。`sharePlans` 需要 `sharePool`;开启 `enabled` 必须提交非空 `groupIds`,
推理允许使用这些组内的 OAuth 和 API Key 账号,[CPR 互联导出](#cpr-互联只读协议) 仅公开本地直连账号的观测。
账号池、原生额度窗口、套餐分布分别按对应开关公开;关闭共享不改变已保存的其他开关值
### Key 客户端身份
`providerRequestProfileOverrides` 按 Provider ID 保存身份选择,列表返回同名对象。创建时各项为完整配置对象,
@@ -2297,7 +2335,6 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
### 名称与密钥值
密钥列表的 `search` 仅匹配名称和标签,不匹配密钥值或可见前缀;搜索不区分大小写,使用字面量包含匹配,`%`、`_` 和 `\` 按普通字符处理。
创建和更新时去除名称首尾空白,并按忽略大小写、首尾空格的名称查重,重复返回 `409`。
更新排除当前记录,并发写入同样执行查重;失败不会留下审计或配置版本变更。
已有同名 Key 的凭据有效,编辑时须使用未被其他 Key 占用的名称
@@ -2308,7 +2345,7 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
应用不另设 Key 长度上限;创建请求和 `Authorization` 头仍受 Web 服务器及反向代理的通用大小限制。
更新接口不接受 `customKey`,防止修改策略时意外替换正在使用的凭据。
列表仅展示最多前 10 个字符,且至少隐藏一半字符;单字符 Key 的可见前缀为空。
完整值仍只通过创建和显式 reveal 返回,不进入普通 Debug 或审计
完整密钥不进入普通 Debug 或审计
自定义 Key 创建示例:
@@ -2324,7 +2361,6 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
创建、更新可传 `validity`,其中 `startsAt`、`expiresAt` 为带时区的 RFC3339 时间点。起点包含在有效期内,到达终点即失效。起止时间须成对填写,终点须晚于起点。
创建时默认立即生效且长期有效;更新时省略整个对象保留原有效期,传入对象会替换两个边界,两者同时为空可恢复长期有效。
管理页面使用浏览器本地时间选择起止日期和时分秒。新建默认留空,选择日期时默认 00:00:00;7 天和 30 天从今天零点起按日历日计算。
列表提供 `validity`、查询时的 `validityStatus`(`scheduled`、`active`、`expired`)和按部署时区格式化的 `startsAtDisplay`、`expiresAtDisplay`。手动重置额度保留密钥有效期
自定义 Key 的分组权限、日/周限额和并发规则按本平台配置执行,不导入其他平台的历史用量
@@ -2333,7 +2369,7 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
金额字段为非负十进制字符串,最多 10 位整数与 10 位小数,`"0"` 表示不限额。
创建时省略金额字段默认为零;更新时省略或 `null` 保留当前值,修改限额不会清空已用金额。
`maxConcurrency` 和 `requestsPerMinute` 是非负整数,零表示不限
`maxConcurrency` 限制同一 Key 同时执行的请求数,`requestsPerMinute` 限制同一 Key 在最近 60 秒内成功准入的请求数。两项接受非负 64 位有符号整数,零表示不限
列表返回 `dailyLimitUsd`、`weeklyLimitUsd`、`dailyUsedUsd`、`weeklyUsedUsd`(均为字符串)、
`dailyResetsAt`、`weeklyResetsAt`(RFC3339 或 `null`)。
+52 -28
View File
@@ -347,7 +347,7 @@ Provider 可为模型提供来源账号集合;Core 在公开目录查询时结
客户端原生模型目录同样由 Provider 拥有,通过 `ExecutionService` 和现有 Registry 的只读调用传递。
`routing::catalog` 的原生条目只包含模型 ID 与不透明协议正文,Core 负责冻结账号范围和整对象模型映射,
不解析上游字段;API 负责协议输出,不直接依赖具体 Provider。原生目录失败不会退回通用画像,只有不提供
该协议原生目录的 Provider才走画像转换。目录读取不创建计量请求或推理 attempt。
该协议原生目录的 Provider 才走画像转换。目录读取不创建计量请求或推理 attempt
请求位置、隐私、Fast 和生图的跨层策略见[请求策略与事实](#请求策略与事实),Provider 目录的刷新与凭据隔离见[账号模型目录](#账号模型目录)
@@ -508,23 +508,7 @@ Client Key 鉴权完成后,API adapter 从有界请求头识别客户端,Cor
生成请求按模型目录编译候选;全局模型映射是精确映射,未命中时模型名原样交给候选 Provider。
Responses、Messages、GenAI 和 Chat 保留各自的正文与协议事实进入共用 Generate 执行链。
HTTP、request 与 attempt 中间件处理当前入站协议,endpoint 保留客户端路由。
原生请求只匹配声明同协议能力的候选;Chat 由 Provider 选定账号后直接转换到目标协议,`outbound` 处理实际发送的请求
Core 独占路由、重试、交付事实与结算;Provider 独占上游身份、账号相关适配、隐私策略及账号隔离。
`gateway-protocol` 的 `openai/`、`anthropic/`、`genai/` 保留原生解析;
`chat_completions/{responses,messages,genai}/` 分别直接映射请求、完整响应和流事件,不借另一平台协议中转。
转换器只保留本次响应身份、增量状态及工具名称映射,不持有输入历史、账号、连接或调度状态。
API 的 `chat_completions/` 负责入口和 Chat 交付校验,复用 `generation/` 的提交、取消与终结生命周期。
Chat 的 finish 与 usage 等待执行终态确认,终结失败不得先交付成功结果
运行设置快照编译并共享提示词改写匹配器,支持字面前缀和正则,按配置顺序索引全局规则和各上游规则。路由计划冻结快照,每次尝试只取所选平台的适用规则。attempt 中间件提交后,协议层定位系统文本,Core 匹配开头;管理端预览复用同一匹配器。生成请求命中后同步更新已解析正文和原始 wire 中的目标字符串。计数由 Provider 解开封套,在已解析的计数正文上应用同一套规则
原始入口协议独立于转换后的正文协议,转换时保留来源与原始能力事实,不能从客户端头、User-Agent 或目标正文推断转换资格。
内置转换只能从 Chat 来源调用;显式插件仍按现有能力声明与中间件合同运行。
字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
Responses 搜索的强制执行判定、声明选择与联网模式解析由 `gateway-protocol::openai::web_search` 统一提供。
Core 按原始协议提取搜索能力要求,Chat 的 `web_search_options` 同样参与候选筛选;Provider 校验实际目标是否支持声明的搜索选项
Provider 选定账号后完成适配,`outbound` 处理实际发送的请求;原生协议和 Chat 转换的职责见[生成协议与转换](#生成协议与转换)
Images 与 standalone Search 是 OpenAI Provider 自有端点:两者都不参与文本模型映射,只在 Client Key
的账号范围确实包含 Codex 账号时生成单一 OpenAI 候选。Images 的图片模型由 Provider 从正文旁路
@@ -543,6 +527,14 @@ API 暂存的下一轮请求和连接泵接收队列共用容量名额,控制
`GenerateRequest` 在构造或替换正文时重算事实,仅改上下文不重复扫描正文;跨协议转换保留来源请求的能力约束和生图事实。
Core 将这些事实转为路由能力要求与生图权限判断,协议解析不决定是否允许请求
Responses 搜索的强制执行判定、声明选择与联网模式解析由 `gateway-protocol::openai::web_search` 统一提供。
Core 按原始协议提取搜索能力要求,Chat 的 `web_search_options` 同样参与候选筛选;Provider 校验实际目标是否支持声明的搜索选项
运行设置快照编译并共享提示词改写匹配器,按配置顺序索引全局规则和各上游规则,路由计划冻结快照,每次尝试只取所选平台的适用规则。
attempt 中间件提交后,协议层定位系统文本,Core 匹配开头;管理端预览复用同一匹配器。
生成请求命中后同步更新已解析正文和原始 wire 中的目标字符串;计数由 Provider 解开封套,在已解析的计数正文上应用同一套规则。
规则格式与匹配行为见[提示词改写](api.md#提示词改写)
全局请求位置及开关由运行设置持久化,快照仅在开关开启时生成全局覆盖,并随
`RuntimeSnapshot → RoutingPlan → AttemptContext` 冻结传递。Provider 在选定账号后优先应用代理位置,
出站字段遵循[请求位置合同](api.md#独立代理管理--managed-proxies)。请求期间不额外查询全局设置,配置发布不改变已开始请求的全局值
@@ -573,10 +565,11 @@ WS 路由提示属于握手,连接复用时不重发;档位变化不重建
## 5. Provider 与协议边界
Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 canonical event,不读取 Provider SDK
类型。Provider 独占 credential schema、OAuth、账号选择、模型目录、额度投影和上游 transport
Core 独占路由、重试、交付事实与结算,只理解 `Operation`、能力要求、Provider 候选、稳定错误和 canonical event,
不读取 Provider SDK 类型。Provider 独占 credential schema、OAuth、账号选择、模型目录、额度投影、上游身份与 transport,
负责选中账号的协议适配、隐私规则解释与执行,以及账号隔离
三个内置 Provider 在各自的 `lib.rs` 返回同一个 `ProviderBundle`。组合根从这一组 Bundle 注册执行器、管理端口和后台任务。共同职责使用一致目录:
三个内置 Provider 分别在各自的 `lib.rs` 构造 `ProviderBundle`。组合根从这一组 Bundle 注册执行器、管理端口和后台任务。共同职责使用一致目录:
| 目录 | 职责 |
| --- | --- |
@@ -587,8 +580,6 @@ Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 ca
| `provider/` | 推理执行和 worker 装配 |
| `transport/` | 出站协议与上游响应采集 |
Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号;OAuth 使用该账号的授权项目,API Key 直接请求配置的 GenAI 地址,停用账号仍可接受探测
数据面入口位于 `gateway-api/src/data_plane`,按协议、客户端扩展和平台专属端点划分职责:
- `responses`、`chat_completions`、`messages`、`genai` 拥有各自协议入口,生成与计数共用 `generation` 的执行交付、取消传播和连接生命周期
@@ -597,11 +588,38 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模
- `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有
- `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者
### 生成协议与转换
`gateway-protocol` 的 `openai/`、`anthropic/`、`genai/` 保留原生解析;
`chat_completions/{responses,messages,genai}/` 分别直接映射请求、完整响应和流事件,不借另一平台协议中转。
原生请求只匹配声明同协议能力的候选,Chat 由 Provider 选定账号后直接转换到目标协议
原始入口协议独立于转换后的正文协议,转换时保留来源与原始能力事实,不能从客户端头、User-Agent 或目标正文推断转换资格。
内置转换只能从 Chat 来源调用;显式插件仍按其能力声明与中间件合同运行
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。
选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段
Chat 响应在 Core 的响应中间件阶段之间直接转换。转换器只保留本次响应身份、增量状态及工具名称映射,
不持有输入历史、账号、连接或调度状态,也不增加账号级签名缓存或对话副本。
正常 EOF 时刷新最后内容块并发出终态,尾部用量先于完成事件交付;错误和取消不合成成功终态,转换状态随单次流释放
API 的 `chat_completions/` 负责入口和 Chat 交付校验,复用 `generation/` 的提交、取消与终结生命周期。
Chat 的 finish 与 usage 等待执行终态确认,终结失败不得先交付成功结果。
字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
### GenAI 目录与原生传输
Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号;OAuth 使用该账号的授权项目,API Key 直接请求配置的 GenAI 地址,停用账号仍可接受探测
GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity OAuth 将选中的 GenAI 请求封装为 Cloud Code 上游请求,API Key 直接请求公开 GenAI 路径
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。
GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。
API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录
GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录。Antigravity 声明生成与输入计数能力,API Key 目录按 `supportedGenerationMethods` 区分生成与计数,选号再次核对所选账号的声明。计数复用选号、中间件及资源释放流程;OAuth 调用 Cloud Code `countTokens`,API Key 调用原生模型的 `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
Antigravity 声明生成与输入计数能力,API Key 目录按 `supportedGenerationMethods` 区分生成与计数,选号再次核对所选账号的声明。
计数复用选号、中间件及资源释放流程;OAuth 调用 Cloud Code `countTokens`,API Key 调用原生模型的 `countTokens`。
计数响应不产生生成用量或费用事实,失败不切换为本地估算
Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
@@ -617,8 +635,6 @@ Antigravity 的 Cloud Code 传输按下游生成模式选择普通 JSON 或 SSE
Cloud Code 连接使用 rustls 与 HTTP/1.1,gzip 协商和流式解压由本 Provider 持有,不启用会影响其他 Provider 的 reqwest 全局压缩特性。解压后的流继续遵循控制面和推理消费方的大小限制、取消及截止时间
Chat 响应在 Core 的响应中间件阶段之间直接转换。转换器在正常 EOF 时刷新最后内容块并发出终态,尾部用量先于完成事件交付;错误和取消不合成成功终态。转换状态随单次流释放,不增加账号级签名缓存或对话副本
### 连接与上游身份
Responses 下游连接的心跳和退出由 API 拥有,每条 WS 使用独立取消信号,沿 Core 的 `ResponseControl` 传到 Provider 请求上下文。
@@ -776,6 +792,9 @@ xAI 的 OAuth 套餐目录保持严格一致;与独立 API 目录合并时,
该反馈不冻结整个账号,不改写管理员模型政策,也不占用 WS 传输恢复预算;重试仍遵守交付边界与原生续写固定账号约束。
管理员诊断旁路目录资格与模型拒绝冷却,OpenAI 的受管上游适配器不继承这两项原生限制
OpenAI 原生 `turn_rate_limit_exceeded` 复用账号、凭据版本与上游模型的冷却合同,等待期限从错误发生时起算。
模型冷却只参与匹配模型的选号,普通成功反馈不清除;当前失败的重放边界不变,已有会话沿用亲和和排队策略,等待时长见[容量拒绝与重试](api.md#容量拒绝与重试)
账号编辑在一个事务中更新调度事实,批量更新只应用显式提供的字段。导入与首次 OAuth 可携带统一账号设置,由 Admin 传递给 Store,
与凭据在同一事务中提交;Provider 仍独占凭据解析。未附带设置的导入、重新授权和后台刷新保留已有分组、
权重、并发与模型政策。模型政策变更推进配置 revision,不推进 credential revision。管理端导入和账号编辑共用设置表单,凭据输入独立于设置
@@ -810,7 +829,7 @@ Continuation 受原请求的 Client Key、账号范围、Provider 和发送/交
- OpenAI Provider 在发送前按上游握手声明的消息大小上限检查最终出站帧,新链可选择 HTTP;超限的 connection-local
续接和已标记为需要重放的 HTTP/WS 增量返回 `ClientReplayRequired`,由客户端重发
完整历史。预检拒绝先释放连接及租约,不消耗 WS 故障预算;Provider session state 只携带元数据,不保存 transcript
- Codex OAuth 的 HTTP 全量历史由独占租用的上游 WS 比较。连接只持有上一轮的响应 ID、项数和绑定 Client Key 与请求属性的前缀摘要,随连接回收;增量只改写出站帧,本次完整请求仍可用于安全回退
- Codex OAuth 的 HTTP 全量历史由独占租用的上游 WS 比较。连接只持有上一轮的响应 ID、项数和绑定 Client Key 与请求属性的前缀摘要,随连接回收。请求属性采用 Codex 的续接字段集。历史项按 Codex `ResponseItem` 及嵌套内容的回传形状计算只读摘要,统一缺省值和别名,未知类型按原值比较。上游采样元数据和客户端内部分析字段不参与比较;客户端回传的工具结果元数据及其调用绑定必须保留,正文、工具参数、工具定义和输出标注不合并。增量只改写出站帧,本次完整请求仍可用于安全回退
- OpenAI 在有效输出交付前收到可安全重放的明确额度拒绝时,先隔离账号,再投影 `ClientReplayRequired`;
丢弃未交付的原错误帧,由客户端提交完整历史开启新链,不把原增量输入交给其他账号。
真实错误分类、状态码、发送状态和上游诊断保持不变,客户端合同见 [Responses API](api.md#3-模型数据面与模型目录)
@@ -1098,6 +1117,9 @@ Host 监督进程和后台任务,各所有者负责传播取消及收尾;连
错误保护与上游限流分别保存恢复事实并聚合冷却投影,探测恢复由 Admin 负责,详见[Worker 与账号冻结](#worker-与账号冻结)
账号目录仅将实际模型限流汇总为 `rate_limited`,详情单独携带模型和期限;整账号冷却事实不混入模型冷却。
Redis 分别保存选号冷却与模型限流的期限,原子维护限流到期索引,目录查询按当前凭据版本过滤;列表筛选、统计和详情使用相同的版本与到期规则
PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规则统一维护在[迁移文档](../backend/migrations/README.md)
<a id="9-credential额度与主动重置"></a>
@@ -1109,6 +1131,7 @@ PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规
OpenAI 在 PostgreSQL 保存账号最近一次成功的模型目录、凭据版本、观测时间及 ETag。启动时批量恢复,按不同正文解析一次,保留每个账号的独立归属。没有历史目录也能发布路由快照;能力读取与推理不等待上游查询。
账号缺少目录或收到新 ETag 时,后台重新查询该账号。正常响应的 ETag 与该账号当前凭据和套餐的目录一致时,在内存中续期。WebSocket 握手的 ETag 由该连接首次生成请求确认一次,预热时保留。距上次成功拉取或确认满 1 小时后,由后台复查。重启后从持久化的目录观测时间起算。
账号上游查询失败后按凭据版本和套餐独立退避,从 1 分钟倍增至最多 1 小时,到期由目录任务重试。手动刷新可立即查询,成功发布后解除该账号的退避。刷新期间继续使用上次成功的目录,凭据或套餐变化后重新发现模型。
常规目录拉取共用 15 秒的凭据加载与上游查询预算。退避到期重试和手动刷新时,凭据加载仍限 15 秒,每页最多等待响应头 30 秒,读取正文后每收到新字节重新计时,连续 30 秒没有正文进展才超时。
刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护
OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再读取本地账号状态核对凭据版本。同一份正文可以复用,但不会把一个账号的模型授予同套餐的其他账号。客户端版本和 Key 身份不触发额外发现
@@ -1469,6 +1492,7 @@ OpenAI 客户端画像由 Provider 每小时检查发布元数据,发布标识
版本及缓存更新失败保留当前画像,下轮继续尝试;Host 只监督调度与取消。
Antigravity 启动时恢复有效制品缓存,每小时检查发布资料。后台按已使用的客户端、平台和架构核对发布包版本并提取 CL,CLI 同时校验清单的 SHA-512。
需要完整下载的制品写入运行数据目录下 `antigravity/` 中的匿名临时文件,解析结束或取消后释放。
版本、CL 和核验时间绑定同一制品。缓存每 24 小时续期,保留 30 天及原核验时间。Provider 在缓存写入成功后整组发布画像,失败保留当前画像。
发布资料单独记录最新观测,供管理端展示。
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+10 -11
View File
@@ -6,6 +6,7 @@
| --- | --- |
| 修改宿主前后端 | [环境与依赖](#环境与依赖) → [启动宿主](#启动宿主) |
| 定位模块与共享实现 | [源码入口](#源码入口) |
| 验证后端改动 | [测试环境](../backend/migrations/README.md#本地测试库) → [验证命令](architecture.md#验证命令) |
| 同时修改 UI 或插件 | [源码联调](#源码联调) → [启动与检查](#启动与检查) |
| 验证本地 SDK | [本地 SDK 验证](#本地-sdk-验证) |
| 提交跨仓库改动 | [编辑与提交](#编辑与提交) |
@@ -31,10 +32,10 @@ pnpm --dir frontend install --frozen-lockfile
使用源码仓库自带的 Compose 与配置模板,按[手动安装](../deploy/README.md#手动安装)中的配置与权限要求准备 `deploy/config.yaml` 和 `.runtime/` 目录
数据库及 Redis 可由 Compose 启动:
启动数据库与 Redis,等待健康检查通过后运行后端:
```bash
docker compose -f deploy/compose.yaml up -d postgres redis
docker compose -f deploy/compose.yaml up -d --wait postgres redis
cargo +1.99.1 run --manifest-path backend/Cargo.toml -p codex-proxy-rs --locked
```
@@ -48,7 +49,7 @@ cargo +1.99.1 run --manifest-path backend/Cargo.toml -p codex-proxy-rs --locked
pnpm --dir frontend dev
```
后端代理由 `frontend/vite.config.ts` 配置,验证 WebSocket 时直接连接后端
访问管理端开发服务输出的地址。HTTP 请求由 `frontend/vite.config.ts` 代理至后端,验证 WebSocket 时直接连接后端
前后端检查见 [贡献与审查](../CONTRIBUTING.md#验证),数据库集成测试使用[专用测试库](../backend/migrations/README.md#本地测试库)
@@ -56,15 +57,13 @@ pnpm --dir frontend dev
[后端 Workspace 边界](architecture.md#3-workspace-边界) · [前端模块职责](architecture.md#34-前端模块职责) · [共享 UI 组件架构](https://github.com/zyycn/codex-proxy-ui/blob/main/playground/guide/architecture.md)
Chat Completions 到 Responses、Messages、GenAI 的纯协议转换位于 `backend/crates/gateway-protocol/src/chat_completions/`,
Chat HTTP 入口位于 `backend/crates/gateway-api/src/data_plane/chat_completions/`,各 Provider 的 `provider/chat/` 或 `provider/chat.rs` 负责调用获准的转换。
Messages 原生类型位于 `backend/crates/gateway-protocol/src/anthropic/`,账号协议分派、HTTP 执行和计数位于 `backend/crates/providers/openai/src/provider/messages/`。
模块职责见 [Provider 与协议边界](architecture.md#5-provider-与协议边界)
协议转换、原生类型和 Provider 执行入口见 [Provider 与协议边界](architecture.md#5-provider-与协议边界),请求格式与支持范围见 [模型数据面](api.md#3-模型数据面与模型目录)
联调协议时为各 Provider 准备对应的原生账号,并通过账号分组与 Client Key 固定上游范围;OpenAI 的 Responses 与 Messages API Key 账号应分组验证。
分别检查各账号的原生入口与 Chat 入口的 JSON、SSE、工具往返、取消和错误;支持计数的账号另测原生计数入口,并确认其他原生协议入口不会触发内置转换。
请求格式与支持范围见 [模型数据面](api.md#3-模型数据面与模型目录)。
Messages 账号只配置 HTTP;本地计数估算不能替代上游计费核对
联调协议时:
1. 为各 Provider 准备对应的原生账号,通过账号分组与 Client Key 固定上游范围;OpenAI 的 Responses 与 Messages API Key 账号分组验证
2. 分别检查原生入口与 Chat 入口的 JSON、SSE、工具往返、取消和错误,确认其他原生协议入口不会触发内置转换
3. 支持计数的账号另测原生计数入口;本地计数估算不能替代上游计费核对
OpenAI 的 `transport::tls::` 测试在本机回环地址采集 ClientHello,覆盖默认 HTTP、自定义 CA 的 HTTP 和 WebSocket。运行方式见[后端验证命令](architecture.md#验证命令)
+6 -2
View File
@@ -33,11 +33,15 @@ export function getAccountModelCatalog(data: AccountIdParam, options: RequestOpt
})
}
export function refreshAccountModels(data: AccountIdParam, options: RequestOptions = {}) {
export function refreshAccountModels({ accountId, provider }: AccountIdParam & { provider?: string }, options: RequestOptions = {}) {
return request<AccountModelsResponse>({
url: '/api/admin/accounts/models/refresh',
method: 'POST',
data,
data: { accountId },
// OpenAI 由上游正文进度决定超时,弹窗通过 signal 取消等待
timeout: provider === 'openai'
? 0
: undefined,
...options,
})
}
@@ -44,6 +44,7 @@ export interface AccountProtectionRule {
}
export interface AccountQuota {
modelRateLimits: { model: string, until: string, untilDisplay: string }[]
refreshedAt: string | null
refreshedAtRelative: RelativeTimeView | null
refreshedAtDisplay: string
@@ -33,7 +33,7 @@ function select() {
<div class="grid gap-2">
<ProviderSelect v-if="!provider" v-model="selectedProvider" :aria-label="t('keys.configuration.platform')" />
<div
class="flex items-center gap-1 rounded-z-sm pr-1 transition-colors hover:bg-z-bg-text-hover has-focus-visible:bg-z-bg-text-hover motion-reduce:transition-none"
class="flex items-center gap-1 rounded-z-sm bg-z-fill-quaternary pr-3 shadow-z-tertiary transition-colors hover:bg-z-bg-text-hover has-focus-visible:bg-z-bg-text-hover motion-reduce:transition-none"
>
<ZMenuItem class="min-h-18 min-w-0 py-3 hover:bg-transparent!" @click="select">
<template #icon>
@@ -14,6 +14,7 @@ import { accountModelAccessError, accountModelIdError } from './validation'
const props = withDefaults(defineProps<{
accountId?: string
provider?: string
groupId?: string | null
disabled?: boolean
allowPreserve?: boolean
@@ -206,7 +207,9 @@ async function load(refresh = false) {
catalog.value = result.models
}
else {
const result = await (refresh ? refreshAccountModels : getAccountModels)({ accountId: id }, options)
const result = refresh
? await refreshAccountModels({ accountId: id, provider: props.provider }, options)
: await getAccountModels({ accountId: id }, options)
if (request.isCurrent(requestId)) {
catalog.value = result.models
catalogObservedAtDisplay.value = result.observedAt ? result.observedAtDisplay : undefined
@@ -596,6 +596,9 @@
"attentionHelp": "This account needs attention",
"retestHelp": "Test the connection again to update the status",
"rateLimitedHelp": "The upstream service rate limited this account, cooldown is in progress",
"limitedModels": "Limited models · Expected recovery",
"modelCooldownRemaining": "{seconds} seconds remaining",
"modelCooldownEnded": "Cooldown ended",
"cooldownHelp": "Scheduling resumes automatically after cooldown",
"credentialsHelp": "This account is excluded from scheduling, update its credentials and test the connection again",
"reauthorizeHelp": "Reauthorize the account to resume scheduling",
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more