
    a
ix3                        d 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m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d!dZdS )"zShared 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)AnyOptionalN)QuotaExceededErrorResourceAlreadyExistsErrorResourceCreationErrorResourceNotFoundErrorResourceTimeoutErrorSandboxAPIErrorSandboxAuthenticationErrorSandboxClientErrorSandboxConnectionErrorSandboxNotReadyErrorSandboxOperationErrorValidationErrorerrorhttpx.HTTPStatusErrorreturn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_typer   c                ~    g | ]:}t          |t                    |                    d t          |                    ;S )msg)
isinstancedictgetstr.0ds     C:\Users\Dell Inspiron 16\Desktop\tws\AgrotaPowerBi\back-agrota-powerbi\mcp-client-agrota\venv\Lib\site-packages\langsmith/sandbox/_helpers.py
<listcomp>z(parse_error_response.<locals>.<listcomp>7   s;    TTT
1d@S@STeSVV,,TTT    Nz; )	responsejsonr   r   r   r    listjoin	Exception)r   datar   messagess       r$   parse_error_responser.   !   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
    r   r   r   r   N)r'   r(   r   r   r   r    r+   r   r,   r   s      r$   parse_error_response_simpler1   C   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")
    r   )r'   r(   r   r   r)   r+   r0   s      r$   parse_validation_errorr4   Y   sm    ~""$$(B''fd## 	M	   			s   AA
 A
 
AAr   r    Optional[str]c                    |                                  }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|v sd|v rdS d	|v rd	S d
S )zExtract quota type from error message.

    Returns one of: "sandbox_count", "cpu", "memory", "volume_count",
    "storage", or None.
    sandboxcountlimitsandbox_countcpumemoryvolumevolume_countstorageN)lower)r   message_lowers     r$   extract_quota_typerB   k   s     MMOOMM!!=  G}$<$<	-		u	]	"	"x	]	"	"=  G}$<$<~	m	#	#y4r&   r7   r,   resource_typeNonec                    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
    r   z creation failedr   rC   r   )r   r   title)r,   r   rC   s      r$   raise_creation_errorrH      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  r   r7   rC     c              3  H   K   | ]}|                     d           dk    V  dS )typevalue_errorN)r   r!   s     r$   	<genexpr>z0handle_sandbox_creation_error.<locals>.<genexpr>   s1      KKa155==M9KKKKKKr&   r   locNr   fielddetails  r   
quota_type  r   UnschedulablerF   )r'   status_coder.   r
   r4   anyr   r   rH   rB   r   r   handle_client_http_error)r   statusr,   rT   rS   rW   s         r$   handle_sandbox_creation_errorr^      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                    | j         j        }t          |           }|dk    rt          |d         dd          | |dk    rt	          |d         d          | t          |            dS )	a   Handle HTTP errors specific to volume creation.

    Maps API error responses to specific exception types:
    - 503: ResourceCreationError (provisioning failed)
    - 504: ResourceTimeoutError (volume didn't become ready in time)
    - Other: Falls through to generic error handling
    rX   r   r=   VolumeProvisioningrF     rJ   N)r'   rZ   r.   r   r
   r\   )r   r]   r,   s      r$   handle_volume_creation_errorrb      s     ^'F&&D}}#O"+
 
 
 		
 
3"4	?(KKKQVV 	!'''''r&   c                   | j         j        }t          |           }|                    d          }|dk    rM|dk    rt	          |d         d          | |dk    rt          |d         |          | t          |            dS |d	k    rt          |d         d
          | |dk    r-t          |d                   }t          |d         |          | |dk    rt          |d         d
          | t          |            dS )a  Handle HTTP errors specific to pool creation/update.

    Maps API error responses to specific exception types:
    - 400: ResourceNotFoundError or ValidationError (template has volumes)
    - 409: ResourceAlreadyExistsError
    - 429: QuotaExceededError (org limits exceeded)
    - 504: ResourceTimeoutError (timeout waiting for ready replicas)
    - Other: Falls through to generic error handling
    r     TemplateNotFoundr   templaterJ   r   )r   i  poolrU   rV   ra   N)r'   rZ   r.   r   r	   r   r\   r   rB   r   r
   )r   r]   r,   r   rW   s        r$   handle_pool_errorrh      sI    ^'F&&D,''J}}+++'Yz   ,,,!$y/jIIIuT %U+++++	3(O6
 
 
	 
3'Y88
 O!
 
 
 	 
3"4	?&IIIuT 	!'''''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).r   r   )i      rK   r   rP   NrQ   rR   rU   rV     ConnectionErrori  )r.   r   r'   rZ   r   r	   r4   r   rB   r   r   r   r   )r   r,   r   r   r]   rT   rS   rW   s           r$   r\   r\     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)
    r   r   
WriteErrorwrite)	operationr   	ReadErrorreadCommandErrorcommandrj   NPermissionDeniedrl   rm   rd   NotReadyrk   FileNotFoundfilerJ   )	r1   r   r'   rZ   r   r   r   r	   r   )r   r,   r   r   r]   s        r$   handle_sandbox_http_errorrz   A  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&   )r   r   r   r   )r   r   r   r2   )r   r    r   r5   )r7   )r,   r   r   r   rC   r    r   rD   )r   r   r   rD   )__doc__
__future__r   typingr   r   httpxlangsmith.sandbox._exceptionsr   r   r   r	   r
   r   r   r   r   r   r   r   r.   r1   r4   rB   rH   r^   rb   rh   r\   rz    r&   r$   <module>r      s    # " " " " "                                            (; ; ; ;D; ; ; ;,   $   D #    (.( .( .( .(b( ( ( (4+( +( +( +(\"1 "1 "1 "1T/1 /1 /1 /1 /1 /1r&   