
    a
ieL                        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
mZmZmZmZ ddlZddlmZmZmZmZ ddlmZ ddlmZmZ dd	lmZ erdd
lmZ e G d d                      ZdS )z0AsyncSandbox class for async sandbox operations.    )annotationsN)	dataclassfield)TYPE_CHECKINGAnyCallableLiteralOptionalUnionoverload)DataplaneNotConfiguredErrorResourceNotFoundErrorSandboxConnectionErrorSandboxNotReadyError)handle_sandbox_http_error)AsyncCommandHandleExecutionResult)AsyncTunnel)AsyncSandboxClientc                     e Zd ZU dZded<   ded<   dZded<   dZded<   d	Zded
<   dZded<   dZ	ded<   dZ
ded<    edd          Zded<    edd          Zded<   e	 dZd[d            Zd\dZd]d#Zd^d$Zed%d%d%d%d%d%d%d%d%d%d%d&d_d8            Zed%d%d%d%d%d%d%d%d%d%d9
d`d<            Zd=ddd>ddd?dd@ddd&dadBZd?dd@ddCdbdDZdcdEZdFdFdGdddKZd=dLdedPZd=dLdfdRZdFdSdTdgdYZdS )hAsyncSandboxar  Represents an active sandbox for running commands and file operations async.

    This class is typically obtained from AsyncSandboxClient.sandbox() and supports
    the async context manager protocol for automatic cleanup.

    Attributes:
        name: Display name (can be updated).
        template_name: Name of the template used to create this sandbox.
        dataplane_url: URL for data plane operations (file I/O, command execution).
            Only functional when status is "ready".
        id: Unique identifier (UUID). Remains constant even if name changes.
            May be None for resources created before ID support was added.
        status: Sandbox lifecycle status. One of "provisioning", "ready", "failed".
        status_message: Human-readable details when status is "failed", None otherwise.
        created_at: Timestamp when the sandbox was created.
        updated_at: Timestamp when the sandbox was last updated.

    Example:
        async with await client.sandbox(template_name="python-sandbox") as sandbox:
            result = await sandbox.run("python --version")
            print(result.stdout)
    strnametemplate_nameNOptional[str]dataplane_urlidreadystatusstatus_message
created_at
updated_atF)reprdefaultr   _clientTbool_auto_deletedatadict[str, Any]clientauto_deletereturnc                b    | |                     dd          |                     dd          |                     d          |                     d          |                     dd          |                     d          |                     d	          |                     d
          ||
  
        S )aD  Create an AsyncSandbox from API response dict.

        Args:
            data: API response dictionary containing sandbox data.
            client: Parent AsyncSandboxClient for operations.
            auto_delete: Whether to delete the sandbox on context exit.

        Returns:
            AsyncSandbox instance.
        r    r   r   r   r   r   r    r!   r"   )
r   r   r   r   r   r    r!   r"   r%   r'   )get)clsr(   r*   r+   s       C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langsmith/sandbox/_async_sandbox.py	from_dictzAsyncSandbox.from_dictC   s    " s&"%%((?B77((?33xx~~88Hg..88$455xx--xx--$
 
 
 	
    c                
   K   | S )zEnter async context manager. selfs    r1   
__aenter__zAsyncSandbox.__aenter__a   s      r3   exc_typeOptional[type]exc_valOptional[BaseException]exc_tbOptional[Any]Nonec                   K   | j         r9	 | j                            | j                   d{V  dS # t          $ r Y dS w xY wdS )z<Exit async context manager, optionally deleting the sandbox.N)r'   r%   delete_sandboxr   	Exception)r7   r9   r;   r=   s       r1   	__aexit__zAsyncSandbox.__aexit__e   st        	l11$)<<<<<<<<<<<   	 	s   %2 
A A c                    | j         dk    r t          d| j         d| j          d          | j        st	          d| j         d          | j        S )a  Validate and return the dataplane URL.

        Returns:
            The dataplane URL.

        Raises:
            SandboxNotReadyError: If sandbox status is not "ready".
            DataplaneNotConfiguredError: If dataplane_url is not configured.
        r   z	Sandbox 'z' is not ready (status: z5). Wait for status 'ready' before running operations.zW' does not have a dataplane_url configured. Runtime operations require a dataplane URL.)r   r   r   r   r   r6   s    r1   _require_dataplane_urlz#AsyncSandbox._require_dataplane_urls   s     ;'!!&EDI E Et{ E E E   ! 	->DI > > >   !!r3   .)timeoutenvcwdshell	on_stdout	on_stderridle_timeoutkill_on_disconnectttl_secondsptywaitcommandrF   intrG   Optional[dict[str, str]]rH   rI   rJ   Optional[Callable[[str], Any]]rK   rL   rM   rN   rO   rP   Literal[True]r   c               
   K   d S Nr5   r7   rQ   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   s                r1   runzAsyncSandbox.run   s        #r3   
rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   Literal[False]r   c               
   K   d S rW   r5   rX   s                r1   rY   zAsyncSandbox.run   s        !Sr3   <   z	/bin/bashi,  iX  *Union[ExecutionResult, AsyncCommandHandle]c                 K   |s|s|rt          d          |                                  | p|p|}|r'|                     ||||||||||	|
|           d{V S 	 |                     |||||ddd||	|
|           d{V S # t          t          t
          t          f$ r# |                     |||||           d{V cY S w xY w)am
  Execute a command in the sandbox asynchronously.

        Args:
            command: Shell command to execute.
            timeout: Command timeout in seconds.
            env: Environment variables to set for the command.
            cwd: Working directory for command execution. If None, uses sandbox default.
            shell: Shell to use for command execution. Defaults to "/bin/bash".
            on_stdout: Callback invoked with each stdout chunk as it arrives.
                Blocks until the command completes and returns ExecutionResult.
                Cannot be combined with wait=False.
            on_stderr: Callback invoked with each stderr chunk as it arrives.
                Blocks until the command completes and returns ExecutionResult.
                Cannot be combined with wait=False.
            idle_timeout: Idle timeout in seconds. If the command has no
                connected clients for this duration, it is killed. Defaults
                to 300 (5 minutes). Set to -1 for no idle timeout.
                Only applies to WebSocket execution.
            kill_on_disconnect: If True, kill the command immediately when
                the last client disconnects. Defaults to False (command
                continues running and can be reconnected to).
            ttl_seconds: How long (in seconds) a finished command's session
                is kept for reconnection. Defaults to 600 (10 minutes).
                Set to -1 to keep indefinitely.
            pty: If True, allocate a pseudo-terminal for the command.
                Useful for commands that require a TTY (e.g., interactive
                programs, commands that use terminal control codes).
                Defaults to False.
            wait: If True (default), block until the command completes and
                return ExecutionResult. If False, return an
                AsyncCommandHandle immediately for streaming output,
                kill, stdin input, and reconnection. Cannot be combined
                with on_stdout/on_stderr callbacks.

        Returns:
            ExecutionResult when wait=True (default).
            AsyncCommandHandle when wait=False.

        Raises:
            ValueError: If wait=False is combined with callbacks.
            DataplaneNotConfiguredError: If dataplane_url is not configured.
            SandboxOperationError: If command execution fails.
            CommandTimeoutError: If command exceeds its timeout.
            SandboxConnectionError: If connection to sandbox fails after retries.
            SandboxNotReadyError: If sandbox is not ready.
            SandboxClientError: For other errors.
        z}Cannot combine wait=False with on_stdout/on_stderr callbacks. Use wait=False and iterate the CommandHandle, or use callbacks.)rF   rG   rH   rI   rP   rJ   rK   rL   rM   rN   rO   NT)rF   rG   rH   rI   )
ValueErrorrE   _run_wsr   ImportErrorOSError	TypeError	_run_http)r7   rQ   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   use_wss                 r1   rY   zAsyncSandbox.run   s     ~  	 	i 	R  
 	##%%%3Y3) 	##)#5' &         "	)#5' &          'WiH 	 	 	 (           	s   &B =CC)rL   rM   rN   rO   c                 K   ddl m} |                                 }| j        j        } |||||||||||	|
||           d{V \  }}t          |||           }|                                 d{V  |s|S |j         d{V S )z"Execute via WebSocket /execute/ws.r   )run_ws_stream_asyncrZ   N)langsmith.sandbox._ws_executerh   rE   r%   _api_keyr   _ensure_startedresult)r7   rQ   rF   rG   rH   rI   rP   rJ   rK   rL   rM   rN   rO   rh   r   api_key
msg_streamcontrolhandles                      r1   ra   zAsyncSandbox._run_ws  s      " 	FEEEEE3355,'$7$7%1#%
 %
 %
 
 
 
 
 
 

G  $J>>$$&&&&&&&&& 	M]"""""""r3   c                 K   |                                  }| d}|||d}|||d<   |||d<   	 | j        j                            |||dz              d{V }	|	                                 |	                                }
t          |
                    dd	          |
                    d
d	          |
                    dd                    S # t          j	        $ r}t          |            d}~ww xY w)z9Execute via HTTP POST /execute (existing implementation).z/execute)rQ   rF   rI   NrG   rH   
   )jsonrF   stdoutr.   stderr	exit_code)rt   ru   rv   )rE   r%   _httppostraise_for_statusrs   r   r/   httpxHTTPStatusErrorr   )r7   rQ   rF   rG   rH   rI   r   urlpayloadresponser(   es               r1   re   zAsyncSandbox._run_httpM  sG      3355(((#
 #

 ? GEN? GEN	!\/44'7R< 5        H %%'''==??D"xx"--xx"--((;33   
 $ 	 	 	%a(((	s   B C C6!C11C6r   stdout_offsetstderr_offset
command_idr   r   c                  K   ddl m} |                                 }| j        j        } ||||||           d{V \  }}t          ||| |||          S )a  Reconnect to a running or recently-finished command.

        Resumes output from the given byte offsets. Any output produced while
        the client was disconnected is replayed from the server's ring buffer.

        Args:
            command_id: The command ID from handle.command_id.
            stdout_offset: Byte offset to resume stdout from (default: 0).
            stderr_offset: Byte offset to resume stderr from (default: 0).

        Returns:
            An AsyncCommandHandle for the command.

        Raises:
            SandboxOperationError: If command_id is not found or session expired.
            SandboxConnectionError: If connection to sandbox fails after retries.
        r   )reconnect_ws_stream_asyncr   N)r   r   r   )ri   r   rE   r%   rj   r   )	r7   r   r   r   r   r   rm   rn   ro   s	            r1   	reconnectzAsyncSandbox.reconnectr  s      0 	LKKKKK3355,'$=$=''%
 %
 %
 
 
 
 
 
 

G "!''
 
 
 	
r3   )rF   pathcontentUnion[str, bytes]c               t  K   |                                  }| d}t          |t                    r|                    d          }dd|fi}	 | j        j                            |d|i||           d{V }|                                 dS # t          j	        $ r}t          |           Y d}~dS d}~ww xY w)a9  Write content to a file in the sandbox asynchronously.

        Args:
            path: Target file path in the sandbox.
            content: File content (str or bytes).
            timeout: Request timeout in seconds.

        Raises:
            DataplaneNotConfiguredError: If dataplane_url is not configured.
            SandboxOperationError: If file write fails.
            SandboxConnectionError: If connection to sandbox fails after retries.
            SandboxNotReadyError: If sandbox is not ready.
            SandboxClientError: For other errors.
        z/uploadzutf-8filer   )paramsfilesrF   N)rE   
isinstancer   encoder%   rx   ry   rz   r{   r|   r   )	r7   r   r   rF   r   r}   r   r   r   s	            r1   writezAsyncSandbox.write  s     * 3355''' gs## 	.nnW--G&'*+	)!\/44VTN% 5        H %%'''''$ 	) 	) 	)%a(((((((((	)s   ?B B7B22B7bytesc               n  K   |                                  }| d}	 | j        j                            |d|i|           d{V }|                                 |j        S # t          j        $ rC}|j        j	        dk    rt          d| d| j         dd	
          |t          |            d}~ww xY w)a  Read a file from the sandbox asynchronously.

        Args:
            path: File path to read. Supports both absolute paths (e.g., /tmp/file.txt)
                  and relative paths (resolved from /home/user/).
            timeout: Request timeout in seconds.

        Returns:
            File contents as bytes.

        Raises:
            DataplaneNotConfiguredError: If dataplane_url is not configured.
            ResourceNotFoundError: If the file doesn't exist.
            SandboxOperationError: If file read fails.
            SandboxConnectionError: If connection to sandbox fails after retries.
            SandboxNotReadyError: If sandbox is not ready.
            SandboxClientError: For other errors.
        z	/downloadr   )r   rF   Ni  zFile 'z' not found in sandbox ''r   )resource_type)rE   r%   rx   r/   rz   r   r{   r|   r   status_coder   r   r   )r7   r   rF   r   r}   r   r   s          r1   readzAsyncSandbox.read  s     & 3355)))	!\/33VTNG 4        H %%'''##$ 	 	 	z%,,+GTGG49GGG"(    &a(((	s   AA" "B41>B//B4   
local_portmax_reconnectsremote_portr   r   r   c               p  K   d|cxk    rdk    sn t          d| d          |r"d|cxk    rdk    sn t          d| d          |                                 }| j        j        }t	          |||||          }t          j                    }|                    d|j        j	                   d{V  |S )a[  Open a TCP tunnel to a port inside the sandbox.

        Creates a local TCP listener that forwards connections through a
        yamux-multiplexed WebSocket to the specified port inside the sandbox.
        Works with any TCP protocol (databases, Redis, HTTP, etc.).

        Usage::

            async with await sandbox.tunnel(remote_port=5432) as t:
                conn = await asyncpg.connect(host="127.0.0.1", port=t.local_port)

        Args:
            remote_port: TCP port inside the sandbox to tunnel to (1-65535).
            local_port: Local port to listen on. Defaults to mirroring
                remote_port. Use 0 to let the OS pick an available port.
            max_reconnects: Maximum number of automatic reconnect attempts
                when the WebSocket session drops. Set to 0 to disable.

        Returns:
            An AsyncTunnel instance (async context manager).

        Raises:
            ValueError: If port values are out of range.
            DataplaneNotConfiguredError: If dataplane_url is not configured.
            SandboxNotReadyError: If sandbox is not ready.
           i  z-remote_port must be between 1 and 65535 (got )z,local_port must be between 1 and 65535 (got r   N)
r`   rE   r%   rj   r   asyncioget_running_looprun_in_executor_tunnel_start)r7   r   r   r   r   rm   tloops           r1   tunnelzAsyncSandbox.tunnel  s     B K((((5((((NNNN    	a:66666666LzLLL   3355,'!)
 
 
 '))""4)9:::::::::r3   )T)r(   r)   r*   r   r+   r&   r,   r   )r,   r   )r9   r:   r;   r<   r=   r>   r,   r?   )r,   r   )rQ   r   rF   rR   rG   rS   rH   r   rI   r   rJ   rT   rK   rT   rL   rR   rM   r&   rN   rR   rO   r&   rP   rU   r,   r   )rQ   r   rF   rR   rG   rS   rH   r   rI   r   rJ   rT   rK   rT   rL   rR   rM   r&   rN   rR   rO   r&   rP   r[   r,   r   )rQ   r   rF   rR   rG   rS   rH   r   rI   r   rJ   rT   rK   rT   rL   rR   rM   r&   rN   rR   rO   r&   rP   r&   r,   r^   )rQ   r   rF   rR   rG   rS   rH   r   rI   r   rP   r&   rJ   rT   rK   rT   rL   rR   rM   r&   rN   rR   rO   r&   r,   r^   )rQ   r   rF   rR   rG   rS   rH   r   rI   r   r,   r   )r   r   r   rR   r   rR   r,   r   )r   r   r   r   rF   rR   r,   r?   )r   r   rF   rR   r,   r   )r   rR   r   rR   r   rR   r,   r   )__name__
__module____qualname____doc____annotations__r   r   r   r    r!   r"   r   r%   r'   classmethodr2   r8   rC   rE   r   rY   ra   re   r   r   r   r   r5   r3   r1   r   r      s         0 III#'M''''BF$(N(((( $J$$$$ $J$$$$ #(%UD"A"A"AGAAAAE4888L8888
 !	
 
 
 
 [
:      " " " ", 
 (+ 4747#&!     X" 
 (+ 4747#&! ! ! ! ! X!* (,! 4848#(p p p p p pz  #(,# ,# ,# ,# ,# ,#\# # # #R ,
 ,
 ,
 ,
 ,
 ,
f $) $) $) $) $) $)L 79 $ $ $ $ $ $T 4 4 4 4 4 4 4 4r3   r   )r   
__future__r   r   dataclassesr   r   typingr   r   r   r	   r
   r   r   r{   langsmith.sandbox._exceptionsr   r   r   r   langsmith.sandbox._helpersr   langsmith.sandbox._modelsr   r   langsmith.sandbox._tunnelr   langsmith.sandbox._async_clientr   r   r5   r3   r1   <module>r      sm   6 6 " " " " " "  ( ( ( ( ( ( ( ( S S S S S S S S S S S S S S S S S S             A @ @ @ @ @        2 1 1 1 1 1 CBBBBBB C C C C C C C C C Cr3   