
    a
iK                        d Z ddlm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 )z?Sandbox class for interacting with a specific sandbox instance.    )annotations)	dataclassfield)TYPE_CHECKINGAnyCallableLiteralOptionalUnionoverloadN)DataplaneNotConfiguredErrorResourceNotFoundErrorSandboxConnectionErrorSandboxNotReadyError)handle_sandbox_http_error)CommandHandleExecutionResult)Tunnel)SandboxClientc                     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SandboxaO  Represents an active sandbox for running commands and file operations.

    This class is typically obtained from SandboxClient.sandbox() and supports
    the 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:
        with client.sandbox(template_name="python-sandbox") as sandbox:
            result = 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 )a4  Create a Sandbox from API response dict.

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

        Returns:
            Sandbox 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/_sandbox.py	from_dictzSandbox.from_dictB   s    " s&"%%((?B77((?33xx~~88Hg..88$455xx--xx--$
 
 
 	
    c                    | S )zEnter context manager. selfs    r1   	__enter__zSandbox.__enter__`   s    r3   exc_typeOptional[type]exc_valOptional[BaseException]exc_tbOptional[Any]Nonec                z    | j         r3	 | j                            | j                   dS # t          $ r Y dS w xY wdS )z6Exit context manager, optionally deleting the sandbox.N)r'   r%   delete_sandboxr   	Exception)r7   r9   r;   r=   s       r1   __exit__zSandbox.__exit__d   s^      	++DI66666   	 	s   * 
88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Sandbox._require_dataplane_urlr   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                   d S Nr5   r7   rQ   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   s                r1   runzSandbox.run   s	      #r3   
rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   Literal[False]r   c                   d S rW   r5   rX   s                r1   rY   zSandbox.run   s	      r3   <   z	/bin/bashi,  iX  %Union[ExecutionResult, CommandHandle]c               f   |s|s|rt          d          |                                  | p|p|}|r!|                     ||||||||||	|
|          S 	 |                     |||||ddd||	|
|          S # t          t          t
          t          f$ r |                     |||||          cY S w xY w)aS
  Execute a command in the sandbox.

        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 a
                CommandHandle immediately for streaming output,
                kill, stdin input, and reconnection. Cannot be combined with
                on_stdout/on_stderr callbacks.

        Returns:
            ExecutionResult when wait=True (default).
            CommandHandle 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   TN)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Sandbox.run   s?   ~  	 	i 	R  
 	##%%% 3Y3) 	<<##)#5'     $	<<)#5'      'WiH 	 	 	>> "     	s    A6 67B0/B0)rL   rM   rN   rO   c                   ddl m} |                                 }| j        j        } |||||||||||	|
||          \  }}t          |||           }|s|S |j        S )z"Execute via WebSocket /execute/ws.r   )run_ws_streamrZ   )langsmith.sandbox._ws_executerh   rE   r%   _api_keyr   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Sandbox._run_ws   s    " 	@?????3355,'+m%1#
 
 

G  z7D99 	M}r3   c                  |                                  }| d}|||d}|||d<   |||d<   	 | j        j                            |||dz             }	|	                                 |	                                }
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)rs   rt   ru   )rE   r%   _httppostraise_for_statusrr   r   r/   httpxHTTPStatusErrorr   )r7   rQ   rF   rG   rH   rI   r   urlpayloadresponser(   es               r1   re   zSandbox._run_httpM  s    3355(((#
 #

 ? GEN? GEN	|)..s'TV,.WWH%%'''==??D"xx"--xx"--((;33   
 $ 	 	 	%a(((	s   BC
 
C.C))C.r   stdout_offsetstderr_offset
command_idr   r   c                   ddl m} |                                 }| j        j        } ||||||          \  }}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:
            A CommandHandle 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_streamr   )r   r   r   )ri   r   rE   r%   rj   r   )	r7   r   r   r   r   r   rl   rm   rn   s	            r1   	reconnectzSandbox.reconnectp  s    0 	FEEEEE3355,'11''
 
 

G !''
 
 
 	
r3   )rF   pathcontentUnion[str, bytes]c               d   |                                  }| d}t          |t                    r|                    d          }dd|fi}	 | j        j                            |d|i||          }|                                 dS # t          j	        $ r}t          |           Y d}~dS d}~ww xY w)a*  Write content to a file in the sandbox.

        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%   rw   rx   ry   rz   r{   r   )	r7   r   r   rF   r   r|   r   r~   r   s	            r1   writezSandbox.write  s    * 3355''' gs## 	.nnW--G&'*+	)|)..VTN% /  H %%'''''$ 	) 	) 	)%a(((((((((	)s   9B B/B**B/bytesc               ^   |                                  }| d}	 | j        j                            |d|i|          }|                                 |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.

        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   i  zFile 'z' not found in sandbox ''r   )resource_typeN)rE   r%   rw   r/   ry   r   rz   r{   r~   status_coder   r   r   )r7   r   rF   r   r|   r~   r   s          r1   readzSandbox.read  s    & 3355)))	|)--VTNG .  H %%'''##$ 	 	 	z%,,+GTGG49GGG"(    &a(((	s   >A B,)>B''B,   
local_portmax_reconnectsremote_portr   r   r   c               "   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	          |||||          }|                                 |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.).

        Use as a context manager for automatic cleanup::

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

        Or manage the lifecycle explicitly::

            t = sandbox.tunnel(remote_port=5432)
            # ... use tunnel ...
            t.close()

        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:
            A Tunnel instance (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   )r`   rE   r%   rj   r   _start)r7   r   r   r   r   rl   ts          r1   tunnelzSandbox.tunnel  s    N K((((5((((NNNN    	a:66666666LzLLL   3355,'!)
 
 
 	



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$$$$ #Ut<<<G<<<<E4888L8888
 !	
 
 
 
 [
:      " " " ", 
 (+ 4747#&!     X" 
 (+ 4747#&     X* (,! 4848#(r r r r r r~  #(+ + + + + +Z! ! ! !N ,
 ,
 ,
 ,
 ,
 ,
f $) $) $) $) $) $)L 13 $ $ $ $ $ $T 9 9 9 9 9 9 9 9r3   r   )r   
__future__r   dataclassesr   r   typingr   r   r   r	   r
   r   r   rz   langsmith.sandbox._exceptionsr   r   r   r   langsmith.sandbox._helpersr   langsmith.sandbox._modelsr   r   langsmith.sandbox._tunnelr   langsmith.sandbox._clientr   r   r5   r3   r1   <module>r      sc   E E " " " " " " ( ( ( ( ( ( ( ( S S S S S S S S S S S S S S S S S S             A @ @ @ @ @        - , , , , , 8777777 G G G G G G G G G Gr3   