
    bi#                        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
 ddlZddlmZmZmZ ddlmZ ddlmZ erdd	lmZ e G d
 d             Zy)z0AsyncSandbox class for async sandbox operations.    )annotations)	dataclassfield)TYPE_CHECKINGAnyOptionalUnionN)DataplaneNotConfiguredErrorResourceNotFoundErrorSandboxConnectionError)handle_sandbox_http_error)ExecutionResult)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
<    e	dd      Z
ded<    e	dd      Zded<   e	 d	 	 	 	 	 	 	 dd       ZddZ	 	 	 	 	 	 	 	 d dZd!dZddddd	 	 	 	 	 	 	 	 	 	 	 d"dZdd	 	 	 	 	 	 	 d#dZddd$dZy)%AsyncSandboxa  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).
        id: Unique identifier (UUID). Remains constant even if name changes.
            May be None for resources created before ID support was added.
        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
created_at
updated_atF)reprdefaultr   _clientTbool_auto_deletec           
          | |j                  dd      |j                  dd      |j                  d      |j                  d      |j                  d      |j                  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   )get)clsdataclientauto_deletes       j/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/langsmith/sandbox/_async_sandbox.py	from_dictzAsyncSandbox.from_dict8   sb    " &"%((?B7((?3xx~xx-xx-$	
 		
    c                   K   | S w)zEnter async context manager. selfs    r&   
__aenter__zAsyncSandbox.__aenter__T   s     s   c                   K   | j                   r/	 | j                  j                  | j                         d{    yy7 # t        $ r Y yw xY ww)z<Exit async context manager, optionally deleting the sandbox.N)r   r   delete_sandboxr   	Exception)r,   exc_typeexc_valexc_tbs       r&   	__aexit__zAsyncSandbox.__aexit__X   sK      ll11$))<<< < s5   A(A ?A AA 	A
AAAc                d    | j                   st        d| j                   d      | j                   S )zValidate and return the dataplane URL.

        Returns:
            The dataplane URL.

        Raises:
            DataplaneNotConfiguredError: If dataplane_url is not configured.
        z	Sandbox 'zW' does not have a dataplane_url configured. Runtime operations require a dataplane URL.)r   r
   r   r+   s    r&   _require_dataplane_urlz#AsyncSandbox._require_dataplane_urlf   s=     !!-DII; '> >  !!!r(   <   z	/bin/bash)timeoutenvcwdshellc               6  K   | j                         }| d}|||d}|||d<   |||d<   	 | j                  j                  j                  |||dz          d{   }	|	j	                          |	j                         }
t        |
j                  dd	      |
j                  d
d	      |
j                  dd            S 7 b# t        j                  $ r!}t        d| j                   d|       |d}~wt        j                  $ r}t        |        d}~ww xY ww)a0  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".

        Returns:
            ExecutionResult with stdout, stderr, and exit_code.

        Raises:
            DataplaneNotConfiguredError: If dataplane_url is not configured.
            SandboxOperationError: If command execution fails.
            SandboxConnectionError: If connection to sandbox fails.
            SandboxNotReadyError: If sandbox is not ready.
            SandboxClientError: For other errors.
        z/execute)commandr8   r;   Nr9   r:   
   )jsonr8   stdoutr    stderr	exit_code)r@   rA   rB   Failed to connect to sandbox '': )r6   r   _httppostraise_for_statusr?   r   r!   httpxConnectErrorr   r   HTTPStatusErrorr   )r,   r=   r8   r9   r:   r;   r   urlpayloadresponser#   es               r&   runzAsyncSandbox.runv   s0    8 335x(#

 ? GEN? GEN	!\\//44'7R< 5  H %%'==?D"xx"-xx"-((;3  !! 	(03qcB $$ 	%a(	sG   *D.C  B>A!C  =D>C   DC//DDDD)r8   c                 K   | j                         }| d}t        |t              r|j                  d      }dd|fi}	 | j                  j
                  j                  |d|i||       d{   }|j                          y7 # t        j                  $ r!}t        d| j                   d|       |d}~wt        j                  $ r}t        |       Y d}~yd}~ww xY ww)	a+  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.
            SandboxNotReadyError: If sandbox is not ready.
            SandboxClientError: For other errors.
        z/uploadzutf-8filepath)paramsfilesr8   NrD   rE   )r6   
isinstancer   encoder   rF   rG   rH   rI   rJ   r   r   rK   r   )	r,   rS   contentr8   r   rL   rU   rN   rO   s	            r&   writezAsyncSandbox.write   s     * 335w' gs#nnW-G&'*+
	)!\\//44VTN% 5  H %%' !! 	(03qcB $$ 	)%a((	)sM   =C# .B .B/B C#B C B55C CC#C  C#c                 K   | j                         }| d}	 | j                  j                  j                  |d|i|       d{   }|j	                          |j
                  S 7  # t        j                  $ r!}t        d| j                   d|       |d}~wt        j                  $ rI}|j                  j                  dk(  rt        d| d	| j                   d
d      |t        |        d}~ww xY w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.
            SandboxNotReadyError: If sandbox is not ready.
            SandboxClientError: For other errors.
        z	/downloadrS   )rT   r8   NrD   rE   i  zFile 'z' not found in sandbox ''rR   )resource_type)r6   r   rF   r!   rH   rX   rI   rJ   r   r   rK   rN   status_coder   r   )r,   rS   r8   r   rL   rN   rO   s          r&   readzAsyncSandbox.read   s    & 335y)	!\\//33VTNG 4  H %%'###	
 !! 	(03qcB $$ 	zz%%,+TF":499+QG"(  &a(	sG   C:-A) A'A) &C:'A) )C7<BC7.AC22C77C:)T)r#   zdict[str, Any]r$   r   r%   r   returnr   )r_   r   )r1   zOptional[type]r2   zOptional[BaseException]r3   zOptional[Any]r_   None)r_   r   )r=   r   r8   intr9   zOptional[dict[str, str]]r:   r   r;   r   r_   r   )rS   r   rX   zUnion[str, bytes]r8   ra   r_   r`   )rS   r   r8   ra   r_   bytes)__name__
__module____qualname____doc____annotations__r   r   r   r   r   r   r   classmethodr'   r-   r4   r6   rP   rY   r^   r*   r(   r&   r   r      s\   * I#'M='B $J$ $J$ #(UD"AGAE48L$8
 !	

 #
 	

 

 
6  ) 	
 
"( (,! :: 	:
 &: : : 
:B ()() #()
 () 
()T 79 (r(   r   )rf   
__future__r   dataclassesr   r   typingr   r   r   r	   rI   langsmith.sandbox._exceptionsr
   r   r   langsmith.sandbox._helpersr   langsmith.sandbox._modelsr   langsmith.sandbox._async_clientr   r   r*   r(   r&   <module>rp      sL    6 " ( 6 6  
 A 5B m m mr(   