
    4Aj/                    >   d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZmZ ddlmZmZ ddlmZ ddlmZ ddlmZmZmZ d$dZ e              G d dee          Z G d dee          Z G d dee          Z G d dee          Z G d dee          Z G d dee          Z G d dee          Z e G d d                      Z!e G d d                      Z"e G d d                      Z# G d  d!e          Z$ G d" d#e%          Z&dS )%zBase tool class implementing the expanded ToolContract.

Every tool in OpenMontage inherits from BaseTool. This enforces a uniform
interface for discovery, execution, cost estimation, and health reporting.
    )annotationsN)ABCabstractmethod)	dataclassfield)Enum)Path)AnyCallableOptionalreturnNonec                 @   t          t                                                    j        j        dz  } |                                 sdS ddl}t          | dd          5 }|D ] }|                                }|r|                    d          sd|vr3|	                    d          \  }}}|                                }|                                }|dd	         d
v r9|d         }|
                    |d	          }|dk    r
|d	|         n	|d	d         }nH|                    d|          }	|	r|d|	                                         }|                                }|r|t          j        vr|t          j        |<   "	 ddd           dS # 1 swxY w Y   dS )a  Load .env into os.environ once at import time.

    This ensures API keys are available before any tool is instantiated,
    even when tools are imported directly without going through the registry.
    Only sets variables that are not already in the environment.
    z.envNr   utf-8ignore)encodingerrors#=   )'"z(^|\s)#)r	   __file__resolveparentis_filereopenstrip
startswith	partitionfindsearchstartosenviron)
env_pathr   flinekey_valuequoteendmatchs
             >/app/working/workspaces/default/OpenMontage/tools/base_tool.py_load_dotenvr2      s    H~~%%''.5>H III	h	:	:	: (a 	( 	(D::<<D 4??3// 3d?? NN3//MCE))++CKKMMERaRyJ&&ajj**(+r		aeuQRRy 		*e44 3!/EKKMM/2E (s"*,,"'
3)	(( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (s    D%FFFc                  *    e Zd ZdZdZdZdZdZdZdZ	dS )	ToolTiercorevoiceenhancegeneratesourceanalyzepublishN)
__name__
__module____qualname__COREVOICEENHANCEGENERATESOURCEANALYZEPUBLISH     r1   r4   r4   =   s1        DEGHFGGGGrG   r4   c                      e Zd ZdZdZdZdS )ToolStabilityexperimentalbeta
productionN)r<   r=   r>   EXPERIMENTALBETA
PRODUCTIONrF   rG   r1   rI   rI   G   s        !LDJJJrG   rI   c                      e Zd ZdZdZdZdS )
ToolStatus	availableunavailabledegradedN)r<   r=   r>   	AVAILABLEUNAVAILABLEDEGRADEDrF   rG   r1   rQ   rQ   M   s        IKHHHrG   rQ   c                  "    e Zd ZdZdZdZdZdZdS )ToolRuntimezWhere and how a tool executes.local	local_gpuapihybridN)r<   r=   r>   __doc__LOCAL	LOCAL_GPUAPIHYBRIDrF   rG   r1   rY   rY   S   s(        ((EI
CFFFrG   rY   c                      e Zd ZdZdZdS )ExecutionModesyncasyncN)r<   r=   r>   SYNCASYNCrF   rG   r1   rd   rd   [   s        DEEErG   rd   c                      e Zd ZdZdZdZdS )Determinismdeterministicseeded
stochasticN)r<   r=   r>   DETERMINISTICSEEDED
STOCHASTICrF   rG   r1   rj   rj   `   s        #MFJJJrG   rj   c                      e Zd ZdZdZdZdS )ResumeSupportnone
from_startfrom_checkpointN)r<   r=   r>   NONE
FROM_STARTFROM_CHECKPOINTrF   rG   r1   rr   rr   f   s        DJ'OOOrG   rr   c                  Z    e Zd ZU dZdZded<   dZded<   dZded<   d	Zded
<   dZ	ded<   dS )ResourceProfilez&Hardware resource envelope for a tool.r   int	cpu_coresi   ram_mbr   vram_mbd   disk_mbFboolnetwork_requiredN)
r<   r=   r>   r^   r|   __annotations__r}   r~   r   r   rF   rG   r1   rz   rz   l   sn         00IFGG"""""""rG   rz   c                  R    e Zd ZU dZdZded<   dZded<    ee          Z	d	ed
<   dS )RetryPolicyzSafe retry behavior for a tool.r   r{   max_retriesg      ?floatbackoff_secondsdefault_factory	list[str]retryable_errorsN)
r<   r=   r>   r^   r   r   r   r   listr   rF   rG   r1   r   r   v   sY         ))K O    "'%"="="=======rG   r   c                      e Zd ZU dZded<    ee          Zded<    ee          Z	ded<   d	Z
d
ed<   dZded<   dZded<   d	Zded<   d	Zd
ed<   d	S )
ToolResultz+Standard result returned by tool execution.r   successr   dict[str, Any]datar   	artifactsNOptional[str]error        r   cost_usdduration_secondsOptional[int]seedmodel)r<   r=   r>   r^   r   r   dictr   r   r   r   r   r   r   r   rF   rG   r1   r   r   ~   s         55MMM 5666D6666 5666I6666EH!!!!!DErG   r   c                     e Zd ZU dZdZded<   dZded<   ej        Z	ded<   e
j        Zd	ed
<   ej        Zded<   ej        Zded<   ej        Zded<   g Zded<   dZded<   dZded<   dZded<   g Zded<   i Zded<   i Zded<   i Zded<   dZded<   i Zd ed!<   g Z ded"<   g Z!ded#<   i Z"d ed$<    e#            Z$d%ed&<    e%            Z&d'ed(<   e'j(        Z)d)ed*<   g Z*ded+<   g Z+ded,<   dZ,d-ed.<   g Z-ded/<   g Z.ded0<   g Z/ded1<   dZ0d2ed3<   dZ1d2ed4<   dZ2d2ed5<   dLd8Z3dMd:Z4dNd;Z5dOd>Z6dOd?Z7dPd@Z8e9dQdB            Z:dRdCZ;dddDdSdKZ<dS )TBaseToolz.Abstract base class for all OpenMontage tools. strnamez0.1.0versionr4   tierrI   	stabilityrd   execution_moderj   determinismrY   runtimer   dependenciesinstall_instructionsgeneric
capabilityopenmontageprovidercapabilitiesr   input_schemaoutput_schemaartifact_schemaNzOptional[dict]progress_schemar   supportsbest_fornot_good_forprovider_matrixrz   resource_profiler   retry_policyrr   resume_supportidempotency_key_fieldsside_effectsr   fallbackfallback_toolsagent_skillsuser_visible_verificationzOptional[float]quality_scorehistorical_success_ratelatency_p50_secondsr   rQ   c                |    	 |                                   t          j        S # t          $ r t          j        cY S w xY w)z0Check if this tool's dependencies are satisfied.)check_dependenciesrQ   rU   DependencyErrorrV   )selfs    r1   
get_statuszBaseTool.get_status   sL    	*##%%%'' 	* 	* 	*))))	*s   " ;;r   c                   | j         D ]}|                    d          r9|dd         }t          j        |          t	          d|d| j                   Q|                    d          rD|dd         }t          j                            |          st	          d|d| j                   |                    d	          rC|d
d         }	 t          |           # t          $ r t	          d|d| j                   w xY wdS )zEVerify all dependencies are installed. Raises DependencyError if not.zcmd:   NzCommand z not found. zenv:zEnvironment variable z
 not set. zpython:   zPython module z not installed. )r   r!   shutilwhichr   r   r&   r'   get
__import__ImportError)r   depcmd_nameenv_namemodule_names        r1   r   zBaseTool.check_dependencies   sc   $ 	 	C~~f%% qrr7<))1)V8VV4;TVV   2 '' qrr7z~~h// )aaadF_aa   	** !!""g{++++"   )cccHacc  		 	s   C""%Dc           	     4   t          j        | j                  }i d| j        d| j        d| j        j        d| j        d| j        d| j	        j        d| 
                                j        d| j        j        d	| j        j        d
| j        j        d| j        j        d|d| j        d| j        d| j        d| j        d| j        i d| j        d| j        d| j        d| j        d| j        d| j        j        | j        j        | j        j        | j        j        | j        j        dd| j        j        d| j         d| j!        d| j"        p| j!        r| j!        gng d| j#        d| j#        d| j$        d | j%        d!| j&        d"| j'        S )#z6Return full tool contract info for registry/discovery.r   r   r   r   r   r   statusr   r   r   module_pathusage_locationr   r   r   r   r   r   r   r   r   r   r   )r|   r}   r~   r   r   r   r   r   r   r   related_skillsr   r   r   r   )(inspectgetfile	__class__r   r   r   r-   r   r   r   r   r   r   r   r=   r   r   r   r   r   r   r   r   r   r   r   r|   r}   r~   r   r   r   r   r   r   r   r   r   r   r   )r   r   s     r1   get_infozBaseTool.get_info   sy    88(
DI(
t|(
 DIO(
 $/	(

 (
 -(
 doo''-(
 d17(
 4+1(
 t|)(
 4>4(
 n(
 D-(
 #D$=(
 D-(
  D-!(
" T/#(
 (
$ t3%(
& '(
( )(
* D-+(
, t3-(
. !2</60808$($9$J! !/(
< d17=(
> D-?(
@ A(
B d1_6^t}oo\^C(
D D-E(
F d/G(
H ()GI(
J T/K(
L &t'CM(
N "4#;O(
 (
 (	
rG   inputsr   c                    dS )zCEstimate cost in USD for the given inputs. Override for paid tools.r   rF   r   r   s     r1   estimate_costzBaseTool.estimate_cost      srG   c                    dS )z=Estimate runtime in seconds. Override for long-running tools.r   rF   r   s     r1   estimate_runtimezBaseTool.estimate_runtime  r   rG   c                    fd| j         D             }t          j        |d          }t          j        |                                                                          dd         S )z,Compute a cache key from idempotency fields.c                <    i | ]}|                     |          S rF   )r   ).0kr   s     r1   
<dictcomp>z,BaseTool.idempotency_key.<locals>.<dictcomp>$  s%    JJJAvzz!}}JJJrG   T)	sort_keysN   )r   jsondumpshashlibsha256encode	hexdigest)r   r   key_dataraws    `  r1   idempotency_keyzBaseTool.idempotency_key"  s`    JJJJd.IJJJjT222~cjjll++5577<<rG   r   c                    dS )z-Run the tool. Subclasses must implement this.NrF   r   s     r1   executezBaseTool.execute*  s	     	rG   c                    | j         |                     |          |                     |          |                                 j        ddS )zIPreflight check without side effects. Override for paid/publishing tools.T)toolestimated_cost_usdestimated_runtime_secondsr   would_execute)r   r   r   r   r-   r   s     r1   dry_runzBaseTool.dry_run/  sM     I"&"4"4V"<"<)-)>)>v)F)Foo''-!
 
 	
rG   )timeoutcwdcmdr   r   r   Optional[Path]subprocess.CompletedProcessc          
         t          |          }t          j                    dk    r#|r!t          j        |d                   }|r||d<   t          j        |dddd||d          S )zRun a subprocess command with standard error handling.

        On Windows, resolves .cmd/.bat wrappers (e.g. npx, npm) via
        shutil.which() so subprocess.run() can find them without shell=True.
        Windowsr   Tr   replace)capture_outputtextr   r   r   r   check)r   platformsystemr   r   
subprocessrun)r   r   r   r   resolved_cmdexes         r1   run_commandzBaseTool.run_command;  s~     Cyy?	))l),|A//C &"%Q~
 
 
 
 	
rG   )r   rQ   r   r   )r   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   r   r   r   r   )=r<   r=   r>   r^   r   r   r   r4   r?   r   rI   rM   r   rd   rg   r   rj   rn   r   rY   r_   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rz   r   r   r   rr   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  rF   rG   r1   r   r      sB        88 DNNNNG]D"""",9I9999$1$6N6666*8K8888&,G,,,, !L     """""  J!H!!!! L    LMO&*O****!H!!!!H L    &(O(((( )8(9(99999 +L---- %2$6N6666(***** !L    "H"""" "N"""" !L     ,.---- &*M))))/33333+/////* * * *   0+
 +
 +
 +
^      = = = =    ^
 
 
 
  "&"
 
 
 
 
 
 
 
rG   r   c                      e Zd ZdZdS )r   z1Raised when a tool's dependency is not satisfied.N)r<   r=   r>   r^   rF   rG   r1   r   r   \  s        ;;DrG   r   r  )'r^   
__future__r   r   r   r   r&   r  r	  r   abcr   r   dataclassesr   r   enumr   pathlibr	   typingr
   r   r   r2   r   r4   rI   rQ   rY   rd   rj   rr   rz   r   r   r   	Exceptionr   rF   rG   r1   <module>r     s0    # " " " " "    				       # # # # # # # # ( ( ( ( ( ( ( (             * * * * * * * * * * (  (  (  (F     sD       C       d       #t       C   
    #t   ( ( ( ( (C ( ( ( # # # # # # # # > > > > > > > > 	  	  	  	  	  	  	  	 N
 N
 N
 N
 N
s N
 N
 N
b	 	 	 	 	i 	 	 	 	 	rG   