Ë
    ñÏjH  ã                  óv  — d Z ddlmZ ddlmZ ddlmZmZ ddlm	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l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„Z!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,d.d„Z-y)0zÀ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ÚOptional)Úhttpx)ÚQuotaExceededErrorÚResourceCreationErrorÚResourceNotFoundErrorÚResourceTimeoutErrorÚSandboxAPIErrorÚSandboxAuthenticationErrorÚSandboxClientErrorÚSandboxConnectionErrorÚSandboxNotReadyErrorÚSandboxOperationErrorÚValidationError)Ú	FileChunkÚFileStatÚ_run_config_payloadNc                ó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         úW/var/www/html/gaurav-v2/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               ó<   — | €y|€|�t        d«      ‚t        | «      S )zøNormalize a per-command run_config, rejecting the deprecated pairing.

    The server answers 400 for a request carrying both spellings rather than
    letting one silently win, so refuse it here where the message can name
    the replacement.
    NzyCannot combine run_config with the deprecated env/cwd arguments. Use run_config.env_vars and run_config.work_dir instead.)Ú
ValueErrorr   )Ú
run_configÚenvÚcwds      r   Úresolve_command_run_configr'   8   s6   € ð ÐØØ
€˜#˜/ÜðGó
ð 	
ô ˜zÓ*Ð*r!   c               ó   — |ry| €y| S )a  Whether to half-close stdin at spawn.

    Defaults on for a non-PTY command: a command that reads stdin otherwise
    blocks on a pipe nobody writes to until the timeout kills it. A PTY has
    no separate write end to close, so the server ignores the flag there.
    FT© )Úclose_inputÚptys     r   Úresolve_close_inputr,   K   s   € ñ ØØÐØØÐr!   c                óÈ   — |�$| €|�t        d«      ‚|dk  rt        d«      ‚d|› �S | €t        d«      ‚| dk  rt        d«      ‚|€d| › d�S || k  rt        d	«      ‚d| › d|› �S )
z:Render a byte range as an RFC 9110 ``Range`` header value.z+Cannot combine suffix_bytes with start/end.r   zsuffix_bytes must be positive.zbytes=-z3Provide start (with optional end), or suffix_bytes.zstart must not be negative.zbytes=Ú-zend must not precede start.©r#   )ÚstartÚendÚsuffix_bytess      r   Úbuild_range_headerr3   Y   sŸ   € ð ÐØÐ  ÜÐJÓKÐKØ˜1ÒÜÐ=Ó>Ð>Ø˜˜Ð'Ð'Ø€}ÜÐNÓOÐOØˆq‚yÜÐ6Ó7Ð7Ø
€{Ø˜�w˜aÐ Ð Ø
ˆU‚{ÜÐ6Ó7Ð7Ø�E�7˜!˜C˜5Ð!Ð!r!   c                ój  — | r| j                  d«      sy| t        d«      d j                  «       }|j                  d«      \  }}}d}|j                  d«      \  }}}|j                  «       j	                  «       rt        |«      }|j                  «       j	                  «       rt        |«      nd}||fS )zCRead the first byte offset and total size out of ``Content-Range``.zbytes )r   NNÚ/r   r.   )Ú
startswithÚlenÚstripÚ	partitionÚisdigitÚint)r   ÚspecÚ
range_partÚ_Ú
total_partr0   ÚfirstÚtotals           r   Ú_parse_content_rangerB   n   s¢   € á˜×(Ñ(¨Ô2ØØ”�X“�Ð!×'Ñ'Ó)€DØ $§¡¨sÓ 3Ñ€J��:Ø€EØ×&Ñ& sÓ+�K€Eˆ1ˆaØ‡{�{ƒ}×ÑÔÜ�E“
ˆØ)×/Ñ/Ó1×9Ñ9Ô;ŒC�
ŒOÀ€EØ�%ˆ<Ðr!   c                ó&  — | j                   j                  d«      }t        |r|j                  «       rt	        |«      nd| j                   j                  d«      | j                   j                  d«      | j                   j                  d«      ¬«      S )z0Build a FileStat from a HEAD response's headers.zcontent-lengthr   Úetagúlast-modifiedzcontent-type)Ú
size_bytesrD   Úlast_modifiedÚcontent_type)r   Úgetr   r:   r;   )ÚresponseÚlengths     r   Úfile_stat_from_responserL   |   sv   € à×Ñ×!Ñ!Ð"2Ó3€FÜÙ"(¨V¯^©^Ô-=”3�v”;À1Ø×Ñ×!Ñ! &Ó)Ø×&Ñ&×*Ñ*¨?Ó;Ø×%Ñ%×)Ñ)¨.Ó9ô	ð r!   c           
     óÊ  — | j                   dk(  rAt        d| j                  j                  d«      d| j                  j                  d«      ¬«      S | j                   dk(  }t	        | j                  j                  d«      «      \  }}| j
                  }|sd	}t        |«      }t        || j                  j                  d«      |||| j                  j                  d«      ¬
«      S )z2Build a FileChunk from a ranged download response.i0  r!   rD   TrE   )ÚcontentrD   Ú	unchangedrG   éÎ   úcontent-ranger   )rN   rD   Útotal_bytesr0   ÚpartialrG   )Ústatus_coder   r   rI   rB   rN   r7   )rJ   rS   r0   rA   rN   s        r   Úfile_chunk_from_responserU   ‡   sÛ   € à×Ñ˜sÒ"ÜØØ×!Ñ!×%Ñ% fÓ-ØØ"×*Ñ*×.Ñ.¨Ó?ô	
ð 	
ð ×"Ñ" cÑ)€GÜ'¨×(8Ñ(8×(<Ñ(<¸_Ó(MÓN�L€Eˆ5Ø×Ñ€GÙð ˆÜ�G“ˆÜØØ×Ñ×!Ñ! &Ó)ØØØØ×&Ñ&×*Ñ*¨?Ó;ôð r!   c          	     óò   — | j                   j                  }|dk(  rt        d|› d|› d�d¬«      | ‚|dk(  r7t        d|› d	| j                   j                  j                  d
d«      › d�«      | ‚t        | «       y)z<Map a file-operation HTTP error, including the non-JSON 416.é”  zFile 'z' not found in sandbox 'Ú'Úfile©Úresource_typei   zRequested range for 'z#' starts past the end of the file (rQ   zunknown sizez).N)rJ   rT   r
   r   r   rI   Úhandle_sandbox_http_error)ÚerrorÚpathÚsandbox_nameÚstatuss       r   Úraise_file_http_errorra   ¢   s˜   € ð �^‰^×'Ñ'€FØ�‚}Ü#Ø�T�FÐ2°<°.ÀÐBØ ô
ð ð	ð �‚}Ü#Ø# D 6ð *Ø—‘×&Ñ&×*Ñ*¨?¸NÓKÐLÈBðPó
ð ð	ô ˜eÕ$r!   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)Ú
isinstancer;   r#   )ÚportÚexpires_in_secondss     r   Úvalidate_service_paramsrg   ´   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_ttlrj   É   sY   € ð €}ØØˆq‚yÜ˜D˜6Ð!4°U°GÐ<Ó=Ð=Ø�‚z�e˜b‘j A’oÜ˜D˜6Ð!HÈÈÐPÓQÐQð &€zr!   c                ó:   — t        |t        «      r
|r| › d|› d�S | S )Nz (error_id=Ú))rd   Ústr)ÚmessageÚerror_ids     r   Ú_message_with_error_idrp   à   s&   € Ü�(œCÔ ¡XØ�˜+ h Z¨qÐ1Ð1Ø€Nr!   c           	     óJ  — 	 | j                   j                  «       }|j                  d«      }t        |t        «      rF|j                  d«      t        |j                  dt        | «      «      |j                  d«      «      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
    Údetailr]   rn   ro   ©Ú
error_typern   ÚmsgNz; )
rJ   ÚjsonrI   rd   Údictrp   rm   ÚlistÚjoinÚ	Exception)r]   Údatarr   ÚdÚmessagess        r   Úparse_error_responser~   æ   s  € ð;Ø�~‰~×"Ñ"Ó$ˆØ—‘˜(Ó#ˆô �fœdÔ#à$Ÿj™j¨Ó1Ü1Ø—J‘J˜y¬#¨e«*Ó5°v·z±zÀ*Ó7Móñð ô �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<   ‚B D ÂD ÂDÂ/DÃD Ã$D Ã1D ÄD ÄD"Ä!D"c           	     ód  — 	 | j                   j                  «       }|j                  d«      }t        |t        «      rF|j                  d«      t        |j                  dt        | «      «      |j                  d«      «      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
    rr   r]   rn   ro   rs   N)rJ   rv   rI   rd   rw   rp   rm   rz   ©r]   r{   rr   s      r   Úparse_error_response_simpler�   
  s    € ð;Ø�~‰~×"Ñ"Ó$ˆØ—‘˜(Ó#ˆä�fœdÔ#à$Ÿj™j¨Ó1Ü1Ø—J‘J˜y¬#¨e«*Ó5°v·z±zÀ*Ó7Móñð ð #¨vÒ/C¼¸U»ÑDÐDøÜò ;Ø"¬s°5«zÑ:Ò:ð;ús   ‚B B ÂB Â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")
    rr   )rJ   rv   rI   rd   rx   rz   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   )rn   Úmessage_lowers     r   Úextract_quota_typer�   4  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
    rn   z creation failedrt   ©r[   rt   )r	   rI   Útitle)r{   r]   r[   s      r   Úraise_creation_errorr‘   M  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˜  rn   r…   rZ   é¦  c              3  óD   K  — | ]  }|j                  d «      dk(  –— Œ y­w)ÚtypeÚvalue_errorN)rI   )Ú.0r|   s     r   Ú	<genexpr>z0handle_sandbox_creation_error.<locals>.<genexpr>t  s   è ø€ ÐKÁ7¸a˜1Ÿ5™5 ›=¨MÕ9Á7ùs   ‚ r   ÚlocNéÿÿÿÿ©rn   ÚfieldÚdetailsé­  ©rn   Ú
quota_typeé÷  rt   ÚUnschedulabler�   )rJ   rT   r~   r   rƒ   ÚanyrI   r   r‘   r�   r   r	   Úhandle_client_http_error)r]   r`   r{   r�   rœ   r    s         r   Úhandle_sandbox_creation_errorr¥   a  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                ó¤   — | j                   j                  dk7  ryt        | «      }|j                  d«      dk7  ryt	        |d   xs d|› d�«      | ‚)us  Raise ``SandboxNotReadyError`` when the API rejected a proxy-config update.

    A proxy config can only be written to a ``ready`` sandbox, and that status
    check is the sole source of ``InvalidRequest`` on the update endpoint for the
    fields this client sends â€” a typed error lets callers start the sandbox and
    retry instead of matching on status codes.
    é�  Nrt   ÚInvalidRequestrn   z	Sandbox 'z' is not ready)rJ   rT   r~   rI   r   )r]   r   r{   s      r   Úraise_if_not_readyr©   ’  s]   € ð ‡~�~×!Ñ! SÒ(ØÜ Ó&€DØ‡x�x�ÓÐ!1Ò1ØÜ
ØˆY‰Ò;˜Y t f¨NÐ;óàð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).rn   rt   )i‘  é“  rW   r“   r   r™   Nrš   r›   rž   rŸ   éö  ÚConnectionErroriô  )r~   rI   rJ   rT   r   r
   rƒ   r   r�   r   r   r   r   )r]   r{   rn   rt   r`   r�   rœ   r    s           r   r¤   r¤   ¤  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)
    rn   rt   Ú
WriteErrorÚwrite)Ú	operationrt   Ú	ReadErrorÚreadÚCommandErrorÚcommandr«   NÚPermissionDeniedr¬   r­   r§   ÚNotReadyr¡   ÚServiceUnavailablerW   ÚFileNotFoundrY   rZ   )	r�   rI   rJ   rT   r   r   r   r
   r   )r]   r{   rn   rt   r`   s        r   r\   r\   Î  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   rº   Úreturnzdict[str, str])r$   r   r%   zOptional[dict[str, str]]r&   úOptional[str]r»   zOptional[dict[str, Any]])r*   zOptional[bool]r+   Úboolr»   r½   )r0   úOptional[int]r1   r¾   r2   r¾   r»   rm   )r   r¼   r»   ztuple[int, Optional[int]])rJ   úhttpx.Responser»   r   )rJ   r¿   r»   r   )r]   úhttpx.HTTPStatusErrorr^   rm   r_   rm   r»   ÚNone)re   r;   rf   r;   r»   rÁ   )r   r¾   r   rm   r»   rÁ   )rn   rm   ro   r   r»   rm   )r]   rÀ   r»   údict[str, Any])r]   rÀ   r»   z
list[dict])rn   rm   r»   r¼   )r…   )r{   rÂ   r]   rÀ   r[   rm   r»   rÁ   )r]   rÀ   r»   rÁ   )r]   rÀ   r   rm   r»   rÁ   ).Ú__doc__Ú
__future__r   Úcollections.abcr   Útypingr   r   Ú langsmith._openapi_client._httpxr   Úlangsmith.sandbox._exceptionsr   r	   r
   r   r   r   r   r   r   r   r   Úlangsmith.sandbox._modelsr   r   r   r    r'   r,   r3   rB   rL   rU   ra   rg   rj   rp   r~   r�   rƒ   r�   r‘   r¥   r©   r¤   r\   r)   r!   r   Ú<module>rÊ      sH  ðñõ #å #ß  å 2÷÷ ÷ ñ ÷ OÑ Nð 15Ø48ðØ-ðà1ðð óð.+Øð+Ø5ð+Ø<Ið+àó+ó&ð"Øð"Ø"/ð"Ø?Lð"àó"ó*óóð6%Ø ð%Ø+.ð%Ø>Að%à	ó%ó$
ó*Ró.ó!;óH;ó0ó$ð8 #ðØ
ðà ðð ðð 
ó	ó(.(óbó$"1ôT21r!   