
    5iO(              	          d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
  e         G d d      Zedk(  r ed	        ed
        ed	       	  e       Z ed       ej                         r	 ed       n ed        ed        ed       ej#                  d      Z eded            eded   dd  d        ed eed                  eed         D ]  \  ZZ ededz    dedd  d         ed        ed	       yy# e$ r*Z ede        ddlZ ej4                          Y dZ[4dZ[ww xY w)a\  
Grok Direct API Provider - Bypass Cloudflare using x-statsig-id token.

This provider makes direct HTTP requests to Grok's internal API without browser automation.
Requires: curl_cffi, x-statsig-id token from browser session.

Usage:
    provider = GrokDirectProvider()
    result = provider.generate_image("a beautiful sunset")
    print(result)
    N)Optional)load_dotenv)requestsc            	       t    e Zd ZdZdZd ZdefdZ	 	 ddede	de	defd	Z
	 	 ddedee   de	defdZdefdZy
)GrokDirectProviderzPDirect API provider for Grok using curl_cffi with TLS fingerprint impersonation.https://grok.comc                    t        j                  d      | _        t        j                  d      | _        t        j                  d      | _        t        j                  d      | _        t        | j                  | j                  | j                  g      st        d      | j
                  st        d      | j                  | j                  | j                  d| _        y )NGROK_SSO_TOKENGROK_SSO_RW_TOKENGROK_USER_IDGROK_STATSIG_IDzBMissing GROK_SSO_TOKEN, GROK_SSO_RW_TOKEN, or GROK_USER_ID in .envul   Missing GROK_STATSIG_ID in .env. Capture this from browser DevTools → Network → any POST request headers)ssozsso-rwzx-userid)	osgetenv	sso_tokensso_rw_tokenuser_id
statsig_idall
ValueErrorcookiesselfs    G/root/.openclaw/workspace/visionaryfx/providers/grok_direct_provider.py__init__zGrokDirectProvider.__init__   s    #34II&9:yy0))$56DNND$5$5t||DEabb^  >>''
    returnc                 n    t        t        j                               | j                  ddddddddd	d
dddS )z(Build request headers with x-statsig-id.z"Linux"zhttps://grok.com/z@"Not(A:Brand";v="8", "Chromium";v="144", "Google Chrome";v="144"z?0zeMozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36zapplication/jsonz*/*r   zsame-origincorsemptyzen-US,en;q=0.9)zx-xai-request-idzx-statsig-idzsec-ch-ua-platformrefererz	sec-ch-uazsec-ch-ua-mobilez
user-agentzcontent-typeacceptoriginzsec-fetch-sitezsec-fetch-modezsec-fetch-destzaccept-language)struuiduuid4r   r   s    r   _get_headerszGrokDirectProvider._get_headers3   sJ     !$DJJL 1 OO"+*[ $ B.(+$%/
 	
r   prompt
num_imagestimeoutc                    i ddd|dg dg ddddd	dd
dddd|dddi dddddddddi ddddd}t        j                  | j                   d| j                         | j                  |d|      }|j
                  dk7  r(t        d|j
                   d|j                  dd        ddg |j                  d}|j                  j                  d       D ]  }|j                         s	 t        j                  |      }d!|v r|d!   }	d"|	v r|	d"   j                  d#      |d$<   d%|	v ru|	d%   }
d&|
v r|d'xx   |
d&   z  cc<   d(|
v r<|
d(   }d)|v r|d*   j                  |d)          nd+|v r|d*   j                  |d+          d,|
v r|
d,   j                  dd      |d'<    |S # t        j                  $ r Y w xY w)-a\  
        Generate images using Grok's internal API.
        
        Args:
            prompt: Text prompt for image generation
            num_images: Number of images to generate (default 2)
            timeout: Request timeout in seconds
            
        Returns:
            dict with conversation_id, response text, and image URLs
        	temporaryFmessagefileAttachmentsimageAttachmentsdisableSearchenableImageGenerationTreturnImageBytesreturnRawGrokInXaiRequestenableImageStreamingimageGenerationCountforceConcisetoolOverridesenableSideBySidesendFinalMetadataisReasoningdisableTextFollowUpsresponseMetadataMODEL_MODE_AUTOdisableMemoryforceSideBySide	modelModeisAsync /rest/app-chat/conversations/new	chrome131headersr   jsonimpersonater*      API request failed:  - N   )conversation_idresponse_text
image_urlsraw_response
resultconversationconversationIdrN   responsetokenrO   imageAttachmentimageUrlrP   urlmodelResponse)r   postBASE_URLr'   r   status_code	ExceptiontextsplitstriprG   loadsgetappendJSONDecodeError)r   r(   r)   r*   payloadresprS   linedataresresponse_dataimgs               r   generate_imagez!GrokDirectProvider.generate_imageF   s   "

v
 r
 	

 U
 $T
 
 (
 #D
 #J
 E
 R
 
  
 5
  #E!
" #
$ #$*+
0 }}}}o=>%%'LL#
 s"243C3C2DC		RVSVGXYZZ  $ II	
 IIOOD) !	D::<zz$'t#x.C &,474G4K4KL\4]01 "S((+J #m3"?3}W7MM3 -="/0A"BC)S0 &| 4 ; ;C
O L!&# &| 4 ; ;CJ G +m;6CO6T6X6XYbdf6gF?3=!	F  '' s   5B2F++G GNr-   rN   c                    i ddd|dg dg ddddddd	dd
ddddddi dddddddddi ddddd}|r||d<   t        j                  | j                   d| j                         | j                  |d|      }|j
                  dk7  r(t        d|j
                   d|j                  dd        dd d!}|j                  j                  d"      D ]  }|j                         s	 t        j                  |      }d#|v rY|d#   }	d$|	v r|	d$   j                  d      |d%<   d&|	v r5|	d&   }
d'|
v r|d(xx   |
d'   z  cc<   d)|
v r|
d)   j                  dd       |d(<    |S # t        j                  $ r Y w xY w)*aJ  
        Send a message to Grok (without image generation).
        
        Args:
            message: Text message to send
            conversation_id: Optional existing conversation ID
            timeout: Request timeout in seconds
            
        Returns:
            dict with conversation_id and response text
        r,   Fr-   r.   r/   r0   r1   r2   r3   r4   r5   r   r6   r7   r8   r9   Tr:   r;   r<   r=   r>   rU   rC   rD   rE   rI   rJ   rK   NrL   rM   )rN   rO   rR   rS   rT   rN   rV   rW   rO   r[   )r   r\   r]   r'   r   r^   r_   r`   ra   rb   rG   rc   rd   rf   )r   r-   rN   r*   rg   rh   rS   ri   rj   rk   rl   s              r   send_messagezGrokDirectProvider.send_message   sa   "

w
 r
 	

 U
 $U
 
 (
 #E
 #A
 E
 R
 
  
 5
  #E!
" #
$ #$*+
0 (7G$%}}}}o=>%%'LL#
 s"243C3C2DC		RVSVGXYZZ  $

 IIOOD) 	D::<zz$'t#x.C%,474G4K4KL\4]01!S((+J"m3"?3}W7MM3*m;6CO6T6X6XYbdf6gF?3	$  '' s   0A2E&&E<;E<c                     	 t        j                  | j                   d| j                         | j                  dd      }|j
                  dk(  S # t        $ r Y yw xY w)z!Test if the API connection works.z'/rest/app-chat/conversations?pageSize=1rD      )rF   r   rH   r*   rI   F)r   rd   r]   r'   r   r^   r_   )r   rh   s     r   test_connectionz"GrokDirectProvider.test_connection   sb    
	<<==/!HI))+'D ##s** 		s   AA 	AA)   x   )N<   )__name__
__module____qualname____doc__r]   r   dictr'   r$   intrn   r   rp   boolrs    r   r   r   r      s    Z!H
*
d 
, 	`` ` 	`
 
`J *.	OO "#O 	O
 
Ob r   r   __main__z<============================================================zGrok Direct Provider Testz
1. Testing connection...u      ✓ Connection successful!u      ✗ Connection failed!   z
2. Testing image generation...z1a cute golden retriever puppy playing in the snowz   Conversation ID: rN   z   Response: rO   rI   z...z   Images found: rP   z	   Image z: P   u   
✓ All tests passed!u   
✗ Error: )rz   r   rG   r%   timetypingr   dotenvr   	curl_cffir   r   rw   printproviderrs   exitrn   rS   len	enumerateirZ   r_   e	traceback	print_excr~   r   r   <module>r      s  
 
       l l^ z	(O	
%&	(O%' 	*+##%12-.G 	01(()\]$V,=%>$?@Af_5ds;<C@A!#f\&:";!<=>| 45 	4FAsIacU"S"XJc23	4 	'( 
(OC 8  aS!"	s   B5D E D==E