
    Zǻ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y)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	 d/	 	 	 	 	 	 	 d0d       Zd1dZ	 	 	 	 	 	 	 	 d2dZd3dZedddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d4d       Zeddddddddddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d5d       Zddddddd dd!ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d6d"Zd dd!dd#	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d7d$Z	 	 	 	 	 	 	 	 	 	 	 	 d8d%Zd&d&d'	 	 	 	 	 	 	 d9d(Zdd)	 	 	 	 	 	 	 d:d*Zdd)d;d+Zd&d,d-	 	 	 	 	 	 	 d<d.Zy)=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_deletec                    | |j                  dd      |j                  dd      |j                  d      |j                  d      |j                  dd      |j                  d      |j                  d	      |j                  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)clsdataclientauto_deletes       X/opt/lhia/marcimex/agent/venv/lib/python3.12/site-packages/langsmith/sandbox/_sandbox.py	from_dictzSandbox.from_dictB   s}    " &"%((?B7((?3xx~88Hg.88$45xx-xx-$
 	
    c                    | S )zEnter context manager. selfs    r/   	__enter__zSandbox.__enter__`   s    r1   c                    | j                   r'	 | j                  j                  | j                         yy# t        $ r Y yw xY w)z6Exit context manager, optionally deleting the sandbox.N)r'   r%   delete_sandboxr   	Exception)r5   exc_typeexc_valexc_tbs       r/   __exit__zSandbox.__exit__d   sA     ++DII6   s   %5 	A Ac                    | j                   dk7  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   r4   s    r/   _require_dataplane_urlzSandbox._require_dataplane_urlr   s{     ;;'!&DII;&>t{{m LE E  !!-DII; '> >  !!!r1   .)timeoutenvcwdshell	on_stdout	on_stderridle_timeoutkill_on_disconnectttl_secondsptywaitc                    y Nr3   r5   commandr@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   s                r/   runzSandbox.run   s      r1   
r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   c                    y rL   r3   rM   s                r/   rO   zSandbox.run   s      r1   <   z	/bin/bashi,  iX  c               >   |s|s|rt        d      | j                          | xs |xs |}|r| j                  ||||||||||	|
|      S 	 | j                  |||||ddd||	|
|      S # t        t        t
        t        f$ r | j                  |||||      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.)r@   rA   rB   rC   rJ   rD   rE   rF   rG   rH   rI   TN)r@   rA   rB   rC   )
ValueErrorr?   _run_wsr   ImportErrorOSError	TypeError	_run_http)r5   rN   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   use_wss                 r/   rO   zSandbox.run   s    ~ iR 
 	##% 3Y3)<<##)#5'    $	<<)#5'     'WiH 	>> "  	s   A* */BB)rF   rG   rH   rI   c                   ddl m} | j                         }| j                  j                  } |||||||||||	|
||      \  }}t        |||       }|s|S |j                  S )z"Execute via WebSocket /execute/ws.r   )run_ws_streamrP   )langsmith.sandbox._ws_executer\   r?   r%   _api_keyr   result)r5   rN   r@   rA   rB   rC   rJ   rD   rE   rF   rG   rH   rI   r\   r   api_key
msg_streamcontrolhandles                      r/   rU   zSandbox._run_ws   s}    " 	@335,,''+%1#

G  z7D9M}}r1   c                  | j                         }| d}|||d}|||d<   |||d<   	 | j                  j                  j                  |||dz         }	|	j	                          |	j                         }
t        |
j                  dd	      |
j                  d
d	      |
j                  dd            S # t        j                  $ r}t        |        d}~ww xY w)z9Execute via HTTP POST /execute (existing implementation).z/execute)rN   r@   rC   NrA   rB   
   )jsonr@   stdoutr)   stderr	exit_code)rg   rh   ri   )r?   r%   _httppostraise_for_statusrf   r   r*   httpxHTTPStatusErrorr   )r5   rN   r@   rA   rB   rC   r   urlpayloadresponser,   es               r/   rY   zSandbox._run_httpM  s     335x(#

 ? GEN? GEN	||))..s'TV,.WH%%'==?D"xx"-xx"-((;3 
 $$ 	%a(	s   BB4 4CCCr   stdout_offsetstderr_offsetc                   ddl m} | j                         }| 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_streamrt   )
command_idru   rv   )r]   rx   r?   r%   r^   r   )	r5   ry   ru   rv   rx   r   r`   ra   rb   s	            r/   	reconnectzSandbox.reconnectp  sd    0 	F335,,''1''

G !''
 	
r1   )r@   c               J   | j                         }| d}t        |t              r|j                  d      }dd|fi}	 | j                  j
                  j                  |d|i||      }|j                          y# t        j                  $ r}t        |       Y d}~y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filepath)paramsfilesr@   N)r?   
isinstancer   encoder%   rk   rl   rm   rn   ro   r   )	r5   r}   contentr@   r   rp   r   rr   rs   s	            r/   writezSandbox.write  s    * 335w' gs#nnW-G&'*+	)||))..VTN% / H %%'$$ 	)%a((	)s   ;A: :B"BB"c               x   | j                         }| d}	 | j                  j                  j                  |d|i|      }|j	                          |j
                  S # t        j                  $ rI}|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~   r@   i  zFile 'z' not found in sandbox ''r|   )resource_typeN)r?   r%   rk   r*   rm   r   rn   ro   rr   status_coder   r   r   )r5   r}   r@   r   rp   rr   rs   s          r/   readzSandbox.read  s    & 335y)	||))--VTNG . H %%'###$$ 	zz%%,+TF":499+QG"(  &a(	s   AA B90AB44B9   
local_portmax_reconnectsc                  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                  j                  }t	        |||||      }|j                          |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   )rT   r?   r%   r^   r   _start)r5   remote_portr   r   r   r`   ts          r/   tunnelzSandbox.tunnel  s    N K(5(?}AN  a:66>zl!L  335,,''!)
 	

r1   )T)r,   zdict[str, Any]r-   r   r.   r&   returnr   )r   r   )r:   zOptional[type]r;   zOptional[BaseException]r<   zOptional[Any]r   None)r   r   )rN   r   r@   intrA   Optional[dict[str, str]]rB   r   rC   r   rD   Optional[Callable[[str], Any]]rE   r   rF   r   rG   r&   rH   r   rI   r&   rJ   zLiteral[True]r   r   )rN   r   r@   r   rA   r   rB   r   rC   r   rD   r   rE   r   rF   r   rG   r&   rH   r   rI   r&   rJ   zLiteral[False]r   r   )rN   r   r@   r   rA   r   rB   r   rC   r   rD   r   rE   r   rF   r   rG   r&   rH   r   rI   r&   rJ   r&   r   %Union[ExecutionResult, CommandHandle])rN   r   r@   r   rA   r   rB   r   rC   r   rJ   r&   rD   r   rE   r   rF   r   rG   r&   rH   r   rI   r&   r   r   )rN   r   r@   r   rA   r   rB   r   rC   r   r   r   )ry   r   ru   r   rv   r   r   r   )r}   r   r   zUnion[str, bytes]r@   r   r   r   )r}   r   r@   r   r   bytes)r   r   r   r   r   r   r   r   )__name__
__module____qualname____doc____annotations__r   r   r   r    r!   r"   r   r%   r'   classmethodr0   r6   r=   r?   r   rO   rU   rY   rz   r   r   r   r3   r1   r/   r   r      s   0 I#'M='BFC$(NM( $J$ $J$ #t<G]<E48L$8
 !	

 
 	

 

 
:  ) 	
 
", 
 (+ 4747#&! 	
 &   2 2  !    
 " 
 (+ 4747#& 	
 &   2 2  !    
 * (,! 4848#(rr 	r
 &r r r 2r 2r r !r r r r 
/r~  #(++ 	+
 &+ + + + 2+ 2+ + !+ + + 
/+Z!! 	!
 &! ! ! 
!N ,
,
 	,

 ,
 
,
f $)$) #$)
 $) 
$)L 13 $T 99 	9
 9 
9r1   r   )r   
__future__r   dataclassesr   r   typingr   r   r   r	   r
   r   r   rn   langsmith.sandbox._exceptionsr   r   r   r   langsmith.sandbox._helpersr   langsmith.sandbox._modelsr   r   langsmith.sandbox._tunnelr   langsmith.sandbox._clientr   r   r3   r1   r/   <module>r      sV    E " ( S S S   A -7 G G Gr1   