
    a
i\K                        d Z ddlmZ ddlZddlmZmZ ddlmZm	Z	m
Z
 ddlmZmZmZmZ d Zd Zd>dZd?dZ G d d          Z G d d          Zd@dZdddAdZd ddd!ddd"d#d$d#d%
dBd6Zddd7dCd:Zd ddd!ddd"d#d$d#d%
dDd<Zddd7dEd=ZdS )Fz<WebSocket-based command execution for long-running commands.    )annotationsN)AsyncIteratorIterator)AnyCallableOptional)CommandTimeoutErrorSandboxConnectionErrorSandboxOperationErrorSandboxServerReloadErrorc                 f    	 ddl m} m} ddlm} || |fS # t
          $ r t          d          dw xY w)z)Import websockets or raise a clear error.r   ConnectionClosedInvalidStatusconnectnWebSocket-based execution requires the 'websockets' package. Install it with: pip install 'langsmith[sandbox]'N)websockets.exceptionsr   r   websockets.sync.clientr   ImportError)r   r   
ws_connects      C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langsmith/sandbox/_ws_execute.py_ensure_websocketsr      sw    	IIIIIIII@@@@@@+]::   @
 
 	    0c                 f    	 ddl m}  ddlm}m} | ||fS # t
          $ r t          d          dw xY w)z/Import async websockets or raise a clear error.r   r   r   r   N)websockets.asyncio.clientr   r   r   r   r   )ws_connect_asyncr   r   s      r   _ensure_websockets_asyncr      sw    	IIIIIIIIIIIIII!1=@@   @
 
 	r   dataplane_urlstrreturnc                `    |                      dd                               dd          }| dS )z<Convert dataplane HTTP URL to WebSocket URL for /execute/ws.zhttps://zwss://zhttp://zws://z/execute/ws)replace)r   ws_urls     r   _build_ws_urlr%   -   s6    "":x88@@GTTF!!!!    api_keyOptional[str]dict[str, str]c                    | rd| iS i S )z5Build auth headers for the WebSocket upgrade request.z	X-Api-Key )r'   s    r   _build_auth_headersr,   3   s     &W%%Ir&   c                  R    e Zd ZdZddZddZddZedd
            ZddZ	ddZ
dS )_WSStreamControla  Control interface for an active WebSocket stream.

    Created before the generator starts, bound to the WebSocket once
    the connection opens. The CommandHandle holds a reference to this
    object to send kill/input messages.

    Thread safety: websockets' sync client supports send() from one
    thread while recv() runs on another. So kill() from user code
    and iteration on a different thread are safe.
    r!   Nonec                0    d | _         d| _        d| _        d S NF_ws_closed_killedselfs    r   __init__z_WSStreamControl.__init__K       r&   wsr   c                    || _         dS )z:Bind to the active WebSocket. Called inside the generator.Nr3   r7   r:   s     r   _bindz_WSStreamControl._bindP   s    r&   c                "    d| _         d| _        dS )z0Mark as closed. Called when the generator exits.TNr4   r3   r6   s    r   _unbindz_WSStreamControl._unbindT   s    r&   boolc                    | j         S )z.True if kill() has been called on this stream.r5   r6   s    r   killedz_WSStreamControl.killedY   s     |r&   c                &   d| _         | j        r| j        s{	 | j                            t	          j        ddi                     n# t          $ r Y nw xY w	 d| j        _        | j                                         dS # t          $ r Y dS w xY wdS dS )z8Send a kill message and immediately close the WebSocket.Ttypekillr   N	r5   r3   r4   sendjsondumps	Exceptionclose_timeoutcloser6   s    r   	send_killz_WSStreamControl.send_kill^   s    8 		DL 		dj&&)9::;;;;   )*&        		 		 		 		s#   .A 
AA%A> >
BBdatar    c                    | j         r8| j        s3| j                             t          j        d|d                     dS dS dS )z'Send stdin data to the running command.inputrG   rQ   Nr3   r4   rJ   rK   rL   r7   rQ   s     r   
send_inputz_WSStreamControl.send_inputl   s[    8 	GDL 	GHMM$*gt%D%DEEFFFFF	G 	G 	G 	Gr&   Nr!   r/   r:   r   r!   r/   r!   rB   rQ   r    r!   r/   __name__
__module____qualname____doc__r8   r>   rA   propertyrE   rP   rW   r+   r&   r   r.   r.   ?   s        	 	   
      
    X   G G G G G Gr&   r.   c                  R    e Zd ZdZddZddZddZedd
            ZddZ	ddZ
dS )_AsyncWSStreamControlz%Async equivalent of _WSStreamControl.r!   r/   c                0    d | _         d| _        d| _        d S r1   r2   r6   s    r   r8   z_AsyncWSStreamControl.__init__u   r9   r&   r:   r   c                    || _         d S Nr<   r=   s     r   r>   z_AsyncWSStreamControl._bindz   s    r&   c                "    d| _         d | _        d S )NTr@   r6   s    r   rA   z_AsyncWSStreamControl._unbind}   s    r&   rB   c                    | j         S rf   rD   r6   s    r   rE   z_AsyncWSStreamControl.killed   s
    |r&   c                B  K   d| _         | j        r| j        s	 | j                            t	          j        ddi                     d {V  n# t          $ r Y nw xY w	 d| j        _        | j                                         d {V  d S # t          $ r Y d S w xY wd S d S )NTrG   rH   r   rI   r6   s    r   rP   z_AsyncWSStreamControl.send_kill   s      8 		DL 		hmmDJ/?$@$@AAAAAAAAAA   )*&hnn&&&&&&&&&&&   		 		 		 		s#   4A 
AA+B 
BBrQ   r    c                   K   | j         r>| j        s9| j                             t          j        d|d                     d {V  d S d S d S )NrS   rT   rU   rV   s     r   rW   z _AsyncWSStreamControl.send_input   sq      8 	MDL 	M(--
GT+J+J K KLLLLLLLLLLL	M 	M 	M 	Mr&   NrX   rY   rZ   r[   r\   r+   r&   r   rc   rc   r   s        //   
          X   M M M M M Mr&   rc   excrM   r$   r/   c                    t          t          | dd          dd          }|dk    rt          d| d          | t          d| d|            | )	u   Raise a clear error when the server rejects the WebSocket upgrade.

    The most common case is HTTP 404 — the server doesn't have the
    /execute/ws endpoint, meaning it doesn't support WebSocket streaming.
    responseNstatus_codei  zJThe sandbox server does not support WebSocket command execution (endpoint z returned 404). Ensure the server is updated to a version that supports the /execute/ws endpoint, or use run() without wait=False or callbacks.z+WebSocket upgrade rejected by server (HTTP z): )getattrr
   )rk   r$   statuss      r   _raise_for_invalid_statusrq      s     WS*d33]DIIF}}$66 6 6
 

 	 !FfFFFF r&    
command_idmsgdictrt   c               <   |                      dd          }|                      dd          }|dk    rt          |          |dk    rt          |rd| n||rdnd	|
          |dk    rt          |rd| n||rdnd	|
          t          ||rdnd	|
          )z<Raise the appropriate exception from a server error message.
error_typeCommandErrorerrorzUnknown errorCommandTimeoutCommandNotFoundzCommand not found: 	reconnectcommand)	operationrx   SessionExpiredzSession expired: )getr	   r   )ru   rt   rx   	error_msgs       r   _raise_from_error_msgr      s    ~66J11I%%%!),,,&&&#2<K.*...)%/>kkY!
 
 
 	

 %%%#0:I,
,,,	%/>kkY!
 
 
 	
  !+:++   r&   <   z	/bin/bashi,  FiX  )
timeoutenvcwdshell	on_stdout	on_stderridle_timeoutkill_on_disconnectttl_secondsptyr~   r   intr   Optional[dict[str, str]]r   r   r   Optional[Callable[[str], Any]]r   r   r   rB   r   r   'tuple[Iterator[dict], _WSStreamControl]c       
           	
 t                      \  t          |           t          |          t                      d	
fd} |            fS )aP  Execute a command over WebSocket, yielding raw message dicts.

    Returns a tuple of (message_iterator, control). The control object
    provides send_kill() and send_input() methods for the CommandHandle.

    The iterator yields dicts with a "type" field:
    - {"type": "started", "command_id": "...", "pid": N}
    - {"type": "stdout", "data": "...", "offset": N}
    - {"type": "stderr", "data": "...", "offset": N}
    - {"type": "exit", "exit_code": N}

    If on_stdout/on_stderr callbacks are provided, they are invoked as
    data arrives in addition to yielding the messages.
    r!   Iterator[dict]c            	   3    K   	  dddd          5 } 	                     |            dd}r|d<   
r
|d<   rd	|d
<   |                     t          j        |                     | D ]}t          j        |          }|                    d          }|dk    r|V  6|dk    rr |d                    |V  T|dk    rr |d                    |V  r|dk    r&|V   d d d            	                                 d S |dk    rt          |           	 d d d            n# 1 swxY w Y   n# $ r}t          |           Y d }~njd }~w$ r?}|j	        r |j	        j
        dk    rt          d          |t          d|           |d }~wt          $ r}t          d|           |d }~ww xY w	                                 d S # 	                                 w xY wN   
   r   additional_headersopen_timeoutrN   ping_intervalping_timeoutexecute)rG   r~   timeout_secondsr   idle_timeout_secondsr   r   r   r   Tr   rG   startedstdoutrQ   stderrexitrz     (Server is reloading, reconnect to resume*WebSocket connection closed unexpectedly: Failed to connect to sandbox: r>   rJ   rK   rL   loadsr   rA   r   rq   rcvdcoder   r
   OSError)r:   payloadraw_msgru   msg_typeer   r   r~   controlr   r   headersr   r   r   r   r   r   r   r   r   r$   s         r   _streamzrun_ws_stream.<locals>._stream   s8     C	#*     33 b!!! &&'.",8*<#.+ +  )%(GEN )%(GEN *%)GEN
7++,,,  " 3 3G*W--C"wwvH9,,!				!X--$ 3%Ic&k222!				!X--$ 3%Ic&k222!				!V++!			a33 33 33 33 33 33D OO! "W,,-c222-3;33 33 33 33 33 33 33 33 33 33 33 33 33 33 33j  	1 	1 	1%a00000000 	 	 	v !&+--.>  )@Q@@   	V 	V 	V()M!)M)MNNTUU	V OOGOOsw   E CD51E D5)E 5D99E <D9=E  G GEG G#:FG*F==GG G1r!   r   r   r%   r,   r.   )r   r'   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r$   s     ``````````` @@@@@@r   run_ws_streamr      s    < 3E2F2F/J -=))F!'**G  GD D D D D D D D D D D D D D D D D D D D D DL 799gr&   )stdout_offsetstderr_offsetr   r   c          
        	
 t                      \  
t          |           t          |          	t                      d	
f	d} |            fS )aY  Reconnect to an existing command over WebSocket.

    Returns a tuple of (message_iterator, control), same as run_ws_stream.
    The iterator yields stdout, stderr, exit, and error messages.
    No 'started' message is sent on reconnection.

    With the ring buffer reader server model, there is no replay/live
    phase distinction and no deduplication needed. The server reads from
    its ring buffer starting at the requested offsets and streams output
    from there. If the requested offset is older than the buffer's
    earliest data, the server sends from the earliest available offset.
    r!   r   c            
   3  <  	K   	  	dddd          5 }                      |            |                     t          j        d
d                     | D ]w}t          j        |          }|                    d          }|dv r|V  4|d	k    r&|V   d d d                                             d S |d
k    rt          |           x	 d d d            n# 1 swxY w Y   n# $ r}t          |           Y d }~njd }~w$ r?}|j	        r |j	        j
        dk    rt          d          |t          d|           |d }~wt          $ r}t          d|           |d }~ww xY w                                 d S #                                  w xY wNr   r   r   r   r}   )rG   rt   r   r   rG   )r   r   r   rz   rs   r   r   r   r   r   )r:   r   ru   r   r   r   r   rt   r   r   r   r   r   r$   s        r   r   z$reconnect_ws_stream.<locals>._streamU  s     3	#*     #J b!!! J$/*4-:-:	  	 	 	  " J JG*W--C"wwvH#777!				!V++!			A#J #J #J #J #J #Jd OO! "W,,-cjIIIIJ/#J #J #J #J #J #J #J #J #J #J #J #J #J #J #JJ  	1 	1 	1%a00000000 	 	 	v !&+--.>  )@Q@@   	V 	V 	V()M!)M)MNNTUU	V OOGOOsw   C+ BCC+ :CC+ C##C+ &C#'C+ *F +E,0D F E,:EE,E''E,,F Fr   r   )r   r'   rt   r   r   r   r   r   r   r   r   r$   s     ``` @@@@@@r   reconnect_ws_streamr   <  s    ( 3E2F2F/J -=))F!'**G  G4 4 4 4 4 4 4 4 4 4 4 4 4 4l 799gr&   1tuple[AsyncIterator[dict], _AsyncWSStreamControl]c       
           	
K   t                      \  t          |           t          |          t                      d	
fd} |            fS )z]Async equivalent of run_ws_stream.

    Returns (async_message_iterator, async_control).
    r!   AsyncIterator[dict]c            	    :  K   	  dddd          4 d {V 	 } 	                     |            dd}r|d<   
r
|d<   rd	|d
<   |                     t          j        |                     d {V  | 2 3 d {V }t          j        |          }|                    d          }|dk    r|W V  <|dk    rr |d                    |W V  [|dk    rr |d                    |W V  z|dk    r-|W V   d d d           d {V  	                                 d S |dk    rt          |           6 	 d d d           d {V  n# 1 d {V swxY w Y   n# $ r}t          |           Y d }~njd }~w$ r?}|j	        r |j	        j
        dk    rt          d          |t          d|           |d }~wt          $ r}t          d|           |d }~ww xY w	                                 d S # 	                                 w xY wr   r   )r:   r   r   ru   r   r   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r$   s         r   r   z$run_ws_stream_async.<locals>._stream  s     =	''#*     -3 -3 -3 -3 -3 -3 -3 -3 b!!! &&'.",8*<#.+ +  )%(GEN )%(GEN *%)GENggdj11222222222%' 3 3 3 3 3 3 3'*W--C"wwvH9,,!					!X--$ 3%Ic&k222!					!X--$ 3%Ic&k222!					!V++!				W-3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3x OO! "W,,-c222% &(R7-3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3^  	1 	1 	1%a00000000 	 	 	v !&+--.>  )@Q@@   	V 	V 	V()M!)M)MNNTUU	V OOGOOs   E* A$EEB EE* .EE* 
E""E* %E"&E* )H *G+/F?H G+:GG+G&&G++H Hr!   r   r   r%   r,   rc   )r   r'   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r$   s     ``````````` @@@@@@r   run_ws_stream_asyncr     s      ( 9Q8R8R5&=))F!'**G#%%G> > > > > > > > > > > > > > > > > > > > > >@ 799gr&   c          
        	
K   t                      \  
t          |           t          |          	t                      d	
f	d} |            fS )z(Async equivalent of reconnect_ws_stream.r!   r   c            
      	K   	  	dddd          4 d {V 	 }                      |            |                     t          j        d
d                     d {V  | 2 3 d {V }t          j        |          }|                    d          }|dv r|W V  :|d	k    r-|W V   d d d           d {V                                   d S |d
k    rt          |           6 	 d d d           d {V  n# 1 d {V swxY w Y   n# $ r}t          |           Y d }~njd }~w$ r?}|j	        r |j	        j
        dk    rt          d          |t          d|           |d }~wt          $ r}t          d|           |d }~ww xY w                                 d S #                                  w xY wr   r   )r:   r   ru   r   r   r   r   rt   r   r   r   r   r   r$   s        r   r   z*reconnect_ws_stream_async.<locals>._stream  s     /	''#*     J J J J J J J J b!!!ggJ$/*4-:-:	  	 	 	 	 	 	 	 	 	 &( 
J 
J 
J 
J 
J 
J 
J'*W--C"wwvH#777!					!V++!				;J J J J J J J J J J J J\ OO! "W,,-cjIIII &(R+J J J J J J J J J J J J J J J J J J J J J J J J J J JB  	1 	1 	1%a00000000 	 	 	v !&+--.>  )@Q@@   	V 	V 	V()M!)M)MNNTUU	V OOGOOs   D A
D 'C,-A D -D D .D  
D

D D
D F, FD,'F, ,F4:E..F;FFF, ,Gr   r   )r   r'   rt   r   r   r   r   r   r   r   r   r$   s     ``` @@@@@@r   reconnect_ws_stream_asyncr     s       9Q8R8R5&=))F!'**G#%%G0 0 0 0 0 0 0 0 0 0 0 0 0 0d 799gr&   )r   r    r!   r    )r'   r(   r!   r)   )rk   rM   r$   r    r!   r/   )ru   rv   rt   r    r!   r/   )r   r    r'   r(   r~   r    r   r   r   r   r   r(   r   r    r   r   r   r   r   r   r   rB   r   r   r   rB   r!   r   )r   r    r'   r(   rt   r    r   r   r   r   r!   r   )r   r    r'   r(   r~   r    r   r   r   r   r   r(   r   r    r   r   r   r   r   r   r   rB   r   r   r   rB   r!   r   )r   r    r'   r(   rt   r    r   r   r   r   r!   r   )r`   
__future__r   rK   collections.abcr   r   typingr   r   r   langsmith.sandbox._exceptionsr	   r
   r   r   r   r   r%   r,   r.   rc   rq   r   r   r   r   r   r+   r&   r   <module>r      sg   B B " " " " " "  3 3 3 3 3 3 3 3 * * * * * * * * * *               " " " "   0G 0G 0G 0G 0G 0G 0G 0Gf"M "M "M "M "M "M "M "MT   ( ;=      J $(0404$i i i i i ib O O O O O Ox $(0404$Y Y Y Y Y YB @ @ @ @ @ @ @ @r&   