
    i/"                    F   d dl mZ d dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
mZmZmZ d dlmZ d dlmZmZmZmZmZ d dlmZ d d	lmZmZ d d
l e G d d             Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d d      Z y)    )annotationsN)	dataclass)Path)AnyDictOptionalType)RateLimitError)	BaseModel
ConfigDictFieldValidationErrorcreate_model)ActionModel)r   r   )*c                  "    e Zd ZU ded<   ded<   y)AgentStepInfointstep_number	max_stepsN)__name__
__module____qualname____annotations__     A/Users/mibo/.openclaw/workspace/data/TuriX-CUA/src/agent/views.pyr   r      s     Nr   r   c                  f    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Z
ded<   y)ActionResultzResult of executing an actionFzOptional[bool]is_doneNzOptional[str]extracted_contenterrorboolinclude_in_memoryzOptional[int]current_app_pidTaction_is_valid)r   r   r   __doc__r    r   r!   r"   r$   r%   r&   r   r   r   r   r      sC    '#G^#'+}+E=#t#%)O])&*O^*r   r   c                  l    e Zd ZU dZ edd      Zded<    edd      Zded<    edd	      Zded
<   y)
AgentBrainzCurrent state of the agent.z)Success/Failed (based on step completion))descriptionstrstep_evaluatezDescribe what you want user to do or No (No if nothing to ask for comfirmation. If something is unclear, ask the user for confirmation, like ask the user to login, or comfirm preference.)	ask_humanz}Actionable goal based on current state (screenshots/memory) and any Selected Skills; adapt skill steps to the current screen.	next_goalN)	r   r   r   r'   r   r,   r   r-   r.   r   r   r   r)   r)   "   sM    $s0[\M3\3  -j  kIs  k3  -l  mIs  mr   r)   c                  X    e Zd ZU dZ ed      Z edddd      Zd	ed
<   e	dd       Z
y)AgentOutputzhOutput model for agent

    @dev note: this model is extended with custom actions in AgentService. 
    T)arbitrary_types_allowed.r   
   z+Ordered list of 0-10 actions for this step.)	min_items	max_itemsr*   zlist[ActionModel]actionc                h    t        dt        t        |    t        d      ft        j                        S )z"Extend actions with custom actionsr0   .)__base__r5   r   )r   r0   listr   r   )custom_actionss    r   type_with_custom_actionsz$AgentOutput.type_with_custom_actions9   s1      (%*5"--	
 	
r   N)r9   zType[ActionModel]returnzType['AgentOutput'])r   r   r   r'   r   model_configr   r5   r   staticmethodr:   r   r   r   r0   r0   *   sG    
 d;L !&A	!F  
 
r   r0   c                  L    e Zd ZU dZded<   ded<   ded<    edd	
      ZddZy)AgentHistoryzHistory item for agent actionszAgentOutput | Nonemodel_outputlist[ActionResult]resultr+   stateTr   )r1   protected_namespacesc                V   d}| j                   rZ| j                   j                  D cg c]  }|j                  d       }}| j                   j                  j                         |d}|| j                  D cg c]  }|j                  d       c}| j
                  dS c c}w c c}w )z1Custom serialization handling circular referencesNTexclude_none)current_stater5   )r@   rB   rC   )r@   r5   
model_dumprH   rB   rC   )selfkwargsmodel_output_dumpr5   action_dumprs         r   rI   zAgentHistory.model_dumpM   s     !NRN_N_NfNfgNfF6,,$,?NfKg!%!2!2!@!@!K!K!M%! .@DL1q|||6LZZ
 	
 h Ms   B!8B&Nr;   zDict[str, Any])r   r   r   r'   r   r   r<   rI   r   r   r   r?   r?   D   s(    ($$JdQSTL
r   r?   c                      e Zd ZU dZded<   ddZddZddZddZe	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g fd"dZy)#AgentHistoryListzList of agent history itemszlist[AgentHistory]historyc                L    d| j                          d| j                          dS )-Representation of the AgentHistoryList objectzAgentHistoryList(all_results=z, all_model_outputs=))action_resultsmodel_actionsrJ   s    r   __str__zAgentHistoryList.__str__d   s.    .t/B/B/D.EEYZ^ZlZlZnYoopqqr   c                "    | j                         S )rT   )rY   rX   s    r   __repr__zAgentHistoryList.__repr__h   s    ||~r   c                   	 t        |      j                  j                  dd       | j                         }t	        |dd      5 }t        j                  ||d       ddd       y# 1 sw Y   yxY w# t        $ r}|d}~ww xY w)	z3Save history to JSON file with proper serializationT)parentsexist_okwutf-8encoding   )indentN)r   parentmkdirrI   openjsondump	Exception)rJ   filepathdatafes        r   save_to_filezAgentHistoryList.save_to_filel   sn    	N!!''t'D??$Dhg6!		$!, 766 	G	s6   AA4 A(A4 (A1-A4 1A4 4	B=A??Bc           	     d    d| j                   D cg c]  } |j                  di | c}iS c c}w )zACustom serialization that properly uses AgentHistory's model_dumprR   r   )rR   rI   )rJ   rK   hs      r   rI   zAgentHistoryList.model_dumpv   s7     E1.v.E
 	
Es   -c                   t        |dd      5 }t        j                  |      }ddd       d   D ]8  }|d   s	t        |d   t              r|j                  |d         |d<   4d|d<   : | j                  |      }|S # 1 sw Y   \xY w)zLoad history from JSON filerN   r`   ra   NrR   r@   )rg   rh   load
isinstancedictmodel_validate)clsrk   output_modelrm   rl   rq   rR   s          r   load_from_filezAgentHistoryList.load_from_file|   s     (C'2a99Q<D 3 iA a/6(4(C(CAnDU(VAn%(,An% ! $$T* 32s   B  B	c                    | j                   rO| j                   d   j                  r6| j                   d   j                  j                  d   j                  d      S y)zLast action in historyTrF   N)rR   r@   r5   rI   rX   s    r   last_actionzAgentHistoryList.last_action   sL    <<DLL,99<<#0077;FFTXFYYr   c                    g }| j                   D ]B  }|j                  |j                  D cg c]  }|j                  s|j                   c}       D |S c c}w )zGet all errors from history)rR   extendrB   r"   )rJ   errorsrq   rN   s       r   r   zAgentHistoryList.errors   sI    AMMAHH@Hq177H@A  A
   A
A
c                    | j                   rL| j                   d   j                  d   j                  r&| j                   d   j                  d   j                  S y)zFinal result from historyr{   N)rR   rB   r!   rX   s    r   final_resultzAgentHistoryList.final_result   sH    <<DLL,33B7II<<#**2.@@@r   c                    | j                   rLt        | j                   d   j                        dkD  r'| j                   d   j                  d   j                  ryy)zCheck if the agent is doner{   r   TF)rR   lenrB   r    rX   s    r   r    zAgentHistoryList.is_done   sG    <<CR 0 7 781<bAQAXAXY[A\AdAdr   c                :    t        | j                               dkD  S )z!Check if the agent has any errorsr   )r   r   rX   s    r   
has_errorszAgentHistoryList.has_errors   s    4;;=!A%%r   c                    g }| j                         D ]2  }t        |j                               }|s|j                  |d          4 |S )z!Get all action names from historyr   rW   r8   keysappend)rJ   action_namesr5   actionss       r   r   zAgentHistoryList.action_names   sG    ((*F6;;=)G##GAJ/ + r   c                    | j                   D cg c]%  }|j                  s|j                  j                  ' c}S c c}w )zGet all thoughts from history)rR   r@   rH   rJ   rq   s     r   model_thoughtszAgentHistoryList.model_thoughts   s.    6:llUlann,,lUUUs   <<c                n    | j                   D cg c]  }|j                  s|j                   c}S c c}w )z"Get all model outputs from history)rR   r@   r   s     r   model_outputszAgentHistoryList.model_outputs   s(    (,G1GGGs   22c                    g }| j                   D ]M  }|j                  s|j                  j                  D ]%  }|j                  d      }|j	                  |       ' O |S )zGet all actions from historyTrF   )rR   r@   r5   rI   r   )rJ   outputsrq   r5   outputs        r   rW   zAgentHistoryList.model_actions   sV    A~~nn33F#..D.AFNN6* 4 
 r   c                    g }| j                   D ].  }|j                  |j                  D cg c]  }|s|	 c}       0 |S c c}w )zGet all results from history)rR   r~   rB   )rJ   resultsrq   rN   s       r   rV   zAgentHistoryList.action_results   s@    ANNqxx5x!1Ax56  6s
   A
A
c                    g }| j                   D ]B  }|j                  |j                  D cg c]  }|j                  s|j                   c}       D |S c c}w )z&Get all extracted content from history)rR   r~   rB   r!   )rJ   contentrq   rN   s       r   r!   z"AgentHistoryList.extracted_content   sM    ANNYAQEXEXA//YZ  Zr   c                    | j                         }g }|D ]:  }|D ]3  }|t        |j                               d   k(  s#|j                  |       5 < |S )z*Get all model actions from history as JSONr   r   )rJ   includer   rB   ois         r   model_actions_filteredz'AgentHistoryList.model_actions_filtered   sS    $$&AQVVXq))MM!$   r   N)r;   r+   )rk   
str | Pathr;   NonerO   )rk   r   rx   zType[AgentOutput]r;   z'AgentHistoryList')r;   zNone | dict)r;   	list[str])r;   z
None | str)r;   r#   )r;   zlist[AgentBrain])r;   zlist[AgentOutput])r;   
list[dict])r;   rA   )r   r   r;   r   )r   r   r   r'   r   rY   r[   ro   rI   classmethodry   r|   r   r   r    r   r   r   r   rW   rV   r!   r   r   r   r   rQ   rQ   _   sw    %r
  &VH ;= r   rQ   c                  0    e Zd ZdZdZdZdZeddd       Zy)	
AgentErrorz"Container for agent error handlingz>Invalid model output format. Please follow the correct schema.z)Rate limit reached. Waiting before retry.zNo valid action foundc                    t        | t              rt        j                   dt	        |        S t        | t
              rt        j                  S |r"t	        |        dt        j                          S t	        |        S )zEFormat error message based on error type and optionally include tracez

Details: z
Stacktrace:
)	rt   r   r   VALIDATION_ERRORr+   r
   RATE_LIMIT_ERROR	traceback
format_exc)r"   include_traces     r   format_errorzAgentError.format_error   sn     e_- 112+c%j\JJe^,...%j\1E1E1G0HIIe*r   N)F)r"   rj   r   r#   r;   r+   )	r   r   r   r'   r   r   NO_VALID_ACTIONr=   r   r   r   r   r   r      s(    ,WB-O r   r   )!
__future__r   rerh   r   dataclassesr   pathlibr   typingr   r   r   r	   openair
   pydanticr   r   r   r   r   src.controller.registry.viewsr   pydantic.v1src.controller.viewsr   r   r)   r0   r?   rQ   r   r   r   r   <module>r      s    " 	   !  , , ! P P 5 ( "
  
+9 +m m
) 
4
9 
6{y {| r   