Skip to content

Commit a4e5df3

Browse files
committed
feat: update dependencies and enhance user agent handling
1 parent 1a9640a commit a4e5df3

7 files changed

Lines changed: 157 additions & 24 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ snafu = { version = "0.8", features = ["futures", "rust_1_81"] }
7878
serde_with = { version = "3", features = ["chrono_0_4"] }
7979
oauth2 = { version = "5", default-features = false }
8080
ractor = "0.15"
81+
sha2 = "0.10"
8182
mimalloc = { version = "0.1", optional = true }
8283
dhat = { version = "0", optional = true }
8384
etcetera = { version = "0", optional = true }

‎src/claude_code_state/chat.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use wreq::Method;
1414

1515
use crate::{
1616
claude_code_state::{ClaudeCodeState, TokenStatus},
17-
config::{CLEWDR_CONFIG, Claude1mChannel, ModelFamily},
17+
config::{CLAUDE_CODE_USER_AGENT, CLEWDR_CONFIG, Claude1mChannel, ModelFamily},
1818
error::{CheckClaudeErr, ClewdrError, WreqSnafu},
1919
services::cookie_actor::CookieActorHandle,
2020
types::claude::{CountMessageTokensResponse, CreateMessageParams},
@@ -23,7 +23,6 @@ use crate::{
2323
pub(super) const CLAUDE_BETA_BASE: &str = "oauth-2025-04-20";
2424
const CLAUDE_BETA_CONTEXT_1M_TOKEN: &str = "context-1m-2025-08-07";
2525
const CLAUDE_USAGE_URL: &str = "https://api.anthropic.com/api/oauth/usage";
26-
const CLAUDE_CODE_USER_AGENT: &str = "claude-code/2.0.32";
2726
pub(super) const CLAUDE_API_VERSION: &str = "2023-06-01";
2827

2928
impl ClaudeCodeState {
@@ -190,6 +189,7 @@ impl ClaudeCodeState {
190189
.to_string(),
191190
)
192191
.bearer_auth(access_token)
192+
.header(USER_AGENT, CLAUDE_CODE_USER_AGENT)
193193
.header("anthropic-beta", beta_header)
194194
.header("anthropic-version", CLAUDE_API_VERSION)
195195
.json(body)
@@ -576,6 +576,7 @@ impl ClaudeCodeState {
576576
.to_string(),
577577
)
578578
.bearer_auth(access_token)
579+
.header(USER_AGENT, CLAUDE_CODE_USER_AGENT)
579580
.header("anthropic-beta", beta_header)
580581
.header("anthropic-version", CLAUDE_API_VERSION)
581582
.json(body)

‎src/claude_code_state/exchange.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,15 @@ use url::Url;
2020

2121
use crate::{
2222
claude_code_state::ClaudeCodeState,
23-
config::{CC_REDIRECT_URI, CC_TOKEN_URL, CLEWDR_CONFIG, CookieStatus, TokenInfo},
23+
config::{
24+
CC_REDIRECT_URI, CC_TOKEN_URL, CLAUDE_CODE_USER_AGENT, CLEWDR_CONFIG, CookieStatus,
25+
TokenInfo,
26+
},
2427
error::{CheckClaudeErr, ClewdrError, UnexpectedNoneSnafu, UrlSnafu, WreqSnafu},
2528
};
2629

2730
use super::chat::{CLAUDE_API_VERSION, CLAUDE_BETA_BASE};
2831

29-
const CLAUDE_CODE_USER_AGENT: &str = "claude-code/2.0.32";
30-
3132
type ClaudeOauthClient = Client<
3233
BasicErrorResponse,
3334
BasicTokenResponse,

‎src/claude_code_state/mod.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ mod exchange;
33
mod organization;
44
use http::{
55
HeaderValue, Method,
6-
header::{COOKIE, ORIGIN, REFERER},
6+
header::{COOKIE, ORIGIN, REFERER, USER_AGENT},
77
};
88
use snafu::ResultExt;
99
use tracing::error;
@@ -12,7 +12,7 @@ use wreq_util::Emulation;
1212

1313
use crate::{
1414
claude_web_state::SUPER_CLIENT,
15-
config::{CLAUDE_ENDPOINT, CLEWDR_CONFIG, CookieStatus, Reason},
15+
config::{CLAUDE_CODE_USER_AGENT, CLAUDE_ENDPOINT, CLEWDR_CONFIG, CookieStatus, Reason},
1616
error::{ClewdrError, WreqSnafu},
1717
middleware::claude::ClaudeApiFormat,
1818
services::cookie_actor::CookieActorHandle,
@@ -102,7 +102,8 @@ impl ClaudeCodeState {
102102
.client
103103
.request(method, url.to_string())
104104
.header(ORIGIN, CLAUDE_ENDPOINT)
105-
.header(REFERER, format!("{CLAUDE_ENDPOINT}new"));
105+
.header(REFERER, format!("{CLAUDE_ENDPOINT}new"))
106+
.header(USER_AGENT, CLAUDE_CODE_USER_AGENT);
106107
if !self.cookie_header_value.as_bytes().is_empty() {
107108
req = req.header(COOKIE, self.cookie_header_value.clone());
108109
}

‎src/config/constants.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ pub const GEMINI_ENDPOINT: &str = "https://generativelanguage.googleapis.com/";
1818
pub const CC_CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
1919
pub const CC_TOKEN_URL: &str = "https://api.anthropic.com/v1/oauth/token";
2020
pub const CC_REDIRECT_URI: &str = "https://console.anthropic.com/oauth/code/callback";
21+
pub const CLAUDE_CODE_VERSION: &str = "2.1.76";
22+
pub const CLAUDE_CODE_USER_AGENT: &str = "claude-code/2.1.76";
23+
pub const CLAUDE_CODE_BILLING_SALT: &str = "59cf53e54c78";
2124

2225
pub static ENDPOINT_URL: LazyLock<Url> = LazyLock::new(|| {
2326
Url::parse(CLAUDE_ENDPOINT).unwrap_or_else(|_| {

‎src/middleware/claude/request.rs‎

Lines changed: 141 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::{
2+
env,
23
hash::{DefaultHasher, Hash, Hasher},
34
mem,
45
sync::LazyLock,
@@ -11,9 +12,10 @@ use axum::{
1112
};
1213
use http::HeaderMap;
1314
use serde_json::{Value, json};
15+
use sha2::{Digest, Sha256};
1416

1517
use crate::{
16-
config::CLEWDR_CONFIG,
18+
config::{CLAUDE_CODE_BILLING_SALT, CLAUDE_CODE_VERSION, CLEWDR_CONFIG},
1719
error::ClewdrError,
1820
middleware::claude::{ClaudeApiFormat, ClaudeContext},
1921
types::{
@@ -70,6 +72,73 @@ static TEST_MESSAGE_OAI: LazyLock<Message> = LazyLock::new(|| Message::new_text(
7072

7173
struct NormalizeRequest(CreateMessageParams, ClaudeApiFormat);
7274

75+
const CLAUDE_CODE_ENTRYPOINT_ENV: &str = "CLAUDE_CODE_ENTRYPOINT";
76+
77+
fn prepend_system_blocks(body: &mut CreateMessageParams, blocks: Vec<ContentBlock>) {
78+
if blocks.is_empty() {
79+
return;
80+
}
81+
82+
let mut prefixed = blocks
83+
.into_iter()
84+
.map(|block| json!(block))
85+
.collect::<Vec<_>>();
86+
match body.system.take() {
87+
Some(Value::String(text)) if !text.trim().is_empty() => {
88+
prefixed.push(json!(ContentBlock::text(text)));
89+
}
90+
Some(Value::Array(mut systems)) => {
91+
prefixed.append(&mut systems);
92+
}
93+
Some(Value::Null) | None => {}
94+
Some(other) => prefixed.push(other),
95+
}
96+
body.system = Some(Value::Array(prefixed));
97+
}
98+
99+
fn first_user_message_text(messages: &[Message]) -> &str {
100+
messages
101+
.iter()
102+
.find(|message| message.role == Role::User)
103+
.and_then(|message| match &message.content {
104+
MessageContent::Text { content } => Some(content.as_str()),
105+
MessageContent::Blocks { content } => content.iter().find_map(|block| match block {
106+
ContentBlock::Text { text, .. } => Some(text.as_str()),
107+
_ => None,
108+
}),
109+
})
110+
.unwrap_or_default()
111+
}
112+
113+
fn sample_js_code_unit(text: &str, idx: usize) -> String {
114+
text.encode_utf16()
115+
.nth(idx)
116+
.map(|unit| String::from_utf16_lossy(&[unit]))
117+
.unwrap_or_else(|| "0".to_string())
118+
}
119+
120+
fn claude_code_billing_header(messages: &[Message]) -> String {
121+
let sampled = [4, 7, 20]
122+
.into_iter()
123+
.map(|idx| sample_js_code_unit(first_user_message_text(messages), idx))
124+
.collect::<String>();
125+
let version_hash = format!(
126+
"{:x}",
127+
Sha256::digest(format!(
128+
"{CLAUDE_CODE_BILLING_SALT}{sampled}{CLAUDE_CODE_VERSION}"
129+
))
130+
);
131+
let entrypoint = env::var(CLAUDE_CODE_ENTRYPOINT_ENV)
132+
.ok()
133+
.filter(|value| !value.trim().is_empty())
134+
.unwrap_or_else(|| "cli".to_string());
135+
136+
format!(
137+
"x-anthropic-billing-header: cc_version={CLAUDE_CODE_VERSION}.{}; cc_entrypoint={entrypoint}; cch=00000;",
138+
&version_hash[..3]
139+
)
140+
}
141+
73142
fn drop_empty_system(body: &mut CreateMessageParams) {
74143
let Some(system) = body.system.take() else {
75144
return;
@@ -278,8 +347,7 @@ where
278347
let anthropic_beta = extract_anthropic_beta_header(req.headers());
279348
let NormalizeRequest(mut body, format) = NormalizeRequest::from_request(req, &()).await?;
280349
// Handle thinking mode by modifying the model name
281-
if body.temperature.is_some()
282-
{
350+
if body.temperature.is_some() {
283351
body.top_p = None; // temperature and top_p cannot be used together in Opus-4.x
284352
}
285353

@@ -295,26 +363,18 @@ where
295363
// Determine streaming status and API format
296364
let stream = body.stream.unwrap_or_default();
297365

366+
let mut system_prefixes = vec![ContentBlock::text(claude_code_billing_header(
367+
&body.messages,
368+
))];
298369
if let Some(custom_system) = CLEWDR_CONFIG
299370
.load()
300371
.custom_system
301372
.clone()
302373
.filter(|s| !s.trim().is_empty())
303374
{
304-
let custom_system_block = ContentBlock::text(custom_system);
305-
match body.system {
306-
Some(Value::String(ref text)) => {
307-
let text_content = ContentBlock::text(text.to_owned());
308-
body.system = Some(json!([custom_system_block, text_content]));
309-
}
310-
Some(Value::Array(ref mut systems)) => {
311-
systems.insert(0, json!(custom_system_block));
312-
}
313-
_ => {
314-
body.system = Some(json!([custom_system_block]));
315-
}
316-
}
375+
system_prefixes.push(ContentBlock::text(custom_system));
317376
}
377+
prepend_system_blocks(&mut body, system_prefixes);
318378

319379
if let Some(system) = body.system.as_mut() {
320380
strip_ephemeral_scope_from_system(system);
@@ -353,3 +413,68 @@ where
353413
Ok(Self(body, ClaudeContext::Code(info)))
354414
}
355415
}
416+
417+
#[cfg(test)]
418+
mod tests {
419+
use super::*;
420+
421+
#[test]
422+
fn claude_code_billing_header_matches_2176_rule() {
423+
let messages = vec![Message::new_text(Role::User, "hey")];
424+
425+
assert_eq!(
426+
claude_code_billing_header(&messages),
427+
"x-anthropic-billing-header: cc_version=2.1.76.4dc; cc_entrypoint=cli; cch=00000;"
428+
);
429+
}
430+
431+
#[test]
432+
fn claude_code_billing_header_uses_first_text_block_of_first_user_message() {
433+
let messages = vec![
434+
Message::new_blocks(
435+
Role::User,
436+
vec![
437+
ContentBlock::Image {
438+
source: crate::types::claude::ImageSource::Url {
439+
url: "https://example.com/a.png".to_string(),
440+
},
441+
cache_control: None,
442+
},
443+
ContentBlock::text("abcdefg"),
444+
ContentBlock::text("ignored"),
445+
],
446+
),
447+
Message::new_text(Role::User, "later"),
448+
];
449+
450+
assert_eq!(
451+
claude_code_billing_header(&messages),
452+
"x-anthropic-billing-header: cc_version=2.1.76.540; cc_entrypoint=cli; cch=00000;"
453+
);
454+
}
455+
456+
#[test]
457+
fn prepend_system_blocks_keeps_billing_before_custom_system() {
458+
let mut body = CreateMessageParams {
459+
messages: vec![Message::new_text(Role::User, "hey")],
460+
model: "claude-sonnet-4-5".to_string(),
461+
system: Some(json!("original system")),
462+
..Default::default()
463+
};
464+
465+
prepend_system_blocks(
466+
&mut body,
467+
vec![
468+
ContentBlock::text("billing"),
469+
ContentBlock::text("custom system"),
470+
],
471+
);
472+
473+
let systems = body.system.unwrap().as_array().cloned().unwrap();
474+
let texts = systems
475+
.iter()
476+
.map(|value| value["text"].as_str().unwrap())
477+
.collect::<Vec<_>>();
478+
assert_eq!(texts, vec!["billing", "custom system", "original system"]);
479+
}
480+
}

0 commit comments

Comments
 (0)