11use std:: {
2+ env,
23 hash:: { DefaultHasher , Hash , Hasher } ,
34 mem,
45 sync:: LazyLock ,
@@ -11,9 +12,10 @@ use axum::{
1112} ;
1213use http:: HeaderMap ;
1314use serde_json:: { Value , json} ;
15+ use sha2:: { Digest , Sha256 } ;
1416
1517use 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
7173struct 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+
73142fn 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