
    i                        d Z ddlZddlZ ej        e          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mZmZ ddlmZ  eg d          Z eh d          Z ed  ej                    D                       Zd	                    d
 eD                       ZdZdZdefdZdZdZ g dZ!de"fdZ#	 dRddde$dee$         dee$         de$fdZ%dee$         fdZ&dee$         dee$         fdZ'dSdededee(         fdZ)	 	 	 	 	 	 dTdede$dee$         deee$                  dee$         d ed!ee$         d"ee$         d#ee$         d$ee$         d%ee$         d&eee$                  fd'Z*	 	 dUdede$dee$ef         fd(Z+	 	 	 	 	 	 	 	 dVdee$         dee$         deee$                  d)eeee$ef                           d ee         d*ee$         d+eee$                  de$fd,Z,d-ee$         fd.Z-d/e.de.fd0Z/de.fd1Z0d2d3d4d5d6d7d5d8d7d9d:d5id;e d<d=d9d4d5d>d7d5d?d7d9d:d5id@e dAd=d5dBd7d9d:d5idCd=dDdgdEdFd=dGdHd7d5dId7d9d:d5idJd=dKg dEdLZ1ddMl2m3Z3m4Z4  e3j5        d2dNe1dO e#dPQ           dS )Wa  
Delegate Tool -- Subagent Architecture

Spawns child AIAgent instances with isolated context, restricted toolsets,
and their own terminal sessions. Supports single-task and batch (parallel)
modes. The parent blocks until all children complete.

Each child gets:
  - A fresh conversation (no parent history)
  - Its own task_id (own terminal session, file ops cache)
  - A restricted toolset (configurable, with blocked tools always stripped)
  - A focused system prompt built from the delegated goal + context

The parent's context only sees the delegation call and the summary result,
never the child's intermediate tool calls or reasoning.
    N)ThreadPoolExecutoras_completed)AnyDictListOptional)TOOLSETS)delegate_taskclarifymemorysend_messageexecute_code>   rlmoasafe	debugging
delegationc              #      K   | ]T\  }}|t           v|                    d           #t          d |                    dg           D                       P|V  UdS )zhermes-c              3   (   K   | ]}|t           v V  d S N)DELEGATE_BLOCKED_TOOLS.0ts     ;/home/agentuser/.hermes/hermes-agent/tools/delegate_tool.py	<genexpr>z<genexpr>.<genexpr>0   s(      KK++KKKKKK    toolsN)_EXCLUDED_TOOLSET_NAMES
startswithallget)r   namedefns      r   r   r   ,   s        T4***OOI&& +KKTXXgr5J5JKKKKK + 	**** r   , c              #   "   K   | ]
}d | d V  dS )'N )r   ns     r   r   r   2   s*      CC1h!hhhCCCCCCr         returnc                     t                      } |                     d          }|V	 t          dt          |                    S # t          t
          f$ r$ t                              d|t                     Y nw xY wt          j
        d          }|r5	 t          dt          |                    S # t          t
          f$ r Y nw xY wt          S )a)  Read delegation.max_concurrent_children from config, falling back to
    DELEGATION_MAX_CONCURRENT_CHILDREN env var, then the default (3).

    Uses the same ``_load_config()`` path that the rest of ``delegate_task``
    uses, keeping config priority consistent (config.yaml > env > default).
    max_concurrent_childrenN   zNdelegation.max_concurrent_children=%r is not a valid integer; using default %d"DELEGATION_MAX_CONCURRENT_CHILDREN)_load_configr"   maxint	TypeError
ValueErrorloggerwarning _DEFAULT_MAX_CONCURRENT_CHILDRENosgetenv)cfgvalenv_vals      r   _get_max_concurrent_childrenr>   8   s     ..C
''+
,
,C
	q#c((###:& 	 	 	NN#$')I    	
 i<==G 	q#g,,''':& 	 	 	D	++s#   A 2A98A9B0 0CC2      )terminalfilewebc                      dS )z<Delegation has no external requirements -- always available.Tr(   r(   r   r   check_delegate_requirementsrE   U   s    4r   workspace_pathgoalcontextrG   c                :   ddd|  g}|r,|                                 r|                    d|            |r:t          |                                           r|                    d| d           |                    d           d                    |          S )	z0Build a focused system prompt for a child agent.z@You are a focused subagent working on a specific delegated task. zYOUR TASK:
z

CONTEXT:
z
WORKSPACE PATH:
zg
Use this exact path for local repository/workdir operations unless the task explicitly says otherwise.a5  
Complete this task using the tools available to you. When finished, provide a clear, concise summary of:
- What you did
- What you found or accomplished
- Any files you created or modified
- Any issues encountered

Important workspace rule: Never assume a repository lives at /workspace/... or any other container-style path unless the task/context explicitly gives that path. If no exact local path is provided, discover it first before issuing git/workdir-specific commands.

Be thorough but concise -- your response is returned to the parent agent as a summary.
)stripappendstrjoin)rH   rI   rG   partss       r   _build_child_system_promptrR   Z   s     	K
tE
  /7==?? /-G--... 
#n--3355 
uu u u	
 	
 	

 
LL		%   99Ur   c                    t          j        d          t          t          | dd          dd          t          | dd          t          | dd          g}|D ]}|s	 t           j                            t           j                            t          |                              }n# t          $ r Y \w xY wt           j                            |          r#t           j        	                    |          r|c S dS )a  Best-effort local workspace hint for child prompts.

    We only inject a path when we have a concrete absolute directory. This avoids
    teaching subagents a fake container path while still helping them avoid
    guessing `/workspace/...` for local repo tasks.
    TERMINAL_CWD_subdirectory_hintsNworking_dirterminal_cwdcwd)
r9   r:   getattrpathabspath
expanduserrO   	Exceptionisabsisdir)parent_agent
candidates	candidatetexts       r   _resolve_workspace_hintrd   }   s     		.!!&;TBBMSWXXnd33eT**	J    	 		7??27#5#5c)nn#E#EFFDD 	 	 	H	7== 	27==#6#6 	KKK4s   A	B''
B43B4toolsetsc                 (    h dfd| D             S )z0Remove toolsets that contain only blocked tools.>   r   r   r   code_executionc                     g | ]}|v|	S r(   r(   )r   r   blocked_toolset_namess     r   
<listcomp>z(_strip_blocked_tools.<locals>.<listcomp>   s$    BBB!1,A#A#AA#A#A#Ar   r(   )re   ri   s    @r   _strip_blocked_toolsrk      s2       CBBBxBBBBr   r/   
task_index
task_countc                    	 t          |dd          	t          |dd          	ssdS |dk    r	d| dz    dnddg dd	t          d
t          dt          f	fd}fd}||_        |S )a  Build a callback that relays child agent tool calls to the parent display.

    Two display paths:
      CLI:     prints tree-view lines above the parent's delegation spinner
      Gateway: batches tool names and relays to parent's progress callback

    Returns None if no display mechanism is available, in which case the
    child agent runs with no progress callback (identical to current behavior).
    _delegate_spinnerNtool_progress_callbackr/   [] rK      
event_type	tool_namepreviewc                    | dv r||p|pd}rrt          |          dk    r|d d         dz   n|}	                     d d| d           n2# t          $ r%}t                              d|           Y d }~nd }~ww xY wd S | d	k    rd S r|r t          |          d
k    r|d d
         dz   n|pd}ddlm}  ||pd          }	d d|	 d| }
|r	|
d| dz  }
	                     |
           n2# t          $ r%}t                              d|           Y d }~nd }~ww xY wr                    |pd           t                    k    rrd                              }	  dd |            n2# t          $ r%}t                              d|           Y d }~nd }~ww xY w	                                 d S d S d S )N)	_thinkingzreasoning.availablerK   7   z... u   ├─ 💭 ""zSpinner print_above failed: %sztool.completed#   r   )get_tool_emojiu   ├─ z  "r%   subagent_progress   🔀 zParent callback failed: %s)
lenprint_abover]   r6   debugagent.displayr}   rN   rP   clear)rt   ru   rv   argskwargsrc   shorter}   emojilinesummary_BATCH_SIZE_batch	parent_cbprefixspinners               r   	_callbackz1_build_child_progress_callback.<locals>._callback   s   
 ===-i-2D F/24yy2~~crcU**4F''(KF(K(K%(K(K(KLLLL  F F FLL!A1EEEEEEEEF F )))F  
	B.5`#g,,:K:KWSbS\E))RYR_]_E444444"N9?33E9v99e99i99D )(u((((B##D)))) B B B=qAAAAAAAAB  	MM)/r***6{{k))))F++BI13L63L73L3LMMMM  B B BLL!=qAAAAAAAAB	 	))sG   A 
A=A88A=C2 2
D!<DD!&E8 8
F'F""F'c                      rrrrd                               } 	  dd |             n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w                                 dS dS dS )z<Flush remaining batched tool names to gateway on completion.r%   r~   r   z Parent callback flush failed: %sN)rP   r]   r6   r   r   )r   r   r   r   r   s     r   _flushz._build_child_progress_callback.<locals>._flush   s     	 	ii''GD	-/Hv/Hw/H/HIIII D D D?CCCCCCCCDLLNNNNN	 	 	 	s   . 
AAA)NNN)rY   rO   r   )
rl   r`   rm   r   r   r   r   r   r   r   s
        @@@@@r   _build_child_progress_callbackr      s     l$7>>G&>EEI 9 t (2A~~#a####2F KF) )c )c )3 ) ) ) ) ) ) ) ) ) )V       Ir   modelmax_iterationsoverride_provideroverride_base_urloverride_api_keyoverride_api_modeoverride_acp_commandoverride_acp_argsc           
        &'() ddl m} t          |dd          }|t          |          (n?|r)t	          |d          rddl'')fd|j        D             (nt          t                    (|rt          (fd|D                       }nG|r|t          |          }n3(rt          t          (                    }nt          t                    }t          |          }t          |||          }t          |d	d          }|s*t	          |d
          r|j                            d	          }t          | |          &d}&rdt          ddf&fd}|}|p|j        }|pt          |dd          }|p|j        }|	p|}|
pt          |dd          }|pt          |dd          }t%          ||nt          |dg           pg           }t          |dd          }|}	 t'                      }t          |                    d          pd                                          }|r1ddlm}   | |          }!|!|!}nt.                              d|           n2# t2          $ r%}"t.                              d|"           Y d}"~"nd}"~"ww xY w |d7i d|d	|d|d|d|d|d|d|dt          |dd          d|dt          |dd          d|ddd|d d!|  d"d#|j        d$dd%dd&dd'|d(t          |d)d          d*t          |d+d          d,|j        d-|j        d.|j        d/|j        d0&d1d}#t          |d2d          |#_         t          |d3d          d4z   |#_!        tE          ||          }$|$|$|#_#        t	          |d5          rbt          |d6d          }%|%r5|%5  |j$        %                    |#           ddd           n# 1 swxY w Y   n|j$        %                    |#           |#S )8a  
    Build a child AIAgent on the main thread (thread-safe construction).
    Returns the constructed child agent without running it.

    When override_* params are set (from delegation config), the child uses
    those credentials instead of inheriting from the parent.  This enables
    routing subagents to a different provider:model pair (e.g. cheap/fast
    model on OpenRouter while the parent runs on Nous Portal).
    r   )AIAgentenabled_toolsetsNvalid_tool_namesc                 B    h | ]}                     |          xS r   )get_toolset_for_tool)r   r#   model_toolstss     r   	<setcomp>z%_build_child_agent.<locals>.<setcomp>  s<     
 
 
!66t<<<I IIIr   c                     g | ]}|v |	S r(   r(   )r   r   parent_toolsetss     r   rj   z&_build_child_agent.<locals>.<listcomp>  s#    .[.[.[Qa?FZFZqFZFZFZr   rF   api_key_client_kwargsrc   r,   c                     | sd S 	  d|            d S # t           $ r&}t                              d|           Y d }~d S d }~ww xY w)Nrx   z(Child thinking callback relay failed: %s)r]   r6   r   )rc   r   child_progress_cbs     r   _child_thinkingz+_build_child_agent.<locals>._child_thinking6  sy     L!!+t44444 L L LGKKKKKKKKKLs    
AA  Aproviderapi_modeacp_commandacp_argsreasoning_configreasoning_effortrK   )parse_reasoning_effortzAUnknown delegation.reasoning_effort '%s', inheriting parent levelz.Could not load delegation reasoning_effort: %sbase_urlr   r   
max_tokensprefill_messages
quiet_modeTephemeral_system_prompt
log_prefix
[subagent-]platformskip_context_filesskip_memoryclarify_callbackthinking_callback
session_db_session_dbparent_session_id
session_idproviders_allowedproviders_ignoredproviders_orderprovider_sortrp   iteration_budget	_print_fn_delegate_depthr/   _active_children_active_children_lockr(   )&	run_agentr   rY   sethasattrr   r   DEFAULT_TOOLSETSrk   sortedrd   rR   r   r"   r   rO   r   r   listr1   rM   hermes_constantsr   r6   r7   r]   r   r   r   r   r   r   r   r   _resolve_child_credential_pool_credential_poolr   rN   )*rl   rH   rI   re   r   r   r`   r   r   r   r   r   r   r   parent_enabledchild_toolsetsworkspace_hintchild_promptparent_api_keychild_thinking_cbr   effective_modeleffective_providereffective_base_urleffective_api_keyeffective_api_modeeffective_acp_commandeffective_acp_argsparent_reasoningchild_reasoningdelegation_cfgdelegation_effortr   parsedexcchild
child_poollockr   r   r   r   s*                                         @@@@r   _build_child_agentr      sX   4 "!!!!! \+=tDDN!n--	 0',0BCC 0
 
 
 
 
'8
 
 

 .// @-.[.[.[.[(.[.[.[\\	 @.4-n==	 @-f_.E.EFF-.>??,\::N-dGN[[[L\9d;;N D6F G G D%488CC 7z<PP  	,	L# 	L$ 	L 	L 	L 	L 	L 	L , 1|1O*UglJPT.U.U*Cl.C(:N*UglJPT.U.U0^GL-Y]4^4^3D3P//W^_kmwy{W|W|  XC  AC  E  E |-?FF&OL% 2 23E F F L"MMSSUU 		??????++,=>>F!"(W%    L L LEsKKKKKKKKL G   ##!! o $#	
 $# *) $# &~ <t<<< ) !/A4HHH ( 4 !- .
----  &&!"  4#$ D%& '( ,+)* <===+, ",dCCC-. '88/0 '8812 %4434 #0056  1078 9E< lK>>EO#L2CQGG!KE 00BLQQJ!+ |/00 8|%<dCC 	8 < <-44U;;;< < < < < < < < < < < < < < < )00777Ls+   A7I 
JI>>J&OOOc                    * t          j                    }t          dd          }ddl}t          dt	          |j                            }t          dd          }	d}
|	|	                                }
|
o	 |	                                }|%t          d          r	                    |           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wt          j                    ** fd}t          j        |d	
          }|                                 	                     |          }|rXt          |d          rH	 |                                 n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wt'          t          j                    |z
  d          }|                    d          pd}|                    dd          }|                    dd          }|                    dd          }|rd}n|rd}nd}g }i }|                    d          pg }t+          |t                    r|D ]}t+          |t,                    s|                    d          dk    r|                    d          pg D ]}|                    di           }|                    dd          t/          |                    dd                    d}|                    |           |                    d          }|r|||<   |                    d          d k    r|                    d!d          }t3          |od"|dd#                                         v           } t/          |          | rd"nd$d%}!|                    d&          }|r|                    |          nd}"|"|"                    |!           |r|d'                             |!           |rd}#n|rd}#nd(}#t          d)d          }$t          d*d          }%t          d+d          }& ||||t+          |&t8                    r|&nd|#t+          |$t:          t<          f          r|$ndt+          |%t:          t<          f          r|%ndd,|d-	}'|dk    r|                    d"d.          |'d"<   |'*                                 |                     d/0           |	K|
I	 |	!                    |
           n2# t          $ r%}t                              d1|           Y d}~nd}~ww xY wddl}t          dd          }(t+          |(t                    rt	          |(          |_        t          d2          r	 t          d3d          })|)r5|)5  j"        #                               ddd           n# 1 swxY w Y   nj"        #                               n9# tH          tJ          f$ r%}t                              d4|           Y d}~nd}~ww xY w	 t          d5          r&                                 S S # t          $ r t                              d6           Y S w xY w# t          $ r}t'          t          j                    |z
  d          }tO          j(        d7  d8            d"dt9          |          d|d9cY d}~*                                 |                     d/0           |	K|
I	 |	!                    |
           n2# t          $ r%}t                              d1|           Y d}~nd}~ww xY wddl}t          dd          }(t+          |(t                    rt	          |(          |_        t          d2          r	 t          d3d          })|)r5|)5  j"        #                               ddd           n# 1 swxY w Y   nj"        #                               n9# tH          tJ          f$ r%}t                              d4|           Y d}~nd}~ww xY w	 t          d5          r&                                 S S # t          $ r t                              d6           Y S w xY wd}~ww xY w# *                                 |                     d/0           |	K|
I	 |	!                    |
           n2# t          $ r%}t                              d1|           Y d}~nd}~ww xY wddl}t          dd          }(t+          |(t                    rt	          |(          |_        t          d2          r	 t          d3d          })|)r5|)5  j"        #                               ddd           n# 1 swxY w Y   nj"        #                               n9# tH          tJ          f$ r%}t                              d4|           Y d}~nd}~ww xY w	 t          d5          r&                                 w w # t          $ r t                              d6           Y w w xY wxY w):zi
    Run a pre-built child agent. Called from within a thread.
    Returns a structured result dict.
    rp   Nr   _delegate_saved_tool_namesr   _swap_credentialz-Failed to bind child to leased credential: %sc                                          t                    s	t          	dd           } | s1d
 d}	                                 }|                    d          }|                    dd          }|                    dd          }|rd| d	| d
| d}n$|                    dd          }|rd| d	| d
| d}n# t
          $ r Y nw xY w	  | |           n# t
          $ r Y nw xY w                     t                    d S d S )N_touch_activityzdelegate_task: subagent z workingcurrent_toolapi_call_countr   r   z delegate_task: subagent running z (iteration /)last_activity_descrK   )wait_HEARTBEAT_INTERVALrY   get_activity_summaryr"   r]   )touchdescchild_summary
child_tool
child_iter	child_max
child_desc_heartbeat_stopr   r`   rl   s          r   _heartbeat_loopz*_run_single_child.<locals>._heartbeat_loop  s   !&&':;; 	#L*;TBBE BjBBBD % : : < <*..~>>
*../?CC
)--.>BB	 IDz D D*4D D7@D D DDD "/!2!23G!L!LJ! I!H: !H !H.8!H !H;D!H !H !H   d   3 "&&':;; 	 	 	 	 	s$   BC 
CCC   
C-,C-T)targetdaemon)user_messager   z"Progress callback flush failed: %sr+   final_responserK   	completedFinterrupted	api_callsfailedmessagesrole	assistant
tool_callsfunctionr#   unknown	arguments)tool
args_bytesidr  contenterrorP   ok)result_bytesstatustool_call_idr   session_prompt_tokenssession_completion_tokensr   )inputoutput)	rl   r  r   r
  duration_secondsr   exit_reasontokens
tool_tracez$Subagent did not produce a response.rs   )timeoutz&Failed to release credential lease: %sr   r   z/Could not remove child from active_children: %sclosez,Failed to close child agent after delegationr   z] failedrl   r  r   r  r
  r"  ))time	monotonicrY   r   r   _last_resolved_tool_namesacquire_leasecurrentr   r   r]   r6   r   	threadingEventThreadstartrun_conversationr   roundr"   
isinstancedictr   rN   boollowerupdaterO   r3   floatr   rP   release_leaser   remover5   UnboundLocalErrorr'  logging	exception)+rl   rH   r   r`   _kwargschild_startr   r   _saved_tool_namesr   leased_cred_idleased_entryr   r  _heartbeat_threadresultr   durationr   r  r	  r
  r  r%  trace_by_idr  msgtcfnentry_ttc_idr  is_errorresult_metar  r#  _input_tokens_output_tokens_modelentrysaved_tool_namesr   r  s+   ` ``                                      @r   _run_single_childrT    sv    .""K  '?FF 'C $[%J K KM M  2D99JN#1133%S)1133+?Q0R0R+**<888 S S SLcRRRRRRRRS  o''O       : "(MMMVI''T'::  	F):H!E!E 	FF!((**** F F FA1EEEEEEEEF ))K7;;**-..4"JJ{E22	jj66JJ{A..	 	"FF 	 !FFF ,.
13::j))/Rh%% 	; ; ;!#t,, 776??k11"ww|44: 	9 	9VVJ33$&FF69$=$=*-bff[".E.E*F*F# # #))'222 "t  918K.	9 WWV__..!ggi44G#CGwss|/A/A/C/C$C   H ),G-5"?''4# #K
  GGN33E7<F[__U333$F)k2222# ;"2--k:::  	+'KK 	+%KK*K  '>BB (CQGG.. %" ()&#66@VVD&*4]S%L*Q*QXWX,6~U|,T,T[..Z[  %!
 !
 X#ZZ1WXXE'N" 	q)))!n&@L((8888 L L LEsKKKKKKKKL
 	"5*FMM&-- 	K489I4J4JK1
 <!344 		SS|-DdKK @ D D$5<<UCCCD D D D D D D D D D D D D D D !188??? 12 S S SNPQRRRRRRRRS	Iug&&  	I 	I 	ILLGHHHHH	Ii  

 

 

))K7;;;z;;;<<<$XX (
 
 	
 	
 	
 	
 	
 	q)))!n&@L((8888 L L LEsKKKKKKKKL
 	"5*FMM&-- 	K489I4J4JK1
 <!344 		SS|-DdKK @ D D$5<<UCCCD D D D D D D D D D D D D D D !188??? 12 S S SNPQRRRRRRRRS	Iug&&  	I 	I 	ILLGHHHHH	Ii

 	q)))!n&@L((8888 L L LEsKKKKKKKKL
 	"5*FMM&-- 	K489I4J4JK1
 <!344 		SS|-DdKK @ D D$5<<UCCCD D D D D D D D D D D D D D D !188??? 12 S S SNPQRRRRRRRRS	Iug&&  	I 	I 	ILLGHHHHH	Is  <;B8 8
C'C""C'0(Y6 E. -Y6 .
F8FY6 FL&Y6 2T
T7T22T7	W,W9W,W			W,W		W,,X"=XX"&$Y$Y32Y36bAb
bb \
]&]]` 2_` _	`  _	!`  `6`11`6:$a  $bb
bb /ici
d"d=idAif<.f	f<ff<ff<;i<g2g-(i-g22i6$hi$i iiitasksr   r   c                 P   |t          d          S t          |dd          }|t          k    rt          j        ddt           di          S t                      }	|	                    dt                    }
|p|
}	 t          |	|          }n3# t          $ r&}t          t          |                    cY d}~S d}~ww xY wt                      }|rNt          |t                    r9t          |          |k    r#t          d	t          |           d
| d          S |}nB| r1t          | t                    r|                                 r| ||dg}nt          d          S |st          d          S t!          |          D ]B\  }}|                    dd                                          st          d| d          c S Ct#          j                    }g }t          |          }d |D             }ddl}t          |j                  }g }	 t!          |          D ]\  }}t+          ||d         |                    d          |                    d          p||d         |||d         |d         |d         |d         |                    d          p||                    d          p|          }||_        |                    |||f           	 ||_        n# ||_        w xY w|dk    r;|d         \  }}}t1          d|d         ||          }|                    |           nd}t          |dd          }t3          |           5 } i }!|D ]0\  }}}|                     t0          ||d         ||!          }"||!|"<   1t7          |!                                          }#|#rJt          |d"d#          d$u r|#D ]}$|!|$         }%|$                                rC	 |$                                }&n6# t>          $ r }|%ddt          |          ddd%}&Y d}~nd}~ww xY w|%d&dd'ddd%}&|                    |&           |dz  }ndd(l m!}'m"}(  |'|#d)|(*          \  })}#|)D ]}"	 |"                                }&n5# t>          $ r(}|!|"         }%|%ddt          |          ddd%}&Y d}~nd}~ww xY w|                    |&           |dz  }|&d+         }%|%t          |          k     r||%         nd|% }*|&                    d,d          }+|&                    d-d.          },|,d/k    rd0nd1}-||z
  }.|- d2|%dz    d3| d4|* d5|+ d6
}/|r9	 |#                    |/           n4# t>          $ r tI          d7|/            Y nw xY wtI          d7|/            |r`|.dk    rZ	 |%                    d8|. d9|.dk    rd:nd d;           [# t>          $ r&}0tL          '                    d<|0           Y d}0~0d}0~0ww xY w|#Jddd           n# 1 swxY w Y   |(                    d= >           |rtS          |d?          r|j*        r|D ]}&	 |&d+         t          |          k     r||&d+                  d         nd}1|j*        +                    |1|&                    d@d          pd|&d+         t          |          k     r#t          ||&d+                  dA         dBd          ndC           # t>          $ r Y w xY wtY          t#          j                    |z
  dA          }2t          j        ||2dDd#E          S )Fa  
    Spawn one or more child agents to handle delegated tasks.

    Supports two modes:
      - Single: provide goal (+ optional context, toolsets)
      - Batch:  provide tasks array [{goal, context, toolsets}, ...]

    Returns JSON with results array, one entry per task.
    Nz.delegate_task requires a parent agent context.r   r   r  z Delegation depth limit reached (z,). Subagents cannot spawn further subagents.r   zToo many tasks: z* provided, but max_concurrent_children is z. Either reduce the task count, split into multiple delegate_task calls, or increase delegation.max_concurrent_children in config.yaml.)rH   rI   re   z7Provide either 'goal' (single task) or 'tasks' (batch).zNo tasks provided.rH   rK   zTask z is missing a 'goal'.c                 .    g | ]}|d          dd         S )rH   N(   r(   r   s     r   rj   z!delegate_task.<locals>.<listcomp>  s$    555a1V9SbS>555r   rI   re   r   r   r   r   r   r   r   )rl   rH   rI   re   r   r   r`   r   r   r   r   r   r   r/   ro   )max_workers)rl   rH   r   r`   _interrupt_requestedFTr(  r	  u9   Parent agent interrupted — child did not finish in time)r   FIRST_COMPLETEDg      ?)r&  return_whenrl   r"  r  ?r  u   ✓u   ✗z [r   rr   z  (zs)z  r   z tasksz
 remainingzSpinner update_text failed: %sc                     | d         S )Nrl   r(   )rs    r   <lambda>zdelegate_task.<locals>.<lambda>A  s
    1\? r   )key_memory_managerr   r+   r   )taskrE  child_session_id)resultstotal_duration_seconds)ensure_ascii)-
tool_errorrY   	MAX_DEPTHjsondumpsr1   r"   DEFAULT_MAX_ITERATIONS_resolve_delegation_credentialsr5   rO   r>   r4  r   r   rM   	enumerater)  r*  r   r+  r   r   rN   rT  r   submitr   keysdonerE  r]   concurrent.futuresr   r[  r   printupdate_textr6   r   sortr   rc  on_delegationr3  )3rH   rI   re   rU  r   r   r   r`   depthr;   default_max_itereffective_max_itercredsr   max_children	task_listird  overall_startrf  n_taskstask_labels_model_tools_parent_tool_nameschildrenr   r   _i_trE  completed_countspinner_refexecutorfuturesfuturependingfidxrR  _cf_waitr[  rr  labeldurr  icon	remainingcompletion_liner   
_task_goaltotal_durations3                                                      r   r
   r
   o  s	   & JKKK L"3Q77E	z<9 < < <
   	 ..Cww/1GHH';+;$/\BB $ $ $#c((########$ 011L UE4(( Uu::$$F3u:: F F.:F F F   			 U*T3'' UDJJLL U"wHMMN		STTT 0./// Y'' @ @4xx##))++ 	@>a>>>?????	@ N$$MG)nnG559555K
 '&&&lDEE
 HDi(( 	+ 	+DAq&1V9aeeI6F6Fz**6heGn1"'
"3uZGX!&y!1"'
"3%&UU=%9%9%H["#%%
"3"3"?x	 	 	E 0BE,OOQ5M****	+  2D..1C.CCCC!|| B"1bj%FFv l,?FFL999 Y	NXG' $ $1e!% 6!- )   #$ ',,..))G GN<)?GG4OO % - -%aj6688 
"()

#, " " "25.5/3-0XX1289)" )"" /2*7+/)d-.45% %E  u---'1,PPPPPPPP (#? [ [ [g" %N %NF &$ 	 	 	%fo*-&-'+%(XX)*01! !	 NN5)))#q(O  -C03c+6F6F0F0FK,,MTWMME))$6::C"YYx55F$*k$9$955uD '/ 9I)-&U&UQ&U&U&U&UE&U&Uc&U&U&UO" 6:'33ODDDD( : : :!"8"8"899999: 4?44555 # Ny1}}N'334uI4u4uS\`aSaSaCCgi4u4u4uvvvv( N N N"LL)I1MMMMMMMMNM  GN%Y	N Y	N Y	N Y	N Y	N Y	N Y	N Y	N Y	N Y	N Y	N Y	N Y	N Y	N Y	Nx 	22333  
.?@@ 
\Ea 
 		 		EGL\GZ]`aj]k]kGkGkYu\':;FCCqs
,::# 99Y339rdijvdwz}  G  {H  {H  eH  eHWXeL6I-J1-M|]_%`%`%`  NP ;    
     4>++m;Q??N:"0     s   ;B 
B<B71B<7B<CK 	K%BW<O/.W</
P9PW<PAW<!Q65W<6
R( R#W<#R((BW<?UW<U41W<3U44W<$V86W<8
W(W#W<#W((W<<X X <B[
[('[(r   c                 D   | st          |dd          S t          |dd          pd}t          |dd          }|| |k    r|S 	 ddlm}  ||           }||                                r|S n3# t          $ r&}t
                              d| |           Y d}~nd}~ww xY wdS )ah  Resolve a credential pool for the child agent.

    Rules:
    1. Same provider as the parent -> share the parent's pool so cooldown state
       and rotation stay synchronized.
    2. Different provider -> try to load that provider's own pool.
    3. No pool available -> return None and let the child keep the inherited
       fixed credential behavior.
    r   Nr   rK   r   )	load_poolz:Could not load credential pool for child provider '%s': %s)rY   agent.credential_poolr  has_credentialsr]   r6   r   )r   r`   parent_providerparent_poolr  poolr   s          r   r   r   X  s      ?|%7>>>lJ==CO,(:DAAK#5#H#H

333333y+,, 4 4 6 6K 
 
 
H	
 	
 	
 	
 	
 	
 	
 	

 4s   (A- -
B7BBr;   c                 p   t          |                     d          pd                                          pd}t          |                     d          pd                                          pd}t          |                     d          pd                                          pd}t          |                     d          pd                                          pd}|rk|p&t          j        dd                                          }|st          d          |                                }d	}d
}	d|v rd}d}	nd|v rd}d}	|||||	dS |s|dddddS 	 ddlm}
  |
|          }n)# t          $ r}t          d| d| d          |d}~ww xY w|                    dd          }|st          d| d          ||                    d          |                    d          ||                    d          |                    d          t          |                    d          pg           dS )u  Resolve credentials for subagent delegation.

    If ``delegation.base_url`` is configured, subagents use that direct
    OpenAI-compatible endpoint. Otherwise, if ``delegation.provider`` is
    configured, the full credential bundle (base_url, api_key, api_mode,
    provider) is resolved via the runtime provider system — the same path used
    by CLI/gateway startup. This lets subagents run on a completely different
    provider:model pair.

    If neither base_url nor provider is configured, returns None values so the
    child inherits everything from the parent agent.

    Raises ValueError with a user-friendly message on credential failure.
    r   rK   Nr   r   r   OPENAI_API_KEYzeDelegation base_url is configured but no API key was found. Set delegation.api_key or OPENAI_API_KEY.customchat_completionszchatgpt.com/backend-api/codexzopenai-codexcodex_responseszapi.anthropic.com	anthropicanthropic_messages)r   r   r   r   r   r   )resolve_runtime_provider)	requestedz$Cannot resolve delegation provider 'z': z. Check that the provider is configured (API key set, valid provider name), or set delegation.base_url/delegation.api_key for a direct endpoint. Available providers: openrouter, nous, zai, kimi-coding, minimax.zDelegation provider 'z]' resolved but has no API key. Set the appropriate environment variable or run 'hermes auth'.r   commandr   )r   r   r   r   r   r  r   )rO   r"   rM   r9   r:   r5   r7  hermes_cli.runtime_providerr  r]   r   )r;   r`   configured_modelconfigured_providerconfigured_base_urlconfigured_api_keyr   
base_lowerr   r   r  runtimer   s                r   rn  rn  x  s    3777++1r2288::Bdcggj117R88>>@@HDcggj117R88>>@@HDSWWY//5266<<>>F$ 
 7y)2..4466 	  	<  
 )..00
%*j88%H(HH J.."H+H & + 
 
 	
  
 &
 
 	
	HHHHHH**5HIII   Q3F Q Q3 Q Q Q
 

 	 kk)R((G 
N$7 N N N
 
 	
 "KK
++KK
++KK
++;;y))W[[((.B//  s   E, ,
F6FFc                      	 ddl m}  |                     di           }|r|S n# t          $ r Y nw xY w	 ddlm}  |            }|                    di           S # t          $ r i cY S w xY w)aN  Load delegation config from CLI_CONFIG or persistent config.

    Checks the runtime config (cli.py CLI_CONFIG) first, then falls back
    to the persistent config (hermes_cli/config.py load_config()) so that
    ``delegation.model`` / ``delegation.provider`` are picked up regardless
    of the entry point (CLI, gateway, cron).
    r   )
CLI_CONFIGr   )load_config)clir  r"   r]   hermes_cli.configr  )r  r;   r  fulls       r   r1   r1     s    """"""nn\2.. 	J	   111111{}}xxb)))   			s   # 
00%A A)(A)r
   a  Spawn one or more subagents to work on tasks in isolated contexts. Each subagent gets its own conversation, terminal session, and toolset. Only the final summary is returned -- intermediate tool results never enter your context window.

TWO MODES (one of 'goal' or 'tasks' is required):
1. Single task: provide 'goal' (+ optional context, toolsets)
2. Batch (parallel): provide 'tasks' array with up to 3 items. All run concurrently and results are returned together.

WHEN TO USE delegate_task:
- Reasoning-heavy subtasks (debugging, code review, research synthesis)
- Tasks that would flood your context with intermediate data
- Parallel independent workstreams (research A and B simultaneously)

WHEN NOT TO USE (use these instead):
- Mechanical multi-step work with no reasoning needed -> use execute_code
- Single tool call -> just call the tool directly
- Tasks needing user interaction -> subagents cannot use clarify

IMPORTANT:
- Subagents have NO memory of your conversation. Pass all relevant info (file paths, error messages, constraints) via the 'context' field.
- Subagents CANNOT call: delegate_task, clarify, memory, send_message, execute_code.
- Each subagent gets its own terminal session (separate working directory and state).
- Results are always returned as an array, one entry per task.objectstringzWhat the subagent should accomplish. Be specific and self-contained -- the subagent knows nothing about your conversation history.)typedescriptionzBackground information the subagent needs: file paths, error messages, project structure, constraints. The more specific you are, the better the subagent performs.arrayr  zcToolsets to enable for this subagent. Default: inherits your enabled toolsets. Available toolsets: z. Common patterns: ['terminal', 'file'] for code work, ['web'] for research, ['browser'] for web interaction, ['terminal', 'file', 'web'] for full-stack tasks.)r  itemsr  z	Task goalzTask-specific contextz,Toolsets for this specific task. Available: zT. Use 'web' for network access, 'terminal' for shell, 'browser' for web interaction.zfPer-task ACP command override (e.g. 'claude'). Overrides the top-level acp_command for this task only.zPer-task ACP args override.)rH   rI   re   r   r   )r  
propertiesrequiredzBatch mode: tasks to run in parallel (limit configurable via delegation.max_concurrent_children, default 3). Each gets its own subagent with isolated context and terminal session. When provided, top-level goal/context/toolsets are ignored.integerzSMax tool-calling turns per subagent (default: 50). Only set lower for simple tasks.a   Override ACP command for child agents (e.g. 'claude', 'copilot'). When set, children use ACP subprocess transport instead of inheriting the parent's transport. Enables spawning Claude Code (claude --acp --stdio) or other ACP-capable agents from any parent, including Discord/Telegram/CLI.zArguments for the ACP command (default: ['--acp', '--stdio']). Only used when acp_command is set. Example: ['--acp', '--stdio', '--model', 'claude-opus-4-6'])rH   rI   re   rU  r   r   r   )r#   r  
parameters)registryri  r   c                 `   t          |                     d          |                     d          |                     d          |                     d          |                     d          |                     d          |                     d          |                    d          	          S )
NrH   rI   re   rU  r   r   r   r`   )rH   rI   re   rU  r   r   r   r`   )r
   r"   )r   kws     r   ra  ra  l  s    }XXf##*%%hhwxx 011HH]++*%%VVN++ -  -  - r   u   🔀)r#   toolsetschemahandlercheck_fnr   r   )r/   )NNNNNN)NN)NNNNNNNN)6__doc__rk  r=  	getLogger__name__r6   r9   r.  r)  rs  r   r   typingr   r   r   r   re   r	   	frozensetr   r   r   r  _SUBAGENT_TOOLSETSrP   _TOOLSET_LIST_STRr8   rj  r3   r>   rm  r   r   r6  rE   rO   rR   rd   rk   callabler   r   rT  r
   r   r5  rn  r1   DELEGATE_TASK_SCHEMAtools.registryr  ri  registerr(   r   r   <module>r     s   "  		8	$	$ 				      ? ? ? ? ? ? ? ? , , , , , , , , , , , ,       # $ $ $    $)$T$T$TUU V  )8>++      IICC0BCCCCC #$  	,c , , , ,0   ... T     "  %)	     
 c]  SM	 
 	       FXc]    2C49 Cc C C C CM Ms Mc MZbckZl M M M Mr (,'+&*'+*.-1_ __
_ c]_ tCy!	_
 C=_ _  }_  }_ sm_  }_ #3-_  S	*_ _ _ _H 	^I ^I^I
^I 
#s(^^I ^I ^I ^IB !$(,0$(!%$(f f
3-fc]f tCy!f Dc3h()	f
 SMf #f tCy!f 	f f f fRx}    @V V V V V Vrd    8 	I2  !,  !J    (+H+<H H H	   $)1+ N N,4E\#]#]$+&,h%7 ,BZk  ,B  ,B  ,B% % %- ,T( (
 %,&,h%7+H% %# #$ "() 4R9   D "7  !c    (+u	 ]V
 V
n sZ Z7v v t 0 / / / / / / /  	- - )
     r   