Ë
    ÂXÕi“R  ã                  óÞ   — 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 dd
lmZ e	rddlmZ eeeef      Z e G d„ d«      «       Z!y)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)ÚTunnel)ÚSandboxClientc                  óD  — 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<   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	 d3	 	 	 	 	 	 	 d4d„«       Zd5d„Z	 	 	 	 	 	 	 	 d6d„Zd7d„Zedddddddddddddœ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d8d„«       Zedddddddddddd œ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d9d!„«       Zd"ddd#ddd$dd%ddddœ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d:d&„Zd$dd%ddd'œ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d;d(„Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 d<d)„Zd*d*dd+œ	 	 	 	 	 	 	 	 	 d=d,„Zd"dd-œ	 	 	 	 	 	 	 	 	 d>d.„Zd"dd-œ	 	 	 	 	 	 	 d?d/„Zd*d0dd1œ	 	 	 	 	 	 	 	 	 d@d2„Zy)AÚ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).
        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.
        ttl_seconds: Maximum lifetime TTL in seconds (0 means disabled).
        idle_ttl_seconds: Idle timeout TTL in seconds (0 means disabled).
        expires_at: Computed expiration timestamp, or None if no TTL is set.

    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_atzOptional[int]Úttl_secondsÚidle_ttl_secondsÚ
expires_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
«      |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"   r#   r$   r%   r&   r)   r+   )Úget)ÚclsÚdataÚclientÚauto_deletes       úf/root/rosshost/parking-map/parking-api/venv/lib/python3.12/site-packages/langsmith/sandbox/_sandbox.pyÚ	from_dictzSandbox.from_dictL   s¢   € ñ" Ø—‘˜& "Ó%ØŸ(™( ?°BÓ7ØŸ(™( ?Ó3Ø�x‰x˜‹~Ø—8‘8˜H gÓ.ØŸ8™8Ð$4Ó5Ø—x‘x Ó-Ø—x‘x Ó-ØŸ™ Ó/Ø!ŸX™XÐ&8Ó9Ø—x‘x Ó-ØØ$ô
ð 	
ó    c                ó   — | S )zEnter context manager.© ©Úselfs    r3   Ú	__enter__zSandbox.__enter__m   s   € àˆr5   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)r9   Úexc_typeÚexc_valÚexc_tbs       r3   Ú__exit__zSandbox.__exit__q   sA   € ð ×ÒðØ—‘×+Ñ+¨D¯I©IÕ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   r8   s    r3   Ú_require_dataplane_urlzSandbox._require_dataplane_url   s{   € ð �;‰;˜'Ò!Ü&Ø˜DŸI™I˜;Ð&>¸t¿{¹{¸mð LEð Eóð ð ×!Ò!Ü-Ø˜DŸI™I˜;ð '>ð >óð ð ×!Ñ!Ð!r5   .)ÚtimeoutÚenvÚcwdÚshellÚ	on_stdoutÚ	on_stderrÚidle_timeoutÚkill_on_disconnectr$   ÚptyÚheadersÚwaitc                ó   — y ©Nr7   ©r9   ÚcommandrD   rE   rF   rG   rH   rI   rJ   rK   r$   rL   rM   rN   s                 r3   ÚrunzSandbox.run•   s   € ð" r5   )rD   rE   rF   rG   rH   rI   rJ   rK   r$   rL   rM   c                ó   — y rP   r7   rQ   s                 r3   rS   zSandbox.run¨   s   € ð" r5   é<   z	/bin/bashi,  iX  c               óD  — |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.)rD   rE   rF   rG   rN   rH   rI   rJ   rK   r$   rL   rM   TN)rD   rE   rF   rG   rM   )Ú
ValueErrorrC   Ú_run_wsr   ÚImportErrorÚOSErrorÚ	TypeErrorÚ	_run_http)r9   rR   rD   rE   rF   rG   rH   rI   rJ   rK   r$   rL   rM   rN   Úuse_wss                  r3   rS   zSandbox.run»   s  € ñ@ ™¡iÜðRóð ð
 	×#Ñ#Ô%ð �Ò3˜YÒ3¨)ˆÙØ—<‘<ØØØØØØØ#Ø#Ø)Ø#5Ø'ØØð  ó ð ð&	Ø—<‘<ØØØØØØØØØ)Ø#5Ø'ØØð  ó ð øô '¬´W¼iÐHò 	Ø—>‘>ØØØØØØð "ó ò ð	ús   ÁA, Á,0BÂB)rJ   rK   r$   rL   rM   c               óØ   — ddl m} | j                  «       }| j                  j                  }|||||||	|
||dœ
}|�||d<    ||||fi |¤Ž\  }}t        ||| «      }|s|S |j                  S )z"Execute via WebSocket /execute/ws.r   )Úrun_ws_stream)
rD   rE   rF   rG   rH   rI   rJ   rK   r$   rL   rM   )Úlangsmith.sandbox._ws_executer_   rC   r)   Ú_api_keyr   Úresult)r9   rR   rD   rE   rF   rG   rN   rH   rI   rJ   rK   r$   rL   rM   r_   r   Úapi_keyÚ	ws_kwargsÚ
msg_streamÚcontrolÚhandles                        r3   rX   zSandbox._run_ws3  s¢   € õ$ 	@à×3Ñ3Ó5ˆØ—,‘,×'Ñ'ˆð ØØØØ"Ø"Ø(Ø"4Ø&Øñ%
ˆ	ð ÐØ#*ˆI�iÑ á+ØØØñ
ð ñ	
Ñˆ
�Gô ˜z¨7°DÓ9ˆáØˆMà�}‰}Ðr5   c               óê  — | j                  «       }|› d�}|||dœ}	|�||	d<   |�||	d<   	 | j                  j                  j                  ||	|dz   | j                  j	                  |«      ¬«      }
|
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)rR   rD   rG   NrE   rF   é
   )ÚjsonrD   rM   Ústdoutr-   ÚstderrÚ	exit_codeéÿÿÿÿ)rk   rl   rm   )rC   r)   Ú_httpÚpostÚ_request_headersÚraise_for_statusrj   r   r.   ÚhttpxÚHTTPStatusErrorr   )r9   rR   rD   rE   rF   rG   rM   r   ÚurlÚpayloadÚresponser0   Úes                r3   r\   zSandbox._run_httpg  s  € ð ×3Ñ3Ó5ˆØ�˜xÐ(ˆàØØñ#
ˆð
 ˆ?Ø ˆG�E‰NØˆ?Ø ˆG�E‰Nð	Ø—|‘|×)Ñ)×.Ñ.ØØØ "™ØŸ™×5Ñ5°gÓ>ð	 /ó ˆHð ×%Ñ%Ô'Ø—=‘=“?ˆDÜ"Ø—x‘x ¨"Ó-Ø—x‘x ¨"Ó-ØŸ(™( ;°Ó3ôð øô
 ×$Ñ$ò 	Ü% aÔ(Øûð	ús   «B"C ÃC2Ã!C-Ã-C2r   )Ústdout_offsetÚstderr_offsetrM   c               ó°   — ddl m} | j                  «       }| 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)ry   rz   rM   )Ú
command_idry   rz   )r`   r|   rC   r)   ra   r   )r9   r}   ry   rz   rM   r|   r   rc   Úreconnect_kwargsre   rf   s              r3   Ú	reconnectzSandbox.reconnect�  s‹   € õ2 	Fà×3Ñ3Ó5ˆØ—,‘,×'Ñ'ˆð +Ø*ñ,
Ðð ÐØ*1Ð˜YÑ'á1ØØØñ
ð ñ	
Ñˆ
�Gô ØØØØ!Ø'Ø'ô
ð 	
r5   )rD   rM   c          	     ó~  — | j                  «       }|› d�}t        |t        «      r|j                  d«      }dd|fi}	 | j                  j
                  j                  |d|i||| j                  j                  |«      ¬«      }|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ÚfilesrD   rM   N)rC   Ú
isinstancer   Úencoder)   ro   rp   rq   rr   rs   rt   r   )
r9   r‚   ÚcontentrD   rM   r   ru   r„   rw   rx   s
             r3   ÚwritezSandbox.writeÅ  s¼   € ð, ×3Ñ3Ó5ˆØ�˜wÐ'ˆô �gœsÔ#Ø—n‘n WÓ-ˆGà˜& 'Ð*Ð+ˆð
	)Ø—|‘|×)Ñ)×.Ñ.ØØ �~ØØØŸ™×5Ñ5°gÓ>ð /ó ˆHð ×%Ñ%Õ'øÜ×$Ñ$ò 	)Ü% a×(Ñ(ûð	)ús   ¾AB ÂB<Â'B7Â7B<c               ó¬  — | j                  «       }|› d�}	 | j                  j                  j                  |d|i|| j                  j	                  |«      ¬«      }|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ƒ   rD   rM   i”  zFile 'z' not found in sandbox 'ú'r�   )Úresource_typeN)rC   r)   ro   r.   rq   rr   r‡   rs   rt   rw   Ústatus_coder   r   r   )r9   r‚   rD   rM   r   ru   rw   rx   s           r3   ÚreadzSandbox.readð  sÜ   € ð* ×3Ñ3Ó5ˆØ�˜yÐ)ˆð	Ø—|‘|×)Ñ)×-Ñ-ØØ �~ØØŸ™×5Ñ5°gÓ>ð	 .ó ˆHð ×%Ñ%Ô'Ø×#Ñ#Ð#øÜ×$Ñ$ò 	Ø�z‰z×%Ñ%¨Ò,Ü+Ø˜T˜FÐ":¸4¿9¹9¸+ÀQÐGØ"(ôð ðô & aÔ(àûð	ús   —AA7 Á7CÂ
ACÃCé   ©Ú
local_portÚmax_reconnectsrM   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                  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�   )rW   rC   r)   ra   r   Ú_start)r9   Úremote_portr�   r‘   rM   r   rc   Úts           r3   ÚtunnelzSandbox.tunnel  s    € ðP �KÔ( 5Ô(ÜØ?À¸}ÈAÐNóð ñ ˜a :Ô6°Ô6ÜØ>¸z¸lÈ!ÐLóð ð ×3Ñ3Ó5ˆØ—,‘,×'Ñ'ˆÜØØØØ!Ø)Øô
ˆð 	
�‰Œ
Øˆr5   )T)r0   zdict[str, Any]r1   r   r2   r*   Úreturnr   )r™   r   )r>   zOptional[type]r?   zOptional[BaseException]r@   zOptional[Any]r™   ÚNone)r™   r   )rR   r   rD   ÚintrE   úOptional[dict[str, str]]rF   r   rG   r   rH   úOptional[Callable[[str], Any]]rI   r�   rJ   r›   rK   r*   r$   r›   rL   r*   rM   ÚRequestHeadersrN   zLiteral[True]r™   r   )rR   r   rD   r›   rE   rœ   rF   r   rG   r   rH   r�   rI   r�   rJ   r›   rK   r*   r$   r›   rL   r*   rM   rž   rN   zLiteral[False]r™   r   )rR   r   rD   r›   rE   rœ   rF   r   rG   r   rH   r�   rI   r�   rJ   r›   rK   r*   r$   r›   rL   r*   rM   rž   rN   r*   r™   ú%Union[ExecutionResult, CommandHandle])rR   r   rD   r›   rE   rœ   rF   r   rG   r   rN   r*   rH   r�   rI   r�   rJ   r›   rK   r*   r$   r›   rL   r*   rM   rž   r™   rŸ   )rR   r   rD   r›   rE   rœ   rF   r   rG   r   rM   rž   r™   r   )
r}   r   ry   r›   rz   r›   rM   rž   r™   r   )
r‚   r   r‡   zUnion[str, bytes]rD   r›   rM   rž   r™   rš   )r‚   r   rD   r›   rM   rž   r™   Úbytes)
r–   r›   r�   r›   r‘   r›   rM   rž   r™   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r    r!   r"   r#   r$   r%   r&   r   r)   r+   Úclassmethodr4   r:   rA   rC   r   rS   rX   r\   r   rˆ   r�   r˜   r7   r5   r3   r   r      s'  … ñð6 ƒIØÓØ#'€M�=Ó'Ø€BˆÓØ€FˆCÓØ$(€N�MÓ(Ø $€J�Ó$Ø $€J�Ó$Ø!%€K�Ó%Ø&*Ð�mÓ*Ø $€J�Ó$ñ #¨°tÔ<€Gˆ]Ó<Ù E°4Ô8€L�$Ó8àð
 !ð	
àð
ð ð
ð ð	
ð
 
ò
ó ð
ó@ðà ðð )ðð ð	ð
 
óó"ð, ð
 Ø(+Ø ØØ47Ø47ØØ#&ØØØ"%Ø!ñàðð ð	ð
 &ðð ðð ðð 2ðð 2ðð ðð !ðð ðð ðð  ðð ðð  
ò!ó ðð$ ð
 Ø(+Ø ØØ47Ø47ØØ#&ØØØ"%ñàðð ð	ð
 &ðð ðð ðð 2ðð 2ðð ðð !ðð ðð ðð  ðð ðð  
ò!ó ðð, Ø(,Ø!Ø Ø48Ø48ØØ#(ØØØ"&Øñvàðvð ð	vð
 &ðvð ðvð ðvð 2ðvð 2ðvð ðvð !ðvð ðvð ðvð  ðvð ðvð  
/ó!vðF  Ø#(ØØØ"&ñ2àð2ð ð	2ð
 &ð2ð ð2ð ð2ð ð2ð 2ð2ð 2ð2ð ð2ð !ð2ð ð2ð ð2ð  ð2ð  
/ó!2ðh'àð'ð ð	'ð
 &ð'ð ð'ð ð'ð  ð'ð 
ó'ðZ ØØ"&ñ3
àð3
ð ð	3
ð
 ð3
ð  ð3
ð 
ó3
ðt Ø"&ñ))àð))ð #ð))ð
 ð))ð  ð))ð 
ó))ðX ,.Èñ)Øð)Ø%(ð)Ø8Fð)à	ó)ð^ ØØ"&ñ;àð;ð ð	;ð
 ð;ð  ð;ð 
ô;r5   r   )"r¤   Ú
__future__r   Úcollections.abcr   Údataclassesr   r   Útypingr   r   r	   r
   r   r   r   rs   Úlangsmith.sandbox._exceptionsr   r   r   r   Úlangsmith.sandbox._helpersr   Úlangsmith.sandbox._modelsr   r   Úlangsmith.sandbox._tunnelr   Úlangsmith.sandbox._clientr   r   rž   r   r7   r5   r3   ú<module>r°      sn   ðÙ Eå "å #ß (ß S× SÑ Sã ÷ó õ A÷õ -áÝ7ð ˜' # s (Ñ+Ñ,€ð ÷vð vó ñvr5   