Compare commits

..
3 Commits
13 changed files with 218 additions and 133 deletions

No files matched your search

@@ -26,6 +26,7 @@ pub(crate) struct VerifiedArtifact {
pub(crate) release: Release,
pub(crate) changelist: u64,
pub(crate) verified_at: DateTime<Utc>,
cache_sequence: u64,
renewed_at: Option<Instant>,
}
@@ -77,7 +78,7 @@ impl VerificationCache {
|| payload.target != target
|| payload.changelist == 0
|| !valid_version(&payload.release.version)
|| cached.artifact_sequence() != sequence(&payload.release.version)?
|| cached.artifact_sequence() < sequence(&payload.release.version)?
{
return Err(error());
}
@@ -85,6 +86,7 @@ impl VerificationCache {
release: payload.release,
changelist: payload.changelist,
verified_at: cached.verified_at().into(),
cache_sequence: cached.artifact_sequence(),
renewed_at: None,
}))
}
@@ -96,28 +98,45 @@ impl VerificationCache {
release: &Release,
previous: Option<&VerifiedArtifact>,
) -> Result<VerifiedArtifact, WorkerTaskError> {
let sequence = sequence(&release.version)?;
if let Some(previous) = previous {
validate_successor(previous, release, sequence)?;
if previous.release == *release
&& previous
.renewed_at
.is_some_and(|at| at.elapsed() < RENEW_INTERVAL)
{
return Ok(previous.clone());
}
if let Some(previous) = previous
&& previous.release == *release
&& previous
.renewed_at
.is_some_and(|at| at.elapsed() < RENEW_INTERVAL)
{
return Ok(previous.clone());
}
let cached = self.load(target).await?;
if let Some(cached) = &cached {
validate_successor(cached, release, sequence)?;
}
let matching = cached
.as_ref()
.filter(|v| v.release == *release)
.or_else(|| previous.filter(|v| v.release == *release));
let (verified_at, changelist) = match matching {
Some(artifact) => (artifact.verified_at, artifact.changelist),
None => {
let current = previous
.into_iter()
.chain(cached.as_ref())
.max_by_key(|artifact| artifact.cache_sequence);
let version_sequence = sequence(&release.version)?;
let (cache_sequence, verified_at, changelist) = match current {
Some(current) if current.release == *release => (
current.cache_sequence,
current.verified_at,
current.changelist,
),
_ => {
let mut cache_sequence = version_sequence;
if let Some(current) = current {
let current_version = sequence(&current.release.version)?;
if version_sequence < current_version
|| (version_sequence == current_version
&& release.build == current.release.build)
|| previous.is_some_and(|p| {
p.release == *release && p.cache_sequence < current.cache_sequence
})
{
return Err(WorkerTaskError::safe(
"Antigravity 发布资料回退或与已核验构建冲突",
));
}
// 旧缓存以版本编码为序号;同版本重发和紧随其后的补丁版本也需单调递增
cache_sequence = version_sequence
.max(current.cache_sequence.checked_add(1).ok_or_else(error)?);
}
let changelist = artifact::verify(
client,
target,
@@ -127,7 +146,7 @@ impl VerificationCache {
&self.artifact_dir,
)
.await?;
(Utc::now(), changelist)
(cache_sequence, Utc::now(), changelist)
}
};
let payload = serde_json::to_value(Payload {
@@ -142,7 +161,7 @@ impl VerificationCache {
let profile = ProviderArtifactProfile::new(
self.provider.clone(),
key(target),
sequence,
cache_sequence,
verified_at.into(),
OpaqueProviderData::new(payload),
);
@@ -158,27 +177,12 @@ impl VerificationCache {
release: release.clone(),
changelist,
verified_at,
cache_sequence,
renewed_at: Some(Instant::now()),
})
}
}
fn validate_successor(
current: &VerifiedArtifact,
next: &Release,
next_sequence: u64,
) -> Result<(), WorkerTaskError> {
let current_sequence = sequence(&current.release.version)?;
if next_sequence < current_sequence
|| (next_sequence == current_sequence && current.release != *next)
{
return Err(WorkerTaskError::safe(
"Antigravity 官方发布版本回退或同版本制品不一致",
));
}
Ok(())
}
pub(crate) fn key(target: ReleaseTarget) -> String {
let client = match target.client {
super::selection::ClientKind::Desktop => "desktop",
@@ -128,7 +128,7 @@ async fn latest_profile_switches_version_and_changelist_only_after_verified_publ
}
#[tokio::test]
async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification() {
async fn conflicting_artifact_for_same_build_or_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(), std::env::temp_dir());
@@ -148,7 +148,7 @@ async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification
.unwrap()
.clone();
let changed = Release {
build: Some("124".into()),
url: format!("{}/unexpected.dmg", server.uri()),
..release.clone()
};
assert!(
@@ -185,6 +185,131 @@ async fn changed_artifact_or_target_and_failed_cache_do_not_publish_verification
);
}
#[tokio::test]
async fn same_version_rebuild_is_verified_before_publication_and_restored_after_restart() {
let version = "2.35.1";
let first_server = super::archive::serve(super::artifact::desktop_zip(version), "").await;
let good = super::archive::serve(
super::artifact::desktop_zip_with_changelist(version, 2_345_678_901),
"",
)
.await;
let bad = super::archive::serve(super::artifact::desktop_zip("2.35.0"), "").await;
let cache = cache();
let client = reqwest::Client::new();
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
let target = Selection::default().target();
let first_release = fixture_release(&first_server, version);
let first = service
.verify(&client, target, &first_release, None)
.await
.unwrap();
let releases = ReleaseService::new(cache.clone(), std::env::temp_dir()).unwrap();
releases.restore().await;
let frozen = default_profile(&releases).frozen();
let candidate = |server: &wiremock::MockServer| Release {
build: Some("124".into()),
..fixture_release(server, version)
};
assert!(
service
.verify(&client, target, &candidate(&bad), Some(&first))
.await
.is_err()
);
assert!(!bad.received_requests().await.unwrap().is_empty());
assert_eq!(
service.load(target).await.unwrap().unwrap().release,
first_release
);
assert_eq!(cache.writes.load(Ordering::SeqCst), 1);
let release = candidate(&good);
releases.observe(target, Some(release.clone()));
let pending = dashboard(&Selection::default(), &releases);
assert_eq!(
pending.release.unwrap().status,
DesktopReleaseStatus::UpdateAvailable
);
assert!(pending.user_agent.contains("cl=1234567890"));
let new = service
.verify(&client, target, &release, Some(&first))
.await
.unwrap();
assert!(!good.received_requests().await.unwrap().is_empty());
assert_eq!(new.changelist, 2_345_678_901);
releases.update().await.unwrap();
let updated = dashboard(&Selection::default(), &releases);
assert_eq!(
updated.release.unwrap().status,
DesktopReleaseStatus::Current
);
assert_eq!(updated.version, version);
assert!(updated.user_agent.contains("cl=2345678901"));
assert_eq!(
ClientProfile::from_frozen(&frozen).unwrap().user_agent(),
pending.user_agent
);
let restarted = ReleaseService::new(cache, std::env::temp_dir()).unwrap();
restarted.restore().await;
assert_eq!(default_profile(&restarted).user_agent(), updated.user_agent);
}
#[tokio::test]
async fn concurrent_rebuilds_cannot_overwrite_each_other_or_block_the_next_patch() {
let version = "2.35.1";
let server = super::archive::serve(super::artifact::desktop_zip(version), "").await;
let cache = cache();
let service = VerificationCache::new(provider(), cache.clone(), std::env::temp_dir());
let client = reqwest::Client::new();
let target = Selection::default().target();
let first = fixture_release(&server, version);
service.verify(&client, target, &first, None).await.unwrap();
let previous = service.load(target).await.unwrap().unwrap();
let candidate = |id: &str| Release {
build: Some(id.into()),
..first.clone()
};
let a = candidate("124");
let b = candidate("125");
let (a, b) = tokio::join!(
service.verify(&client, target, &a, Some(&previous)),
service.verify(&client, target, &b, Some(&previous)),
);
assert_ne!(a.is_ok(), b.is_ok());
let winner = a.or(b).unwrap();
let published = service.load(target).await.unwrap().unwrap();
assert_eq!(published.release, winner.release);
assert_eq!(published.changelist, previous.changelist);
assert!(
service
.verify(&client, target, &first, Some(&previous))
.await
.is_err()
);
let patch = "2.35.2";
let patch_server = super::archive::serve(super::artifact::desktop_zip(patch), "").await;
let patched = service
.verify(
&client,
target,
&fixture_release(&patch_server, patch),
Some(&published),
)
.await
.unwrap();
assert_eq!(patched.release.version, patch);
assert!(
service
.verify(&client, target, &first, Some(&patched))
.await
.is_err()
);
assert_eq!(cache.writes.load(Ordering::SeqCst), 3);
}
#[tokio::test]
async fn version_disagreement_leaves_the_previous_cache_intact() {
let server = super::archive::serve(super::artifact::desktop_zip("2.35.1"), "").await;
@@ -68,15 +68,6 @@ impl Default for CodexWireProfile {
}
impl CodexWireProfile {
pub(crate) fn sends_responses_installation_header(&self) -> bool {
static FIRST_VERSION: std::sync::LazyLock<semver::Version> =
std::sync::LazyLock::new(|| {
semver::Version::parse("0.175.0-alpha.3").expect("valid Core version")
});
semver::Version::parse(&self.codex_version)
.is_ok_and(|version| version.cmp_precedence(&FIRST_VERSION).is_ge())
}
/// 原样返回已解析的完整 UA;默认预设按 bundled Core app-server 格式生成
pub fn user_agent(&self) -> String {
if let Some(user_agent) = &self.exact_user_agent {
@@ -46,44 +46,6 @@ pub(crate) fn parse_upstream_base_url(value: &str) -> Option<url::Url> {
.then_some(url)
}
/// Responses 的 HTTP 请求与 WS 握手使用同一上游基址;仅官方 TLS 目的地接收独立安装头
pub(super) fn supports_installation_header(base_url: &str) -> bool {
let Some(url) = parse_upstream_base_url(base_url) else {
return false;
};
if url.scheme() != "https" || url.port_or_known_default() != Some(443) {
return false;
}
let Some(host) = url.host_str() else {
return false;
};
let host = host.strip_suffix('.').unwrap_or(host);
matches!(
host,
"api.openai.com"
| "gov.api.openai.com"
| "us.api.openai.com"
| "eu.api.openai.com"
| "au.api.openai.com"
| "ca.api.openai.com"
| "jp.api.openai.com"
| "in.api.openai.com"
| "sg.api.openai.com"
| "kr.api.openai.com"
| "gb.api.openai.com"
| "ae.api.openai.com"
| "mtls.api.openai.com"
| "mtls-us.api.openai.com"
| "mtls-eu.api.openai.com"
| "api.openai.org"
| "api.openai-staging.com"
| "chat.openai.com"
| "chatgpt.com"
| "chatgpt-staging.com"
) || host.ends_with(".chatgpt.com")
|| host.ends_with(".chatgpt-staging.com")
}
/// 返回与 base path 对应的唯一 usage endpoint
pub fn usage_endpoint_url(base_url: &str) -> String {
account_endpoint_url(base_url, "usage")
@@ -234,8 +234,6 @@ impl CodexBackendClient {
if !guardian.is_some_and(CodexGuardianRole::uses_sampler_transport)
&& !context.authorization.is_empty()
&& let Some(id) = context.installation_id.filter(|id| !id.is_empty())
&& profile.sends_responses_installation_header()
&& super::endpoints::supports_installation_header(&self.base_url)
&& let Ok(mut value) = HeaderValue::from_str(id)
{
value.set_sensitive(true);
@@ -293,7 +293,10 @@ async fn backend_http_should_preserve_business_headers_without_downstream_transp
raw_header_values(&raw, "x-openai-account-routing-override"),
vec![b"configured-route".to_vec()]
);
assert!(raw_header_values(&raw, "x-codex-installation-id").is_empty());
assert_eq!(
raw_header_values(&raw, "x-codex-installation-id"),
[b"lease-installation".as_slice()]
);
let session = raw_header_values(&raw, "session-id");
assert!(uuid::Uuid::parse_str(std::str::from_utf8(&session[0]).unwrap()).is_ok());
// 指纹头由运行时画像生成,不透传客户端值
@@ -483,7 +486,10 @@ async fn backend_websocket_should_preserve_business_headers_without_downstream_t
values("x-openai-account-routing-override"),
vec![b"configured-route".to_vec()]
);
assert!(values("x-codex-installation-id").is_empty());
assert_eq!(
values("x-codex-installation-id"),
[b"lease-installation".as_slice()]
);
let session = values("session-id");
assert!(uuid::Uuid::parse_str(std::str::from_utf8(&session[0]).unwrap()).is_ok());
assert!(values("x-codex-turn-state").is_empty());
@@ -169,7 +169,10 @@ async fn account_correlation_preserves_turns_across_transports_and_account_switc
flat["ws_request_header_baggage"],
"sentry-environment=synthetic"
);
assert!(!headers.contains_key("x-codex-installation-id"));
assert_eq!(
headers["x-codex-installation-id"],
flat["x-codex-installation-id"].as_str().unwrap()
);
let header: Value =
serde_json::from_str(headers["x-codex-turn-metadata"].to_str().unwrap()).unwrap();
let full: Value =
@@ -6588,7 +6588,7 @@ async fn installation_seed_scopes_http_identity_and_cache_by_key_and_account() {
let id = body["client_metadata"]["x-codex-installation-id"]
.as_str()
.unwrap();
assert!(!request.headers.contains_key("x-codex-installation-id"));
assert_eq!(request.headers["x-codex-installation-id"], id);
assert!(uuid::Uuid::parse_str(id).is_ok());
assert_ne!(id, KEY_INSTALLATION_SEED);
assert_ne!(id, other_seed);
@@ -6620,7 +6620,7 @@ async fn installation_seed_scopes_http_identity_and_cache_by_key_and_account() {
}
#[tokio::test]
async fn http_account_scoping_keeps_installation_in_metadata() {
async fn http_account_scoping_matches_installation_header_and_metadata() {
for owner in ["acct_scope_same", "acct_scope_old"] {
let raw = r#"{"installation_id":"client-installation","future":true}"#;
let request = capture_scoped_http_request(
@@ -6661,7 +6661,10 @@ async fn http_account_scoping_keeps_installation_in_metadata() {
assert_ne!(installation_id, "client-installation");
assert!(uuid::Uuid::parse_str(installation_id).is_ok());
assert_eq!(body["installation_id"], installation_id);
assert!(captured_header_values(&request, "x-codex-installation-id").is_empty());
assert_eq!(
captured_header_values(&request, "x-codex-installation-id"),
[installation_id.as_bytes()]
);
let headers = captured_header_values(&request, "x-codex-turn-metadata");
assert_eq!(headers.len(), 1);
for encoded in [
@@ -6679,7 +6682,7 @@ async fn http_account_scoping_keeps_installation_in_metadata() {
}
#[tokio::test]
async fn websocket_account_scoping_keeps_installation_in_metadata() {
async fn websocket_account_scoping_matches_installation_header_and_metadata() {
for owner in ["acct_scope_same", "acct_scope_old"] {
let raw = r#"{"installation_id":"client-installation","future":true}"#;
let store = Arc::new(MemoryAccountStore::default());
@@ -6769,7 +6772,7 @@ async fn websocket_account_scoping_keeps_installation_in_metadata() {
assert_ne!(installation_id, KEY_INSTALLATION_SEED);
assert!(uuid::Uuid::parse_str(installation_id).is_ok());
assert_eq!(body["installation_id"], installation_id);
assert!(!header.contains_key("x-codex-installation-id"));
assert_eq!(header["x-codex-installation-id"], installation_id);
for encoded in [
header["x-codex-turn-metadata"]
.to_str()
@@ -6841,7 +6844,10 @@ async fn same_account_scope_preserves_future_protocol_shapes() {
body.pointer("/client_metadata/x-codex-installation-id")
);
assert!(body.pointer("/client_metadata/installation_id").is_none());
assert!(!request.headers.contains_key("x-codex-installation-id"));
assert_eq!(
request.headers["x-codex-installation-id"],
body["installation_id"].as_str().unwrap()
);
}
#[tokio::test]
@@ -55,34 +55,19 @@ pub(in crate::provider) fn outbound_context(
}
#[tokio::test]
async fn responses_installation_id_follows_core_version_destination_and_transport() {
async fn responses_installation_id_matches_metadata_across_upstreams_and_core_profiles() {
use provider_openai::credential::ResponsesTransport;
const ID: &str = "x-codex-installation-id";
const FIRST: &str = "0.175.0-alpha.3";
for (version, base, role, send_header) in [
("0.174.0", OFFICIAL_CODEX_BASE_URL, None, false),
("0.175.0-alpha.2", OFFICIAL_CODEX_BASE_URL, None, false),
(FIRST, OFFICIAL_CODEX_BASE_URL, None, true),
(
"0.175.0-alpha.10",
"https://eu.api.openai.com/v1",
None,
true,
),
(
FIRST,
"https://app.chatgpt.com.:443/backend-api",
None,
true,
),
(FIRST, "https://chatgpt.com.example.test/v1", None, false),
(FIRST, "https://unknown.api.openai.com/v1", None, false),
(FIRST, "https://api.openai.com:8443/v1", None, false),
(FIRST, "http://api.openai.com/v1", None, false),
(FIRST, OFFICIAL_CODEX_BASE_URL, Some("classifier"), false),
(FIRST, OFFICIAL_CODEX_BASE_URL, Some("housekeeper"), false),
(FIRST, OFFICIAL_CODEX_BASE_URL, Some("reviewer"), true),
const CORE: &str = "0.174.0";
for (version, base, role) in [
(CORE, OFFICIAL_CODEX_BASE_URL, None),
("0.176.0", OFFICIAL_CODEX_BASE_URL, None),
(CORE, "https://proxy.example.test:8443/v1", None),
(CORE, "http://proxy.example.test/v1", None),
(CORE, OFFICIAL_CODEX_BASE_URL, Some("classifier")),
(CORE, OFFICIAL_CODEX_BASE_URL, Some("housekeeper")),
(CORE, OFFICIAL_CODEX_BASE_URL, Some("reviewer")),
] {
for websocket in [false, true] {
let store = Arc::new(MemoryAccountStore::default());
@@ -172,7 +157,7 @@ async fn responses_installation_id_follows_core_version_destination_and_transpor
}
assert_eq!(
headers.get(ID).map(|value| value.to_str().unwrap()),
id.filter(|_| send_header),
id,
"{version} {base} {role:?} websocket={websocket}"
);
}
@@ -226,6 +226,7 @@ async fn backend_websocket_should_forward_context_headers_and_preserve_payload_f
assert_eq!(metadata["x-codex-turn-state"], "turn-state");
let headers = received_headers.lock().expect("headers lock");
for (name, expected) in [
("x-codex-installation-id", "install-123"),
("x-client-request-id", "cp_derived"),
("openai-beta", "responses_websockets=2026-02-06"),
("x-codex-turn-metadata", "{\"thread_source\":\"subagent\"}"),
@@ -251,7 +252,6 @@ async fn backend_websocket_should_forward_context_headers_and_preserve_payload_f
}
for forbidden in [
"x-codex-turn-state",
"x-codex-installation-id",
"x-openai-internal-codex-residency",
"accept",
"content-type",
@@ -359,7 +359,12 @@ async fn backend_http_should_send_codex_context_without_browser_headers() {
let scoped_session = read_header_value(&raw_request, "session-id").unwrap();
assert_ne!(scoped_session, "session-1");
assert!(uuid::Uuid::parse_str(scoped_session).is_ok());
assert_eq!(
read_header_value(&raw_request, "x-codex-installation-id"),
Some("3b11bc82-c666-417d-b9ff-2a34fd040385")
);
let mut expected_names = vec![
"x-codex-installation-id",
"authorization",
"chatgpt-account-id",
"originator",
@@ -386,7 +391,6 @@ async fn backend_http_should_send_codex_context_without_browser_headers() {
header_names.sort_unstable();
assert_eq!(header_names, expected_names);
for forbidden in [
"x-codex-installation-id",
"x-openai-internal-codex-residency",
"sec-ch-ua",
"sec-ch-ua-mobile",
@@ -76,7 +76,7 @@ async fn official_websocket_wire_fingerprint_should_remain_aligned() {
"authorization",
"user-agent",
"originator",
"openai-beta",
"x-codex-installation-id",
"version",
"x-codex-beta-features",
"x-client-request-id",
@@ -85,6 +85,7 @@ async fn official_websocket_wire_fingerprint_should_remain_aligned() {
"x-codex-window-id",
"x-codex-turn-metadata",
"x-codex-routing-hint",
"openai-beta",
"sec-websocket-extensions",
]
);
+2 -2
View File
@@ -552,7 +552,7 @@ Responses API Key 与 OAuth 共用模拟客户端画像(`User-Agent`、`origin
`X-OpenAI-Actor-Authorization` 托管认证声明。
Responses 正文的 `client_metadata["x-codex-installation-id"]` 与 turn metadata 中已有的安装 ID 使用同一身份。
Key 配置种子时,网关按种子、Key ID 和选中账号 ID 稳定派生安装 ID;其余请求使用账号持久化的安装 ID。
出站 Core 画像从 `0.175.0-alpha.3` 起,向官方认可的 OpenAI API 或 ChatGPT 主机发起已认证的 HTTPS 请求或 WSS 握手时,还会发送同值的 `x-codex-installation-id`。
所有 Core 画像向配置的上游发送已认证的普通 Responses 请求时,HTTP 请求头和 WebSocket 握手头都携带同值的 `x-codex-installation-id`。
Guardian 的 classifier 和 housekeeper 走专用采样路径,只改写已有的正文安装字段。Images、Search、Live、模型目录和账号接口均不主动添加独立安装头。下游同名头由网关过滤。
`x-openai-internal-codex-residency` 和 `x-openai-account-routing-override` 由运行设置
@@ -2998,7 +2998,7 @@ User-Agent 使用 `grok-shell/<版本> (<系统>; <架构>)`,其中 `arm64`
```
- `client` 为 `desktop` 或 `cli`,`platform` 为 `macos`、`linux` 或 `windows`。可显式选择 `arm64`、`amd64`;`arch: null` 时 macOS 使用 `arm64`,Linux 和 Windows 使用 `amd64`
- `versionMode: "latest"` 使用已核验发布包的版本与 CL,更新失败保留当前画像。启动时恢复缓存,无可用画像时先使用内置版本并省略 CL。`"fixed"` 要求 `clientVersion` 为三段数字版本,有对应制品的核验结果时附带 CL。[Google 官方下载](https://antigravity.google/download)
- `versionMode: "latest"` 使用已核验发布包的版本与 CL。同版本发布新构建时重新核验安装包,成功后切换,失败沿用上次已核验的画像。启动时恢复缓存,无可用画像时先使用内置版本并省略 CL。`"fixed"` 要求 `clientVersion` 为三段数字版本,有对应制品的核验结果时附带 CL。[Google 官方下载](https://antigravity.google/download)
- `systemPrompt` 最长 16 KiB。省略、`null` 或空白时使用默认提示词,选项响应通过 `defaultSystemPrompt` 和 `systemPromptSource` 返回默认模板及其来源(AGY CLI 1.5.23)。原生 OAuth 生成和计数在客户端系统指令前加入该提示词,普通 Chat 使用[提示词改写规则](#提示词改写)
OAuth 模型请求按选中的画像重建 User-Agent,同一请求的重试沿用首次画像。Desktop 使用 `hub`,CLI 使用 `cli` 并携带 `auth_method=consumer`;不会继承入站 UA 或 ACP 的 `host_path`。个人 OAuth 画像省略 `datacollection_opt_in`,不修改 Google 账号的遥测设置。授权码交换、导入和续期各自固定当轮的全局画像
+3 -3
View File
@@ -2,6 +2,6 @@ version: 3.62.1-rc.4
published:
'3':
stable: 3.62.0
rc: 3.62.1-rc.3
beta: 3.62.1-rc.3
alpha: 3.62.1-rc.3
rc: 3.62.1-rc.4
beta: 3.62.1-rc.4
alpha: 3.62.1-rc.4