Ë
    ³Œjl1  ã                  óæ   — 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	 	 	 	 	 	 	 dd„Zdd„Zdd„Zdd„Zy)zÀShared 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ÚValidationErrorc                óz   — i }| |fD ]1  }|xs i j                  «       D ]  \  }}|||j                  «       <   Œ Œ3 |S )uT  Merge request headers, giving precedence to overrides.

    Names are normalized to lowercase so an override replaces a base header that
    differs only in casing. HTTP header names are case-insensitive, so keeping
    both would be ambiguous â€” a server reading the first value would see the
    base header instead of the override.
    )ÚitemsÚlower)Úbase_headersÚoverride_headersÚmergedÚheadersÚnameÚvalues         úd/var/www/html/Fitness-lenito-AI-main/venv/lib/python3.12/site-packages/langsmith/sandbox/_helpers.pyÚmerge_headersr   !   sK   € ð  €FØ Ð"2Ó3ˆØ#šM r×0Ñ0Ö2‰KˆD�%Ø#(ˆF�4—:‘:“<Ò ñ 3ð 4ð €Mó    c                ó    — t        | t        «      r| dk  rt        d| ›�«      ‚t        |t        «      rd|cxk  rdk  sn t        d|›�«      ‚y)zÕValidate 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 é   i€Q z4expires_in_seconds must be between 1 and 86400, got N)Ú
isinstanceÚintÚ
ValueError)ÚportÚexpires_in_secondss     r   Úvalidate_service_paramsr%   8   sb   € ô �dœCÔ  D¨A¢IÜÐ@ÀÀÐIÓJÐJÜÐ(¬#Ô.Ø	ÐÔ( 5Ô(äðØ%Ð(ð*ó
ð 	
ð 	)r   c                óp   — | €y| dk  rt        |› d| › �«      ‚| dk7  r| dz  dk7  rt        |› d| › �«      ‚yy)zýValidate 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(   M   sY   € ð €}ØØˆq‚yÜ˜D˜6Ð!4°U°GÐ<Ó=Ð=Ø�‚z�e˜b‘j A’oÜ˜D˜6Ð!HÈÈÐPÓQÐQð &€zr   c           	     ó  — 	 | j                   j                  «       }|j                  d«      }t        |t        «      r-|j                  d«      |j                  dt        | «      «      dœS t        |t        «      r^|r\|D �cg c].  }t        |t        «      sŒ|j                  dt        |«      «      ‘Œ0 }}d|rdj                  |«      dœS t        | «      dœS d|xs t        | «      dœS c c}w # t        $ r dt        | «      dœcY S w xY w)zôParse 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
    ÚdetailÚerrorÚmessage©Ú
error_typer,   ÚmsgNz; )	ÚresponseÚjsonÚgetr    ÚdictÚstrÚlistÚjoinÚ	Exception)r+   Údatar*   ÚdÚmessagess        r   Úparse_error_responser;   d   sý   € ð;Ø�~‰~×"Ñ"Ó$ˆØ—‘˜(Ó#ˆô �fœdÔ#à$Ÿj™j¨Ó1Ø!Ÿ:™: i´°U³Ó<ñð ô �fœdÔ#©Ù6<ÓT±f°Ä
È1ÌdÕ@S˜Ÿ™˜e¤S¨£VÕ,°fˆHÐTà"Ù2:˜4Ÿ9™9 XÓ.ñð ä@CÀEÃ
ñð ð #¨vÒ/C¼¸U»ÑDÐDùò Uøô ò ;Ø"¬s°5«zÑ:Ò:ð;ús<   ‚A'C/ Á*C/ Â C*ÂC*Â3C/ ÃC/ ÃC/ Ã*C/ Ã/D	ÄD	c                ó2  — 	 | j                   j                  «       }|j                  d«      }t        |t        «      r-|j                  d«      |j                  dt        | «      «      dœS d|xs t        | «      dœS # t        $ r dt        | «      dœcY S w xY w)z­Parse error response (simplified version for sandbox operations).

    Returns a dict with:
    - error_type: The error type
    - message: Human-readable error message
    r*   r+   r,   r-   N)r0   r1   r2   r    r3   r4   r7   ©r+   r8   r*   s      r   Úparse_error_response_simpler>   †   s�   € ð;Ø�~‰~×"Ñ"Ó$ˆØ—‘˜(Ó#ˆä�fœdÔ#à$Ÿj™j¨Ó1Ø!Ÿ:™: i´°U³Ó<ñð ð
 #¨vÒ/C¼¸U»ÑDÐDøÜò ;Ø"¬s°5«zÑ:Ò:ð;ús   ‚A'A< Á*A< Á<BÂBc                ó¦   — 	 | j                   j                  «       }|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")
    r*   )r0   r1   r2   r    r5   r7   r=   s      r   Úparse_validation_errorr@   œ   sQ   € ðØ�~‰~×"Ñ"Ó$ˆØ—‘˜( BÓ'ˆÜ�fœdÔ#ØˆMØˆ	øÜò ØŠ	ðús   ‚=A Á A ÁAÁAc                ó\   — | j                  «       }d|v r	d|v sd|v ryd|v ryd|v ryd|v ryy)	zvExtract quota type from error message.

    Returns one of: "sandbox_count", "cpu", "memory", "storage", or None.
    ÚsandboxÚcountÚlimitÚsandbox_countÚcpuÚmemoryÚstorageN)r   )r,   Úmessage_lowers     r   Úextract_quota_typerJ   ®   sM   € ð
 —M‘M“O€Mà�MÑ!Ø�=Ñ  G¨}Ñ$<àØ	�-Ñ	ØØ	�]Ñ	"ØØ	�mÑ	#ØØr   c                ó€   — t        | j                  d|j                  «       › d�«      || j                  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
    r,   z creation failedr.   ©Úresource_typer.   )r   r2   Útitle)r8   r+   rM   s      r   Úraise_creation_errorrO   Ç   sE   € ô  Ø�‰�˜}×2Ñ2Ó4Ð5Ð5EÐFÓGØ#Ø—8‘8˜LÓ)ôð ð	r   c                óä  — | j                   j                  }t        | «      }|dk(  rt        |d   d¬«      | ‚|dk(  r[t	        | «      }|rAt        d„ |D «       «      r/|r|d   j                  dd	g«      d
   nd	}t        |d   ||¬«      | ‚t        || «       y	|dk(  rt        |d   «      }t        |d   |¬«      | ‚|dk(  r%t        |d   d|j                  d«      xs d¬«      | ‚t        | «       y	)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˜  r,   rB   ©rM   é¦  c              3  óD   K  — | ]  }|j                  d «      dk(  –— Œ y­w)ÚtypeÚvalue_errorN)r2   )Ú.0r9   s     r   Ú	<genexpr>z0handle_sandbox_creation_error.<locals>.<genexpr>î   s   è ø€ ÐKÁ7¸a˜1Ÿ5™5 ›=¨MÕ9Á7ùs   ‚ r   ÚlocNéÿÿÿÿ©r,   ÚfieldÚdetailsé­  ©r,   Ú
quota_typeé÷  r.   ÚUnschedulablerL   )r0   Ústatus_coder;   r
   r@   Úanyr2   r   rO   rJ   r   r   Úhandle_client_http_error)r+   Ústatusr8   r\   r[   r_   s         r   Úhandle_sandbox_creation_errorrf   Û   s  € ð �^‰^×'Ñ'€FÜ Ó&€Dà�‚}ä" 4¨	¡?À)ÔLÐRWÐWØ	�3Šä(¨Ó/ˆÙ”sÑKÁ7ÓKÔKá9@�G˜A‘J—N‘N 5¨4¨&Ó1°"Ò5ÀdˆEÜ!Ø˜Y™ØØôð ð	ô !  uÕ-Ø	�3Šä'¨¨Y©Ó8ˆ
Ü Ø˜‘OØ!ô
ð ð	ð 
�3Šä#Ø�‰OØ#Ø—x‘x Ó-Ò@°ô
ð ð		ô 	! Õ'r   c                óÌ  — t        | «      }|d   }|j                  d«      }| j                  j                  }|dv rt	        |«      | ‚|dk(  rt        |«      | ‚|dk(  r7t        | «      }|r|d   j                  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).r,   r.   )i‘  é“  é”  rR   r   rX   NrY   rZ   r]   r^   éö  ÚConnectionErroriô  )r;   r2   r0   rb   r   r	   r@   r   rJ   r   r   r   r   )r+   r8   r,   r.   re   r\   r[   r_   s           r   rd   rd     s  € ä Ó&€DØ�9‰o€GØ—‘˜,Ó'€JØ�^‰^×'Ñ'€Fà�ÑÜ(¨Ó1°uÐ<Ø�‚}Ü# GÓ,°%Ð7ð �‚}Ü(¨Ó/ˆÙ5<�˜‘
—‘˜u t fÓ-¨bÒ1À$ˆÜØØØô
ð ð		ð �‚}Ü'¨Ó0ˆ
Ü ØØ!ô
ð ð	ð
 �‚}˜Ð'8Ò8Ü$ WÓ-°5Ð8Ø�‚}Ü˜gÓ&¨EÐ1Ü
˜WÓ
%¨5Ð0r   c                óÄ  — t        | «      }|d   }|j                  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(  s
|dk(  r|dk(  rt        |«      | ‚|dk(  s|dk(  rt        |d¬«      | ‚t        |«      | ‚)aJ  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
    - ServiceUnavailable (503) -> SandboxNotReadyError
    - 403 -> SandboxOperationError (permission denied)
    r,   r.   Ú
WriteErrorÚwrite)Ú	operationr.   Ú	ReadErrorÚreadÚCommandErrorÚcommandrh   NÚPermissionDeniedrj   rk   i�  ÚNotReadyr`   ÚServiceUnavailableri   ÚFileNotFoundÚfilerQ   )	r>   r2   r0   rb   r   r   r   r	   r   )r+   r8   r,   r.   re   s        r   Úhandle_sandbox_http_errorry   6  s,  € ô ' uÓ-€DØ�9‰o€GØ—‘˜,Ó'€JØ�^‰^×'Ñ'€Fð �\Ò!Ü#Ø˜w°:ô
àð	ð �[Ò Ü#Ø˜v°*ô
àð	ð �^Ò#Ü#Ø˜y°Zô
àð	ð
 �‚}Ü#Ø˜tÐ0Bô
àð	ð
 �‚}˜Ð'8Ò8Ü$ WÓ-°5Ð8ð 	�#Š˜*¨
Ò2Ø�#Š˜*Ð(<Ò<ä" 7Ó+°Ð6Ø�‚}˜
 nÒ4Ü# G¸6ÔBÈÐMä
˜WÓ
%¨5Ð0r   )NN)r   úOptional[Mapping[str, str]]r   rz   Úreturnzdict[str, str])r#   r!   r$   r!   r{   ÚNone)r   zOptional[int]r   r4   r{   r|   )r+   úhttpx.HTTPStatusErrorr{   údict[str, Any])r+   r}   r{   z
list[dict])r,   r4   r{   zOptional[str])rB   )r8   r~   r+   r}   rM   r4   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(   r;   r>   r@   rJ   rO   rf   rd   ry   © r   r   Ú<module>r†      s²   ðñõ #å #ß  ã ÷÷ ÷ ñ ð( 15Ø48ðØ-ðà1ðð óó.
ó*Ró.;óD;ó,ó$ð8 #ðØ
ðà ðð ðð 
ó	ó(.(ób"1ôT21r   