feat(claude-code): 增加动态 CLI 客户端画像并按官方发布刷新版本

- 将 Claude Code 传输身份拆分为带版本的静态模板(Stainless/运行时/beta 策略)与动态 CLI 画像(cli_version / User-Agent),请求按快照读取保证 UA 与 billing cc_version 一致
- 将 codex_profile 泛化为 cli_client_profile,Codex 与 Claude Code 共享发布校验、缓存恢复、防回退与每日刷新逻辑
- Claude Code 跟随 npm latest,要求 8 个平台包版本与主包一致;支持 AETHER_CLAUDE_CODE_CLIENT_PROFILE_REFRESH 与 AETHER_CLAUDE_CODE_CLIENT_VERSION
- 新增定时任务 maintenance.claude_code.client.profile,启动时与 Codex 画像并发预热
- 额度查询 User-Agent 改用动态画像,移除硬编码 CLAUDE_CODE_USAGE_USER_AGENT
This commit is contained in:
dalamudx
2026-10-01 15:56:21 +08:00
parent 54fbcc25a1
commit d13f52bdf8
15 changed files with 975 additions and 556 deletions
@@ -11,7 +11,6 @@ use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
pub const CLAUDE_CODE_OAUTH_USAGE_URL: &str =
"https://api.anthropic.com/api/oauth/usage?cedar_ember=1&skip_spend=1";
pub const CLAUDE_CODE_OAUTH_BETA: &str = "oauth-2025-04-20";
pub const CLAUDE_CODE_USAGE_USER_AGENT: &str = "claude-cli/2.1.284 (external, cli)";
#[derive(Debug, Clone, Default)]
pub struct ClaudeCodeProviderPoolAdapter;
@@ -62,7 +61,7 @@ pub fn build_claude_code_pool_quota_request(
("x-app".to_string(), "cli".to_string()),
(
"user-agent".to_string(),
CLAUDE_CODE_USAGE_USER_AGENT.to_string(),
aether_provider_transport::claude_code::claude_code_client_user_agent(),
),
]);
@@ -24,7 +24,6 @@ pub use chatgpt_web::{
pub use claude_code::ClaudeCodeProviderPoolAdapter;
pub use claude_code::{
build_claude_code_pool_quota_request, CLAUDE_CODE_OAUTH_BETA, CLAUDE_CODE_OAUTH_USAGE_URL,
CLAUDE_CODE_USAGE_USER_AGENT,
};
pub use codex::CodexProviderPoolAdapter;
pub use codex::{
@@ -14,7 +14,7 @@ pub fn generate_fingerprint(seed: &str) -> Value {
}
fn generate_header_fingerprint(seed: &str) -> Value {
let profile = *current_claude_code_transport_identity_profile();
let profile = current_claude_code_transport_identity_profile();
let vscode_session_id = Uuid::new_v5(
&Uuid::NAMESPACE_URL,
format!("aether:fingerprint:{seed}").as_bytes(),
@@ -40,7 +40,7 @@ fn generate_header_fingerprint(seed: &str) -> Value {
}
fn wrap_header_fingerprint(header_fingerprint: Value) -> Value {
let profile = *current_claude_code_transport_identity_profile();
let profile = current_claude_code_transport_identity_profile();
serde_json::json!({
"transport_profile": {
"profile_id": profile.transport_profile_id(),
@@ -103,7 +103,7 @@ pub fn apply_claude_code_body_mimicry(
return false;
}
let profile = *current_claude_code_transport_identity_profile();
let profile = current_claude_code_transport_identity_profile();
let model = object
.get("model")
.and_then(Value::as_str)
@@ -20,8 +20,11 @@ pub use policy::{
supports_local_claude_code_transport_with_network,
};
pub use profile::{
current_claude_code_transport_identity_profile, ClaudeCodeBodyCapabilityGate,
claude_code_client_profile, claude_code_client_user_agent, claude_code_client_version,
current_claude_code_transport_identity_profile, set_claude_code_cli_version,
set_claude_code_client_profile, ClaudeCodeBodyCapabilityGate, ClaudeCodeClientProfile,
ClaudeCodeTransportIdentityProfile, ClaudeCodeTransportIdentityProfileVersion,
ClaudeCodeTransportIdentityTemplate, CLAUDE_CODE_BUILTIN_CLI_VERSION,
CLAUDE_CODE_CONTEXT_MANAGEMENT_BETA, CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04,
};
pub use request::{
@@ -1,9 +1,14 @@
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, OnceLock, RwLock};
use aether_ai_formats::ApiOperation;
pub const CLAUDE_CODE_CONTEXT_MANAGEMENT_BETA: &str = "context-management-2025-06-27";
/// Built-in Claude Code CLI version used until the gateway publishes a newer
/// verified release (or when release checks are disabled / unavailable).
pub const CLAUDE_CODE_BUILTIN_CLI_VERSION: &str = "2.1.284";
const MESSAGE_BETAS_2026_04: &[&str] = &[
"claude-code-20250219",
"oauth-2025-04-20",
@@ -53,15 +58,93 @@ pub struct ClaudeCodeBodyCapabilityGate {
pub default_edit_type: Option<&'static str>,
}
/// Versioned upstream identity used when Aether is intentionally acting as a
/// Claude Code transport. Native Anthropic transports never resolve this
/// profile and therefore keep their original headers and body untouched.
/// Dynamic Claude Code CLI identity (version-derived wire values).
///
/// The gateway refreshes this from verified official releases in a background
/// task; request paths only read an immutable snapshot and never touch the
/// network.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaudeCodeClientProfile {
pub cli_version: String,
pub user_agent: String,
}
impl ClaudeCodeClientProfile {
/// Builds a CLI profile from a release version. Release verification is owned
/// by the release checker; the constructor only rejects clearly invalid values.
pub fn cli(version: &str) -> Result<Self, &'static str> {
let version = version.trim();
if version.is_empty()
|| version.len() > 64
|| !version.bytes().all(|byte| (33..=126).contains(&byte))
{
return Err("invalid Claude Code CLI version");
}
Ok(Self {
cli_version: version.to_owned(),
user_agent: format!("claude-cli/{version} (external, cli)"),
})
}
}
impl Default for ClaudeCodeClientProfile {
fn default() -> Self {
Self::cli(CLAUDE_CODE_BUILTIN_CLI_VERSION)
.expect("built-in Claude Code CLI profile must be valid")
}
}
static ACTIVE_CLIENT_PROFILE: OnceLock<RwLock<Arc<ClaudeCodeClientProfile>>> = OnceLock::new();
fn active_client_profile() -> &'static RwLock<Arc<ClaudeCodeClientProfile>> {
ACTIVE_CLIENT_PROFILE.get_or_init(|| RwLock::new(Arc::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()
}
/// 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))
}
/// Publishes a CLI profile for the given release version.
pub fn set_claude_code_cli_version(
version: &str,
) -> Result<Arc<ClaudeCodeClientProfile>, &'static str> {
let profile = ClaudeCodeClientProfile::cli(version)?;
Ok(set_claude_code_client_profile(profile))
}
/// Returns the active Claude Code CLI version.
pub fn claude_code_client_version() -> String {
claude_code_client_profile().cli_version.clone()
}
/// Returns the active Claude Code CLI User-Agent.
pub fn claude_code_client_user_agent() -> String {
claude_code_client_profile().user_agent.clone()
}
/// Versioned, static part of the Claude Code transport identity: Stainless SDK
/// and runtime values, beta policy and body capability gates. These values are
/// calibrated together and change only with a new template version; the CLI
/// version itself is supplied by the dynamic [`ClaudeCodeClientProfile`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClaudeCodeTransportIdentityProfile {
pub struct ClaudeCodeTransportIdentityTemplate {
version: ClaudeCodeTransportIdentityProfileVersion,
transport_profile_id: &'static str,
anthropic_version: &'static str,
cli_version: &'static str,
stainless_lang: &'static str,
stainless_package_version: &'static str,
stainless_os: &'static str,
@@ -77,12 +160,11 @@ pub struct ClaudeCodeTransportIdentityProfile {
body_capability_gates: &'static [ClaudeCodeBodyCapabilityGate],
}
pub const CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04: ClaudeCodeTransportIdentityProfile =
ClaudeCodeTransportIdentityProfile {
pub const CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04: ClaudeCodeTransportIdentityTemplate =
ClaudeCodeTransportIdentityTemplate {
version: ClaudeCodeTransportIdentityProfileVersion::V2026_04,
transport_profile_id: "claude_code_nodejs",
anthropic_version: "2023-06-01",
cli_version: "2.1.284",
stainless_lang: "js",
stainless_package_version: "0.112.1",
stainless_os: "Linux",
@@ -98,115 +180,139 @@ pub const CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04: ClaudeCodeTransportIdentityPro
body_capability_gates: BODY_CAPABILITY_GATES_2026_04,
};
pub const fn current_claude_code_transport_identity_profile(
) -> &'static ClaudeCodeTransportIdentityProfile {
&CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04
/// Upstream identity used when Aether is intentionally acting as a Claude Code
/// transport. Native Anthropic transports never resolve this profile and
/// therefore keep their original headers and body untouched.
///
/// Each value is one coherent snapshot of the static template plus the active
/// CLI profile, so headers and billing attribution derived from the same
/// snapshot always agree on the CLI version.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClaudeCodeTransportIdentityProfile {
template: &'static ClaudeCodeTransportIdentityTemplate,
client: Arc<ClaudeCodeClientProfile>,
}
pub fn current_claude_code_transport_identity_profile() -> ClaudeCodeTransportIdentityProfile {
ClaudeCodeTransportIdentityProfile::new(
&CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04,
claude_code_client_profile(),
)
}
impl ClaudeCodeTransportIdentityProfile {
pub const fn version(self) -> ClaudeCodeTransportIdentityProfileVersion {
self.version
pub fn new(
template: &'static ClaudeCodeTransportIdentityTemplate,
client: Arc<ClaudeCodeClientProfile>,
) -> Self {
Self { template, client }
}
pub const fn transport_profile_id(self) -> &'static str {
self.transport_profile_id
pub fn version(&self) -> ClaudeCodeTransportIdentityProfileVersion {
self.template.version
}
pub const fn cli_version(self) -> &'static str {
self.cli_version
pub fn transport_profile_id(&self) -> &'static str {
self.template.transport_profile_id
}
pub const fn billing_cli_version(self) -> &'static str {
self.cli_version
pub fn cli_version(&self) -> &str {
&self.client.cli_version
}
pub fn user_agent(self) -> String {
format!("claude-cli/{} (external, cli)", self.cli_version)
pub fn billing_cli_version(&self) -> &str {
&self.client.cli_version
}
pub const fn stainless_package_version(self) -> &'static str {
self.stainless_package_version
pub fn user_agent(&self) -> &str {
&self.client.user_agent
}
pub const fn stainless_lang(self) -> &'static str {
self.stainless_lang
pub fn stainless_package_version(&self) -> &'static str {
self.template.stainless_package_version
}
pub const fn stainless_os(self) -> &'static str {
self.stainless_os
pub fn stainless_lang(&self) -> &'static str {
self.template.stainless_lang
}
pub const fn stainless_arch(self) -> &'static str {
self.stainless_arch
pub fn stainless_os(&self) -> &'static str {
self.template.stainless_os
}
pub const fn stainless_runtime(self) -> &'static str {
self.stainless_runtime
pub fn stainless_arch(&self) -> &'static str {
self.template.stainless_arch
}
pub const fn stainless_runtime_version(self) -> &'static str {
self.stainless_runtime_version
pub fn stainless_runtime(&self) -> &'static str {
self.template.stainless_runtime
}
pub const fn stainless_retry_count(self) -> &'static str {
self.stainless_retry_count
pub fn stainless_runtime_version(&self) -> &'static str {
self.template.stainless_runtime_version
}
pub const fn stainless_timeout(self) -> &'static str {
self.stainless_timeout
pub fn stainless_retry_count(&self) -> &'static str {
self.template.stainless_retry_count
}
pub fn required_beta_tokens(self, operation: Option<ApiOperation>) -> &'static [&'static str] {
pub fn stainless_timeout(&self) -> &'static str {
self.template.stainless_timeout
}
pub fn required_beta_tokens(&self, operation: Option<ApiOperation>) -> &'static [&'static str] {
if operation == Some(ApiOperation::ClaudeCountTokens) {
self.count_tokens_required_betas
self.template.count_tokens_required_betas
} else {
self.message_required_betas
self.template.message_required_betas
}
}
pub const fn preserves_incoming_betas(self) -> bool {
self.preserve_incoming_betas
pub fn preserves_incoming_betas(&self) -> bool {
self.template.preserve_incoming_betas
}
pub const fn dropped_beta_tokens(self) -> &'static [&'static str] {
self.dropped_betas
pub fn dropped_beta_tokens(&self) -> &'static [&'static str] {
self.template.dropped_betas
}
pub const fn body_capability_gates(self) -> &'static [ClaudeCodeBodyCapabilityGate] {
self.body_capability_gates
pub fn body_capability_gates(&self) -> &'static [ClaudeCodeBodyCapabilityGate] {
self.template.body_capability_gates
}
pub fn body_capability_gate(self, field: &str) -> Option<ClaudeCodeBodyCapabilityGate> {
self.body_capability_gates
pub fn body_capability_gate(&self, field: &str) -> Option<ClaudeCodeBodyCapabilityGate> {
self.template
.body_capability_gates
.iter()
.copied()
.find(|gate| gate.body_field == field)
}
pub fn apply_fixed_headers(self, headers: &mut BTreeMap<String, String>, stream: bool) {
pub fn apply_fixed_headers(&self, headers: &mut BTreeMap<String, String>, stream: bool) {
let template = self.template;
for (name, value) in [
("accept", "application/json"),
("anthropic-version", self.anthropic_version),
("anthropic-version", template.anthropic_version),
("anthropic-dangerous-direct-browser-access", "true"),
("x-app", "cli"),
("x-stainless-lang", self.stainless_lang),
("x-stainless-lang", template.stainless_lang),
(
"x-stainless-package-version",
self.stainless_package_version,
template.stainless_package_version,
),
("x-stainless-os", self.stainless_os),
("x-stainless-arch", self.stainless_arch),
("x-stainless-runtime", self.stainless_runtime),
("x-stainless-os", template.stainless_os),
("x-stainless-arch", template.stainless_arch),
("x-stainless-runtime", template.stainless_runtime),
(
"x-stainless-runtime-version",
self.stainless_runtime_version,
template.stainless_runtime_version,
),
("x-stainless-retry-count", self.stainless_retry_count),
("x-stainless-timeout", self.stainless_timeout),
("x-stainless-retry-count", template.stainless_retry_count),
("x-stainless-timeout", template.stainless_timeout),
] {
headers.insert(name.to_string(), value.to_string());
}
headers.insert("user-agent".to_string(), self.user_agent());
headers.insert("user-agent".to_string(), self.user_agent().to_string());
if stream {
headers.insert(
"x-stainless-helper-method".to_string(),
@@ -218,7 +324,7 @@ impl ClaudeCodeTransportIdentityProfile {
}
pub fn apply_beta_policy(
self,
&self,
headers: &mut BTreeMap<String, String>,
operation: Option<ApiOperation>,
) {
@@ -232,7 +338,7 @@ impl ClaudeCodeTransportIdentityProfile {
}
pub fn merge_beta_tokens(
self,
&self,
incoming: Option<&str>,
operation: Option<ApiOperation>,
) -> String {
@@ -242,7 +348,7 @@ impl ClaudeCodeTransportIdentityProfile {
for token in self.required_beta_tokens(operation) {
self.append_beta_token(&mut seen, &mut merged, token);
}
if self.preserve_incoming_betas {
if self.template.preserve_incoming_betas {
for token in incoming.unwrap_or_default().split(',') {
self.append_beta_token(&mut seen, &mut merged, token);
}
@@ -250,7 +356,7 @@ impl ClaudeCodeTransportIdentityProfile {
merged.join(",")
}
pub fn beta_header_enables_body_field(self, beta_header: &str, field: &str) -> bool {
pub fn beta_header_enables_body_field(&self, beta_header: &str, field: &str) -> bool {
let Some(gate) = self.body_capability_gate(field) else {
return true;
};
@@ -260,10 +366,16 @@ impl ClaudeCodeTransportIdentityProfile {
.any(|token| token.eq_ignore_ascii_case(gate.beta_token))
}
fn append_beta_token(self, seen: &mut BTreeSet<String>, merged: &mut Vec<String>, token: &str) {
fn append_beta_token(
&self,
seen: &mut BTreeSet<String>,
merged: &mut Vec<String>,
token: &str,
) {
let token = token.trim();
if token.is_empty()
|| self
.template
.dropped_betas
.iter()
.any(|dropped| token.eq_ignore_ascii_case(dropped))
@@ -278,12 +390,17 @@ impl ClaudeCodeTransportIdentityProfile {
#[cfg(test)]
mod tests {
use super::current_claude_code_transport_identity_profile;
use std::sync::Arc;
use super::{
current_claude_code_transport_identity_profile, ClaudeCodeClientProfile,
ClaudeCodeTransportIdentityProfile, CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04,
};
use aether_ai_formats::ApiOperation;
#[test]
fn profile_versions_cli_user_agent_stainless_and_billing_together() {
let profile = *current_claude_code_transport_identity_profile();
let profile = current_claude_code_transport_identity_profile();
assert_eq!(profile.version().as_str(), "2026-04");
assert_eq!(profile.cli_version(), "2.1.284");
@@ -296,9 +413,43 @@ mod tests {
assert_eq!(profile.stainless_runtime_version(), "v26.3.0");
}
#[test]
fn cli_profile_derives_wire_identity_from_version() {
let client = ClaudeCodeClientProfile::cli(" 2.1.300 ").expect("valid version");
assert_eq!(client.cli_version, "2.1.300");
assert_eq!(client.user_agent, "claude-cli/2.1.300 (external, cli)");
// A snapshot keeps headers and billing attribution on the same CLI version
// without mutating the process-wide active profile.
let profile = ClaudeCodeTransportIdentityProfile::new(
&CLAUDE_CODE_TRANSPORT_IDENTITY_2026_04,
Arc::new(client),
);
let mut headers = std::collections::BTreeMap::new();
profile.apply_fixed_headers(&mut headers, false);
assert_eq!(
headers.get("user-agent").map(String::as_str),
Some("claude-cli/2.1.300 (external, cli)")
);
assert_eq!(profile.billing_cli_version(), "2.1.300");
assert_eq!(
headers
.get("x-stainless-package-version")
.map(String::as_str),
Some("0.112.1")
);
}
#[test]
fn cli_profile_rejects_empty_or_control_values() {
assert!(ClaudeCodeClientProfile::cli("").is_err());
assert!(ClaudeCodeClientProfile::cli("2.1.0\nspoof").is_err());
assert!(ClaudeCodeClientProfile::cli("2.1.0 spoof").is_err());
}
#[test]
fn profile_preserves_context_1m_and_adds_operation_specific_betas() {
let profile = *current_claude_code_transport_identity_profile();
let profile = current_claude_code_transport_identity_profile();
let messages = profile.merge_beta_tokens(Some("context-1m-2025-08-07,custom"), None);
assert!(messages
@@ -49,7 +49,7 @@ pub fn build_claude_code_passthrough_headers(
out.insert("anthropic-beta".to_string(), incoming_beta_values.join(","));
}
let profile = *current_claude_code_transport_identity_profile();
let profile = current_claude_code_transport_identity_profile();
profile.apply_fixed_headers(&mut out, stream);
profile.apply_beta_policy(&mut out, None);
@@ -57,15 +57,15 @@ pub fn build_claude_code_passthrough_headers(
}
pub fn sanitize_claude_code_request_body(body: &mut Value) {
let profile = *current_claude_code_transport_identity_profile();
let profile = current_claude_code_transport_identity_profile();
let beta_header = profile.merge_beta_tokens(None, None);
sanitize_claude_code_request_body_for_beta_header(body, &beta_header, profile);
sanitize_claude_code_request_body_for_beta_header(body, &beta_header, &profile);
}
pub fn sanitize_claude_code_request_body_for_beta_header(
body: &mut Value,
beta_header: &str,
profile: ClaudeCodeTransportIdentityProfile,
profile: &ClaudeCodeTransportIdentityProfile,
) {
let Some(body_object) = body.as_object_mut() else {
return;
@@ -303,7 +303,7 @@ mod tests {
#[test]
fn context_management_body_is_gated_by_the_matching_beta_token() {
let profile = *current_claude_code_transport_identity_profile();
let profile = current_claude_code_transport_identity_profile();
let original = json!({
"context_management": {
"edits": [{"type":"clear_thinking_20251015", "keep":"all"}]
@@ -315,7 +315,7 @@ mod tests {
sanitize_claude_code_request_body_for_beta_header(
&mut without_beta,
"oauth-2025-04-20",
profile,
&profile,
);
assert!(without_beta.get("context_management").is_none());
@@ -323,7 +323,7 @@ mod tests {
sanitize_claude_code_request_body_for_beta_header(
&mut with_beta,
"oauth-2025-04-20, context-management-2025-06-27",
profile,
&profile,
);
assert_eq!(with_beta, original);
}
@@ -177,7 +177,7 @@ fn resolve_claude_code_transport_profile(
return None;
}
let identity_profile = *current_claude_code_transport_identity_profile();
let identity_profile = current_claude_code_transport_identity_profile();
Some(ResolvedTransportProfile {
profile_id: identity_profile.transport_profile_id().to_string(),
backend: TRANSPORT_BACKEND_REQWEST_RUSTLS.to_string(),
@@ -812,7 +812,7 @@ pub fn build_same_format_provider_headers(
} else {
replace_upstream_auth_headers(&mut provider_request_headers, "", "");
}
let claude_code_profile = *current_claude_code_transport_identity_profile();
let claude_code_profile = current_claude_code_transport_identity_profile();
if input.behavior.is_claude_code_transport {
claude_code_profile.apply_fixed_headers(
&mut provider_request_headers,