refactor: unify provider client identity profiles and node synchronization

This commit is contained in:
dalamudx
2026-10-05 15:18:36 +08:00
parent 716c35bf56
commit 7acbaab82b
35 changed files with 1006 additions and 773 deletions
@@ -0,0 +1,67 @@
//! Immutable client identity snapshots shared by provider adapters.
use std::sync::{Arc, RwLock};
/// Readers release the lock before constructing a request. Publishing never
/// changes snapshots already held by an in-flight request.
#[derive(Debug)]
pub struct ClientProfileStore<T> {
current: RwLock<Arc<T>>,
}
impl<T> ClientProfileStore<T> {
pub fn new(profile: T) -> Self {
Self {
current: RwLock::new(Arc::new(profile)),
}
}
pub fn snapshot(&self) -> Arc<T> {
self.current
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
pub fn publish(&self, profile: T) -> Arc<T> {
let mut current = self
.current
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
std::mem::replace(&mut *current, Arc::new(profile))
}
}
/// Constructors validate wire safety; release adapters separately validate
/// official stable semantic versions before publishing them.
pub fn validate_client_version(version: &str) -> Result<&str, &'static str> {
let version = version.trim();
if version.is_empty() || version.len() > 64 || !version.bytes().all(|b| (33..=126).contains(&b))
{
return Err("invalid client version");
}
Ok(version)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn publishing_does_not_mutate_inflight_snapshots() {
let store = ClientProfileStore::new(("1.0.0", "client/1.0.0"));
let inflight = store.snapshot();
let old = store.publish(("1.1.0", "client/1.1.0"));
assert_eq!(inflight, old);
assert_eq!(inflight.0, "1.0.0");
assert_eq!(store.snapshot().1, "client/1.1.0");
}
#[test]
fn rejects_header_injection_and_oversized_versions() {
for version in ["", "1.0\r\nx: y", "1.0 0", "é"] {
assert!(validate_client_version(version).is_err());
}
assert!(validate_client_version(&"1".repeat(65)).is_err());
assert_eq!(validate_client_version(" 1.0.0 ").unwrap(), "1.0.0");
}
}
+8 -12
View File
@@ -1,4 +1,6 @@
use std::sync::{LazyLock, OnceLock, RwLock};
use std::sync::{LazyLock, OnceLock};
use crate::client_profile::ClientProfileStore;
static OS_INFO: LazyLock<os_info::Info> = LazyLock::new(os_info::get);
@@ -59,26 +61,20 @@ impl Default for CodexClientProfile {
}
}
static ACTIVE_PROFILE: OnceLock<RwLock<CodexClientProfile>> = OnceLock::new();
static ACTIVE_PROFILE: OnceLock<ClientProfileStore<CodexClientProfile>> = OnceLock::new();
fn active_profile() -> &'static RwLock<CodexClientProfile> {
ACTIVE_PROFILE.get_or_init(|| RwLock::new(CodexClientProfile::default()))
fn active_profile() -> &'static ClientProfileStore<CodexClientProfile> {
ACTIVE_PROFILE.get_or_init(|| ClientProfileStore::new(CodexClientProfile::default()))
}
/// 返回当前画像的独立快照,调用方不会持有全局锁。
pub fn codex_client_profile() -> CodexClientProfile {
active_profile()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
(*active_profile().snapshot()).clone()
}
/// 原子替换当前画像,并返回替换前的画像。
pub fn set_codex_client_profile(profile: CodexClientProfile) -> CodexClientProfile {
let mut current = active_profile()
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
std::mem::replace(&mut *current, profile)
(*active_profile().publish(profile)).clone()
}
/// 发布一份新的 CLI 画像。
+1
View File
@@ -1,6 +1,7 @@
extern crate self as aether_ai_formats;
pub mod api;
pub mod client_profile;
pub mod codex_profile;
pub mod contracts;
pub mod formats;
+22 -7
View File
@@ -27,8 +27,6 @@ use crate::{
build_models_fetch_url_for_client_version, deepseek_anthropic_models_fetch_uses_openai_auth,
};
const CLAUDE_CLI_USER_AGENT: &str = "claude-code/1.0.1";
const GEMINI_CLI_USER_AGENT: &str = "GeminiCLI/0.1.5 (Windows; AMD64)";
const CLAUDE_VERSION_HEADER: &str = "2023-06-01";
const ANTIGRAVITY_FETCH_PROVIDER_API_FORMAT: &str = "antigravity:fetch_available_models";
const ANTIGRAVITY_LOAD_CODE_ASSIST_PROVIDER_API_FORMAT: &str = "antigravity:load_code_assist";
@@ -37,7 +35,7 @@ const KIRO_LIST_AVAILABLE_MODELS_PROVIDER_API_FORMAT: &str = "kiro:list_availabl
const WINDSURF_MODEL_CONFIGS_PROVIDER_API_FORMAT: &str = "windsurf:model_configs";
const WINDSURF_MODEL_CONFIGS_PATH: &str =
"/exa.api_server_pb.ApiServerService/GetCascadeModelConfigs";
const WINDSURF_IDE_VERSION: &str = "1.9600.41";
const WINDSURF_IDE_VERSION: &str = aether_provider_transport::client_identity::WINDSURF.version;
const BROWSER_FINGERPRINT_HEADERS: &[(&str, &str)] = &[
(
@@ -319,7 +317,10 @@ pub async fn build_gemini_cli_load_code_assist_plan(
.ok_or_else(|| "GeminiCLI loadCodeAssist requires bearer or OAuth auth".to_string())?;
let mut headers = BTreeMap::from([
("user-agent".to_string(), GEMINI_CLI_USER_AGENT.to_string()),
(
"user-agent".to_string(),
aether_provider_transport::gemini_cli::gemini_cli_client_user_agent(),
),
("accept-encoding".to_string(), "identity".to_string()),
("content-type".to_string(), "application/json".to_string()),
]);
@@ -662,8 +663,19 @@ fn standard_models_fetch_headers(
"anthropic-version".to_string(),
CLAUDE_VERSION_HEADER.to_string(),
)]);
if matches!(provider_type.as_str(), "claude_code" | "kiro") {
headers.insert("user-agent".to_string(), CLAUDE_CLI_USER_AGENT.to_string());
if provider_type == "claude_code" {
headers.insert(
"user-agent".to_string(),
aether_provider_transport::claude_code::claude_code_client_profile()
.user_agent
.clone(),
);
} else if provider_type == "kiro" {
headers.insert(
"user-agent".to_string(),
aether_provider_transport::client_identity::KIRO_MODELS_LEGACY_USER_AGENT
.to_string(),
);
}
headers
}
@@ -673,7 +685,10 @@ fn standard_models_fetch_headers(
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<BTreeMap<_, _>>();
if provider_type == "gemini_cli" {
headers.insert("user-agent".to_string(), GEMINI_CLI_USER_AGENT.to_string());
headers.insert(
"user-agent".to_string(),
aether_provider_transport::gemini_cli::gemini_cli_client_user_agent(),
);
}
headers
}
@@ -20,11 +20,10 @@ use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
pub const CHATGPT_WEB_DEFAULT_BASE_URL: &str = "https://chatgpt.com";
pub const CHATGPT_WEB_CONVERSATION_INIT_PATH: &str = "/backend-api/conversation/init";
const CHATGPT_WEB_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0";
const CHATGPT_WEB_CLIENT_VERSION: &str = "prod-be885abbfcfe7b1f511e88b3003d9ee44757fbad";
const CHATGPT_WEB_BUILD_NUMBER: &str = "5955942";
const CHATGPT_WEB_SEC_CH_UA: &str =
r#""Microsoft Edge";v="143", "Chromium";v="143", "Not A(Brand";v="24""#;
use aether_provider_transport::client_identity::{
CHATGPT_WEB_BUILD_NUMBER, CHATGPT_WEB_CLIENT_VERSION, CHATGPT_WEB_SEC_CH_UA,
CHATGPT_WEB_USER_AGENT,
};
#[derive(Debug, Clone, Default)]
pub struct ChatGptWebProviderPoolAdapter;
@@ -10,7 +10,7 @@ use crate::provider::{
use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
pub const GEMINI_CLI_RETRIEVE_USER_QUOTA_PATH: &str = "/v1internal:retrieveUserQuota";
pub const GEMINI_CLI_USER_AGENT: &str = "GeminiCLI/0.1.5 (Windows; AMD64)";
pub use aether_provider_transport::gemini_cli::GEMINI_CLI_USER_AGENT;
#[derive(Debug, Clone, Default)]
pub struct GeminiCliProviderPoolAdapter;
@@ -52,7 +52,10 @@ pub fn build_gemini_cli_pool_quota_request(
("authorization".to_string(), authorization.1),
("content-type".to_string(), "application/json".to_string()),
("accept".to_string(), "application/json".to_string()),
("user-agent".to_string(), GEMINI_CLI_USER_AGENT.to_string()),
(
"user-agent".to_string(),
aether_provider_transport::gemini_cli::gemini_cli_client_user_agent(),
),
]);
ProviderPoolQuotaRequestSpec {
@@ -158,7 +158,7 @@ fn normalize_region(value: &str) -> &str {
fn normalize_kiro_version(value: &str) -> &str {
let value = value.trim();
if value.is_empty() {
"0.3.210"
aether_provider_transport::client_identity::DEFAULT_KIRO_VERSION
} else {
value
}
@@ -177,7 +177,12 @@ fn build_windsurf_connect_rpc_request(
headers.insert("content-type".to_string(), "application/json".to_string());
headers.insert("accept".to_string(), "application/json".to_string());
headers.insert("connect-protocol-version".to_string(), "1".to_string());
headers.insert("user-agent".to_string(), "windsurf/1.9600.41".to_string());
headers.insert(
"user-agent".to_string(),
aether_provider_transport::client_identity::WINDSURF
.user_agent
.to_string(),
);
ProviderPoolQuotaRequestSpec {
request_id,
@@ -200,9 +205,9 @@ fn windsurf_metadata(api_key: &str) -> Value {
json!({
"apiKey": api_key,
"ideName": "windsurf",
"ideVersion": "1.9600.41",
"ideVersion": aether_provider_transport::client_identity::WINDSURF.version,
"extensionName": "windsurf",
"extensionVersion": "1.9600.41",
"extensionVersion": aether_provider_transport::client_identity::WINDSURF.version,
"locale": "en",
})
}
@@ -769,6 +769,7 @@ async fn register_codex_agent_identity_from_access_token_with_auth_api_base_url(
.map_err(|_| CodexAgentIdentityEnrollmentError::KeyGenerationFailed)?;
let agent_private_key = STANDARD.encode(private_key_der.as_bytes());
let agent_public_key = agent_identity_ssh_public_key(&signing_key);
let client_profile = aether_ai_formats::codex_client_profile();
let registration_url = agent_registration_url(auth_api_base_url)
.map_err(|_| CodexAgentIdentityEnrollmentError::RegistrationRequestFailed)?;
let mut headers = BTreeMap::from([
@@ -778,14 +779,8 @@ async fn register_codex_agent_identity_from_access_token_with_auth_api_base_url(
"authorization".to_string(),
format!("Bearer {access_token}"),
),
(
"user-agent".to_string(),
aether_ai_formats::codex_client_user_agent(),
),
(
"originator".to_string(),
aether_ai_formats::codex_client_originator(),
),
("user-agent".to_string(), client_profile.user_agent.clone()),
("originator".to_string(), client_profile.originator.clone()),
]);
if options.is_fedramp_account {
headers.insert("x-openai-fedramp".to_string(), "true".to_string());
@@ -799,7 +794,7 @@ async fn register_codex_agent_identity_from_access_token_with_auth_api_base_url(
content_type: Some("application/json".to_string()),
json_body: Some(json!({
"abom": {
"agent_version": aether_ai_formats::codex_client_version(),
"agent_version": client_profile.codex_version,
"agent_harness_id": CODEX_AGENT_IDENTITY_AGENT_HARNESS_ID,
"running_location": format!("cli-{}", std::env::consts::OS),
},
@@ -5,8 +5,8 @@ use serde_json::Value;
use super::super::snapshot::GatewayProviderTransportSnapshot;
pub const ANTIGRAVITY_PROVIDER_TYPE: &str = "antigravity";
pub const ANTIGRAVITY_CLIENT_VERSION: &str = "4.3.0";
pub const ANTIGRAVITY_REQUEST_USER_AGENT: &str = "vscode/1.X.X (Antigravity/4.3.0)";
pub const ANTIGRAVITY_CLIENT_VERSION: &str = crate::client_identity::ANTIGRAVITY.version;
pub const ANTIGRAVITY_REQUEST_USER_AGENT: &str = crate::client_identity::ANTIGRAVITY.user_agent;
const ANTIGRAVITY_CLIENT_NAME: &str = "antigravity";
const ANTIGRAVITY_GOOG_API_CLIENT: &str = "gl-node/18.18.2 fire/0.8.6 grpc/1.10.x";
@@ -28,7 +28,7 @@ pub use profile::{
CLAUDE_CODE_CONTEXT_MANAGEMENT_BETA, CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04,
};
pub use request::{
build_claude_code_passthrough_headers, sanitize_claude_code_request_body,
sanitize_claude_code_request_body_for_beta_header,
build_claude_code_passthrough_headers, finalize_claude_code_request_identity,
sanitize_claude_code_request_body, sanitize_claude_code_request_body_for_beta_header,
};
pub use url::build_claude_code_messages_url;
@@ -1,5 +1,7 @@
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, OnceLock, RwLock};
use std::sync::{Arc, OnceLock};
use aether_ai_formats::client_profile::ClientProfileStore;
use aether_ai_formats::ApiOperation;
@@ -94,28 +96,24 @@ impl Default for ClaudeCodeClientProfile {
}
}
static ACTIVE_CLIENT_PROFILE: OnceLock<RwLock<Arc<ClaudeCodeClientProfile>>> = OnceLock::new();
static ACTIVE_CLIENT_PROFILE: OnceLock<ClientProfileStore<ClaudeCodeClientProfile>> =
OnceLock::new();
fn active_client_profile() -> &'static RwLock<Arc<ClaudeCodeClientProfile>> {
ACTIVE_CLIENT_PROFILE.get_or_init(|| RwLock::new(Arc::new(ClaudeCodeClientProfile::default())))
fn active_client_profile() -> &'static ClientProfileStore<ClaudeCodeClientProfile> {
ACTIVE_CLIENT_PROFILE
.get_or_init(|| ClientProfileStore::new(ClaudeCodeClientProfile::default()))
}
/// Returns a snapshot of the active CLI profile without holding the global lock.
pub fn claude_code_client_profile() -> Arc<ClaudeCodeClientProfile> {
active_client_profile()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
active_client_profile().snapshot()
}
/// Atomically replaces the active CLI profile and returns the previous one.
pub fn set_claude_code_client_profile(
profile: ClaudeCodeClientProfile,
) -> Arc<ClaudeCodeClientProfile> {
let mut current = active_client_profile()
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
std::mem::replace(&mut *current, Arc::new(profile))
active_client_profile().publish(profile)
}
/// Publishes a CLI profile for the given release version.
@@ -310,8 +308,13 @@ impl ClaudeCodeTransportIdentityProfile {
("x-stainless-retry-count", template.stainless_retry_count),
("x-stainless-timeout", template.stainless_timeout),
] {
headers.retain(|existing, _| !existing.eq_ignore_ascii_case(name));
headers.insert(name.to_string(), value.to_string());
}
headers.retain(|name, _| {
!name.eq_ignore_ascii_case("user-agent")
&& !name.eq_ignore_ascii_case("x-stainless-helper-method")
});
headers.insert("user-agent".to_string(), self.user_agent().to_string());
if stream {
headers.insert(
@@ -328,8 +331,14 @@ impl ClaudeCodeTransportIdentityProfile {
headers: &mut BTreeMap<String, String>,
operation: Option<ApiOperation>,
) {
let incoming = headers.get("anthropic-beta").map(String::as_str);
let merged = self.merge_beta_tokens(incoming, operation);
let incoming = headers
.iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("anthropic-beta"))
.map(|(_, value)| value.as_str())
.collect::<Vec<_>>()
.join(",");
let merged = self.merge_beta_tokens(Some(&incoming), operation);
headers.retain(|name, _| !name.eq_ignore_ascii_case("anthropic-beta"));
if merged.is_empty() {
headers.remove("anthropic-beta");
} else {
@@ -56,6 +56,33 @@ pub fn build_claude_code_passthrough_headers(
out
}
/// Reconcile header/body identity using one immutable profile at the common
/// outbound boundary. Preserve the planner's content negotiation and count-token contract.
pub fn finalize_claude_code_request_identity(
headers: &mut BTreeMap<String, String>,
body: &mut Value,
profile: &ClaudeCodeTransportIdentityProfile,
operation: Option<aether_ai_formats::ApiOperation>,
) {
let accept = headers.get("accept").cloned();
let stream = body.get("stream").and_then(Value::as_bool).unwrap_or(false)
|| accept
.as_deref()
.is_some_and(|v| v.contains("text/event-stream"));
profile.apply_fixed_headers(headers, stream);
if stream {
crate::headers::force_identity_accept_encoding(headers);
}
profile.apply_beta_policy(headers, operation);
if let Some(accept) = accept {
headers.insert("accept".to_string(), accept);
}
if operation != Some(aether_ai_formats::ApiOperation::ClaudeCountTokens) {
let beta = headers.get("anthropic-beta").cloned().unwrap_or_default();
sanitize_claude_code_request_body_for_beta_header(body, &beta, profile);
}
}
pub fn sanitize_claude_code_request_body(body: &mut Value) {
let profile = current_claude_code_transport_identity_profile();
let beta_header = profile.merge_beta_tokens(None, None);
@@ -371,3 +398,55 @@ mod tests {
);
}
}
#[cfg(test)]
mod final_identity_tests {
use super::*;
use crate::claude_code::{ClaudeCodeClientProfile, CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04};
use std::sync::Arc;
fn profile() -> ClaudeCodeTransportIdentityProfile {
ClaudeCodeTransportIdentityProfile::new(
&CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04,
Arc::new(ClaudeCodeClientProfile::cli("2.1.286").unwrap()),
)
}
#[test]
fn terminal_snapshot_reconciles_billing_and_headers_without_changing_negotiation() {
let mut headers = BTreeMap::from([
("accept".into(), "text/event-stream".into()),
("User-Agent".into(), "old-client".into()),
("X-Stainless-Package-Version".into(), "old-sdk".into()),
("Anthropic-Beta".into(), "custom-beta".into()),
]);
let mut body = serde_json::json!({"stream":true, "system":[{"type":"text", "text":"x-anthropic-billing-header: cc_version=2.1.280.abc; cc_entrypoint=cli;"}]});
finalize_claude_code_request_identity(&mut headers, &mut body, &profile(), None);
assert_eq!(headers["user-agent"], "claude-cli/2.1.286 (external, cli)");
assert_eq!(headers["accept"], "text/event-stream");
assert_eq!(headers["accept-encoding"], "identity");
assert_eq!(headers["x-stainless-package-version"], "0.112.1");
assert!(!headers.contains_key("User-Agent"));
assert!(!headers.contains_key("X-Stainless-Package-Version"));
assert!(!headers.contains_key("Anthropic-Beta"));
assert!(headers["anthropic-beta"].contains("custom-beta"));
assert!(body["system"][0]["text"]
.as_str()
.unwrap()
.contains("cc_version=2.1.286.abc;"));
let before = body.clone();
finalize_claude_code_request_identity(&mut headers, &mut body, &profile(), None);
assert_eq!(body, before);
}
#[test]
fn count_token_body_remains_untouched() {
let mut headers = BTreeMap::new();
let mut body = serde_json::json!({"model":"claude-test", "messages":[], "thinking":{"type":"enabled"}});
let before = body.clone();
finalize_claude_code_request_identity(
&mut headers,
&mut body,
&profile(),
Some(aether_ai_formats::ApiOperation::ClaudeCountTokens),
);
assert_eq!(body, before);
assert_eq!(headers["user-agent"], "claude-cli/2.1.286 (external, cli)");
}
}
@@ -0,0 +1,65 @@
//! Provider wire templates. Dynamic CLI versions are independent of SDK and
//! browser fingerprints; pinned templates are changed only after verification.
use aether_ai_formats::client_profile::validate_client_version;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionedClientIdentity {
pub version: String,
pub user_agent: String,
}
impl VersionedClientIdentity {
pub fn new(version: &str, agent: &str, suffix: &str) -> Result<Self, &'static str> {
let version = validate_client_version(version)?;
Ok(Self {
version: version.to_owned(),
user_agent: format!("{agent}/{version}{suffix}"),
})
}
}
#[derive(Debug, Clone, Copy)]
pub struct PinnedClientIdentity {
pub version: &'static str,
pub user_agent: &'static str,
}
pub const GEMINI_CLI: PinnedClientIdentity = PinnedClientIdentity {
version: "0.1.5",
user_agent: "GeminiCLI/0.1.5 (Windows; AMD64)",
};
// Legacy standard-models fallback; dedicated Kiro requests use OAuth SDK identity.
pub const KIRO_MODELS_LEGACY_USER_AGENT: &str = "claude-code/1.0.1";
pub const ANTIGRAVITY: PinnedClientIdentity = PinnedClientIdentity {
version: "4.3.0",
user_agent: "vscode/1.X.X (Antigravity/4.3.0)",
};
pub const WINDSURF: PinnedClientIdentity = PinnedClientIdentity {
version: "1.9600.41",
user_agent: "windsurf/1.9600.41",
};
// Verified browser release tuple, shared by inference and quota requests.
// Do not update these independently or derive a web build from a CLI release.
pub const CHATGPT_WEB_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0";
pub const CHATGPT_WEB_CLIENT_VERSION: &str = "prod-be885abbfcfe7b1f511e88b3003d9ee44757fbad";
pub const CHATGPT_WEB_BUILD_NUMBER: &str = "5955942";
pub const CHATGPT_WEB_SEC_CH_UA: &str =
r#""Microsoft Edge";v="143", "Chromium";v="143", "Not A(Brand";v="24""#;
pub const CHATGPT_WEB_BROWSER_PROFILE: &str = "chrome143";
// Kiro authentication and request adapters already share the OAuth model.
pub use aether_oauth::provider::providers::{
DEFAULT_KIRO_VERSION, DEFAULT_NODE_VERSION, DEFAULT_SYSTEM_VERSION,
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pinned_headers_and_body_versions_are_calibrated_together() {
for identity in [ANTIGRAVITY, WINDSURF] {
assert!(identity.user_agent.contains(identity.version));
}
}
}
@@ -1,5 +1,9 @@
mod auth;
mod policy;
mod profile;
pub use profile::{
gemini_cli_client_user_agent, gemini_cli_client_version, set_gemini_cli_client_version,
};
mod request;
mod url;
@@ -0,0 +1,41 @@
use crate::client_identity::VersionedClientIdentity;
use aether_ai_formats::client_profile::ClientProfileStore;
use std::sync::OnceLock;
pub const GEMINI_CLI_BUILTIN_VERSION: &str = crate::client_identity::GEMINI_CLI.version;
// Keep the established template; a version release does not change platform identity.
fn identity(version: &str) -> Result<VersionedClientIdentity, &'static str> {
VersionedClientIdentity::new(version, "GeminiCLI", " (Windows; AMD64)")
}
static ACTIVE: OnceLock<ClientProfileStore<VersionedClientIdentity>> = OnceLock::new();
fn active() -> &'static ClientProfileStore<VersionedClientIdentity> {
ACTIVE.get_or_init(|| {
ClientProfileStore::new(
identity(GEMINI_CLI_BUILTIN_VERSION).expect("valid built-in Gemini identity"),
)
})
}
pub fn gemini_cli_client_version() -> String {
active().snapshot().version.clone()
}
pub fn gemini_cli_client_user_agent() -> String {
active().snapshot().user_agent.clone()
}
pub fn set_gemini_cli_client_version(version: &str) -> Result<String, &'static str> {
Ok(active().publish(identity(version)?).version.clone())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn version_updates_preserve_the_existing_platform_template() {
let profile = identity("0.62.0").unwrap();
assert_eq!(profile.user_agent, "GeminiCLI/0.62.0 (Windows; AMD64)");
assert!(identity("0.62.0\nx: y").is_err());
assert_eq!(
identity(GEMINI_CLI_BUILTIN_VERSION).unwrap().user_agent,
super::super::GEMINI_CLI_USER_AGENT
);
}
}
@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use url::form_urlencoded;
pub const GEMINI_CLI_USER_AGENT: &str = "GeminiCLI/0.1.5 (Windows; AMD64)";
pub const GEMINI_CLI_USER_AGENT: &str = crate::client_identity::GEMINI_CLI.user_agent;
pub const GEMINI_CLI_V1INTERNAL_PATH_TEMPLATE: &str = "/v1internal:{action}";
pub const GEMINI_CLI_RETRIEVE_USER_QUOTA_PATH: &str = "/v1internal:retrieveUserQuota";
@@ -81,7 +81,7 @@ pub fn should_skip_request_header(name: &str) -> bool {
}
fn is_untrusted_forwarding_metadata_header(normalized_name: &str) -> bool {
matches!(normalized_name, "forwarded" | "via")
matches!(normalized_name, "forwarded" | "via" | "x-envoy-internal")
|| normalized_name.starts_with("x-forwarded-")
|| normalized_name.starts_with("x_forwarded_")
|| normalized_name.starts_with("x-real-")
@@ -186,6 +186,7 @@ pub(crate) fn remove_declared_connection_headers(
));
headers.retain(|name, _| {
!name.eq_ignore_ascii_case("connection")
&& !name.eq_ignore_ascii_case("x-envoy-internal")
&& !is_declared_connection_header(name, &all_declared)
});
}
@@ -455,6 +456,7 @@ mod tests {
"X-Rewrite-URL",
"X-Override-URL",
"X-Envoy-Original-Path",
"X-Envoy-Internal",
] {
assert!(should_skip_request_header(header));
assert!(should_skip_upstream_passthrough_header(header));
@@ -5,6 +5,7 @@ pub mod auth;
mod auth_config;
mod cache;
pub mod claude_code;
pub mod client_identity;
mod codex_fingerprint;
pub mod conversion;
mod diagnostics;
@@ -199,6 +199,23 @@ pub fn apply_provider_outbound_request_policies(
provider_request_headers: &mut BTreeMap<String, String>,
provider_request_body: &mut Value,
) -> Vec<ProviderOutboundRequestPolicyResult> {
// This is the common boundary after planner rules and before transport.
provider_request_headers.retain(|name, _| !name.eq_ignore_ascii_case("x-envoy-internal"));
if transport
.provider
.provider_type
.trim()
.eq_ignore_ascii_case("claude_code")
&& aether_ai_formats::normalize_api_format_alias(provider_api_format) == "claude:messages"
{
let profile = crate::claude_code::current_claude_code_transport_identity_profile();
crate::claude_code::finalize_claude_code_request_identity(
provider_request_headers,
provider_request_body,
&profile,
context.api_operation(),
);
}
if !transport
.provider
.provider_type
@@ -23,7 +23,7 @@ pub mod proto;
pub const PROVIDER_TYPE: &str = "windsurf";
pub const WINDSURF_ENVELOPE_NAME: &str = "windsurf:GetChatMessage";
pub const GET_CHAT_MESSAGE_PATH: &str = "/exa.api_server_pb.ApiServerService/GetChatMessage";
const DEFAULT_IDE_VERSION: &str = "1.9600.41";
pub const DEFAULT_IDE_VERSION: &str = crate::client_identity::WINDSURF.version;
const PLACEHOLDER_API_KEY: &str = "__placeholder__";
pub fn is_windsurf_provider_transport(transport: &GatewayProviderTransportSnapshot) -> bool {
+19 -22
View File
@@ -1,7 +1,10 @@
pub mod video;
use std::collections::BTreeMap;
use std::sync::{OnceLock, RwLock};
use std::sync::OnceLock;
use crate::client_identity::VersionedClientIdentity;
use aether_ai_formats::client_profile::ClientProfileStore;
use aether_ai_formats::normalize_api_format_alias;
use serde_json::Value;
@@ -23,37 +26,31 @@ pub const XAI_CLIENT_IDENTIFIER_VALUE: &str = "grok-shell";
pub const XAI_AUTHENTICATE_RESPONSE_HEADER: &str = "x-authenticateresponse";
pub const XAI_AUTHENTICATE_RESPONSE_VALUE: &str = "authenticate-response";
static ACTIVE_CLIENT_VERSION: OnceLock<RwLock<String>> = OnceLock::new();
static ACTIVE_CLIENT_VERSION: OnceLock<ClientProfileStore<VersionedClientIdentity>> =
OnceLock::new();
fn active_client_version() -> &'static RwLock<String> {
ACTIVE_CLIENT_VERSION.get_or_init(|| RwLock::new(XAI_DEFAULT_CLIENT_VERSION.to_owned()))
fn active_client_version() -> &'static ClientProfileStore<VersionedClientIdentity> {
ACTIVE_CLIENT_VERSION.get_or_init(|| {
ClientProfileStore::new(
VersionedClientIdentity::new(XAI_DEFAULT_CLIENT_VERSION, "xai-grok-workspace", "")
.expect("valid built-in Grok identity"),
)
})
}
/// 返回当前发布的 Grok CLI 版本快照。
pub fn xai_client_version() -> String {
active_client_version()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
active_client_version().snapshot().version.clone()
}
/// 原子替换当前 Grok CLI 版本,返回替换前的版本;版本校验由发布检查器负责,这里只拒绝明显非法值。
/// 原子替换当前 Grok CLI 身份,返回替换前的版本。
pub fn set_xai_client_version(version: &str) -> Result<String, &'static str> {
let version = version.trim();
if version.is_empty()
|| version.len() > 64
|| !version.bytes().all(|byte| (33..=126).contains(&byte))
{
return Err("invalid Grok CLI version");
}
let mut current = active_client_version()
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
Ok(std::mem::replace(&mut *current, version.to_owned()))
let profile = VersionedClientIdentity::new(version, "xai-grok-workspace", "")?;
Ok(active_client_version().publish(profile).version.clone())
}
pub fn xai_cli_user_agent() -> String {
format!("xai-grok-workspace/{}", xai_client_version())
active_client_version().snapshot().user_agent.clone()
}
pub fn is_xai_provider_transport(transport: &GatewayProviderTransportSnapshot) -> bool {
@@ -125,7 +122,7 @@ pub fn should_attach_cli_identity_headers(
pub fn insert_cli_identity_headers(headers: &mut BTreeMap<String, String>) {
let client_version = xai_client_version();
let user_agent = xai_cli_user_agent();
let user_agent = format!("xai-grok-workspace/{client_version}");
for (name, value) in [
(XAI_TOKEN_AUTH_HEADER, XAI_TOKEN_AUTH_VALUE),
(XAI_CLIENT_VERSION_HEADER, client_version.as_str()),