
    iA)                        d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
mZ  ej                  d      Z e ej                  dd            ZdZd	ed
ededz  fdZdedz  ded	ed
edef
dZ G d d      Zdee   de	e   fdZdededz  fdZdee   dz  de	e   fdZdee   dz  de	e   fdZde
eef   dz  deeef   fdZddddde	e   dededz  deeef   dz  dedz  deeef   fdZd dd!dee   d"ed#eeef   dz  deeef   fd$Zddd%d&edz  d#eeef   dz  deeef   fd'Zddddddd(d)edz  d*edz  dee   dz  de
eef   dz  dedz  d#eeef   dz  deeef   fd+Zy),z2Utility tool to manage Python environments via uv.    N)Path)AnyDictListMappingSequencez^[A-Za-z0-9_.\-+=<>!\[\],@:/]+$LIB_INSTALL_TIMEOUT120   stdoutstderrreturnc                     | j                         xs |j                         }|syt        |      t        k  r|S |dt         j                          dS )zAReturn a short preview from stdout or stderr for error messaging.Nz... [truncated])striplen_OUTPUT_SNIPPET_LIMITrstrip)r   r   preview_sources      R/Users/bowang/.openclaw/workspace/ChatDev/functions/function_calling/uv_related.py_trim_output_previewr      sT     \\^5v||~N
>33334;;=>oNN    steptimeout_valuec                 X    d}| r| d|  d}| d| d}t        ||      }|r| d| S |S )zHCreate a descriptive timeout error message with optional output preview.z
uv commandz ()z timed out after z secondsz. Last output: )r   )r   r   r   r   labelmessagepreviews          r   _build_timeout_messager      sV     E'D6#(x@G"662G/'33Nr   c                   \    e Zd ZdZdeeef   dz  fdZedede	fd       Z
dee	z  de	fd	Zy)
WorkspaceCommandContextz=Resolve the workspace root from the injected runtime context.ctxNc                 v    |t        d      | j                  |j                  d            | _        || _        y )Nz!_context is required for uv toolspython_workspace_root)
ValueError_require_workspacegetworkspace_root_raw_ctx)selfr"   s     r   __init__z WorkspaceCommandContext.__init__)   s7    ;@AA"55cgg>U6VWr   raw_pathr   c                     | t        d      t        |       j                         j                         }|j	                  dd       |S )Nz+python_workspace_root missing from _contextT)parentsexist_ok)r%   r   
expanduserresolvemkdir)r,   paths     r   r&   z*WorkspaceCommandContext._require_workspace/   sD    JKKH~((*224

4$
/r   relative_pathc                     t        |      }|j                         r|n| j                  |z  }|j                         j	                         }| j                  |j
                  vr|| j                  k7  rt        d      |S )Nz%script path is outside workspace root)r   is_absoluter(   r0   r1   r.   r%   )r*   r4   	candidateabsolutes       r   resolve_under_workspacez/WorkspaceCommandContext.resolve_under_workspace7   ss    '	 ) 5 5 79T=P=PS\=\&&(002h&6&668tGZGZ;ZDEEr   )__name__
__module____qualname____doc__r   strr   r+   staticmethodr   r&   r9    r   r   r!   r!   &   sW    GDcNT1  S T  S4Z D r   r!   packagesc                 H   g }| D ]  }t        |t              st        d      |j                         }|st        d      t        j                  |      st        d|       |j                  d      rt        d|       |j                  |        |st        d      |S )Nzpackage entries must be stringszpackage names cannot be emptyz+unsafe characters detected in package spec -z(flags are not allowed in packages list: z at least one package is required)
isinstancer>   r%   r   _SAFE_PACKAGE_REmatch
startswithappend)rA   
normalizedpkgstrippeds       r   _validate_packagesrL   @   s    J#s#>??99;<==%%h/J3%PQQs#GuMNN(#  ;<<r   timeout_secondsc                    | y t        | t              rt        d      t        | t        t        f      rt	        |       }npt        | t
              rU| j                         }|st        d      	 t        j                  d|      rt	        t        |            }nt	        |      }nt        d      |dk  rt        d      |S # t        $ r}t        d      |d }~ww xY w)Nz timeout_seconds must be a numberztimeout_seconds cannot be emptyz[+-]?\d+r   z timeout_seconds must be positive)	rD   boolr%   intfloatr>   r   re	fullmatch)rM   valuerawexcs       r   _coerce_timeout_secondsrW   R   s    /4(;<</C<0o&	OS	)##%>??	J||K-c#hc
 ;<<z;<<L  	J?@cI	Js   /6C 	CCCargsc                     g }| s|S | D ]j  }t        |t              st        d      |j                         }|st        d      |j	                  d      st        d|       |j                  |       l |S )Nzextra args must be stringszextra args cannot be emptyrC   zextra args must be flags, got )rD   r>   r%   r   rG   rH   rX   rI   argrK   s       r   _validate_flag_argsr\   l   s    J#s#9::99;9::""3'=cUCDD(#  r   c                     g }| s|S | D ]K  }t        |t              st        d      |j                         }|st        d      |j	                  |       M |S )Nzargs entries must be stringszargs entries cannot be empty)rD   r>   r%   r   rH   rZ   s       r   _validate_argsr^   |   s`    J#s#;<<99;;<<(#  r   envc                     | i S i }| j                         D ]B  \  }}t        |t              r|st        d      t        |t              st        d      |||<   D |S )Nz3environment variable keys must be non-empty stringsz+environment variable values must be strings)itemsrD   r>   r%   )r_   resultkeyrT   s       r   _validate_envrd      sc    
{	Fiik
U#s#3RSS%%JKKs " Mr   r   r_   timeoutcmdr(   rf   c          
         |t         n|}|d ni t        j                  |}	 t        j                  | t        |      dd|d|      }| |j                  xs d|j                  xs d|j                  |dS # t        $ r}t        d      |d }~wt        j                  $ rR}|j                  }	|	t        |dd      xs d}	|j                  xs d}
t        |||	|
      }| |	|
d |d||dcY d }~S d }~ww xY w)	NTF)cwdcapture_outputtextrf   checkr_   zuv command not found in PATHoutput )commandr   r   
returncoder   	timed_outrf   error)ro   r   r   rp   r   )_DEFAULT_TIMEOUTosenviron
subprocessrunr>   FileNotFoundErrorRuntimeErrorTimeoutExpiredr   getattrr   r   rp   )rg   r(   r   r_   rf   r   env_vars	completedrV   stdout_textstderr_textr   s               r   _run_uv_commandr      s     )0$WM{t(=2::(=(=H
NNN#!
	: ""(b""(b** '  D9:C$$ 
jj!#x4:Kjj&B(}k;W!!$	
 		

s*   %A7 7	C4 BC4"AC/)C4/C4F)upgrade_contextr   r   c                    t        |      }t        |       }ddg}|r|j                  d       |j                  |       t	        ||j
                  d      }|S )z:Install Python packages inside the workspace using uv add.uvaddz	--upgradezuv addr   )r!   rL   rH   extendr   r(   )rA   r   r   r"   safe_packagesrg   rb   s          r   install_python_packagesr      sW     "(
+C&x0ME]C

; JJ}S#"4"48DFMr   )python_versionr   r   c                    t        |      }g }ddg}t        ||j                  d      }|j                  |       |d   dk7  rt	        |j                        |dS ddg}| 0| j                         }|st        d	      |j                  d
|g       t        ||j                  d      }|j                  |       g d}	t        |	|j                  d      }
|j                  |
       t	        |j                        |dS )z-Run uv lock and uv venv inside the workspace.r   lockzuv lockr   rp   r   )r(   stepsvenvzpython argument cannot be emptyz--pythonzuv venv)r   initz--barez--no-workspacezuv init)r!   r   r(   rH   r>   r   r%   r   )r   r   r"   r   lock_cmdlock_resultvenv_cmdpython_specvenv_resultinit_cmdinit_results              r   init_python_envr      s    "(
+C"$E.H!(C,>,>YOK	LL< A%!#"4"45
 	

  .H !$**,>??[12!(C,>,>YOK	LLDH!(C,>,>YOK	LL c001 r   )modulescriptrX   r_   rM   r   r   r   c                 4   t        |      }t        |      }| du}|du}||k(  rt        d      ddg}	|r2| j                         }
|
st        d      |	j	                  dd|
g       nZt        |t              r|j                         n|}|st        d      |j                  |      }|	j                  t        |             |	j	                  t        |             t        |      }t        |	|j                  d	||
      }t        |j                        |d<   |S )z@Execute uv run for a module or script inside the workspace root.Nz'Provide exactly one of module or scriptr   rw   zmodule cannot be emptypythonz-mzscript cannot be emptyzuv runre   r(   )r!   rW   r%   r   r   rD   r>   r9   rH   r^   rd   r   r(   )r   r   rX   r_   rM   r   r"   
has_module
has_scriptrg   module_namescript_valuescript_pathenv_overridesrb   s                  r   uv_runr     s    "(
+C-o>Ot#Jt#JZBCCE]Clln566

HdK01)3FC)@v||~f56611,?

3{#$JJ~d#$!#&MF  #3#5#56FMr   ) r=   rt   rR   rv   pathlibr   typingr   r   r   r   r   compilerE   rQ   getenvrs   r   r>   r   r   r!   rL   rW   r\   r^   rd   r   rO   r   r   r   r@   r   r   <module>r      s   8 	 	   5 52::@A #8%@A  O Oc OcDj O
t 
E 
3 
X[ 
`c 
 4# 49 $S UT\ 4hsmd2 tCy  #- $s) 
wsCx(4/ 
DcN 
" !% .	c.. *	.
 
c3h$	. T\. 
#s(^.h &*sm 
 38nt# 
#s(^8 "& '++ $J+ 38nt#+ 
#s(^+` !%$($(&**$J* $J* 3-$
	*
 
c	T	!* T\* 38nt#* 
#s(^*r   