
    a
i]                       d Z ddlmZ ddlmZm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 e
rddlmZ ddlmZ dd	lmZmZ e G d
 d                      Ze G d d                      Ze G d d                      Ze G d d                      Ze G d d                      Ze G d d                      Ze G d d                      Ze G d d                      Z G d d          Z  G d d          Z!dS )z#Data models for the sandbox client.    )annotations)AsyncIteratorIterator)	dataclassfield)TYPE_CHECKINGAnyOptional)SandboxConnectionErrorSandboxOperationErrorSandboxServerReloadError)AsyncSandbox)Sandbox)_AsyncWSStreamControl_WSStreamControlc                  J    e Zd ZU dZded<   ded<   ded<   edd	            Zd
S )ExecutionResultz+Result of executing a command in a sandbox.strstdoutstderrint	exit_codereturnboolc                    | j         dk    S )z.Return True if the command exited with code 0.r   )r   selfs    C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langsmith/sandbox/_models.pysuccesszExecutionResult.success    s     ~""    N)r   r   )__name__
__module____qualname____doc____annotations__propertyr    r    r   r   r      sU         55KKKKKKNNN# # # X# # #r    r   c                  >    e Zd ZU dZdZded<   dZded<   dZded	<   dS )
ResourceSpecz%Resource specification for a sandbox.500mr   cpu512MimemoryNOptional[str]storage)r!   r"   r#   r$   r+   r%   r-   r/   r'   r    r   r)   r)   &   sK         //CF!G!!!!!!r    r)   c                  t    e Zd ZU dZded<   ded<   ded<   dZded<   dZded	<   dZded
<   edd            Z	dS )Volumea@  Represents a persistent volume.

    Volumes are persistent storage that can be mounted in sandboxes.

    Attributes:
        id: Unique identifier (UUID). Remains constant even if name changes.
            May be None for resources created before ID support was added.
        name: Display name (can be updated).
    r   namesizestorage_classNr.   id
created_at
updated_atdatadict[str, Any]r   c           
         | |                     dd          |                     dd          |                     dd          |                     d          |                     d          |                     d	          
          S )z'Create a Volume from API response dict.r2    r3   unknownr4   defaultr5   r6   r7   )r2   r3   r4   r5   r6   r7   getclsr8   s     r   	from_dictzVolume.from_dictB   s{     s&"%%&),,((?I>>xx~~xx--xx--
 
 
 	
r    )r8   r9   r   r1   
r!   r"   r#   r$   r%   r5   r6   r7   classmethodrB   r'   r    r   r1   r1   /   s           IIIIIIB $J$$$$ $J$$$$	
 	
 	
 [	
 	
 	
r    r1   c                  (    e Zd ZU dZded<   ded<   dS )VolumeMountSpecz:Specification for mounting a volume in a sandbox template.r   volume_name
mount_pathNr!   r"   r#   r$   r%   r'   r    r   rF   rF   O   s+         DDOOOOOr    rF   c                      e Zd ZU dZded<   ded<   ded<    ee          Zded	<   d
Zded<   d
Z	ded<   d
Z
ded<   edd            Zd
S )SandboxTemplatea  Represents a SandboxTemplate.

    Templates define the image, resource limits, and volume mounts for sandboxes.
    All other container details are handled by the server with secure defaults.

    Attributes:
        id: Unique identifier (UUID). Remains constant even if name changes.
            May be None for resources created before ID support was added.
        name: Display name (can be updated).
    r   r2   imager)   	resources)default_factoryzlist[VolumeMountSpec]volume_mountsNr.   r5   r6   r7   r8   r9   r   c                   |                     di           }|                     dg           } | |                     dd          |                     dd          t          |                     dd          |                     d	d
          |                     d                    d |D             |                     d          |                     d          |                     d                    S )z0Create a SandboxTemplate from API response dict.rM   rO   r2   r;   rL   r<   r+   r*   r-   r,   r/   )r+   r-   r/   c           	         g | ];}t          |                    d d          |                    dd                    <S )rG   r;   rH   )rG   rH   )rF   r?   ).0vms     r   
<listcomp>z-SandboxTemplate.from_dict.<locals>.<listcomp>y   s[       
 	   "}b 9 9!vvlB77    r    r5   r6   r7   )r2   rL   rM   rO   r5   r6   r7   )r?   r)   )rA   r8   resources_datavolume_mounts_datas       r   rB   zSandboxTemplate.from_dictl   s     +r22!XXor::s&"%%((7I..""&&uf55%))(G<<&**955  
 
 -   xx~~xx--xx--#
 
 
 	
r    )r8   r9   r   rK   )r!   r"   r#   r$   r%   r   listrO   r5   r6   r7   rD   rB   r'   r    r   rK   rK   W   s         	 	 IIIJJJ+05+F+F+FMFFFFB $J$$$$ $J$$$$
 
 
 [
 
 
r    rK   c                  D    e Zd ZU dZded<   dZded<   edd
            ZdS )ResourceStatusa  Lightweight provisioning status for any async-created resource.

    Attributes:
        status: Resource lifecycle status. One of "provisioning", "ready", "failed".
        status_message: Human-readable details when status is "failed", None otherwise.
    r   statusNr.   status_messager8   r9   r   c                j     | |                     dd          |                     d                    S )z/Create a ResourceStatus from API response dict.rZ   provisioningr[   )rZ   r[   r>   r@   s     r   rB   zResourceStatus.from_dict   s>     s88Hn5588$455
 
 
 	
r    )r8   r9   r   rY   )r!   r"   r#   r$   r%   r[   rD   rB   r'   r    r   rY   rY      sZ           KKK$(N((((
 
 
 [
 
 
r    rY   c                  t    e Zd ZU dZded<   ded<   ded<   dZded	<   dZded
<   dZded<   edd            Z	dS )Poola  Represents a Sandbox Pool for pre-provisioned sandboxes.

    Pools pre-provision sandboxes from a template for faster startup.
    Instead of waiting for a new sandbox to be created, sandboxes can
    be served from a pre-warmed pool.

    Note: Templates with volume mounts cannot be used in pools.

    Attributes:
        id: Unique identifier (UUID). Remains constant even if name changes.
            May be None for resources created before ID support was added.
        name: Display name (can be updated).
    r   r2   template_namer   replicasNr.   r5   r6   r7   r8   r9   r   c           
         | |                     dd          |                     dd          |                     dd          |                     d          |                     d          |                     d          	          S )
z%Create a Pool from API response dict.r2   r;   r`   ra   r   r5   r6   r7   )r2   r`   ra   r5   r6   r7   r>   r@   s     r   rB   zPool.from_dict   s{     s&"%%((?B77XXj!,,xx~~xx--xx--
 
 
 	
r    )r8   r9   r   r_   rC   r'   r    r   r_   r_      s           IIIMMMB $J$$$$ $J$$$$	
 	
 	
 [	
 	
 	
r    r_   c                  2    e Zd ZU dZded<   ded<   ded<   dS )OutputChunkaf  A single chunk of streaming output from command execution.

    Attributes:
        stream: Either "stdout" or "stderr".
        data: The text content of this chunk (valid UTF-8, server handles
            boundary splitting).
        offset: Byte offset within the stream. Used internally for
            reconnection; users typically don't need this.
    r   streamr8   r   offsetNrI   r'   r    r   rd   rd      s7           KKKIIIKKKKKr    rd   c                      e Zd ZdZdZdZdZddddd'dZd(dZe	d)d            Z
e	d*d            Ze	d+d            Zd,dZd,dZd(d Zd-d"Ze	d.d#            Ze	d.d$            Zd/d%Zd&S )0CommandHandleaE  Handle to a running command with streaming output and auto-reconnect.

    Iterable, yielding OutputChunk objects (stdout and stderr interleaved
    in arrival order). Access .result after iteration to get the full
    ExecutionResult.

    Auto-reconnect behavior:
    - Server hot-reload (1001 Going Away): reconnect immediately
    - Network error / unexpected close:    reconnect with exponential backoff
    - User called kill():                  do NOT reconnect (propagate error)

    The auto-reconnect is transparent -- the iterator reconnects and
    continues yielding chunks without any user intervention. If all
    reconnect attempts are exhausted, SandboxConnectionError is raised.

    Construction modes (controlled by ``command_id``):
    - **New execution** (``command_id=""``, the default): the constructor
      eagerly reads the server's ``"started"`` message to populate
      ``command_id`` and ``pid`` before returning.
    - **Reconnection** (``command_id`` set): skips the started-message
      read, since reconnect streams don't emit one.

    Example:
        handle = sandbox.run("make build", timeout=600, wait=False)

        for chunk in handle:          # auto-reconnects on transient errors
            print(chunk.data, end="")

        result = handle.result
        print(f"Exit code: {result.exit_code}")
             ?       @r;   r   
command_idstdout_offsetstderr_offsetmessage_streamIterator[dict]controlOptional[_WSStreamControl]sandboxr   rm   r   rn   r   ro   r   Nonec                   || _         || _        || _        d | _        d | _        d | _        g | _        g | _        d| _        || _	        || _
        |r	|| _        d S |                                  d S )NF)_stream_control_sandbox_command_id_pid_result_stdout_parts_stderr_parts
_exhausted_last_stdout_offset_last_stderr_offset_consume_startedr   rp   rr   rt   rm   rn   ro   s          r   __init__zCommandHandle.__init__   s     &*.#'	26(*(*#0 #0 
  	$)D!!#####r    c                Z   	 t          | j                  }n# t          $ r t          dd          w xY w|                    d          dk    r(t          d|                    d           dd          |                    d          | _        |                    d	          | _        d
S )aH  Eagerly read the 'started' message to populate command_id and pid.

        Blocks briefly until the server sends the started message (arrives
        near-instantly after connection). After this call, command_id and
        pid are available, and the WebSocket is bound to the control object
        (so kill() works).
        -Command stream ended before 'started' messagecommand	operationtypestarted!Expected 'started' message, got ''rm   pidN)nextrw   StopIterationr   r?   rz   r{   r   	first_msgs     r   r   zCommandHandle._consume_started  s    	T\**II 	 	 	'?#   	
 ==  I--'LIMM&4I4ILLL#    %==66MM%((			s    3r.   c                    | j         S )z=The server-assigned command ID. Available after construction.rz   r   s    r   rm   zCommandHandle.command_id/       r    Optional[int]c                    | j         S )z<The process ID on the sandbox. Available after construction.r{   r   s    r   r   zCommandHandle.pid4       yr    r   c                X    | j         | D ]}| j         t          dd          | j         S )zThe final execution result. Blocks until the command completes.

        Drains the remaining stream if not already exhausted, then returns
        the ExecutionResult with aggregated stdout, stderr, and exit_code.
        N)Command stream ended without exit messager   r   r|   r   r   _s     r   resultzCommandHandle.result9  sM     <  <';#    |r    Iterator[OutputChunk]c           	   #    K   | j         rdS | j        D ]}|                    d          }|dv rxt          ||d         |                    dd                    }|dk    r!| j                            |d                    n | j                            |d                    |V  |d	k    rWt          d
                    | j                  d
                    | j                  |d                   | _	        d| _          dS d| _         dS zBIterate over output chunks from the current stream (no reconnect).Nr   )r   r   r8   rf   r   )re   r8   rf   r   exitr;   r   )r   r   r   T)
r   rw   r?   rd   r}   appendr~   r   joinr|   r   msgmsg_typechunks       r   _iter_streamzCommandHandle._iter_streamJ  s0     ? 	F< 	 	CwwvH///##V778Q//  
 x''&--c&k::::&--c&k:::V##.774#566774#566!+.     
 #' $ r    c              #  $  K   ddl }d}	 	 |                                 D ]|}d}|j        dk    r5|j        t	          |j                            d                    z   | _        n4|j        t	          |j                            d                    z   | _        |V  }dS # t          $ r}| j
        r| j
        j        r |dz  }|| j        k    rt          d| d          |t          |t                    }|s8t          | j        d	|dz
  z  z  | j                  }|                    |           | j        J | j                            | j        | j        | j        
          }|j        | _        |j
        | _
        d| _        Y d}~nd}~ww xY w)aE  Iterate over output chunks, auto-reconnecting on transient errors.

        Reconnect strategy:
        - 1001 Going Away (hot-reload): immediate reconnect, no delay
        - Other SandboxConnectionError:  exponential backoff (0.5s, 1s, 2s...)
        - After kill():                  no reconnect, error propagates
        r   NTr   utf-8   Lost connection  times in succession, giving up   rn   ro   F)timer   re   rf   lenr8   encoder   r   r   rx   killedMAX_AUTO_RECONNECTS
isinstancer   min_BACKOFF_BASE_BACKOFF_MAXsleeprz   ry   	reconnectrw   r   )r   r   reconnect_attemptsr   eis_hot_reloaddelay
new_handles           r   __iter__zCommandHandle.__iter__e  s      	*	()(!..00 
  
 E)*&|x//38<#!J--g66C C 400 49<#!J--g66C C 40  KKKK) ( ( (= T]%9 "a'"%(@@@01+= 1 1 1  
 !+1.F G G$ &*a4F4J.KL) E JJu%%%'333!]44$"&":"&": 5  

  *1 * 3"'7(*	(s   BB 
F(CFFc                J    | j         r| j                                          dS dS )a/  Send a kill signal to the running command (SIGKILL).

        The server kills the entire process group. The stream will
        subsequently yield an exit message with a non-zero exit code.

        Has no effect if the command has already exited or the
        WebSocket connection is closed.
        Nrx   	send_killr   s    r   killzCommandHandle.kill  s2     = 	&M##%%%%%	& 	&r    r8   c                L    | j         r| j                             |           dS dS )zWrite data to the command's stdin.

        Args:
            data: String data to write to stdin.

        Has no effect if the command has already exited or the
        WebSocket connection is closed.
        Nrx   
send_inputr   r8   s     r   r   zCommandHandle.send_input  s4     = 	+M$$T*****	+ 	+r    c                    | j         S z8Last known stdout byte offset (for manual reconnection).r   r   s    r   last_stdout_offsetz CommandHandle.last_stdout_offset       ''r    c                    | j         S z8Last known stderr byte offset (for manual reconnection).r   r   s    r   last_stderr_offsetz CommandHandle.last_stderr_offset  r   r    c                l    | j         J | j                            | j         | j        | j                  S )a  Reconnect to this command from the last known offsets.

        Returns a new handle that resumes output from where this one
        left off. Any output produced while disconnected is replayed
        from the server's ring buffer.

        Returns:
            A new CommandHandle.

        Raises:
            SandboxOperationError: If command_id is not found or
                session expired.
            SandboxConnectionError: If connection to sandbox fails.
        Nr   rz   ry   r   r   r   r   s    r   r   zCommandHandle.reconnect  sD     +++}&&22 ' 
 
 	
r    N)rp   rq   rr   rs   rt   r   rm   r   rn   r   ro   r   r   ru   r   ru   r   r.   r   r   r   r   )r   r   r8   r   r   ru   r   r   )r   rh   )r!   r"   r#   r$   r   r   r   r   r   r&   rm   r   r   r   r   r   r   r   r   r   r'   r    r   rh   rh      ss        @ ML $ $ $ $ $ $<) ) ) ).       X     X    X    65( 5( 5( 5(n
& 
& 
& 
&
+ 
+ 
+ 
+ ( ( ( X( ( ( ( X(
 
 
 
 
 
r    rh   c                      e Zd ZdZdZdZdZddddd'dZd(dZe	d)d            Z
e	d*d            Ze	d+d            Zd,dZd,dZd(d Zd-d"Ze	d.d#            Ze	d.d$            Zd/d%Zd&S )0AsyncCommandHandlea  Async handle to a running command with streaming output and auto-reconnect.

    Async iterable, yielding OutputChunk objects (stdout and stderr interleaved
    in arrival order). Access .result after iteration to get the full
    ExecutionResult.

    Auto-reconnect behavior:
    - Server hot-reload (1001 Going Away): reconnect immediately
    - Network error / unexpected close:    reconnect with exponential backoff
    - User called kill():                  do NOT reconnect (propagate error)

    Construction modes (controlled by ``command_id``):
    - **New execution** (``command_id=""``, the default): call
      ``await handle._ensure_started()`` after construction to read the
      server's ``"started"`` message and populate ``command_id`` / ``pid``.
    - **Reconnection** (``command_id`` set): skips the started-message
      read, since reconnect streams don't emit one.

    Example:
        handle = await sandbox.run("make build", timeout=600, wait=False)

        async for chunk in handle:    # auto-reconnects on transient errors
            print(chunk.data, end="")

        result = await handle.result
        print(f"Exit code: {result.exit_code}")
    ri   rj   rk   r;   r   rl   rp   AsyncIterator[dict]rr   Optional[_AsyncWSStreamControl]rt   r   rm   r   rn   r   ro   r   ru   c                   || _         || _        || _        d | _        d | _        d | _        g | _        g | _        d| _        || _	        || _
        |r|| _        d| _        d S d| _        d S )NFT)rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   _startedr   s          r   r   zAsyncCommandHandle.__init__  s~     &*.#'	26(*(*#0 #0 
  	")D DMMM!DMMMr    c                  K   | j         rdS 	 | j                                         d{V }n# t          $ r t	          dd          w xY w|                    d          dk    r(t	          d|                    d           dd          |                    d	          | _        |                    d
          | _        d| _         dS )z:Read the 'started' message to populate command_id and pid.Nr   r   r   r   r   r   r   rm   r   T)r   rw   	__anext__StopAsyncIterationr   r?   rz   r{   r   s     r   _ensure_startedz"AsyncCommandHandle._ensure_started  s      = 	F	"l4466666666II! 	 	 	'?#   	
 ==  I--'LIMM&4I4ILLL#    %==66MM%((	s	   - A	r.   c                    | j         S )z@The server-assigned command ID. Available after _ensure_started.r   r   s    r   rm   zAsyncCommandHandle.command_id)  r   r    r   c                    | j         S )z?The process ID on the sandbox. Available after _ensure_started.r   r   s    r   r   zAsyncCommandHandle.pid.  r   r    r   c                h   K   | j         | 2 3 d{V }6 | j         t          dd          | j         S )z&The final execution result. Awaitable.Nr   r   r   r   r   s     r   r   zAsyncCommandHandle.result3  so       <       a  <';#    |s   AsyncIterator[OutputChunk]c           	    \  K   |                                   d{V  | j        rdS | j        2 3 d{V }|                    d          }|dv ryt	          ||d         |                    dd                    }|dk    r!| j                            |d                    n | j                            |d                    |W V  |d	k    rWt          d
	                    | j                  d
	                    | j                  |d                   | _
        d| _         dS 6 d| _        dS r   )r   r   rw   r?   rd   r}   r   r~   r   r   r|   r   s       r   _aiter_streamz AsyncCommandHandle._aiter_stream@  st     ""$$$$$$$$$? 	F 	 	 	 	 	 	 	#wwvH///##V778Q//  
 x''&--c&k::::&--c&k:::V##.774#566774#566!+.     
 #' $ &* s   D$c               J  K   ddl }d}	 	 |                                 2 3 d{V }d}|j        dk    r5|j        t	          |j                            d                    z   | _        n4|j        t	          |j                            d                    z   | _        |W V  6 dS # t          $ r}| j
        r| j
        j        r |dz  }|| j        k    rt          d| d          |t          |t                    }|s>t          | j        d	|dz
  z  z  | j                  }|                    |           d{V  | j        J | j                            | j        | j        | j        
           d{V }|j        | _        |j
        | _
        d| _        Y d}~nd}~ww xY w)z6Async iterate with auto-reconnect on transient errors.r   NTr   r   r   r   r   r   r   F)asyncior   re   rf   r   r8   r   r   r   r   rx   r   r   r   r   r   r   r   r   rz   ry   r   rw   r   )r   r   r   r   r   r   r   r   s           r   	__aiter__zAsyncCommandHandle.__aiter__\  sW     *	()(#'#5#5#7#7 
  
  
  
  
  
  
 %)*&|x//38<#!J--g66C C 400 49<#!J--g66C C 40  KKKKK $8 ) ( ( (= T]%9 "a'"%(@@@04+= 4 4 4  
 !+1.F G G$ /*a4F4J.KL) E "--.........'333#'=#:#:$"&":"&": $; $ $      

  *1 * 3"'7(*	(s#   B% B"A>B% %
F /C'FF c                Z   K   | j         r!| j                                          d{V  dS dS )z*Send a kill signal to the running command.Nr   r   s    r   r   zAsyncCommandHandle.kill  sF      = 	,-))+++++++++++	, 	,r    r8   c                \   K   | j         r"| j                             |           d{V  dS dS )z"Write data to the command's stdin.Nr   r   s     r   r   zAsyncCommandHandle.send_input  sH      = 	1-**400000000000	1 	1r    c                    | j         S r   r   r   s    r   r   z%AsyncCommandHandle.last_stdout_offset  r   r    c                    | j         S r   r   r   s    r   r   z%AsyncCommandHandle.last_stderr_offset  r   r    c                |   K   | j         J | j                            | j         | j        | j                   d{V S )z6Reconnect to this command from the last known offsets.Nr   r   r   s    r   r   zAsyncCommandHandle.reconnect  sd      +++],,22 - 
 
 
 
 
 
 
 
 	
r    N)rp   r   rr   r   rt   r   rm   r   rn   r   ro   r   r   ru   r   r   r   r   )r   r   r   r   )r   r   )r!   r"   r#   r$   r   r   r   r   r   r&   rm   r   r   r   r   r   r   r   r   r   r'   r    r   r   r     sr        8 ML " " " " " ">   (       X     X 
 
 
 X
   8/( /( /( /(b, , , ,
1 1 1 1
 ( ( ( X( ( ( ( X(
 
 
 
 
 
r    r   N)"r$   
__future__r   collections.abcr   r   dataclassesr   r   typingr   r	   r
   langsmith.sandbox._exceptionsr   r   r    langsmith.sandbox._async_sandboxr   langsmith.sandbox._sandboxr   langsmith.sandbox._ws_executer   r   r   r)   r1   rF   rK   rY   r_   rd   rh   r   r'   r    r   <module>r      s   ) ) " " " " " " 3 3 3 3 3 3 3 3 ( ( ( ( ( ( ( ( / / / / / / / / / /           ======222222        
# 
# 
# 
# 
# 
# 
# 
# " " " " " " " " 
 
 
 
 
 
 
 
>         +
 +
 +
 +
 +
 +
 +
 +
\ 
 
 
 
 
 
 
 
(  
  
  
  
  
  
  
  
P         }
 }
 }
 }
 }
 }
 }
 }
@S
 S
 S
 S
 S
 S
 S
 S
 S
 S
r    