
    joc                        d Z ddlm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mZmZ dd
lmZ e	rddlm Z  eee!e!f                  Z"e G d d                      Z#dS )z?Sandbox class for interacting with a specific sandbox instance.    )annotations)Mapping)	dataclassfield)TYPE_CHECKINGAnyCallableLiteralOptionalUnionoverloadN)DataplaneNotConfiguredErrorResourceNotFoundErrorSandboxConnectionErrorSandboxNotReadyError)handle_sandbox_http_error)CommandHandleExecutionResult
ServiceURLSnapshot)Tunnel)SandboxClientc                     e Zd ZU 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<   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<   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	 dndod!            Zdpd"Zdqd*Zdrd+Zed,d,d,d,d,d,d,d,d,d,d,d,d-dsd@            Zed,d,d,d,d,d,d,d,d,d,d,dAdtdD            ZdEdddFdddGddHdddd-dudJZdGddHdddKdvdLZdwdMZdNdNddOdxdSZdEddTdydXZdEddTdzdZZ dNd[dd\d{daZ!dHddbd|dfZ"dgddTd}dhZ#ddid~djZ$ddid~dkZ%dEddTddmZ&dS )Sandboxa  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).
        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", "stopped".
        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.
        ttl_seconds: Maximum lifetime TTL in seconds (0 means disabled).
        idle_ttl_seconds: Idle timeout TTL in seconds (``0`` means disabled).
            Newly-created sandboxes receive a server-side default of ``600``
            seconds (10 minutes) when the caller did not set ``idle_ttl_seconds``
            explicitly.
        expires_at: Computed expiration timestamp, or None if no TTL is set.
        snapshot_id: Snapshot ID used to create this sandbox.
        vcpus: Number of vCPUs allocated.
        mem_bytes: Memory allocation in bytes.
        fs_capacity_bytes: Root filesystem capacity in bytes.

    Example:
        with client.sandbox(snapshot_id="<snapshot-uuid>") as sandbox:
            result = sandbox.run("python --version")
            print(result.stdout)
    strnameNOptional[str]dataplane_urlidreadystatusstatus_message
created_at
updated_atzOptional[int]ttl_secondsidle_ttl_seconds
expires_atsnapshot_idvcpus	mem_bytesfs_capacity_bytesF)reprdefaultr   _clientTbool_auto_deletedatadict[str, Any]clientauto_deletereturnc           	         | di d|                     dd          d|                     d          d|                     d          d|                     dd          d|                     d          d|                     d          d	|                     d	          d
|                     d
          d|                     d          d|                     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.   r0    )get)clsr1   r3   r4   s       d/lsinfo/ai/hellotax_ai/base_platform/venv/lib/python3.11/site-packages/langsmith/sandbox/_sandbox.py	from_dictzSandbox.from_dictX   s   " s 
 
 
&"%%%
((?333
 xx~~~
 88Hg...	

  88$4555
 xx---
 xx---
 ///
 "XX&8999
 xx---
 ///
 ((7###
 hh{+++
 #hh':;;;
 F
  %!
 	
    c                    | S )zEnter context manager.r8   selfs    r;   	__enter__zSandbox.__enter__|   s    r=   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)r0   r.   delete_sandboxr   	Exception)r@   rB   rD   rF   s       r;   __exit__zSandbox.__exit__   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   r?   s    r;   _require_dataplane_urlzSandbox._require_dataplane_url   s     ;'!!&EDI E Et{ E E E   ! 	->DI > > >   !!r=   .)timeoutenvcwdshell	on_stdout	on_stderridle_timeoutkill_on_disconnectr%   ptyheaderswaitcommandrO   intrP   Optional[dict[str, str]]rQ   rR   rS   Optional[Callable[[str], Any]]rT   rU   rV   rW   rX   RequestHeadersrY   Literal[True]r   c                   d S Nr8   r@   rZ   rO   rP   rQ   rR   rS   rT   rU   rV   r%   rW   rX   rY   s                 r;   runzSandbox.run   s	    " #r=   )rO   rP   rQ   rR   rS   rT   rU   rV   r%   rW   rX   Literal[False]r   c                   d S ra   r8   rb   s                 r;   rc   zSandbox.run   s	    " r=   <   z	/bin/bashi,  iX  %Union[ExecutionResult, CommandHandle]c               l   |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.)rO   rP   rQ   rR   rY   rS   rT   rU   rV   r%   rW   rX   TN)rO   rP   rQ   rR   rX   )
ValueErrorrN   _run_wsr   ImportErrorOSError	TypeError	_run_http)r@   rZ   rO   rP   rQ   rR   rS   rT   rU   rV   r%   rW   rX   rY   use_wss                  r;   rc   zSandbox.run   sH   @  	 	i 	R  
 	##%%% 3Y3) 	<<##)#5'     &	<<)#5'      'WiH 	 	 	>> "     	s   !A8 88B32B3)rU   rV   r%   rW   rX   c                   ddl m} |                                 }| j        j        }|||||||	|
||d
}|||d<    ||||fi |\  }}t          |||           }|s|S |j        S )z"Execute via WebSocket /execute/ws.r   )run_ws_stream)
rO   rP   rQ   rR   rS   rT   rU   rV   r%   rW   NrX   )langsmith.sandbox._ws_executerq   rN   r.   _api_keyr   result)r@   rZ   rO   rP   rQ   rR   rY   rS   rT   rU   rV   r%   rW   rX   rq   r   api_key	ws_kwargs
msg_streamcontrolhandles                        r;   rj   zSandbox._run_wsB  s    $ 	@?????3355,' ""("4&%
 %
	 #*Ii +m
 
 	
 

G z7D99 	M}r=   c                  |                                  }| d}|||d}	|||	d<   |||	d<   	 | j        j                            ||	|dz   | j                            |                    }
|
                                 |
                                }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)rZ   rO   rR   NrP   rQ   
   )jsonrO   rX   stdoutr7   stderr	exit_code)r}   r~   r   )rN   r.   _httppost_request_headersraise_for_statusr|   r   r9   httpxHTTPStatusErrorr   )r@   rZ   rO   rP   rQ   rR   rX   r   urlpayloadresponser1   es                r;   rn   zSandbox._run_httpv  s:    3355(((#
 #

 ? GEN? GEN	|).."55g>>	 /  H %%'''==??D"xx"--xx"--((;33   
 $ 	 	 	%a(((	s   B3C# #D2DDr   )stdout_offsetstderr_offsetrX   
command_idr   r   c                   ddl m} |                                 }| j        j        }||d}|||d<    ||||fi |\  }	}
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_stream)r   r   NrX   )r   r   r   )rr   r   rN   r.   rs   r   )r@   r   r   r   rX   r   r   ru   reconnect_kwargsrw   rx   s              r;   	reconnectzSandbox.reconnect  s    2 	FEEEEE3355,' +*,
 ,
 *1Y'11
 
 	
 

G !''
 
 
 	
r=   rO   rX   pathcontentUnion[str, bytes]c          	        |                                  }| d}t          |t                    r|                    d          }dd|fi}	 | j        j                            |d|i||| j                            |                    }|                                 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filesrO   rX   N)rN   
isinstancer   encoder.   r   r   r   r   r   r   r   )
r@   r   r   rO   rX   r   r   r   r   r   s
             r;   writezSandbox.write  s    , 3355''' gs## 	.nnW--G&'*+
	)|)..~55g>> /  H %%'''''$ 	) 	) 	)%a(((((((((	)s   AB C.CCbytesc                  |                                  }| d}	 | j        j                            |d|i|| j                            |                    }|                                 |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   rO   rX   i  zFile 'z' not found in sandbox ''r   )resource_typeN)rN   r.   r   r9   r   r   r   r   r   r   status_coder   r   r   )r@   r   rO   rX   r   r   r   r   s           r;   readzSandbox.read  s    * 3355)))	|)--~55g>>	 .  H %%'''##$ 	 	 	z%,,+GTGG49GGG"(    &a(((	s   AA3 3C>C  C   
local_portmax_reconnectsrX   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   )ri   rN   r.   rs   r   _start)r@   r   r   r   rX   r   ru   ts           r;   tunnelzSandbox.tunnel*  s    P K((((5((((NNNN    	a:66666666LzLLL   3355,'!)
 
 
 	



r=   expires_in_secondsrX   portr   r   c               H    | j                             | j        |||          S )a  Get an authenticated URL for a service running in this sandbox.

        Returns a :class:`ServiceURL` whose properties auto-refresh the
        token transparently before it expires.

        Args:
            port: Port the service is listening on inside the sandbox.
            expires_in_seconds: Token TTL in seconds (1--86400, default 600).
            headers: Optional per-request header overrides.

        Returns:
            ServiceURL with auto-refreshing token and HTTP helpers.

        Raises:
            ResourceNotFoundError: If sandbox not found.
            ValueError: If port or expires_in_seconds is out of range.
            SandboxClientError: For other errors.
        r   )r.   servicer   )r@   r   r   rX   s       r;   r   zSandbox.serviceg  s1    2 |##I1	 $ 
 
 	
r=   x   c               z    | j                             | j        ||          }|j        | _        |j        | _        dS )a1  Start a stopped sandbox and wait until ready.

        After starting, the sandbox's status and dataplane_url are updated
        in place.

        Args:
            timeout: Timeout in seconds when waiting for ready.
            headers: Optional per-request header overrides.

        Raises:
            ResourceNotFoundError: If sandbox not found.
            ResourceCreationError: If sandbox fails during startup.
            ResourceTimeoutError: If sandbox doesn't become ready within timeout.
            SandboxClientError: For other errors.
        r   N)r.   start_sandboxr   r!   r   )r@   rO   rX   	refresheds       r;   startzSandbox.start  sF    * L..Iw / 
 
	  &&4r=   rX   c               d    | j                             | j        |           d| _        d| _        dS )a  Stop a running sandbox (preserves sandbox files for later restart).

        Args:
            headers: Optional per-request header overrides.

        Raises:
            ResourceNotFoundError: If sandbox not found.
            SandboxClientError: For other errors.
        r   stoppedN)r.   stop_sandboxr   r!   r   r@   rX   s     r;   stopzSandbox.stop  s6     	!!$)W!===!r=   c               H    | j                             | j        |           dS )zDelete this sandbox.

        Args:
            headers: Optional per-request header overrides.

        Raises:
            ResourceNotFoundError: If sandbox not found.
            SandboxClientError: For other errors.
        r   N)r.   rJ   r   r   s     r;   deletezSandbox.delete  s'     	##DIw#?????r=   r   c               H    | j                             | j        |||          S )a!  Capture a snapshot from this sandbox.

        Args:
            name: Snapshot name.
            timeout: Timeout in seconds when waiting for ready.
            headers: Optional per-request header overrides.

        Returns:
            Snapshot in "ready" status.

        Raises:
            ResourceNotFoundError: If sandbox not found.
            ResourceTimeoutError: If snapshot doesn't become ready within timeout.
            ResourceCreationError: If snapshot capture fails.
            SandboxClientError: For other errors.
        r   )r.   capture_snapshotr   )r@   r   rO   rX   s       r;   r   zSandbox.capture_snapshot  s1    . |,,I	 - 
 
 	
r=   )T)r1   r2   r3   r   r4   r/   r5   r   )r5   r   )rB   rC   rD   rE   rF   rG   r5   rH   )r5   r   )rZ   r   rO   r[   rP   r\   rQ   r   rR   r   rS   r]   rT   r]   rU   r[   rV   r/   r%   r[   rW   r/   rX   r^   rY   r_   r5   r   )rZ   r   rO   r[   rP   r\   rQ   r   rR   r   rS   r]   rT   r]   rU   r[   rV   r/   r%   r[   rW   r/   rX   r^   rY   rd   r5   r   )rZ   r   rO   r[   rP   r\   rQ   r   rR   r   rS   r]   rT   r]   rU   r[   rV   r/   r%   r[   rW   r/   rX   r^   rY   r/   r5   rg   )rZ   r   rO   r[   rP   r\   rQ   r   rR   r   rY   r/   rS   r]   rT   r]   rU   r[   rV   r/   r%   r[   rW   r/   rX   r^   r5   rg   )rZ   r   rO   r[   rP   r\   rQ   r   rR   r   rX   r^   r5   r   )
r   r   r   r[   r   r[   rX   r^   r5   r   )
r   r   r   r   rO   r[   rX   r^   r5   rH   )r   r   rO   r[   rX   r^   r5   r   )
r   r[   r   r[   r   r[   rX   r^   r5   r   )r   r[   r   r[   rX   r^   r5   r   )rO   r[   rX   r^   r5   rH   )rX   r^   r5   rH   )r   r   rO   r[   rX   r^   r5   r   )'__name__
__module____qualname____doc____annotations__r   r   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r   r.   r0   classmethodr<   rA   rL   rN   r   rc   rj   rn   r   r   r   r   r   r   r   r   r   r8   r=   r;   r   r   !   s?         D III#'M''''BF$(N(((( $J$$$$ $J$$$$!%K%%%%&***** $J$$$$!%K%%%%E#I####'+++++ #Ut<<<G<<<<E4888L8888
 !	!
 !
 !
 !
 [!
F      " " " ", 
 (+ 4747#&"%!     X$ 
 (+ 4747#&"%     X, (,! 4848#("&v v v v v vF  #("&2 2 2 2 2 2h' ' ' 'Z "&3
 3
 3
 3
 3
 3
t "&)) )) )) )) )) ))X ,.) ) ) ) ) )^ "&; ; ; ; ; ;B #&"&
 
 
 
 
 
F "&	5 5 5 5 5 56 15 " " " " " " 37 
@ 
@ 
@ 
@ 
@ 
@  "&
 
 
 
 
 
 
 
r=   r   )$r   
__future__r   collections.abcr   dataclassesr   r   typingr   r   r	   r
   r   r   r   r   langsmith.sandbox._exceptionsr   r   r   r   langsmith.sandbox._helpersr   langsmith.sandbox._modelsr   r   r   r   langsmith.sandbox._tunnelr   langsmith.sandbox._clientr   r   r^   r   r8   r=   r;   <module>r      s   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 '#s(+, v

 v

 v

 v

 v

 v

 v

 v

 v

 v

r=   