
    j/                        d Z ddlmZ ddlmZ ddlmZmZ ddlZddl	m
Z
mZmZmZmZmZmZmZmZmZmZ 	 	 d(d)dZd*dZd+dZd,dZd,dZd-dZd.d Z	 d/d0d$Zd1d%Zd1d&Zd1d'ZdS )2zShared helper functions for error handling.

These functions are used by both sync and async clients to parse error responses
and raise appropriate exceptions. They contain no I/O operations.
    )annotations)Mapping)AnyOptionalN)QuotaExceededErrorResourceCreationErrorResourceNotFoundErrorResourceTimeoutErrorSandboxAPIErrorSandboxAuthenticationErrorSandboxClientErrorSandboxConnectionErrorSandboxNotReadyErrorSandboxOperationErrorValidationErrorbase_headersOptional[Mapping[str, str]]override_headersreturndict[str, str]c                V    t          | pi           }|r|                    |           |S )z6Merge request headers, giving precedence to overrides.)dictupdate)r   r   mergeds      d/lsinfo/ai/hellotax_ai/base_platform/venv/lib/python3.11/site-packages/langsmith/sandbox/_helpers.pymerge_headersr   !   s6    
 ","4"55F (&'''M    portintexpires_in_secondsNonec                    t          | t                    r| dk    rt          d|           t          |t                    rd|cxk    rdk    sn t          d|          dS )zValidate parameters for service URL generation.

    Args:
        port: Target port inside the sandbox.
        expires_in_seconds: Token TTL.

    Raises:
        ValueError: If port or TTL is out of range.
    r   z%port must be a positive integer, got    iQ z4expires_in_seconds must be between 1 and 86400, got N)
isinstancer   
ValueError)r   r    s     r   validate_service_paramsr&   1   s     dC   KDAIIIIIJJJ(#.. 
	((((5((((*%* *
 
 	
 	)(r   valueOptional[int]namestrc                    | dS | dk     rt          | d|            | dk    r| dz  dk    rt          | d|            dS dS )zValidate a TTL value for sandbox create/update.

    Args:
        value: TTL in seconds (None means unset, 0 disables).
        name: Parameter name for error messages.

    Raises:
        ValueError: If value is negative or not a multiple of 60.
    Nr   z must be >= 0, got <   z' must be a multiple of 60 seconds, got )r%   )r'   r)   s     r   validate_ttlr-   F   so     }qyyD<<U<<===zzebjAooDPPPPQQQ zoor   errorhttpx.HTTPStatusErrordict[str, Any]c                    	 | j                                         }|                    d          }t          |t                    r9|                    d          |                    dt          |                     dS t          |t                    r7|r5d |D             }d|rd                    |          nt          |           dS d|pt          |           dS # t          $ r dt          |           dcY S w xY w)zParse standardized error response.

    Expected format: {"detail": {"error": "...", "message": "..."}}

    Returns a dict with:
    - error_type: The error type (e.g., "ImagePull", "CrashLoop")
    - message: Human-readable error message
    detailr.   message
error_typer3   c                ~    g | ]:}t          |t                    |                    d t          |                    ;S )msg)r$   r   getr*   .0ds     r   
<listcomp>z(parse_error_response.<locals>.<listcomp>s   s;    TTT
1d@S@STeSVV,,TTTr   Nz; )	responsejsonr8   r$   r   r*   listjoin	Exception)r.   datar2   messagess       r   parse_error_responserD   ]   s#   ;~""$$(## fd## 	$jj11!::iU<<   fd## 	 	TTfTTTH"2:J499X...E

   #v/CUDDD ; ; ;"s5zz:::::;s   A;C >AC 
C C=<C=c                h   	 | j                                         }|                    d          }t          |t                    r9|                    d          |                    dt          |                     dS d|pt          |           dS # t          $ r dt          |           dcY S w xY w)zParse error response (simplified version for sandbox operations).

    Returns a dict with:
    - error_type: The error type
    - message: Human-readable error message
    r2   r.   r3   r4   N)r=   r>   r8   r$   r   r*   rA   r.   rB   r2   s      r   parse_error_response_simplerG      s    ;~""$$(##fd## 	$jj11!::iU<<  
 #v/CUDDD ; ; ;"s5zz:::::;s   A;B >B B10B1
list[dict]c                    	 | j                                         }|                    dg           }t          |t                    r|S g S # t
          $ r g cY S w xY w)a  Parse Pydantic validation error response.

    Returns a list of validation error details, each containing:
    - loc: Location of the error (e.g., ["body", "resources", "cpu"])
    - msg: Human-readable error message
    - type: Error type (e.g., "value_error")
    r2   )r=   r>   r8   r$   r?   rA   rF   s      r   parse_validation_errorrJ      sm    ~""$$(B''fd## 	M	   			s   AA
 A
 
AAr3   Optional[str]c                n    |                                  }d|v r
d|v sd|v rdS d|v rdS d|v rdS d|v rdS dS )	zvExtract quota type from error message.

    Returns one of: "sandbox_count", "cpu", "memory", "storage", or None.
    sandboxcountlimitsandbox_countcpumemorystorageN)lower)r3   message_lowers     r   extract_quota_typerV      sk    
 MMOOMM!!=  G}$<$<	-		u	]	"	"x	m	#	#y4r   rM   rB   resource_typec                    t          |                     d|                                 d          ||                     d                    |)a-  Raise ResourceCreationError with the error_type from the API response.

    The error_type indicates the specific failure reason:
    - ImagePull: Image pull failed
    - CrashLoop: Container crashed during startup
    - SandboxConfig: Configuration error
    - Unschedulable: Cannot be scheduled
    r3   z creation failedr5   rW   r5   )r   r8   title)rB   r.   rW   s      r   raise_creation_errorr[      sX      }2244FFFGG#88L))   	r   c                h   | j         j        }t          |           }|dk    rt          |d         d          | |dk    r|t	          |           }|rYt          d |D                       r@|r#|d                             dd	g          d
         nd	}t          |d         ||          | t          ||            d	S |dk    r-t          |d                   }t          |d         |          | |dk    r.t          |d         d|                    d          pd          | t          |            d	S )a  Handle HTTP errors specific to sandbox creation.

    Maps API error responses to specific exception types:
    - 408: ResourceTimeoutError (sandbox didn't become ready in time)
    - 422: ValidationError (bad input) or ResourceCreationError (runtime)
    - 429: QuotaExceededError (org limits exceeded)
    - 503: ResourceCreationError (no resources available)
    - Other: Falls through to generic error handling
    i  r3   rM   rW     c              3  H   K   | ]}|                     d           dk    V  dS )typevalue_errorN)r8   r9   s     r   	<genexpr>z0handle_sandbox_creation_error.<locals>.<genexpr>   s1      KKa155==M9KKKKKKr   r   locNr3   fielddetails  r3   
quota_typei  r5   UnschedulablerY   )r=   status_coderD   r
   rJ   anyr8   r   r[   rV   r   r   handle_client_http_error)r.   statusrB   rg   rf   rj   s         r   handle_sandbox_creation_errorrp      s~    ^'F&&D}}"4	?)LLLRWW	3(// 
	.sKK7KKKKK 
	.9@JGAJNN54&11"55dE!Y   	 !u-----	3'Y88
 O!
 
 
 	 
3#O#xx--@
 
 
 		 	!'''''r   c                6   t          |           }|d         }|                    d          }| j        j        }|dv rt	          |          | |dk    rt          |          | |dk    rIt          |           }|r#|d                             ddg          d	         nd}t          |||
          | |dk    r!t          |          }t          ||          | |dk    r|dk    rt          |          | |dk    rt          |          | t          |          | )zLHandle HTTP errors and raise appropriate exceptions (for client operations).r3   r5   )i      r^   r   rc   Nrd   re   rh   ri     ConnectionErrori  )rD   r8   r=   rl   r   r	   rJ   r   rV   r   r   r   r   )r.   rB   r3   r5   ro   rg   rf   rj   s           r   rn   rn     sU   &&D9oG,''J^'F(11u<}}#G,,%7 }}(//5<F
utf--b11$
 
 
 		 }}'00
 !
 
 
 	
 }}'888$W--58}}g&&E1
W
%
%50r   c                   t          |           }|d         }|                    d          }| j        j        }|dk    rt	          |d|          | |dk    rt	          |d|          | |dk    rt	          |d	|          | |d
k    rt	          |dd          | |dk    r|dk    rt          |          | |dk    r|dk    rt          |          | |dk    s|dk    rt          |d          | t          |          | )a  Handle HTTP errors for sandbox operations (run, read, write).

    Maps API error types to specific exceptions:
    - WriteError -> SandboxOperationError (operation="write")
    - ReadError -> SandboxOperationError (operation="read")
    - CommandError -> SandboxOperationError (operation="command")
    - ConnectionError (502) -> SandboxConnectionError
    - FileNotFound / 404 -> ResourceNotFoundError (resource_type="file")
    - NotReady (400) -> SandboxNotReadyError
    - 403 -> SandboxOperationError (permission denied)
    r3   r5   
WriteErrorwrite)	operationr5   	ReadErrorreadCommandErrorcommandrr   NPermissionDeniedrt   ru   i  NotReadyrs   FileNotFoundfiler]   )	rG   r8   r=   rl   r   r   r   r	   r   )r.   rB   r3   r5   ro   s        r   handle_sandbox_http_errorr   /  so    'u--D9oG,''J^'F \!!#w:
 
 
	 [  #v*
 
 
	 ^###yZ
 
 
	
 }}#t0B
 
 
	
 }}'888$W--58 }}z11"7++6}}
n44#G6BBBM
W
%
%50r   )NN)r   r   r   r   r   r   )r   r   r    r   r   r!   )r'   r(   r)   r*   r   r!   )r.   r/   r   r0   )r.   r/   r   rH   )r3   r*   r   rK   )rM   )rB   r0   r.   r/   rW   r*   r   r!   )r.   r/   r   r!   ) __doc__
__future__r   collections.abcr   typingr   r   httpxlangsmith.sandbox._exceptionsr   r   r	   r
   r   r   r   r   r   r   r   r   r&   r-   rD   rG   rJ   rV   r[   rp   rn   r    r   r   <module>r      s    # " " " " " # # # # # #                                          ( 1548     
 
 
 
*R R R R.; ; ; ;D; ; ; ;,   $   8 #    (.( .( .( .(b"1 "1 "1 "1T/1 /1 /1 /1 /1 /1r   