
    sjW             !          U d Z ddlZddlZddl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ZddlmZ ddlmZmZmZmZ ddlmZmZ ddlmZ ddlmZ dZdd	lmZ dd
lm Z! ddl"m#Z#m$Z$  e%g d          Z&de'de'de'fdZ(de'de'de'fdZ)d Z*dZ+da,dZ-dZ. e
j/                    Z0da1e2e3d<    e
j/                    Z4i Z5ee'ee'ef         f         e3d<   dZ6i Z7ee'ee'ef         f         e3d<   dee'         deee'ef                  fdZ8de2de2fdZ9de2fdZ:dee'ef         ddfd Z;dee'ef         ddfd!Z<dd"d#e'd$eddfd%Z=d#e'd$edee'         fd&Z>d#e'de2fd'Z?dddd(d#e'd)e'd*ee'         d+ed,ede2fd-Z@d*ee'         deAeef         fd.ZBdeee'ef                  fd/ZCdd1ed2ed3eDde2fd4ZE e%h d5          ZFd6ee'         d2ede'fd7ZGdee'ef         d2ede2fd8ZHd9e'd#ee'         d:ee'         d2ede'f
d;ZId<d=d>d?ee'ef         d@eDdAeDdeee'ef                  fdBZJdCede'fdDZK e%h dE          ZL e%h dF          ZMdGe'dHedefdIZNdJedee'ef         fdKZOdLedee'ef         fdMZPdNedeee'ef                  fdOZQdCede2fdPZRdQee'         de'fdRZSdeDfdSZTde2fdTZUdaVdeDfdUZWdeeX         fdVZYdeDfdWZZde2fdXZ[de2fdYZ\dZe'de2fd[Z]d\e^de^fd]Z_d^ee'         d\e^e'         dee'         fd_Z`d`ZadaZbdbZcdcZddZeeeX         e3dd<   deZfdfZgdgZhg dhZi G di dje'ejj                  Zkekjl        ekjl        ekjm        ekjn        ekjo        dkZpee'ekf         e3dl<   de2fdmZq	 dddndoddpdqe'dree'         dsee'         dte'dueDdveDde'fdwZrdee'         fdxZsdyee'         dee'         fdzZtdte'dee'         fd{Zud|e'ddfd}Zv	 dddddddd~deDdqe'deDd#ee'         dee'         deeD         dee'         dyeee'                  deee'ef                  deew         fdZxdHede'fdZydee'         dee'         fdZz	 	 	 	 	 	 	 	 	 ddeDdqe'dree'         dyeee'                  dee'         deDdeDdee'         dee'         dee'         dee'         deee'ef                  deeD         dee'         deee'                  dte'f dZ{dedeDdeXdeXdee
j|                 dqe'dee'         fdZ}deDdLe'dee'         fdZ~dLe'deDdeDdeAe'ee'         f         fdZdeDdeeD         fdZdeee'ef                  ddfdZ	 	 ddddd(deDdqe'd*ee'         d+ed,edee'ef         fdZ e
j/                    Z e
j                    Z e
j                    Zd Zde
j        fdZdeee'ef                  deee'ef                  deeAeDee'ef         ef                  ddfdZ	 	 ddeDdqe'dee'ef         fdZdedeAeeee'ef                           ee'         f         fdZ ej        dej                  Z ej        d          ZdZdeee'ef                  dee'         fdZ	 	 	 	 	 	 	 	 	 	 	 ddqee'         dree'         deeee'ef                           deeD         dtee'         dee2         deee'ef                  d9ee'         d#ee'         d:ee'         de'fdZ	 ddee'         dee'         fdZdedefdZdefdZde'fdZde'fdZde'fdZdefdZdddddddddddddddddddndgddĜddddƜdqgdǜddɜddndgddĜdddddddg d͢ddĜdddddddќ	g dǜdҜZddlmZmZ ddede2fdՄZddhZdedefd؄Z ej        ddedڄ eqdeܦ           dS )a  
Delegate Tool -- Subagent Architecture

Spawns child AIAgent instances with isolated context, inherited toolsets,
and their own terminal sessions. Supports single-task and batch (parallel)
modes. Top-level model calls run in the background; orchestrator children
wait for their own workers so they can synthesize the results.

Each child gets:
  - A fresh conversation (no parent history)
  - Its own task_id (own terminal session, file ops cache)
  - The parent's toolsets, with child-only blocked tools 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)TimeoutError)AnyDictListOptional)urlsplit
urlunsplit)TOOLSETS)request_hard_interruptcustom)
file_state)set_approval_callback)base_url_hostnameis_truthy_value)delegate_taskclarifymemorysend_messagecronjobcommanddescriptionreturnc                 >    t                               d| |           dS )zAuto-deny dangerous commands in subagent threads (safe default).

    Returns 'deny' so the subagent sees a refusal it can recover from, and
    never calls input() (which would deadlock the parent TUI).
    zeSubagent auto-denied dangerous command: %s (%s). Set delegation.subagent_auto_approve: true to allow.denyloggerwarningr   r   kwargss      7/home/agent/.hermes/hermes-agent/tools/delegate_tool.py_subagent_auto_denyr!   N   s+     NN	?  
 6    c                 >    t                               d| |           dS )zAuto-approve dangerous commands in subagent threads (opt-in YOLO).

    Only installed when delegation.subagent_auto_approve=true. Returns 'once'
    so the subagent proceeds without blocking the parent UI.
    z1Subagent auto-approved dangerous command: %s (%s)oncer   r   s      r    _subagent_auto_approver%   \   s)     NN;   6r"   c                      t                      } |                     dd          }t          |          rt          S t          S )a  Return the callback to install into subagent worker threads.

    Config key: delegation.subagent_auto_approve (bool, default False).
    Reads via the same _load_config() path as the rest of delegate_task so
    priority is config.yaml > (no env override for this knob) > default.
    subagent_auto_approveF)_load_configgetr   r%   r!   cfgvals     r    _get_subagent_approval_callbackr-   i   s=     ..C
'')5
1
1Cs &%%r"   
   F   _spawn_paused_active_subagents   _recent_subagentstask_idc                    | rt          | t                    sdS t          5  t                              |           }|8| |                    d          |                    d          dcddd           S t
                              |           }|8| |                    d          |                    d          dcddd           S 	 ddd           n# 1 swxY w Y   dS )a  Resolve a process task_id to its originating delegation, if any.

    Children run their terminal sessions under ``task_id == subagent_id``
    (see _run_single_child's child_task_id), so a background process spawned
    by a subagent carries that id in ``ProcessSession.task_id``. Returns
    ``{subagent_id, goal, delegation_id}`` for live AND recently-finished
    children, or None when the task_id is not a known subagent.
    Ngoaldelegation_id)subagent_idr6   r7   )
isinstancestr_active_subagents_lockr1   r)   r3   )r4   recordretaineds      r    get_subagent_attributionr>      sc     *Wc22 t	  "&&w//&

6**!'O!<!<         %((11& V,,!)o!>!>                         4s   AC6ACCCpausedc                 p    t           5  t          |           at          cddd           S # 1 swxY w Y   dS )zGlobally block/unblock new delegate_task spawns.

    Active children keep running; only NEW calls to delegate_task fail fast
    with a "spawning paused" error until unblocked.  Returns the new state.
    N)_spawn_pause_lockboolr0   )r?   s    r    set_spawn_pausedrC      s|     
  V                 s   +//c                  R    t           5  t          cd d d            S # 1 swxY w Y   d S N)rA   r0    r"   r    is_spawn_pausedrG      so    	                   s     r<   c                     |                      d          }|sd S |                     dd           t          5  | t          |<   d d d            d S # 1 swxY w Y   d S )Nr8   accepting_steerT)r)   
setdefaultr;   r1   r<   sids     r    _register_subagentrM      s    
**]
#
#C 
'...	 ( (!'#( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (s   AAAc                    |                      d          }|sdS |                      d          |                      d          |                      d          dt          |<   t          t                    t          k    rYt                              t          t          t                              d           t          t                    t          k    WdS dS )zCKeep a bounded attribution stub after a child finishes (lock held).r8   Nr6   r7   owner_agent_session_id)r6   r7   rO   )r)   r3   len_RECENT_SUBAGENTS_CAPpopnextiterrK   s     r    _retain_recent_subagentrU      s    
**]
#
#C 

6""O44"(**-E"F"F c
 
 
 #8
8
8d4(9#:#:;;TBBB 
 
 #8
8
8
8
8
8
8r"   agentr8   rW   c                   t           5  t                              |           }|C||                    d          |u r*t                              | d            t	          |           d d d            d S # 1 swxY w Y   d S )NrW   )r;   r1   r)   rR   rU   )r8   rW   r<   s      r    _unregister_subagentrY      s    	 , ,"&&{335=FJJw4G4G54P4P!!+t444#F+++	, , , , , , , , , , , , , , , , , ,s   A A55A9<A9c                    t           5  t                              |           }||                    d          |ur	 ddd           dS d|d<   t          |dd          }t	          |          s	 ddd           dS 	  |            }n?# t
          $ r2}t                              d| |           Y d}~ddd           dS d}~ww xY wt          |t                    r|
                                r|ndcddd           S # 1 swxY w Y   dS )a  Atomically close steer acceptance and drain its final durable artifact.

    ``steer_subagent`` holds the same registry lock through ``agent.steer``.
    Therefore either acceptance wins and this drain sees its exact text, or
    closure wins and the caller is rejected. Exact agent identity prevents a
    finishing child with a recycled public id from closing its replacement.
    NrW   FrI   _drain_pending_steerz#final steer drain for %s failed: %s)r;   r1   r)   getattrcallable	Exceptionr   debugr9   r:   strip)r8   rW   r<   drainpendingexcs         r    _close_subagent_steeringrd      s    
  Q Q"&&{33>VZZ00==Q Q Q Q Q Q Q Q %* !5t<< 	Q Q Q Q Q Q Q Q	eggGG 	 	 	LL>SQQQ444Q Q Q Q Q Q Q Q	 %Wc22Pw}}PwwDQ Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q QsA   5D
&D>
B	D	
CC /D C/DDDc                 J   t           5  t                              |           }ddd           n# 1 swxY w Y   |sdS |                    d          }|dS 	 t          |d|  d          sdS n4# t          $ r'}t
                              d| |           Y d}~dS d}~ww xY wdS )aC  Request that a single running subagent stop at its next iteration boundary.

    Does not hard-kill the worker thread (Python can't); sets the child's
    interrupt flag which propagates to in-flight tools and recurses into
    grandchildren via AIAgent.interrupt().  Returns True if a matching
    subagent was found.
    NFrW   zInterrupted via TUI ()z!interrupt_subagent(%s) failed: %sT)r;   r1   r)   r   r^   r   r_   )r8   r<   rW   rc   s       r    interrupt_subagentrg   
  s    
  4 4"&&{334 4 4 4 4 4 4 4 4 4 4 4 4 4 4 uJJwE}u%e-S[-S-S-STT 	5	   8+sKKKuuuuu 4s$   /33A/ /
B 9BB owner_session_idowner_transportowner_session_recordtextri   rj   rk   c                   |r|                                 sdS t          5  t                              |           }|r|                    dd          s	 ddd           dS |Y|                    d          |k    s2|0|                    d          |us||                    d          |ur	 ddd           dS |                    d          }|	 ddd           dS 	 t	          |                    |                    cddd           S # t          $ r2}t                              d| |           Y d}~ddd           dS d}~ww xY w# 1 swxY w Y   dS )	u  Queue steering text into a single running subagent without stopping it.

    The redirection-side mirror of interrupt_subagent(): resolves the live
    child in the registry and calls AIAgent.steer(), which appends the text
    to the child's last tool result at its next iteration boundary — the
    current tool call is never cut. Returns True if a matching subagent
    QUEUED the text while the child was still accepting work; False for an
    unknown/closed id, an ownership mismatch, a record with no live agent, or
    empty text. ``owner_session_id=None`` deliberately preserves the internal
    in-process helper contract; gateway callers must pass exact authority.

    Acceptance and completion are linearized by the registry lock. If
    acceptance wins but no delivery boundary remains, ``_run_single_child``
    drains the exact text into the completion entry as ``missed_steer``.
    FrI   Nri   rj   rk   rW   zsteer_subagent(%s) failed: %s)	r`   r;   r1   r)   rB   steerr^   r   r_   )r8   rl   ri   rj   rk   r<   rW   rc   s           r    steer_subagentro   "  s7   .  tzz|| u	  "&&{33 	VZZ(95AA 	        '

-..2BBB"*::/00GG'/::455=QQQ        

7##=        	D))**#       $  	 	 	LL8+sKKK555)       $	%         sB   4E!AE<E"!D
EE6EEEEEc                 P    | sdS 	 ddl m}  ||           S # t          $ r Y dS w xY w)zCapture exact request transport + live session generation, if any.

    This is intentionally an in-process bridge, not a serializable capability.
    Non-gateway hosts (including the CLI helper path) receive ``(None, None)``.
    NNr   ) _current_session_steer_authority)tui_gateway.serverrr   r^   )ri   rr   s     r     _capture_gateway_steer_authorityrt   R  s\      zGGGGGG//0@AAA   zzs    
%%c                      t           5  d t                                          D             cddd           S # 1 swxY w Y   dS )u   Snapshot of the currently running subagent tree.

    Each record: {subagent_id, parent_id, depth, goal, model, started_at,
    tool_count, status}.  Safe to call from any thread — returns a copy.
    c                 J    g | ] }d  |                                 D             !S )c                 "    i | ]\  }}|d v	||S )>   rW   rI   rj   ri   rk   rF   .0kvs      r    
<dictcomp>z4list_active_subagents.<locals>.<listcomp>.<dictcomp>l  s@       Aq  1  r"   )itemsry   rs     r    
<listcomp>z)list_active_subagents.<locals>.<listcomp>k  sI     
 
 
  GGII  
 
 
r"   N)r;   r1   valuesrF   r"   r    list_active_subagentsr   d  s     
  
 

 
 '--//
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   #8<<   child_agentparent_agentmax_hopsc                     | |dS | }t          |          D ]<}t          |dd          }t          |          r
 |            nd}| dS ||u r dS |}=dS )u+  True when *child_agent* sits below *parent_agent* in the spawn tree.

    Walks the ``_delegate_parent_ref`` weakref chain stamped at build time.
    Identity comparison only — a parent may steer/stop its own children and
    grandchildren, never a sibling tree owned by another conversation.
    NF_delegate_parent_refT)ranger\   r]   )r   r   r   cur_refancestors          r    _is_descendant_ofr   |  s     l2u
C8__  c1488$SMM333555t55|##445r"   >   liststoprn   
session_idc                     t          | pd          }|sdS t          |dd          }||S 	 |                    |          }|rt          |          n|S # t          $ r |cY S w xY w)a  Resolve a session id to the tip of its compression lineage.

    Best-effort: uses the parent's live SessionDB handle when present so a
    delegation dispatched before a compression rotation still matches the
    rotated parent. Returns the input unchanged when resolution fails.
     _session_dbN)r:   r\   resolve_resume_session_idr^   )r   r   rL   dbresolveds        r    _resolve_session_lineager     s     jB

C r	}d	3	3B	z
//44 (1s8}}}c1   


s   'A A#"A#c                 <   |                      d          }t          ||          rdS t          |                      d          pd          }|sdS t          t          |dd          pd          }|sdS ||k    rdS t	          ||          |t	          ||          hv S )u  True when *parent_agent*'s conversation owns this live-child record.

    Two-tier check:

    1. Object identity — the ``_delegate_parent_ref`` weakref chain stamped
       at build time reaches *parent_agent*. Fast path for the common case
       where the parent AIAgent object survives the whole run.
    2. Durable conversation lineage — the child was registered with the
       owning conversation's durable session id
       (``owner_agent_session_id``); match it against the calling parent's
       ``session_id``, resolving compression-rotation lineage on both sides.

    Tier 2 exists because the identity chain is BRITTLE across parent-agent
    rebuilds: the CLI sets ``self.agent = None`` mid-session (route-signature
    change, credential refresh, /model, MoA one-shots) and constructs a NEW
    AIAgent for the next turn while the child keeps running with a weakref to
    the old object. The delivery path always survived this (it routes by
    durable session id); the control path must use the same durable spine or
    running children go invisible/unsteerable (observed live: deleg_88454b70
    / sa-0-dc0100f4, 2026-08-17).
    rW   TrO   r   Fr   )r)   r   r:   r\   r   )r<   r   rW   	owner_sid
parent_sids        r    _owns_subagent_recordr     s    , JJwE-- tFJJ788>B??I uW\<<<BCCJ uJt#I|<< \::A  r"   actionmessagec                    | dk    rt           5  t          t                                                    }ddd           n# 1 swxY w Y   g }|D ]+}|                    d          }t          ||          s)|                    d          }|                    |                    d          |                    d          |                    d          |                    d          |                    d	          t          |t          t          f          r$t          t          j                    |z
  d
          ndt          |                    dd                    t          |dd          d           -dt          |          |d}	|sd|	d<   t          j        |	d          S |pd                                }
|
st%          d|  d          S t           5  t                              |
          }ddd           n# 1 swxY w Y   |t          ||          st%          d|
 d          S | dk    r=t'          |
          rt          j        d|
dddd          S t%          d|
 d          S | dk    re|pd                                }|st%          d          S t)          |
|          rt          j        d|
d d!dd          S t%          d"|
 d#          S t%          d$|  d%          S )&u  Synchronous control plane for delegate_task: list/steer/stop.

    Runs in-turn (never backgrounded) and only over subagents descended from
    *parent_agent* — the same registry the TUI overlay drives, but scoped so
    a conversation can only control its own spawn tree.
    r   NrW   
started_atr8   	parent_idr6   modelstatusr/   rI   F_live_transcript_path)r8   r   r6   r   r   running_secondsrI   live_transcript)r   count	subagentsu   No live subagents right now. Children that already finished have delivered (or will deliver) their results as normal completion messages — there is nothing to steer or stop.noteensure_asciir   zaction='zK' requires subagent_id (from the spawn dispatch response or action='list').zNo live subagent 'z' in this conversation's spawn tree. It may have already finished (its result arrives as a normal completion message). Use action='list' to see live children.r   interrupt_requestedu   The subagent stops at its next iteration boundary (in-flight tool calls are asked to cancel). Its partial result still re-enters the conversation as a completion message — do not wait or poll.)r   r8   r   r   zCould not interrupt 'u_   ' — it likely finished in the last moment. Its result arrives as a normal completion message.rn   zOaction='steer' requires a non-empty 'message' describing the course correction.queuedu   Steering text queued. The subagent sees it appended to its next tool result — the current tool call is never cut. If the child finishes before a delivery boundary remains, the text is reported back as missed_steer in its completion entry.z
Subagent 'z' is no longer accepting steering (finishing or already finished). Its result arrives as a normal completion message; re-delegate a follow-up task if more work is needed.Unknown action 'z#'. Use spawn, list, steer, or stop.)r;   r   r1   r   r)   r   appendr9   intfloatroundtimerB   r\   rP   jsondumpsr`   
tool_errorrg   ro   )r   r8   r   r   recordsentriesr   rW   startedpayloadrL   r<   rl   s                r    _handle_control_actionr     s3    # 	7 	7,335566G	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	 	AEE'NNE(L99 eeL))GNN#$55#7#7!"{!3!3EE&MMUU7^^eeHoo &gU|<<"dikkG3Q777!'+AEE2CU,K,K'L'L'.u6Mt'T'T    " \\ #
 #

  	M FO
 z'6666 "
#
#
%
%C 
*v * * *
 
 	
 
  , ,"&&s++, , , , , , , , , , , , , , ,~26<HH~K K K K
 
 	
 c"" 	:$#&3F
 
 #    IC I I I
 
 	

 2$$&& 	%   #t$$ 	:%#&&@  #    L L L L
 
 	
 TTTTUUUs#   'AA	A HHH   i@  max_entries	max_charsresultr   r   c                   t          | t                    r|                     d          nd}t          |t                    sg S g }i }|D ]}t          |t                    s|                    d          dk    ro|                    d          pg D ]W}|                    d          }|                    d          pi }	|r't	          |	                    d          pd	          ||<   Xt          |          D ]}t          |          |k    r nt          |t                    r|                    d          d	k    rFt          |                    d
          pd          }
t          |
          }|                    |                    d          pdd	          }|
d|         }|	                    |||d           |
                                 |S )u8  Pull the last N tool-call results from a child's conversation.

    Powers the overlay's "Output" section — the cc-swarm-parity feature.
    We reuse the same messages list the trajectory saver walks, taking
    only the tail to keep event payloads small.  Each entry is
    ``{tool, preview, is_error}``.
    messagesNrole	assistant
tool_callsidfunctionnametoolcontentr   tool_call_id)r   previewis_error)r9   dictr)   r   r:   reversedrP   _stringify_tool_content_looks_like_error_outputr   reverse)r   r   r   r   tailpending_call_by_idmsgtctc_idfnr   r   	tool_namer   s                 r    _extract_output_tailr   I  s    *4FD)A)AKvzz*%%%tHh%% 	 "$D)+  N N#t$$ 	776??k))ggl++1r N NtVVJ''-2 N03BFF6NN4Lf0M0M&u- !! S St99##E#t$$ 	6(A(A
 *#'')*<*<*BCC+G44&**377>+B+B+Hb&QQ	 *9*%Y7QQRRRRLLNNNKr"   r   c                 h   | dS t          | t                    r| S t          | t                    rg }| D ]}t          |t                    rp|                    d          }t          |t                    r|                    |           W|                    t          j        |dt                               |                    t          |                     d                    |          S t          | t                    rt          j        | dt                    S t          |           S )a+  Return a stable text representation for tool-result content.

    Most providers store tool results as strings, but some OpenAI-compatible
    paths can return content-block lists. Delegate observability must never
    crash while summarising a child run just because the transport used blocks.
    Nr   rl   F)r   default
)	r9   r:   r   r   r)   r   r   r   join)r   partsitemrl   s       r    r   r     s    r'3 '4     	( 	(D$%% (xx''dC(( TLL&&&&LLDuc!R!R!RSSSSSYY''''yy'4   Dz'sCCCCw<<r"   >   cwddstsrcurlpathurlsendpointnew_pathold_path	directory	file_pathsource_pathtarget_pathdestination_path>   r   r   r   keyvaluec                     t          |t                    r$d  fd|dd         D             D             }|pdS t          |t                    r|sdS |dd         } t          v rw	 t	          |          }|j        rN|j        rG|j        }|sdS d|v rd| dn|}|j        }|| d| n|}t          |j        ||j
        d	d	f          S n# t          $ r Y dS w xY w|S )
z<Keep bounded side-effect targets while dropping URL secrets.c                     g | ]}||S rE   rF   )ry   r   s     r    r   z)_sanitize_tool_target.<locals>.<listcomp>  s(     
 
 
 r"   c              3   8   K   | ]}t          |          V  d S rE   )_sanitize_tool_target)ry   r   r   s     r    	<genexpr>z(_sanitize_tool_target.<locals>.<genexpr>  s.      VV43C>>VVVVVVr"   N   i   :[]r   )r9   r   r:   _TOOL_INPUT_URL_KEYSr   schemenetlochostnameportr	   r   
ValueError)	r   r   cleanedboundedparsedr   hostr   r   s	   `        r    r   r     sT   % 
 
VVVV5QTRTQT:VVV
 
 
 $eS!!  tETElG
"""	g&&F} P P!?  4
 +.//8x{-1-=D))4)))4!6=&&+r2"NOOO 	 	 	44	Ns   (&C ;C 
CC	argumentsc                    t          | t                    sg i dS 	 t          j        |           }n# t          t
          f$ r g i dcY S w xY wt          |t                    sg i dS t          d |D                       dd         }i }|                                D ]G\  }}t          |          	                                }|t          vr0t          ||          }||||<   H||dS )zFSummarize argument names and side-effect targets without raw payloads.argument_keystargetsc              3   D   K   | ]}t          |          d d         V  d S N   r:   ry   r   s     r    r   z,_summarize_tool_arguments.<locals>.<genexpr>  s0      33S#c((4C4.333333r"   N@   )r9   r:   r   loads	TypeErrorr   r   sortedr}   lower_TOOL_INPUT_TARGET_KEYSr   )r  r  keysr  raw_keyr   r   r   s           r    _summarize_tool_argumentsr    s$   i%% 4!#3334I&&z" 4 4 4!#333334fd## 4!#33333F33333CRC8D G ,,.. # #'ll  ""---'U33"GCL!g666s   1 A
	A
summaryc                    t          | t                    sg i dS |                     d          }t          |t                    rd |d d         D             ng }|                     d          }i }t          |t                    r\|                                D ]G\  }}t          |                                          }|t          vr0t          ||          }||||<   H||dS )Nr  r  c                 <    g | ]}t          |          d d         S r
  r  r  s     r    r   z0_sanitize_tool_input_summary.<locals>.<listcomp>  s&    ---CS$3$---r"   r  r  )	r9   r   r)   r   r}   r:   r  r  r   )	r  r  	safe_keysr  safe_targetsr  r   r   r   s	            r    _sanitize_tool_input_summaryr    s   gt$$ 4!#333;;''D dD!!	--49---- 
 kk)$$G#%L'4   ,%mmoo 	, 	,NGUg,,$$&&C111+C77G"$+S!&<@@@r"   
tool_tracec           	         t          | t                    sg S g }| D ]t          t                    st                              d          pd          dd         }t                              d          pd                                          }|dvrd}dt          dt          ffd	}|                    |t                              d
                     |d           |d          |d           |S )zABuild a detached, metadata-only tool history for lifecycle hooks.r   unknownN   r   >   okerrorr   r   c                                          | d          }t          |t          t          f          rt          |t                    rdS t          dt          |                    S )Nr   )r)   r9   r   r   rB   max)r   r   r   s     r    _byte_countz5_subagent_stop_tool_call_history.<locals>._byte_count	  sX    HHS!$$Eec5\22 j6M6M qq#e**%%%r"   input_summary
args_bytesresult_bytes)r   
tool_inputinput_bytesoutput_bytesr   )	r9   r   r   r:   r)   r  r   r   r  )r  historyr   r   r%  r   s        @r     _subagent_stop_tool_call_historyr-    s5   j$'' 	$&G  $%% 	((5I66tt<	TXXh''4955;;==((F	&S 	&S 	& 	& 	& 	& 	& 	& 	"6txx7P7PQQ&;|44'K77
 
 	 	 	 	 Nr"   c                 4   t          |           } | sdS |                                 }|                    d          s|                    d          r	 t          j        |           }t          |t                    re|                    d          rdS t          |                    d          pd          	                                
                                }|dv rdS n# t          $ r Y nw xY w|                                 r>|                                 d	         	                                
                                nd}|                    d
          p>|                    d          p)|                    d          p|                    d          S )a  Conservative stderr/error detector for tool-result previews.

    The old heuristic flagged any preview containing the substring "error",
    which painted perfectly normal terminal/json output red.  We now only
    mark output as an error when there is stronger evidence:
      - structured JSON with an ``error`` key
      - structured JSON with ``status`` of error/failed
      - first line starts with a classic error marker
    F{r   r"  Tr   r   >   r"  failedfailuretimeoutr   zerror:zfailed:z
traceback z
exception:)r   lstrip
startswithr   r  r9   r   r)   r:   r`   r  r^   
splitlines)r   headr  r   firsts        r    r   r     s    &g..G u>>Ds 
ts33 
		Z((F&$''  ::g&&  4VZZ117R88>>@@FFHHFFF4 	 	 	D	 8?7I7I7K7KSG  #))++11333QSE"" 	*I&&	*L))	* L))	s   >C" AC" "
C/.C/r   c                     | | sdS t          |                                                                           }|dv r|S t                              d|            dS )a/  Normalise a caller-provided role to 'leaf' or 'orchestrator'.

    None/empty -> 'leaf'.  Unknown strings coerce to 'leaf' with a
    warning log (matches the silent-degrade pattern of
    _get_orchestrator_enabled).  _build_child_agent adds a second
    degrade layer for depth/kill-switch bounds.
    Nleaf>   r9  orchestratorz1Unknown delegate_task role=%r, coercing to 'leaf')r:   r`   r  r   r   )r   r_norms     r    _normalize_roler<  =  s\     	yyvVV\\^^!!##F)))
NNFJJJ6r"   c                     t                      } |                     d          }|	 t          dt          |                    }|dk    r$t          sdat
                              d|           |S # t          t          f$ r+ t
                              d|t                     t          cY S w xY wt          j        d          }|r<	 t          dt          |                    S # t          t          f$ r
 t          cY S w xY wt          S )	az  Read delegation.max_concurrent_children from config, falling back to
    DELEGATION_MAX_CONCURRENT_CHILDREN env var, then the default (10).

    Users can raise this as high as they want; only the floor (1) is enforced.

    Uses the same ``_load_config()`` path that the rest of ``delegate_task``
    uses, keeping config priority consistent (config.yaml > env > default).
    max_concurrent_childrenNr/   r.   Tzxdelegation.max_concurrent_children=%d: each child consumes API tokens independently. High values multiply cost linearly.zNdelegation.max_concurrent_children=%r is not a valid integer; using default %d"DELEGATION_MAX_CONCURRENT_CHILDREN)r(   r)   r$  r   _HIGH_CONCURRENCY_WARNEDr   r   r  r    _DEFAULT_MAX_CONCURRENT_CHILDRENosgetenv)r+   r,   r   env_vals       r    _get_max_concurrent_childrenrE  N  s1    ..C
''+
,
,C
	4CHH%%F{{/ /3,NNM  
 M:& 	4 	4 	4NN#0	   4333	4 i<==G 4	4q#g,,''':& 	4 	4 	43333	4++s$   AA0 09B,+B,C# #C>=C>c                  d    t                      } t          |                     dd                    S )u  Read delegation.worktree_isolation from config (bool, default False).

    Inspired by Muse Code's ``--subagent-worktree-isolation`` (Meta, Aug
    2026): when enabled, each delegated child gets its own git worktree
    checked out from the parent's current commit so parallel children never
    contend for the same working copy. Opt-in and git-only — in a non-git
    workspace or on a non-local terminal backend the flag is ignored without
    an error and children share the parent's workspace as before.
    worktree_isolationF)r(   rB   r)   r+   s    r    _get_worktree_isolationrI  w  s*     ..C,e44555r"   c                      t                      } |                     d          #t          sdat                              d           t                      S )u  Concurrency cap for background (``background=true``) delegations.

    DEPRECATED KNOB: ``delegation.max_async_children`` has been unified into
    ``delegation.max_concurrent_children`` — one cap governs both a single
    synchronous batch's parallelism and how many background delegation units
    may run at once. When at capacity, a new async dispatch is REJECTED (not
    queued) so a runaway model can't pile up unbounded background work; the
    caller falls back to running the work synchronously.

    A leftover ``max_async_children`` in config.yaml is ignored (the config
    migration removes it, folding a raised value into
    ``max_concurrent_children``); we log a one-time deprecation warning if
    one is still present.
    max_async_childrenNTzdelegation.max_async_children is deprecated and ignored; delegation.max_concurrent_children now caps background delegations too. Remove the stale key from config.yaml.)r(   r)   _LEGACY_MAX_ASYNC_WARNEDr   r   rE  rH  s    r    _get_max_async_childrenrM    sV      ..C
ww#$$09Q0#' F	
 	
 	

 ()))r"   c                     t                      } |                     d          }|Z	 t          |          }|dk    rdnt          d|          S # t          t
          f$ r t                              d|           Y nw xY wt          j	        d          }|r?	 t          |          }|dk    rdnt          d|          S # t          t
          f$ r Y nw xY wt          S )u  Read delegation.child_timeout_seconds from config.

    Returns the number of seconds a single child agent is allowed to run
    before being cut off, or ``None`` when no wall-clock cap applies.

    Default: ``None`` (no timeout). Subagents doing legitimate heavy work
    (deep code review, large research fan-outs, slow reasoning models) were
    routinely killed mid-task by the old blanket cap even though they were
    making steady progress. Failures should come from what the child is
    actually doing — API errors, tool errors, iteration budget — not from a
    generic delegation-level stopwatch. Stuck-child protection is handled
    separately by the heartbeat staleness monitor, which stops refreshing
    parent activity so the gateway inactivity timeout can fire.

    Set ``delegation.child_timeout_seconds`` to a positive number to opt back
    in to a hard cap (floor 30 s); ``0`` or a negative value means disabled.
    child_timeout_secondsNr   g      >@zUdelegation.child_timeout_seconds=%r is not a valid number; using default (no timeout) DELEGATION_CHILD_TIMEOUT_SECONDS)r(   r)   r   r$  r  r   r   r   rB  rC  DEFAULT_CHILD_TIMEOUT)r+   r,   r  rD  s       r    _get_child_timeoutrR    s   $ ..C
'')
*
*C
		>3ZZF "Q;;44Cf,=,== :& 	 	 	NN-    	 i:;;G >	>7^^F "Q;;44Cf,=,== :& 	 	 	D	 ! s#   A ,A=<A=B> >CCc                  x   t                      } |                     d          }|t          S 	 t          |          }n?# t          t
          f$ r+ t                              d|t                     t          cY S w xY wt          t          |          }||k    r"t                              d|t          |           |S )u  Read delegation.max_spawn_depth from config, floored at 1 (no ceiling).

    depth 0 = parent agent.  max_spawn_depth = N means agents at depths
    0..N-1 can spawn; depth N is the leaf floor.  Default 1 is flat:
    parent spawns children (depth 1), depth-1 children cannot spawn
    (blocked by this guard AND, for leaf children, by the delegation
    toolset strip in _strip_blocked_tools).

    Raise to 2+ to unlock nested orchestration. role="orchestrator"
    removes the toolset strip for spawning children when
    max_spawn_depth >= 2, enabling them to spawn their own workers.
    Like max_concurrent_children, there is no upper ceiling — but each
    extra level multiplies API cost, so raise it deliberately.
    max_spawn_depthNzFdelegation.max_spawn_depth=%r is not a valid integer; using default %dz6delegation.max_spawn_depth=%d below floor %d; using %d)
r(   r)   	MAX_DEPTHr   r  r   r   r   r$  _MIN_SPAWN_DEPTH)r+   r,   ivalflooreds       r    _get_max_spawn_depthrY    s     ..C
''#
$
$C
{3xxz"   W	
 	
 	

  "D))G$D		
 	
 	
 Ns   > 9A:9A:c                      t                      } |                     dd          }t          |t                    r|S t          |t                    r(|                                                                dv S dS )a   Global kill switch for the orchestrator role.

    When False, role="orchestrator" is silently forced to "leaf" in
    _build_child_agent and the delegation toolset is stripped as before.
    Lets an operator disable the feature without a code revert.
    orchestrator_enabledT>   1onyestrue)r(   r)   r9   rB   r:   r`   r  r*   s     r    _get_orchestrator_enabledr`    sp     ..C
''($
/
/C#t 
#s Ayy{{  ""&@@@4r"   c                  f    t                      } t          |                     d          d          S )zFWhether narrowed child toolsets should keep the parent's MCP toolsets.inherit_mcp_toolsetsTr   )r(   r   r)   rH  s    r    _get_inherit_mcp_toolsetsrd    s+    
..C377#9::DIIIIr"   r   c                 "   | sdS t          |                               d          rdS 	 ddlm}  |j        t          |                     }n# t
          $ r d}Y nw xY wt          |o!t          |                              d                    S )zDReturn True for canonical MCP toolsets and their registered aliases.Fzmcp-Tr   )registryN)r:   r4  tools.registryrf  get_toolset_alias_targetr^   rB   )r   rf  targets      r    _is_mcp_toolset_namerj    s     u
4yyF## t++++++223t99==   93v;;11&99:::s   #A AAparent_toolsetsc                    t                      }| D ]A}t          j        |          }|r)|                    |                    dg                      B|st          |           S t          |           }t          j                    D ]Y\  }}||v r
|                    dg           }|r7t          |                              |          r|                    |           Z|S )a@  Expand composite toolsets so individual toolset names are recognized.

    When a parent uses a composite toolset like ``hermes-cli`` (which bundles
    all core tools), the child may request individual toolsets such as ``web``
    or ``terminal``.  A simple name-based intersection would reject them
    because ``"web" != "hermes-cli"``.

    This helper collects the tool names from each parent toolset, then adds
    the names of any individual toolsets whose tools are a *subset* of the
    parent's available tools.  The original parent toolset names are preserved.
    tools)setr
   r)   updater}   issubsetadd)rk  parent_tool_namests_namets_defexpandedts_toolss         r    _expand_parent_toolsetsrw    s     !UU" > >g&& 	>$$VZZ%<%<=== $?###?##H#>++ " "h::gr** 	"H../@AA 	"LL!!!Or"   child_toolsetsc                     t          |           }t          |          D ]*}t          |          r||vr|                    |           +|S )zFAppend any parent MCP toolsets that are missing from a narrowed child.)r   r  rj  r   )rx  rk  	preservedtoolset_names       r    _preserve_parent_mcp_toolsetsr|  9  s]     ^$$I// + +-- 	+,i2O2O\***r"      i]        ?i  rQ        (   )terminalfilewebc                   .    e Zd ZdZdZdZdZdZdZdZ	dZ
d	S )
DelegateEventu  Formal event types emitted during delegation progress.

    _build_child_progress_callback normalises incoming legacy strings
    (``tool.started``, ``_thinking``, …) to these enum values via
    ``_LEGACY_EVENT_MAP``.  External consumers (gateway SSE, ACP adapter,
    CLI) still receive the legacy strings during the deprecation window.

    TASK_SPAWNED / TASK_COMPLETED / TASK_FAILED are reserved for
    future orchestrator lifecycle events and are not currently emitted.
    zdelegate.task_spawnedzdelegate.task_progresszdelegate.task_completedzdelegate.task_failedzdelegate.task_thinkingzdelegate.tool_startedzdelegate.tool_completedN)__name__
__module____qualname____doc__TASK_SPAWNEDTASK_PROGRESSTASK_COMPLETEDTASK_FAILEDTASK_THINKINGTASK_TOOL_STARTEDTASK_TOOL_COMPLETEDrF   r"   r    r  r  p  sA        	 	 +L,M.N(K,M/3r"   r  )	_thinkingzreasoning.availableztool.startedztool.completedsubagent_progress_LEGACY_EVENT_MAPc                      dS )z<Delegation has no external requirements -- always available.TrF   rF   r"   r    check_delegate_requirementsr    s    4r"   r9     workspace_pathr   rT  child_depthr6   contextr  r   rT  r  c                   ddd|  g}|r,|                                 r|                    d|            |r:t          |                                           r|                    d| d           |                    d           |dk    r+|d	z   |k    rd
nd}|                    d| d| d|            d                    |          S )a  Build a focused system prompt for a child agent.

    When role='orchestrator', appends a delegation-capability block
    modeled on OpenClaw's buildSubagentSystemPrompt (canSpawn branch at
    inspiration/openclaw/src/agents/subagent-system-prompt.ts:63-95).
    The depth note is literal truth (grounded in the passed config) so
    the LLM doesn't confabulate nesting capabilities that don't exist.
    z@You are a focused subagent working on a specific delegated task.r   zYOUR TASK:
z

CONTEXT:
z
WORKSPACE PATH:
zg
Use this exact path for local repository/workdir operations unless the task explicitly says otherwise.a  
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.

Keep your final summary tight: lead with outcomes, prefer bullet points over paragraphs, and don't replay your whole process. Your response is returned to the parent agent as a summary, and overlong summaries crowd out the parent's context window.r:  r/   u   Your own children MUST be leaves (cannot delegate further) because they would be at the depth floor — you cannot pass role='orchestrator' to your own delegate_task calls.zYour own children can themselves be orchestrators or leaves, depending on the `role` you pass to delegate_task. Default is 'leaf'; pass role='orchestrator' explicitly when a child needs to further decompose its work.u  
## Subagent Spawning (Orchestrator Role)
You have access to the `delegate_task` tool and CAN spawn your own subagents to parallelize independent work.

WHEN to delegate:
- The goal decomposes into 2+ independent subtasks that can run in parallel (e.g. research A and B simultaneously).
- A subtask is reasoning-heavy and would flood your context with intermediate data.

WHEN NOT to delegate:
- Single-step mechanical work — do it directly.
- Trivial tasks you can execute in one or two tool calls.
- Re-delegating your entire assigned goal to one worker (that's just pass-through with no value added).

Coordinate your workers' results and synthesize them before reporting back to your parent. You are responsible for the final summary, not your workers.

NOTE: You are at depth z3. The delegation tree is capped at max_spawn_depth=z. r   )r`   r   r:   r   )r6   r  r  r   rT  r  r   
child_notes           r    _build_child_system_promptr    s]   $ 	K
tE
  /7==?? /-G--... 
#n--3355 
uu u u	
 	
 	

 
LL	;   ~
 Q/11C C3 	 	L  '2!L L" -<#L L" @J#L L	
 	
 	
( 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_cwdr   )
rB  rC  r\   r   abspath
expanduserr:   r^   isabsisdir)r   
candidates	candidaterl   s       r    _resolve_workspace_hintr    s     		.!!L"7>>t	
 	
 	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                     t          dh          fdt          j                    D                                 d           fd| D             S )a^  Remove toolsets that contain only blocked tools.

    The strip set is derived from DELEGATE_BLOCKED_TOOLS plus the explicit
    composite/scenario toolsets (delegation, code_execution) that have no
    one-to-one tool. This keeps the blocklist and the strip set in lockstep
    so new blocked tools can't silently leak through as toolset names.
    
delegationc           	      |    h | ]8\  }}|v s-t          d  |                    dg           D                       6|9S )c              3   (   K   | ]}|t           v V  d S rE   )DELEGATE_BLOCKED_TOOLSry   ts     r    r   z1_strip_blocked_tools.<locals>.<setcomp>.<genexpr>  s(      JJqq**JJJJJJr"   rm  )allr)   )ry   r   defn_COMPOSITE_BLOCKED_TOOLSETSs      r    	<setcomp>z'_strip_blocked_tools.<locals>.<setcomp>	  s`       D$...JJDHHWb4I4IJJJJJ / 	...r"   kanbanc                     g | ]}|v|	S rF   rF   )ry   r  blocked_toolset_namess     r    r   z(_strip_blocked_tools.<locals>.<listcomp>  s$    BBB!1,A#A#AA#A#A#Ar"   )	frozensetr
   r}   rq  )r  r  r  s    @@r    _strip_blocked_toolsr    sw     #,\N";";   ".**   h'''BBBBxBBBBr"   c                     t          t                    | dk    r                    d           t          fdt	          j                    D                       S )a  Return one-tool deny toolsets for a delegated child role.

    ``_strip_blocked_tools`` can remove fully blocked toolsets, but it must keep
    mixed platform bundles such as ``hermes-cli`` because those also contain
    useful tools. Passing these exact deny toolsets to AIAgent lets
    ``model_tools`` subtract blocked names *after* composite expansion, and the
    restriction survives later registry/MCP refreshes through the agent's
    stored ``disabled_toolsets``.
    r:  r   c              3      K   | ]T\  }}|                     d           t          |                     d d                                                  P|V  UdS )rm  rF   N)r)   rn  rp  )ry   r   r  blocked_namess      r    r   z-_blocked_toolsets_for_role.<locals>.<genexpr>   s{        D$88G "%%&&//>>	     r"   )rn  r  discardr  r
   r}   )r   r  s    @r    _blocked_toolsets_for_roler    sr     .//M~o...    ".**     r"   linec                     t          | dd          }t          |          r	  ||           dS # t          $ r Y nw xY wt          |           dS )aW  Emit a human-readable progress line to the parent's console.

    Routes through ``parent_agent._safe_print`` when available so headless
    stdio hosts (ACP, gateway API) can redirect non-protocol output to
    stderr via their configured ``_print_fn``. A bare ``print()`` would
    otherwise land on stdout and corrupt JSON-RPC framing.
    _safe_printN)r\   r]   r^   print)r   r  printers      r    _emit_parent_consoler  (  sk     lM488G 	GDMMMF 	 	 	D		$KKKKKs   / 
<<r8   r   depthr   r  session_ref
task_index
task_countr   r  r   r  c                   	 t          |dd          t          |dd          ssdS dk    r	d dz    dnd|pd                                dg d	gd
t          t          t          f         f	 f
d	 ddt          dt          dt          ffd	 ddt          dt          ff	d}
fd}||
_        |
S )u  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

    The identity kwargs (``subagent_id``, ``parent_id``, ``depth``, ``model``,
    ``toolsets``) are threaded into every relayed event so the TUI can
    reconstruct the live spawn tree and route per-branch controls (kill,
    pause) back by ``subagent_id``.  All are optional for backward compat —
    older callers that ignore them still produce a flat list on the TUI.

    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/   r   ] r      r   r   c                     
 	d} | d<   | d<   | d<   | d<   
t          
          | d<   r-                    d          rt          d                   | d<   d	         | d
<   | S )N)r  r  r6   r8   r   r  r   r  r   child_session_idr   
tool_count)r   r)   r:   )kw_tool_countr  
goal_labelr   r   r  r8   r  r  r  s    r    _identity_kwargsz8_build_child_progress_callback.<locals>._identity_kwargse  s    $$
 

 " +B} 'B{OBwKBwK!(^^BzN  	D;??<88 	D%(\)B%C%CB!"&q><	r"   
event_typer   r   c                     sd S              }|                     |           	  | |||fi | d S # t          $ r&}t                              d|           Y d }~d S d }~ww xY w)NzParent callback failed: %s)ro  r^   r   r_   )	r  r   r   argsr   r   er  	parent_cbs	          r    _relayz._build_child_progress_callback.<locals>._relay}  s      	F""$$v	:Ij)WdFFgFFFFF 	: 	: 	:LL5q999999999	:s   4 
A$AA$c                   	 | dk    rrsrqt                    dk    rd d         dz   n}	                     d d|            n2# t          $ r%}t                              d|           Y d }~nd }~ww xY w dd|ppdi| d S | d	k    r dd|i| d S | d
k    r d
|           d S t          | t                    r| }nEt                              |           }|)	 t          |           }n# t          t          f$ r Y d S w xY w|t          j        k    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|           d S |t          j        k    rd S |t          j        k    r|p|pd}	rQ|	rO	                     d d|	            n2# t          $ r%}t                              d|           Y d }~nd }~ww xY wrD	  d |	            n2# t          $ r%}t                              d|           Y d }~nd }~ww xY wd S dxx         dz  cc<   Mt          5  t                                        }
|
d         |
d<   |pd|
d<   d d d            n# 1 swxY w Y   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ru d|||                               |pd           t                    k    r?d                              } dd |                                             d S d S d S )Nsubagent.start7   z... u   ├─ 🔀 zSpinner print_above failed: %sr   r   subagent.completesubagent.textr   u   ├─ 💭 ""zsubagent.thinkingr  z Parent callback relay failed: %sr   r/   r  	last_tool#   )get_tool_emojiu   ├─ z  "zsubagent.tool, subagent.progress   🔀 )r  r  )rP   print_abover^   r   r_   r9   r  r  r)   r   r  r  r  r  r;   r1   agent.displayr  r   r   clear)r  r   r   r  r   shortr  eventrl   summary_textrecr  emojir  r  _BATCH_SIZE_batchr  r  r  r  prefixspinnerr8   s                  r    	_callbackz1_build_child_progress_callback.<locals>._callback  s   
 ))) F: F14Z21E1EZ_u,,: F''(GF(G(G(G(GHHHH  F F FLL!A1EEEEEEEEFFSSW-H
-HbSFSSSF,,,FBBB6BBBF(( F?G4444F j-00 	EE%))*55E})*55EE"I.   FF M///-i-2D F/24yy2~~crcU**4F''(IF(I(I(I(I(IJJJJ  F F FLL!A1EEEEEEEEFF&5555FM555FM/// %552L F< FF''(NF(N(N(N(NOOOO  F F FLL!A1EEEEEEEEF HHI1f3Ll3L3LMMMM  H H HLL!CQGGGGGGGGHF 	A!"' 7 7'++K88?(3AC%'0BC$	7 7 7 7 7 7 7 7 7 7 7 7 7 7 7
  	B %"7||b00 "%%m 
 544444"N9?33E9v99e99i99D 'e&B##D)))) B B B=qAAAAAAAAB  	F?Iw===MM)/r***6{{k))))F++*4MF4MG4M4MNNNN	 	 *)s   A 
A:A55A:)C9 9DDE) )
F3FFG3 3
H"=HH"(H9 9
I(I##I(/KKKL4 4
M#>MM#c                      r?r?d                               }  dd |                                              dS dS dS )z<Flush remaining batched tool names to gateway on completion.r  r  r  r  N)r   r  )r  r  r  r  r  s    r    _flushz._build_child_progress_callback.<locals>._flush  sl     	 	ii''GF&0I0I0I0IJJJJLLNNNNN	 	 	 	r"   )NNN)r\   r`   r   r:   r   r  )r  r6   r   r  r8   r   r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  s   `  ```````  @@@@@@@@@r    _build_child_progress_callbackr  :  s   8 l$7>>G&>EEI 9 t (2A~~#a####2F*"##%%J KF#Kd38n               2 KO
: 
:
:$'
:9<
: 
: 
: 
: 
: 
: 
: FJn n"n47n n n n n n n n n n n n n n`        Ir"   c                 n    t          | pd                                                              d          S )Nr   /)r:   r`   rstrip)r   s    r    _normalized_runtime_urlr     s.    u{!!##**3///r"   fallback_base_urlc                    t          |          }t          | dd          }t          |t                    rAt          |                    d                    }|r||k    r|                    d          r|S t          | dd          }|=t          t          |dd                    }|r||k    r|                    d          r|S |pdS )al  Return the base URL the parent is actually calling, not a stale attribute.

    ``parent_agent.base_url`` can still carry a leftover OpenRouter URL from an
    old config while the live OpenAI client in ``_client_kwargs`` already points
    at local Ollama. Subagents must inherit the active endpoint or they 401
    against OpenRouter with a dummy/local key.
    _client_kwargsNbase_url)zhttp://zhttps://clientr   )r   r\   r9   r   r)   r4  )r   r  surface_urlclient_kwargs
kwargs_urlr  live_urls          r    _inherit_parent_base_urlr
    s     **;<<KL*:DAAM-&& ,]->->z-J-JKK
	k))%%&=>> * \8T22F +76:r+J+JKK	K''##$;<< ( O$$r"   max_iterationsoverride_provideroverride_base_urloverride_api_keyoverride_api_modeoverride_request_overridesoverride_max_tokensoverride_acp_commandoverride_acp_argsc                 :  MNOP ddl m} ddl}t          |dd          dz   }t	                      }t                      o||k     }|dk    r|r|nd}d|  d	|                                j        dd
          }t          |dd          }t          d|dz
            }t                      }t          |dd          }|t          |          }n?|r)t          |d          rddlOOPfd|j        D             }nt          t                    }|rKt          |          NNfd|D             }t!                      rt#          ||          }t%          |          }nG|r|t%          |          }n3|rt%          t'          |                    }nt%          t                    }t          |dd          }t)          |t*          t,          t          f          rd |D             }ng }|dk    rd |D             }t+          t.                              |t3          |          z   dgz                       } |dk    rd|vr|                    d           t7          |          }!t9          |||!|||          }"t          |dd          }#|#s*t          |d          r|j                            d          }#|pt          |dd          }$i }%t?          | |||||||$||%
  
        Md}&Mrdt@          ddfMfd}'|'}&|p|j!        }(|pt          |dd          })|	p|j"        }*|	stG          ||*          }*|
p|#}+t          |dd          pd},|)pd$                                %                                }-||}.n0|-dv rdd l&m'}/  |/|(          }.n|)|,k    rd}.nt          |d!d          }.|r,ddl(}0|0)                    |          stU          d"| d#          |pt          |d$d          }1t+          ||nt          |d%g           pg           }2|r|sd}1g }2|rd&})d'}.t          |d(d          }3|3}4	 |                    d)          }5|5s|5d*u r1dd+l+m,}6  |6|5          }7|7|7}4ntZ          .                    d,|5           n2# t^          $ r%}8tZ          0                    d-|8           Y d}8~8nd}8~8ww xY w|rdnt          |d.d          pd}9t          |d/d          }:t          |d0d          };t          |d1d          }<t          |d2d          }=t          |d3d*          }>t          |d4d          pd}?t          |d5d          }@|rd}:d};d}<d}=d*}>d}?||nt          |d6d          }Ai }Bt)          |Atb                    r|A|Bd6<   d}Ct          |d7d          }D|D_	 dd8l2m3}E t          |Dd9d          }F|F |E|F:          n	 |E            }Cn.# t^          $ r! tZ          0                    d;d<=           d}CY nw xY wdd>l4m5}G  |G            5  	  |dai d?|*d|+d|(d|)d!|.d$|1d%|2d@|d(|4dAt          |dAd          dB|9d|d| dCd<dD|"dEdF|  dGdHdIdJd<dKd<dLddM|&dN|CdOt          |dPd          d/|:d0|;d1|<d2|=d3|>d4|?dQ|rt/          |pi           nt/          t          |dQi           pi           d5|@dRMdSd|B}Hn7# tl          $ r* |C&	 |C7                                 n# t^          $ r Y nw xY w w xY w	 ddd           n# 1 swxY w Y   t          |dTd          |H_8        |Cd<|H_9        t          |HdPd          pd|%dP<   ||H_:        ||H_;        ||H_<        ||H_=        ||H_>        t          |dUd          pd|H_?        	 t          jA        |          |H_B        n# t          $ r
 d|H_B        Y nw xY wt          |dPd          }I|Irt          |HdVd          
|I|HjD        dW<   t          |)||*          }J|J|J|H_F        t          |dX          rbt          |dYd          }K|Kr5|K5  |jG                            |H           ddd           n# 1 swxY w Y   n|jG                            |H           MrA	  MdZ|[           n2# t^          $ r%}8tZ          0                    d\|8           Y d}8~8nd}8~8ww xY w	 dd]lHmI}L  |Ld^t          |dPd          t          |dUd          pd|t          |HdPd          |||_           n,# t^          $ r tZ          0                    d`d<=           Y nw xY w|HS )ba  
    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   )AIAgentN_delegate_depthr/   r:  r9  zsa--r   _subagent_idenabled_toolsetsvalid_tool_namesc                 B    h | ]}                     |          xS rE   )get_toolset_for_tool)ry   r   model_toolstss     r    r  z%_build_child_agent.<locals>.<setcomp>o  s<     
 
 
!66t<<<I IIIr"   c                     g | ]}|v |	S rF   rF   )ry   r  expanded_parents     r    r   z&_build_child_agent.<locals>.<listcomp>|  s#    FFFo1E1E!1E1E1Er"   disabled_toolsetsc                 ,    g | ]}t          |          S rF   r  ry   r   s     r    r   z&_build_child_agent.<locals>.<listcomp>  s    HHHDc$iiHHHr"   c                     g | ]
}|d k    |S )r  rF   r#  s     r    r   z&_build_child_agent.<locals>.<listcomp>  s)     
 
 
4<3G3GD3G3G3Gr"   r  r  r  api_keyr  r   r  rl   r   c                     | sd S 	  d|            d S # t           $ r&}t                              d|           Y d }~d S d }~ww xY w)Nr  z(Child thinking callback relay failed: %sr^   r   r_   )rl   r  child_progress_cbs     r    _child_thinkingz+_build_child_agent.<locals>._child_thinking  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providerr   >   nous-portalnousnousresearch)nous_api_modeapi_modezPinned delegation command 'zR' was not found on PATH. Install it or remove delegation.command from config.yaml.acp_commandacp_argszcopilot-acpchat_completionsreasoning_configreasoning_effortF)parse_reasoning_effortzAUnknown delegation.reasoning_effort '%s', inheriting parent levelz.Could not load delegation reasoning_effort: %s_fallback_chainproviders_allowedproviders_ignoredproviders_orderprovider_sortprovider_require_parametersprovider_data_collectionopenrouter_min_coding_score
max_tokensr   )	SessionDBdb_path)r@  zHsubagent: failed to open dedicated SessionDB; child persistence disabledTexc_infodelegated_child_contextr  r  prefill_messagesfallback_model
quiet_modeephemeral_system_prompt
log_prefix
[subagent-r   platformsubagentskip_context_filesskip_memoryclarify_callbackthinking_callback
session_dbparent_session_idr   request_overridesr  iteration_budget	_print_fn_current_turn_id_session_init_model_config_delegate_from_active_children_active_children_lockzsubagent.spawn_requestedr  z spawn_requested relay failed: %sinvoke_hooksubagent_start)rR  parent_turn_idparent_subagent_idr  child_subagent_id
child_role
child_goalz%subagent_start hook invocation failedrF   )J	run_agentr  uuidr\   rY  r`  uuid4hexr$  r(   rn  hasattrr  r  DEFAULT_TOOLSETSrw  rd  r|  r  r  r9   r   tupler   fromkeysr  r   r  r  r  r)   r  r:   r   r  r
  r`   r  hermes_cli.providersr.  shutilwhichr   hermes_constantsr5  r   r   r^   r_   r   hermes_stater?  agent.delegation_contextrD  BaseExceptioncloserU  _owns_session_dbr  _delegate_roler  _parent_subagent_id_subagent_goal_parent_turn_idweakrefr   r   r  rW  _resolve_child_credential_pool_credential_poolrY  hermes_cli.lifecycler\  )Qr  r6   r  r  r   r  r  r   r  r  r  r  r  r  r  r  r   r  _uuidr  	max_spawnorchestrator_okeffective_roler8   r_  	tui_depthdelegation_cfgparent_enabledrk  rx  raw_parent_disabledinherited_disabledchild_disabled_toolsetsworkspace_hintchild_promptparent_api_keyeffective_model_for_cbchild_session_refchild_thinking_cbr)  effective_modeleffective_providereffective_base_urleffective_api_key_parent_provider_effective_provider_normeffective_api_moder.  _shutileffective_acp_commandeffective_acp_argsparent_reasoningchild_reasoningdelegation_effortr5  r  rc   parent_fallbackchild_providers_allowedchild_providers_ignoredchild_providers_orderchild_provider_sort!child_provider_require_parameterschild_provider_data_collection!child_openrouter_min_coding_scorechild_max_tokenschild_optional_kwargschild_session_dbparent_session_dbr?  _parent_db_pathrD  childr   
child_poollock_invoke_hookr(  r   r  r  sQ                                                                                @@@@r    _build_child_agentr  *  s   B "!!!!! ,(91==AK$&&I/11MkI6MO"n444TTvN =
<<U[[]]%6rr%:<<K ~tDDA{Q''I!^^N \+=tDDN!n--	 
0',0BCC 
0
 
 
 
 
$5
 
 
 .// @ 2/BBFFFFXFFF$&& 	: N .n==	 @.4-n==	 @-f_.E.EFF-.>?? ",0CTJJ%eS'9::  HH4GHHH''
 
/
 
 
 #!;N!K!KKxjX	
 	
  ''L,N,Nl+++,\::N-%!  L \9d;;N D6F G G D%488CC #JglGT&J&J
 )+6$$%  $  
,	L# 	L$ 	L 	L 	L 	L 	L 	L , 1|1O*UglJPT.U.U*Cl.C X5lDVWW(:N |Z>>D" 2 8b??AAGGII$.	!%L	L	L666666*]?;;	/	/	/!$\:tDD      }}122 	 .B        
 1 GmT5 5 ( 	lJ339r    !5   $ 0 +/ |-?FF&OL +../ABB 
	 1U : :??????++,=>>F!"(W%    L L LEsKKKKKKKKL" 	Fl$5t<<D  &l4GNN%l4GNN#L2CTJJ!,FF(/3U) )% &-0$& & &	 # )0>[]a(b(b% ,"&"& $",1))+& * 	\<66 
 -/"C(( ?.>l+  mTBB$	$......%&7DIIO #. 	/2222Y[[ 
  	$ 	$ 	$LLZ      $	$ A@@@@@	 	 	"	" 4 43	G ( ( (++())( &o( ,+	(
 ,+( 21( ,+(  .~( "1( ")7I4!P!P!P(  /( "0( #:"9(  4(  )5!(" 6
5555#($ $%(& $(4'(( !D)(* "&+(, #4"3-(. ,+/(0 #*,d"K"K"K1(2 #:"93(4 #:"95(6 !6 57(8 219(: -N,M;(< *H)G=(B )TD39r:::gl4GLLRPRSSE(H -N,MI(J (9'8K(L "&'O( (EER  		 		 		  +$**,,,,    D		S 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4j lK>>EO #!% '.e\2&F&F&L"l#'E *E %E 2EE#L2DbIIORE
*%,[%>%>"" * * * &*"""* |T::J Hge%A4HHT=G()9: 0L*< J !+ |/00 8|%<dCC 	8 < <-44U;;;< < < < < < < < < < < < < < < )00777
  B	B8$GGGGG 	B 	B 	BLL;SAAAAAAAA	BMDDDDDD%lL$GG"<1CRHHNB1$UL$??)%		
 		
 		
 		
 		
  M M M<tLLLLLM Ls   $AQ1 1
R ;RR /V8 8(W#"W#6[;8B>Z76[;7[+[[+
[&#[+%[&&[++[;;[?[?7^ ^%$^%`<<a a %a3 3
b"=bb"&Ac/ /&ddr  timeout_secondsduration_secondsworker_threadc                   * 	 ddl m} ddl}ddl}ddl}	ddl}
 |            }|dz  }	 |                    dd           n# t          $ r Y dS w xY wt          | dd          pd| }|j        	                                
                    d	          }|d
| d| dz  }g *dRdt          ddf*fd} |d            |d|j        	                                                                             |d            |d            |d|             |d|             |d| d            |d|dd            |d            |d           |pd                                }t          |          dk    r|dd         dz   } ||pd            |d            |d           dD ]`}	 t          | |d          }t          |t                    r|d k    r	  |d!| d"|           B# t          $ r  |d!| d#           Y ]w xY w |d            |d$           t          | d%d          } |d&|           t          | d'd          }|rH |d(t          |                      	  |d)t!          |                      n# t          $ r Y nw xY w |d            |d*           	 t          | d+d          pt          | d,d          pd} |d-t          |t                    r"t          |                    d.                    nd/             |d0t          |t                    rt          |          nd/            n&# t          $ r} |d1| d2           Y d}~nd}~ww xY w	 t          | d3d          }|dt%          j        |t          4          } |d5t          |                       |d6t          |                    d.                                n&# t          $ r} |d7| d2           Y d}~nd}~ww xY w |d            |d8           	 |                                 }|                                D ]\  }} |d!| d"|           n&# t          $ r} |d9| d2           Y d}~nd}~ww xY w |d            |d:           ||                                r|                                }|                    |j                  }|S|	                    |          }|D ]:} |                                                     d;          D ]}! |d!|!            ;n% |d<           n| |d=           n |d>            |d            |d?           	 |                                }d@ |
                                D             }"|r|j        nd}#d}$|                                D ]\  }%}&|%|#k    r|$dAk    r$ |dBt          |          |$z
  dCz
   dD            n|"                    |%          }'|'r|'j        ndE|% }(|'r	|'j        rdFnd}) |dG|( |) dH           |	                    |&          D ]:} |                                                     d;          D ]}! |dI|!            ;|$dCz  }$n&# t          $ r} |dJ| d2           Y d}~nd}~ww xY w |d            |dK            |dL            |dM            |dN            |dO           |                     d;!                    *          d.P           t          |          S # t          $ r&}tD          #                    dQ|           Y d}~dS d}~ww xY w)Sa,  Write a structured diagnostic dump for a subagent that timed out
    before making any API call.

    See issue #14726: users hit "subagent timed out after 300s with no response"
    with zero API calls and no way to inspect what happened. This helper
    writes a dedicated log under ``~/.hermes/logs/subagent-<sid>-<ts>.log``
    capturing the child's config, system-prompt / tool-schema sizes, activity
    tracker snapshot, and the worker thread's Python stack at timeout.

    Returns the absolute path to the diagnostic file, or None on failure.
    r   )get_hermes_homeNlogsTparentsexist_okr  idxz%Y%m%d_%H%M%Szsubagent-timeout-r  z.logr   r  r   c                 2                         |            d S rE   )r   )r  liness    r    _wz-_dump_subagent_timeout_diagnostic.<locals>._w=  s    LLr"   u.   # Subagent timeout diagnostic — issue #14726z# Generated: z
## Timeoutz  task_index:        z  subagent_id:       z  configured_timeout: sz  actual_duration:   z.2fz## Goal  z ...[truncated](empty)z## Child config)r   r*  r/  r  r  rG  rN  rM  rK  rt  r  r    z: z: <unreadable>z## Toolsetsr  z  enabled_toolsets:  r  z  loaded tool count: z  loaded tools:      z## Prompt / schema sizesrH  system_promptz  system_prompt_bytes: zutf-8zn/az  system_prompt_chars: z  system_prompt: <error: >rm  rc  z  tool_schema_count: z  tool_schema_bytes: z  tool_schema: <error: z## Activity summaryz   <get_activity_summary failed: z!## Worker thread stack at timeoutr   z  <worker frame not available>z  <no worker thread handle>z   <worker thread already exited>z## All thread stacks at timeoutc                 ,    i | ]}|j         	|j         |S rF   )ident)ry   ths     r    r|   z5_dump_subagent_timeout_diagnostic.<locals>.<dictcomp>  s3       !#"  r"   r  z  <r/   z more threads omitted>zident=z daemonz  --- z ---z    z  <all-thread dump failed: z## NoteszG  This file is written ONLY when a subagent times out with 0 API calls.zI  0-API-call timeouts mean the child never reached its first LLM request.zG  Common causes: oversized prompt rejected by provider, transport hang,z<  credential resolution stuck. See issue #14726 for context.)encodingz+Subagent timeout diagnostic dump failed: %s)r   )$rn  r  datetimesys	traceback	threadingmkdirr^   r\   nowstrftimer:   	isoformatr`   rP   r9   r  encoder   r   get_activity_summaryr}   is_alive_current_framesr)   r  format_stackr  split	enumerater   daemon
write_textr   r   r   )+r  r  r  r  r  r6   r  _dt_sys
_traceback
_threadinghermes_homelogs_dirr8   r  	dump_pathr  _goal_previewattrr,   enabled
tool_names
sys_promptrc   tools_schema_schema_jsonr  rz   r{   framesworker_framestack
frame_linesubby_identworker_identdumpedr  framer  r   r  r  s+                                             @r    !_dump_subagent_timeout_diagnosticr    sz
   (Y444444&&&&&&&&%o'''	NN4$N7777 	 	 	44	 e^T::P>PJ>P>P\((99I;IIIIII		 	S 	$ 	 	 	 	 	 	 	;<<<
;3<++--7799;;<<<
2
<
/://000
0;00111
6O666777
:#3::::;;;
2
9**,,}$$)%4%03DDM
=%I&&&
2

 	. 	.D
.eT400c3'' DJ,>,>'''''(((( . . .,,,,-----.
2
=%!3T::
.7..///U$6==
 	B8s:88999?6*+=+=??@@@@   
2
%&&&	3 (A4HH 5/488  BtJWacfLgLg)rZ->->w-G-G)H)H)HmrttuuuBdJzSV<W<W)bZ]bddeeee 	3 	3 	3B1311122222222	3	1"5'488L'#z,DDD>3|+<+<>>???N3|/B/B7/K/K+L+LNNOOO 	1 	1 	1B////00000000	1
2
 !!!	:0022G $ $1???Q??####$ 	: 	: 	:B8#88899999999	:
2
.///$)?)?)A)A$))++F!::m&9::L'"//=="' ' 'J)002288>> ' ':::'' 34444"B,----B1222
2 	,---	5))++F '1';';'='=  H 3@I=..TLF &  uL((R<<BMS[[61A5MMMNNNE\\%(("$:rww*:5*:*:')@bi@b.D.&...///","9"9%"@"@ ) )J)002288>> ) )<#<<(((()! 	5 	5 	5B3S33344444444	5
2
:
TUUU
VWWW
TUUU
IJJJTYYu--@@@9~~   DcJJJttttts1  %]	 A  ]	 
A]	 AE)]	 9>G87]	 8H]	 HA&]	 ;J ]	 
J$!]	 #J$$]	 >BM ]	 
M=$M83]	 8M==]	 A7O9 8]	 9
PP]	 P]	 6?Q6 5]	 6
R R]	 RC-]	 D Z( ']	 (
[2[]	 [A=]	 	
]9]44]9c                 z   	 ddl m} ddl} |dd          }|                    dd           |j                                                            d          }|d	|  d
| dz  }ddlm}  |||d           t          |          S # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)a  Write a subagent's full summary to the delegation cache and return path.

    Mirrors web_extract's ``_store_full_text``: the file lands in
    ``cache/delegation`` which is mounted read-only into remote backends
    (Docker/Modal/SSH) via ``credential_files._CACHE_DIRS``, so the parent's
    terminal/``read_file`` tools can page through the complete text on any
    backend. Returns the absolute path, or None on failure (best-effort:
    the trimmed head+tail is still returned to the parent regardless).
    r   )get_hermes_dirNzcache/delegationdelegation_cacheTr  z%Y%m%d_%H%M%S_%fzsubagent-summary-r  z.txt)write_text_exclusiveF)privatez,Failed to spill subagent summary to file: %s)rn  r  r  r  r  r  tools.spill_safetyr  r:   r^   r   r_   )	r  r  r  r  	cache_dirr  r   r  rc   s	            r    _spill_summary_to_filer    s   333333"N#57IJJ	t444\(();<<DzDDBDDDD;;;;;;
 	T7E::::4yy   CSIIIttttts   BB
 

B:B55B:capc           	         t          |           }t          |dz            }||z
  }| d|         }| | d         }|                    d          }||dz  k    r
|d|         }|                    d          }d|cxk    r	|dz  k     rn n||dz   d         }t	          ||           }	ddd	t          |          d
dt          |          d
d|d
dg}
|	rM|                    d          dz   }|
                    d|	            |
                    d|	 d| d           n|
                    d           |
                    d           |dz   |z   d                    |
          z   }||	fS )a  Return (model_text, spill_path) for one over-budget summary.

    Mirrors web_extract's ``_truncate_with_footer``: keep a head+tail window
    (~75% head / ~25% tail, snapped to line boundaries) so the subagent's
    opening AND its closing (outcomes / files-changed / issues, which live at
    the end) both survive, spill the full text to disk, and append a footer
    telling the parent exactly how much it's seeing and the precise
    ``read_file offset=`` to page into the omitted middle. Deterministic.
    g      ?Nr   r~  r   r/   r   uE   ──────── [SUMMARY TRUNCATED] ────────zShowing ,z chars (head) + z chars (tail) of u:    total — trimmed to protect the parent's context window.r  zFull subagent output saved to: z,To read the omitted middle: read_file path="z	" offset=zV limit=200  (the file is the complete summary; raise/lower offset to page through it).zWFull output could not be stored to disk; the head+tail above is all that was preserved.uo   ─────────────────────────────────────u+   

[... middle omitted — see footer ...]

)rP   r   rfindfindr  r   r   r   )r  r  r  original_lenhead_budgettail_budgetr6  r   nl
spill_pathfooter_linesmiddle_start_line
model_texts                r    _trim_summary_with_footerr     s    w<<LcDj//K#K<K< DK<==!D	D		B	K#CRCy	4BB""""s""""""BFGG}'
G<<J 	7	Y3t99K 	Y 	YD		K 	Y 	YX	Y 	Y 	YL  
 JJt,,q0JjJJKKK@: @ @'@ @ @	
 	
 	
 	
 	&	
 	
 	
 
###IIDPSWS\S\]iSjSjjJz!!r"   n_summariesc                 R   	 t          | dd          }t          |dd          }t          |t                    r|dk    rdS t          | dd          }t          |t          t          f          r|dk     rd}t          |dd          pd}|t          |          z
  t          |          z
  }|dk    rt          S t          |t
          z            }|t          d|          z  }|dz  }	t          t          |	          S # t          $ r  t          	                    d	d
           Y dS w xY w)u  Per-summary character budget sized against the parent's *remaining*
    context headroom, split across the batch.

    The overflow this guards against is N summaries entering the parent
    context at once (batch fan-out), not any single summary being large.  We
    take a fraction of the headroom the parent has left (resolved context
    length minus what's already in its prompt) and divide it across the batch,
    converting tokens→chars at the standard ~4 chars/token estimate.

    Returns the per-summary char budget, or None when the parent's context
    state is unknown (no compressor / no token count) — in which case the
    caller falls back to the static char ceiling only.
    context_compressorNcontext_lengthr   session_prompt_tokensr>  r/      z!Summary budget computation failedTrA  )
r\   r9   r   r   _MIN_SUMMARY_CHARS_SUMMARY_HEADROOM_FRACTIONr$  r^   r   r_   )
r   r  
compressorr  used_tokensreservedheadroom_tokensbatch_token_budgetper_summary_tokensper_summary_charss
             r    _parent_summary_char_budgetr  	  sF   \+?FF
 -=tDD.#.. 	.A2E2E4l,CQGG+U|44 	aK :|Q77<1(3{+;+;;c(mmKa%% 3M!MNN/3q+3F3FF.2%'8999   84HHHtts   =C< A6C< 8AC< <&D&%D&resultsc           	         d | D             }|sdS t                      }	 t          |                    dt                              }n# t          t
          f$ r
 t          }Y nw xY wt          |t          |                    }d ||fD             }|sdS t          |          }|D ]}|d         }	t          |	          |k    rt          |	          }
t          |	||                    dd                    \  }}||d<   d|d	<   |r||d
<   t                              d|                    dd          |
||pd           dS )u  Trim subagent summaries in-place so the batch can't overflow the
    parent's context window, spilling full text to disk so nothing is lost.

    The effective per-summary cap is the MIN of:
      - the dynamic headroom budget (remaining parent context ÷ batch size), and
      - the static ``delegation.max_summary_chars`` ceiling (0 = disabled).

    When a summary exceeds the cap, its full text is written to a file and the
    in-context summary becomes a head slice plus a pointer to that file. This
    addresses issue/PR #9126: batch fan-out returned N full summaries verbatim,
    blowing the parent context and (on rate-limited providers) triggering a
    compression/429 death spiral.
    c                     g | ]I}t          |t                    t          |                    d           t                    ?|d          G|JS )r  )r9   r   r)   r:   r~   s     r    r   z)_apply_summary_budget.<locals>.<listcomp>Q	  sd       jD116@yAQAQSV6W6W\]^g\h	  r"   Nmax_summary_charsc                 "    g | ]}||d k    
|S )r   rF   )ry   cs     r    r   z)_apply_summary_budget.<locals>.<listcomp>`	  s"    MMMMq1uu!uuur"   r  r  Tsummary_truncatedsummary_full_pathu9   [subagent-%s] summary trimmed %d → ~%d chars (spill=%s)?none)r(   r   r)   DEFAULT_MAX_SUMMARY_CHARSr  r   r  rP   minr   r   r_   )r  r   	summariesr+   static_ceilingdynamic_budgetr  r  entryr  r  r  r  s                r    _apply_summary_budgetr"  C	  s      I  
..C3SWW%8:STTUUz" 3 3 323 1s9~~NNN NMnn=MMMJ 
j//C 
 
	"w<<37||!:S%))L"55"
 "

J &i%)!" 	4)3E%&GIIlC(( &	
 	
 	
 	

 
s   (A	 	A$#A$c                <   nopqrstuvw t          j                    }t          dd          vd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                    ndgpdgqdgodgsnopqs fd}t          j        |d	
          }t          dd          }t!          |t"                    r|nd}|rs|(	 ddlm}  |dd          pd}n# t          $ r d}Y nw xY w|r||t)          |          \  }}t          dd          }t!          |t*                    rt-          d|dz
            nd}t          dd          }t#          t          dd          pd          pt#          t          dd          pd          }t          dd          }t/          |t!          |t"                    r|nd|t!          |t"                    r|ndt!          t          dd          t"                    rt          dd          ndt          j                     dd|pd|||d           dudt0          t"          t2          f         ddfufd}	 |                                 vrA	  vd           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY wddl}|p&d  d|                                j        dd           wt          d!d          }	 dd"lm}m }m!}  |w ||                      |w|           n2# t          $ r%}t                              d#|           Y d}~nd}~ww xY wtE                      r	 dd$l#m$}  | %                                rLd}!	 dd%lm}"  |"|          }!n# t          $ r Y nw xY w| &                    |!ptO                    |&          unt                              d'           n2# t          $ r%}t                              d(|           Y d}~nd}~ww xY wu`	 dd)lm }#  |#wud*                    n2# t          $ r%}t                              d+|           Y d}~nd}~ww xY wdd,l(m)}$  |$u          z   t          j                     }%|r!t	          tU          j+        |                    ng }&tY                      }'dd-l-m.}(  |(dt^          ta                      f.          })d/ditd0t"          ddfvfd1rrtwfd2}*tc          j2                    }+|)3                    |+j4        |*          },	 |,5                    |'3          }-n# t          $ r}.|rtm          |          nd}/	 duoto                    }0|0st          d4          rd	_8        n# t          $ r Y nw xY wt!          |.tr          tt          f          }1tw          t          j                    |z
  d5          }2t          <                    d6 |1rd7nd8t{          |.          j>         |2           d}3d}4	 ?                                }5t+          |5@                    d9d          pd          }4n# t          $ r Y nw xY w|1rh|4dk    rbt           t          |'pd:          t          |2          t@                    d/          ;          }3|3rt          <                    d< |3           vr;	  vd=|1rd>|2 d?nt#          |.          |1rd@ndA|2dB           n# t          $ r Y nw xY w|1r+|4dk    rdC|' dD}6|3r|6dE|3 z  }6n#dC|' dF|4 dG}6|3r|6dE|3 z  }6nt#          |.          }6 |1rd@ndAd|6|1rd@ndA|4|2|1r|'nd|1r|2nd|1r|4dk    rdHn|1rdIndt          dJd          |3dK}7|/r|/|7dL<   |7dAxx         dM|/ dNz  cc<    ||7           |7cY d}.~.|)C                    dOP           nD                                 |jE        |F                    dQ3           |rt          |R           |K|I	 |H                    |           n2# t          $ r%}t                              dS|           Y d}~nd}~ww xY wddl}	t          dd          }8t!          |8t                    rt	          |8          |	_        t          dT          r	 t          dUd          }9|9r5|95  jI        J                               ddd           n# 1 swxY w Y   njI        J                               n9# t          t          f$ r%}t                              dV|           Y d}~nd}~ww xY w	 t          dW          rM                                 n*# t          $ r t                              dX           Y nw xY w	 ddYlNmO}: |:P                    dOZ          };t#          t          dd          pd          }<|:jQ        R                    |:S                                |<[          }=|;|<r|=s|;T                    d\|<i           S S S S # t          $ r t                              d]           Y S w xY wd}.~.ww xY w	 |)C                    dOP           n# |)C                    dOP           w xY wt          d^d          }>d}?g }@d}At!          |>t                    rdd_lVmW}BmX}C |-@                    d`          pd}D |C|D|>          \  }?}@|?s|DY                                r|-@                    dadO          svd}Ad}E	 Z                     |B|@          wrb          }En3# t          $ r&}Ft          <                    dc |F           Y d}F~Fnd}F~Fww xY wt!          |Et                    r|E@                    d`          pd}G|GY                                r|G|-d`<   	 t+          |-@                    ddd          pd          t+          |E@                    ddd          pd          z   |-dd<   n# t          t          f$ r Y nw xY w|E@                    de          }Ht!          |Ht                    r6t!          |-@                    de          t                    r|-de         |Hz   |-de<    |C|G|>          \  }?}@|rtm          |          nd}/|/r8|-@                    df          }It!          |It"                    r	|Ir|I dg|/ n|/|-df<   vrXt          vdh          rH	 v\                                 n2# t          $ r%}t                              di|           Y d}~nd}~ww xY wtw          t          j                    |z
  d5          }2|-@                    d`          pd}J|-@                    djdO          }K|-@                    dadO          }0|-@                    ddd          }L|JY                                dkk    }M|0rda}Nn	|Jr|Msdj}Nndl}Ng }Oi }P|-@                    de          pg }Qt!          |Qt                    r|QD ]}Rt!          |Rt                    s|R@                    dm          dnk    r|R@                    do          pg D ]}S|S@                    dpi           }T|T@                    dqd          }U|T@                    drds          t          |U          t          |U          dt}V|O_                    |V           |S@                    du          }W|Wr|V|P|W<   |R@                    dm          dvk    rt          |R@                    dwd                    }Xt          |X          }Yt          |X          |YrdAndxdy}Z|R@                    dz          }W|Wr|P@                    |W          nd}[|[|[b                    |Z           |Or|Od{         b                    |Z           |0rda}\n|Krdj}\nd|}\t          d}d          }]t          d~d          }^t          dd          }_ |N|J|L|2t!          |_t"                    r|_nd|\|\d|k    t!          |]t*          t          f          r|]ndt!          |^t*          t          f          r|^ndd|Ot          dJd          t!          t          dd:          t*          t          f          r t          t          dd:          pd:          nd:d}`tw          |`d         d          |`d<   t          dd          }at!          |at"                    r|ar|ands|`d<   |Ndlk    r|-@                    dAd          |`dA<   t!          |>t                    r"t          |?          |`d<   |Ar|A|`d<   |?s|@r|@|`d<   |-@                    df          }bt!          |bt"                    r-|bY                                r|b|`dL<   d|b dN}c|Jr|J d|c n|c|`d<   	 |r|&rtU          jd        ||%|&          }d|drt          d |df                                D                       }e|erxddF                    |edd                    z   t          |e          d k    rdt          |e          d z
   dndz   dNz   }f|`@                    d          r|`d         |fz   |`d<   n|e|`d<   n,# t          $ r t                              dd	           Y nw xY wt          dd          }gt          dd          }h	 t	          tU          j+        w                    dd         }in# t          $ r g }iY nw xY w	 tU          jd        d|%g           }jn# t          $ r i }jY nw xY wt          wfd|jg                                D                       dd         }kt          |-d d          }l|Jr
|Jdd         n|`@                    dAd          |N|2|Jr
|Jdd         n|`@                    dAd          t!          |]t*          t          f          rt+          |]          ndt!          |^t*          t          f          rt+          |^          ndt!          |ht*          t          f          rt+          |h          ndt!          |Lt*          t          f          rt+          |L          nd|i|k|ld}m|g+	 t          |g          |md<   n# t          t          f$ r Y nw xY wvr<	  vdi |m n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w ||`           |`nD                                 |jE        |F                    dQ3           |rt          |R           |K|I	 |H                    |           n2# t          $ r%}t                              dS|           Y d}~nd}~ww xY wddl}	t          dd          }8t!          |8t                    rt	          |8          |	_        t          dT          r	 t          dUd          }9|9r5|95  jI        J                               ddd           n# 1 swxY w Y   njI        J                               n9# t          t          f$ r%}t                              dV|           Y d}~nd}~ww xY w	 t          dW          rM                                 n*# t          $ r t                              dX           Y nw xY w	 ddYlNmO}: |:P                    dOZ          };t#          t          dd          pd          }<|:jQ        R                    |:S                                |<[          }=|;|<r|=s|;T                    d\|<i           S S S S # t          $ r t                              d]           Y S w xY w# t          $ r}|rtm          |          nd}/tw          t          j                    |z
  d5          }2t          jj        d  d           vr^	  vd=t#          |          dl|2t#          |          B           n2# t          $ r%}t                              d|           Y d}~nd}~ww xY w dAdt#          |          d|2t          dJd          d}7|/r|/|7dL<   |7dAxx         dM|/ dNz  cc<    ||7           |7cY d}~nD                                 |jE        |F                    dQ3           |rt          |R           |K|I	 |H                    |           n2# t          $ r%}t                              dS|           Y d}~nd}~ww xY wddl}	t          dd          }8t!          |8t                    rt	          |8          |	_        t          dT          r	 t          dUd          }9|9r5|95  jI        J                               ddd           n# 1 swxY w Y   njI        J                               n9# t          t          f$ r%}t                              dV|           Y d}~nd}~ww xY w	 t          dW          rM                                 n*# t          $ r t                              dX           Y nw xY w	 ddYlNmO}: |:P                    dOZ          };t#          t          dd          pd          }<|:jQ        R                    |:S                                |<[          }=|;|<r|=s|;T                    d\|<i           S S S S # t          $ r t                              d]           Y S w xY wd}~ww xY w# nD                                 |jE        |F                    dQ3           |rt          |R           |K|I	 |H                    |           n2# t          $ r%}t                              dS|           Y d}~nd}~ww xY wddl}	t          dd          }8t!          |8t                    rt	          |8          |	_        t          dT          r	 t          dUd          }9|9r5|95  jI        J                               ddd           n# 1 swxY w Y   njI        J                               n9# t          t          f$ r%}t                              dV|           Y d}~nd}~ww xY w	 t          dW          rM                                 n*# t          $ r t                              dX           Y nw xY w	 ddYlNmO}: |:P                    dOZ          };t#          t          dd          pd          }<|:jQ        R                    |:S                                |<[          }=|;|<r|=s|;T                    d\|<i           w w w w # t          $ r t                              d]           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.
    r  Nr   _delegate_saved_tool_namesrz  _swap_credentialz-Failed to bind child to leased credential: %sc                                          t                    st          dd           } | s2d d}	                                 }|                    d          }|                    dd          }|                    dd          }|                    d          }|d         k    }|d         k    }|d uod         d u p|d         k    }	|s|s|	r|d<   |d<   ||d<   dd<   ndxx         d	z  cc<   |rt
          nt          }
d         |
k    r't                              d
d         |pd           d S |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  last_activity_tsr/   u_   Subagent %d appears stale (no progress for %d heartbeat cycles, tool=%s) — stopping heartbeatz<none>z delegate_task: subagent running z (iteration r  rf   last_activity_descr   )
wait_HEARTBEAT_INTERVALr\   r  r)   _HEARTBEAT_STALE_CYCLES_IN_TOOL_HEARTBEAT_STALE_CYCLES_IDLEr   r   r^   )touchdescchild_summary
child_tool
child_iter	child_maxchild_activity_tsiter_advancedtool_changedactivity_advancedstale_limit
child_desc_heartbeat_stop_last_seen_activity_ts_last_seen_iter_last_seen_tool_stale_countr  r   r  s               r    _heartbeat_loopz*_run_single_child.<locals>._heartbeat_loop	  s   !&&':;; L	#L*;TBBE BjBBBD@ % : : < <*..~>>
*../?CC
)--.>BB	$1$5$56H$I$I! !+_Q-? ?)_Q-??%T1 .q1T9 I,/Ea/HH	 " ! )L )4E ))3OA&)3OA&(44E.q1&'LOO OOOq(OOO "6335 
  ?k11NNL"$Q".h   E @: @ @&0@ @3<@ @ @ D
 "/!2!23G!L!LJ! Dz D D*4D D7@D D D     d   W "&&':;; L	 L	 L	 L	 L	s*   D
E; 3E; ;
FFF 
F%$F%T)ri  r  r  get_session_envHERMES_UI_SESSION_IDr   r  r/   ru  _parent_session_idr   _delegation_idr   running)r8   r   r  r6   r7   r   r   r   r  rW   rO   ri   rj   rk   
entry_dictr   c                    dS 	 ddl m} |                              | d<   dS # t          $ r}t                              d|           	 ddl m} |                    d|           | d<   n`# t          $ rS                     dd                              d	d          dd
d
dd| d                    dd           dd| d<   Y n
w xY wY d}~dS Y d}~dS d}~ww xY w)z=Inspect + prune the child worktree, reporting into the entry.Nr   subagent_worktreeworktreezworktree finalize failed: %szfinalize raised: r   r   branchFTzworktree finalize raised (zg) and the reporting helper was unavailable: 'commits' and 'dirty' are UNKNOWN, not zero/clean. Inspect z before assuming no work.)r   rM  commitsdirtyprunedinspection_failedr   )rm  rK  finalize_subagent_worktreer^   r   r   unproven_worktree_payloadr)   )rH  rK  r  _sw_worktree_infos       r    _attach_worktreez+_run_single_child.<locals>._attach_worktreeE
  s   !F#	////// "<<^LL z"""  	 	 	
 NN91===::::::),)F)F"$;$;$;* *
:&&     +..vr::,002>> "#)-#Q # # *--fb99# # #* *
:&&& '&&&&& '&&&&&	s9   ' 
C!C"A0/C0AC
CCCC!r  r  z"Progress callback start failed: %sz	subagent-r  r   _current_task_id)get_session_cwdrecord_session_cwdregister_container_aliaszChild cwd seed failed: %srJ  )rX  )r8   z6worktree isolation skipped: non-local terminal backendz#worktree isolation setup failed: %s)rY  r   zworktree cwd seed failed: %s)build_worktree_context_noteDaemonThreadPoolExecutor)max_workersinitializerinitargsr  deltac                     | rsd S 	  d|            d S # t           $ r&}t                              d|           Y d }~d S d }~ww xY w)Nr  r  zChild text relay failed: %sr'  )ra  r  r(  s     r    _relay_child_textz,_run_single_child.<locals>._relay_child_text
  s       1 ?!!/5AAAAAA ? ? ?:A>>>>>>>>>?s    
AAAc            	          t          j                    d<   ddlm}   | t	          t          dd          pd                    5                                cd d d            S # 1 swxY w Y   d S )Nr  r   rC  r   r   user_messager4   stream_callback)r  current_threadrp  rD  r:   r\   run_conversation)rD  rc  _worker_thread_holderr  child_task_idr6   s    r    _run_with_thread_capturez3_run_single_child.<locals>._run_with_thread_capture
  s    )2)A)C)C!#&HHHHHH((WUL"-M-M-SQS)T)TUU  --!%)$5 .                   s   A,,A03A0)r2  _interrupt_requestedr  zSubagent %d %s after %.1fsz	timed outzraised r)          )r  r  r  r  r  r6   u;   Subagent %d 0-API-call timeout — diagnostic written to %sr  zTimed out after r  r2  r"  )r   r   r  r  zSubagent timed out after u   s without making any API call — the child never reached its first LLM request (prompt construction, credential resolution, or transport may be stuck).z Diagnostic: zs with ug    API call(s) completed — likely stuck on a slow API call, tool call, or unresponsive network request.before_first_llm_callafter_llm_callsrt  )r  r   r  r"  exit_reason	api_callsr  r  timed_out_after_secondstimeout_phase_child_rolediagnostic_pathmissed_steerz2 [steer did not land before the subagent stopped: r   F)r,  r  rV   z&Failed to release credential lease: %srY  rZ  z/Could not remove child from active_children: %srr  z,Failed to close child agent after delegation)relay_runtime)create)profile_keyr   r  z4Failed to close child Relay session after delegation_delegate_output_schema)build_retry_messagevalidate_outputfinal_responseinterruptedre  z(Subagent %d schema-retry turn failed: %srr  r   pending_steerr   r  z"Progress callback flush failed: %s	completedr  r0  r   r   r   r   r  r   r  )r   r'  r&  r   r   r   r!  )r(  r   r   r  r  r  session_completion_tokens)inputoutputsession_estimated_cost_usd)r  r   r  rr  r  r   rq  	truncatedtokensr  ru  _child_cost_usdr     cost_usdsession_cost_statuscost_statusz$Subagent did not produce a response.schema_validschema_retriesschema_errorsuL   [steer did not land — the subagent finished before it could be delivered: z

r  c                     h | ]	}|D ]}|
S rF   rF   )ry   pathsps      r    r  z$_run_single_child.<locals>.<setcomp>h  s%    OOOuOOAOOOOr"   uX   

[NOTE: subagent modified files the parent previously read — re-read before editing: r  z (+z more)stale_pathsz%file_state sibling-write check failedrA  session_reasoning_tokensr  c                 0    h | ]\  }}|k    |D ]}|S rF   rF   )ry   tidr  r  rk  s       r    r  z$_run_single_child.<locals>.<setcomp>  sC       C-'' (' ''''r"   iX  r      i  )r   r   r  r  input_tokensoutput_tokensreasoning_tokensrr  
files_readfiles_writtenoutput_tailz'Progress callback completion failed: %srJ  z] failedz*Progress callback failure relay failed: %sr  r   r  r"  rr  r  ru  r  )kr   	monotonicr\   r  r   _last_resolved_tool_namesacquire_leasecurrentrg  r%  r^   r   r_   r  EventThreadr9   r:   gateway.session_contextrC  rt   r   r$  rM   r   r   startrd  re  rf  tools.terminal_toolrX  rY  rZ  rI  rm  rK  local_backend_activecreate_subagent_worktreer  tools.subagent_worktreer[  r   known_readsrR  tools.daemon_poolr]  _set_subagent_approval_cbr-   contextvarscopy_contextsubmitrunr   rd   r   rm  FuturesTimeoutErrorr   r   r   typer  r  r)   r  r   shutdownrn  r  r   rY   release_leaserY  remover   UnboundLocalErrorrr  rW   rx  get_runtimeSESSION_COORDINATORhas_active_turncurrent_profile_keyunregister_subagentr   tools.delegation_output_schemar|  r}  r`   ri  r  r  rP   r  r   r   r   ro  rB   writes_sincer  r   r}   r   logging	exception)xr  r6   r  r   ri   rj   rk   _kwargschild_startr  _saved_tool_namesr  leased_cred_idleased_entryrc   rA  _heartbeat_thread_raw_sidr  rC  
_raw_depth
_tui_depth_parent_sid_owner_agent_session_idrF  rV  r  r|  parent_task_idrX  rY  rZ  rK  _parent_cwd_gsc_rscr[  
wall_startparent_reads_snapshotchild_timeoutr]  _timeout_executorrl  _child_context_child_futurer   _timeout_exc_late_pending_steerr  
is_timeoutdurationrv  child_api_calls_summary_err_error_entrysaved_tool_namesr  rx  runtimer  child_turn_is_active_output_schema_schema_valid_schema_errors_schema_retriesr|  r}  _first_text_retry_result
_retry_exc_retry_text_retry_messages_existing_pendingr  r  rr  _empty_sentinelr   r  trace_by_idr   r   r   r   r  entry_tr   r   r   result_metari  rq  _input_tokens_output_tokens_modelr!  _cost_status_missed_steer
_miss_notesibling_writes	mod_pathsreminder	_cost_usd_reasoning_tokens_files_read_files_written_map_files_written_output_tailcomplete_kwargsr<  r=  r>  r?  rc  r@  rj  rU  r(  rk  sx   ````                                                                                                          @@@@@@@@@@r    _run_single_childr  z	  s)    .""K  '?FF +T+2W-X-X   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 cOfO"V3LM M M M M M M M M M M M^ "(MMM und33H)(C88B88dL 7
#(CCCCCC#2?3I2#N#N#VRV   ( ( (#'   ( 	#';'C 11ABB 2O1 U$5q99
/9*c/J/JQSJN+++PQ
e%:DAA 3R88>B?? B7<r::@bAA 	  !(8$??+,6{C,H,HR[[d#&0&E&EONN4 "'%$"?"?EEGE7D111"ikk#
 +B*IT %5#2(<5 	
 	
 	
B 04N'T#s(^ ' ' ' ' ' ' 'Ru
Q!!! 	FF!!"2DAAAAA F F FA1EEEEEEEEF 	$X(XJ(X(XARSUTUSUAV(X(X /A4HH	9          }oon.M.MNNN
 %$]NCCCC 	9 	9 	9LL4a88888888	9 #$$ "	JG333333$99;; "&KOOOOOO&*d>&:&:$   %6%O%O#L'>|'L'L$0 &P & &NN
 LLP    G G GBAFFFFFFFFG)DNNNNNNDv(>????  D D DLL!?CCCCCCCCD
 POOOOO99.IIIY[[
<JRD'77888PR 	 +,, 	?>>>>>44
 25779
 
 
 ILT{		?S 		?T 		? 		? 		? 		? 		? 		?		 		 		 		 		 		 		 		 		 %133)00$
 
y	3"))-)@@FF s	  s	  s	 
 BNW(u===SW  #4/Q4J54Q4Q" 6u'8WULb=c=c'815E.    $L3F2UVVJT^--;Q??HNN,)V/Vl9K9K9T/V/V	   .2OO 5577"%hll3CQ&G&G&L1"M"M    o22"C) %*-*>3$?$?%*8__"7";";C"@"@	# 	# 	# # NNU"'   ! %%+  *3:x::::!$\!2!2,6CyyG)1 "
 
 
 
 
 !   D  )"a''CM C C C  ' B A A AA,M , ,*, , ,  ' B A A AA<(( )'1>))w,6CyyG,$,4>#H==D7A+K88t/9 oQR>R>R++.8 **&u.>EE#2! L$ # /B^,W%%%.*. . .%%% \*** &&E&222v 	".""1"---  	< U;;;;!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	Q++++++#//u/==G"75,#C#C#IrJJ#0#D#T#T)==??+ $U $ $  "'7"@T"++-?AQ,RSSSS #"" 	Q 	Q 	QLLOPPPPP	Q]s	  p &&E&2222&&E&2222 !(A4HH(,$&nd++ 1	       
 !**%566<"K,;O^- -)M> "'%%''' 

=%88' #$ $$)$:$:%8%8%H%H -(9 %; % %MM
 !   NNB""        mT22 "/"3"34D"E"E"KK"((** ?3>/0.1"JJ{A66;!/ / 1 1+q A A FQGG/H{++ &z2   &3&7&7
&C&CO!/488 RZ

:..> > R .4J-?/-Qz*4CO#^5 51M> >JS$\5999t 	  	 &

? ; ; /55):K)$==(;===( ?#  	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..	 "--//Y6 	"FF 	_ 	 !FFF ,.
13::j))/Rh%% 	; ; ;!#t,, 776??k11!ggl339r 9 9VVJ33$&FF;$;$;	$&FF69$=$=*-i..-Fy-Q-Q# #
 #))'222 "t  918K.9 WWV__..5cggi6L6LMMG7@@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& %(88 &0U|%L%LSMMRS '1#u&N&NUNNTU  % #5*:DAA E#?EE%L ge%A3GGN3OOO
 O)!
 )!
^ "%(9":A>>ju&;TBB&|S99 l LL 	m X#ZZ1WXXE'N nd++ 	8$($7$7E.! :*9&'  8^ 8)7o& 

?33mS)) 	Wm.A.A.C.C 	W$1E.!2!.2 2 2  @GV';;z;;;JE)	Q ="7 =!+!8"J0E" " " = &OO(=(=(?(?OOO! !I ! =K"ii	"1"667
 $'y>>A#5#5 !Ac)nnq&8 @ @ @ @%' "" ! !99Y// =/4Y/?(/JE),,3<E-0 	Q 	Q 	QLL@4LPPPPP	Q E#?FF	#E+EqII	z5mDDEEcrcJKK 	 	 	KKK		$!+!8J" "  	$ 	$ 	$!#	$   "4":":"<"<  
 
 2# ,FSQQQ )0Kwtt}}UYYw5K5K ((/Kwtt}}UYYw5K5K&0e&M&MTM"""ST (2.3,'O'OVN###UV /#u>>%&&&+5i#u+N+NUYTU%+''+
 +
*  .3I.>.>
++z*     	KK!!IIIIII K K KFJJJJJJJJK 	X 	".""1"---  	< U;;;;!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	Q++++++#//u/==G"75,#C#C#IrJJ#0#D#T#T)==??+ $U $ $  "'7"@T"++-?AQ,RSSSS #"" 	Q 	Q 	QLLOPPPPP	QM  " " "=IS$\5999t 	 ))K7;;;z;;;<<< 
	N	N!!'HH#%-HH      N N NI1MMMMMMMMN %XX ("5*:DAA
 
  	+>L(!!!*&* * *!!!
 	&&& 	".""1"---  	< U;;;;!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	Q++++++#//u/==G"75,#C#C#IrJJ#0#D#T#T)==??+ $U $ $  "'7"@T"++-?AQ,RSSSS #"" 	Q 	Q 	QLLOPPPPP	QM"T 	".""1"---  	< U;;;;!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	Q++++++#//u/==G"75,#C#C#IrJJ#0#D#T#T)==??+ $U $ $  "'7"@T"++-?AQ,RSSSS #"" 	Q 	Q 	QLLOPPPPP	Qsv  ;C 
C1C,,C1%E: :F	F	9A_/ L A_/ 
M(MA_/ MAA_/ +N; :A_/ ;
O*O% A_/ %O**A_/ =Q> P, +Q> ,
P96Q> 8P99AQ> =A_/ >
R-R(#A_/ (R--A_/ 3S A_/ 
S;S61A_/ 6S;;CA_/ 	W! l !k-,k(.X0/k(0
X=:k(<X==A=k(;9[54k(5
\?k(\A/k(2)^k(
^)&k((^))B"k(k-l A_/ /c
c4c//c4f)f6f)f	f)	f	
f))g:gg#$h$h/.h/3Bj>>$k%$k%(k--l 1A_/ l  BA_/ 2!o A_/ 
po?:A_/ ?pA	A_/ Ar A_/ r1.A_/ 0r11CA_/ v A_/ 
w#w>A_/ wQ5A_/ H>CAL  K?A_/ L &AL)L&A_/ L(AL)L)%A_/ M)AM9 M8A_/ M9ANNA_/ NANNA_/ NAN# N"A_/ N#AN2N/A_/ N1AN2N2EA_/ S9AT TA_/ TAT TA_/ TAT T A_/ T&AT/ T.A_/ T/
AUT9AUUA_/ UAUUA_/ V6AWW
AW;WAW6W6AW;YAZ0Y"AZ	Y=AZ0Z	AZ	ZAZ0ZAZ	ZAZ0Z0A[&[A[![!A[&[*$A\\$A\6\5A\6\:BA__$A_,_+A_,_/An_:AAm>a*Aa8a7Am>a8
Ab'bAb"bAm>b"Ab'b'AAm>c7Anc8An eAee
Af
e%AffAf
gAh?g1AhhAh?hAh	hAh?hAh	h Ah?h?Ai5iAi0i0Ai5i9$Ajj$AkkAkk	BAmm$Am;m:Am;m>AnnAn nA	Ax	oAo&o%Ax	o&
Apo0AppAx	pAppAAx	q'As
q<Ar#rAs
r#Ar'r'As
r*Ar'r+As
s	Ax	s
At sAs;s6Ax	s;At t Ax	t$At)t(Ax	t)$AuuAx	uAuuAx	uBAwwAx	w$AxxAx	xAxxAx	c                      ddl }t          5  t          |j                  }	 t	          di | }||_        n# ||_        w xY w	 ddd           n# 1 swxY w Y   ||_        |S )zCBuild a child without leaking its resolved toolset into the parent.r   NrF   )r  _CHILD_CONSTRUCTION_LOCKr   r  r  r$  )r   r  rr  r  s       r    $_build_child_preserving_parent_toolsr  +  s    	! F F !FGG	F&0000E4EK114EK1EEEE1F F F F F F F F F F F F F F F (9E$Ls#   A6A	?AAAc                 8   | t           S t          | dd          }||S t          5  t          | dd          }|It          j                    }	 t          | d|           n## t          $ r t           cY cddd           S w xY wddd           n# 1 swxY w Y   |S )zBReturn the per-parent lock that serializes lifecycle side effects.N_subagent_finalization_lock)"_PARENT_FINALIZATION_FALLBACK_LOCKr\   _PARENT_FINALIZATION_LOCK_GUARDr  RLocksetattrr^   )r   r  s     r    _parent_finalization_lockr	  9  s   11<!>EED	( : :|%BDII<?$$D:&CTJJJJ : : :999: : : : : : : ::: : : : : : : : : : : : : : : Ks5   'BA B B 1B?B  BBB	task_listchildrenc                 r   t          |          5  t          | |           d |D             }|rt          |dd          r| D ]}	 |                    dd          }t	          |t
                    r+d|cxk    rt          |          k     rn n||         d         nd}|                    |          }|j                            ||                    d	d          pdt          |d
d                     # t          $ r Y w xY wt          |d
d          }		 ddl
m}
 n# t          $ r d}
Y nw xY wd}| D ]W}|                    dd          }|                    dd          }	 |r|t          |          z  }n# t          t          f$ r Y nw xY w|
_	 |                    dd          }|                    |          } |
d|	t          |dd          pdt          |d
d          ||                    d	          |                    d          t!          |                    d                    t          |                    d          pddz            	  	         ,# t          $ r  t"                              dd           Y Uw xY w|dk    r	 t          t          |dd          pd          }||z   |_        t          |dd          dv rd|_        t          |dd           d!v rd"|_        n,# t          $ r t"                              d#d           Y nw xY wddd           dS # 1 swxY w Y   dS )$z@Apply host-owned summary, memory, hook, and cost contracts once.c                     i | ]	\  }}}||
S rF   rF   )ry   index_taskr  s       r    r|   z+_finalize_child_results.<locals>.<dictcomp>T  s!    KKK+>5%%KKKr"   _memory_managerNr  r  r   r6   r   r  r   )taskr   r  r[  rn  ru  r  subagent_stoprV  r   r  r  r  )rR  r^  r  ra  r2  child_statustool_call_historyduration_msz$subagent_stop hook invocation failedTrA  r  session_cost_sourcer  >   Nr   r  rL  r  r  >   Nr   r  	estimatedzSubagent cost rollup failed)r	  r"  r\   r)   r9   r   rP   r  on_delegationr^   hermes_cli.pluginsr\  rR   r   r  r   r-  r   r_   r  r  r  )r  r
  r  r   child_by_indexr!  r  	task_goalr  rR  r\  children_cost_totalra  
child_costchild_indexr  s                   r    _finalize_child_resultsr  K  s    
#<	0	0 NK NKg|444KK(KKK 	GL2CTJJ 	   !&<!<!<J &j#66 <<<<c)nn<<<<< "*-f55  	  +..z::E 0>>&$yyB77=2)0b)I)I ?    
 !   D $L,EE	EEEEEEE 	 	 	KKK	 " 	T 	TE=$77J#4c::J ='5+<+<<'z*   "T#iib99&**;77#&7#*<9KR#P#P#VTV%,UL$%G%G)"'))I"6"6!&8!4!4&F		,//' ' !$UYY/A%B%B%Ga4$O P P      T T TCdSSSSST $$KL*FLLSPS  ;BDW:W7<)>GG L  
 8BL4<)>	JJ O  
 8CL4 K K K:TJJJJJK[NK NK NK NK NK NK NK NK NK NK NK NK NK NK NK NK NK NKs   4L,B/C54L,5
D?L,DL,DL,D-*L,,D--6L,$E98L,9F
L,FL,C
I L, &J
L,	J

	L,AK32L,3&LL,LL,,L03L0c                     t          | |||          }|                    d|            d|i}t          |gd t          |           D             |gz   | ||fg|           |S )zFRun one child and apply the same host lifecycle used by delegate_task.r  r6   c                     g | ]}d diS )r6   r   rF   )ry   r   s     r    r   z(_run_child_lifecycle.<locals>.<listcomp>  s    111!&"111r"   )r  rJ   r  r   )r  r6   r  r   r   r  s         r    _run_child_lifecycler"    s     z4EEF
lJ///D>D	11uZ00111TF:
dE	"#	   Mr"   tasksc                 D   t          | t                    sdS |                                 }|sdS 	 t          j        |          }n)# t          j        $ r}d d|j         dfcY d }~S d }~ww xY wt          |t                    sd dt          |          j	         dfS |d fS )Nrq   )N7Provide either 'goal' (single task) or 'tasks' (batch).z`tasks must be a JSON array of task objects; received a string that could not be parsed as JSON (z).z3tasks must be a JSON array of task objects; parsed z	 instead.)
r9   r:   r`   r   r  JSONDecodeErrorr   r   r  r  )r#  rawr  rc   s       r    _recover_tasks_from_json_stringr(    s     eS!! z
++--C ONN
C 
 
 
=14= = =
 	
 	
 	
 	
 	
 	


 fd## 
0F||$0 0 0
 	
 4<s   A A,A'!A,'A,z^(todo|task\s*\d+)$z[<[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+>|\{[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+\}c                 L   t          |           dk     r	 dS t          |           D ]\  }}t          |                    dd                                                    }d                    |                                                                          }t          	                    |          rd| d|dc S t                              |          }|rd| d	|                    d
          dc S t          |          t          k     rd| d|dt           dc S dS )a  Validate a tasks=[...] batch beyond per-task goal presence.

    Returns an actionable error string, or None when the batch is valid.
    Batch-only by design: the single-`goal` form legitimately uses short
    goals, so these checks must never run on it.

    Duplicate goals are deliberately NOT rejected: identical-goal fan-outs
    are a legitimate pattern (best-of-N / ensemble sampling), and blocking
    them broke real workflows (post-merge audit of #81141).
    r  zBatch mode requires at least 2 tasks. For a single task, use the `goal` parameter instead of `tasks`: delegate_task(goal="...", context="...").r6   r   r  Task z has a placeholder goal (za). Replace it with a specific, self-contained description of what the subagent should accomplish.z. goal contains an unexpanded template marker (r   ud   ). Substitute the real value before calling delegate_task — subagents cannot resolve placeholders.z goal is too short (z5). Write a specific, self-contained goal of at least z5 characters so the subagent knows exactly what to do.N)rP   r  r:   r)   r`   r   r  r  _PLACEHOLDER_GOAL_REmatch_TEMPLATE_MARKER_REsearchgroup_MIN_BATCH_GOAL_LEN)r
  ir  r6   
normalizedmarkers         r    _validate_batch_tasksr4    s    9~~8	
 	
 Y''  4488FB''((..00XXdjjll002233
%%j11 	. . .D . . .  
 %++D11 	     LLOO        t99***& & &t & &&& & &   + 4r"   
backgroundoutput_schemac                 X  
ABCDEFGHIJKLMNOP 
t          d          S |pd                                                                }|t          v rt	          |||	
          S |r|dk    rt          d| d          S t                      rt          d          S t          |          }|t          |d	          nd}t          
d
d          }t                      }||k    rt          d| d| d          S t                      }|                    dt                    }|"||k    rt                              d||           |}	 t          |
          }n3# t           $ r&}t          t#          |                    cY d}~S d}~ww xY wt%                      Jt'          |          \  }}|rt          |          S ||}t)          |t*                    r|sd}|rNt)          |t*                    r9t-          |          Jk    r#t          dt-          |           dJ d          S |OnK| r:t)          | t"                    r%|                                 r| ||d}|||d<   |gOnt          d          S Ost          d          S t/          O          D ]\  }}t)          |t0                    s*t          d| dt3          |          j         d          c S |                    dd                                          st          d| d          c S |5t)          |t*                    r t7          O          }|rt          |          S ddlm} g }t/          O          D ]o\  }}|                    d          }|t-          O          dk    r||} ||          \  }}|rt          d| d|           c S |                    |           pt?          j                     Lg Mt-          O          Kd  OD             Ndd!l!m"}m#Pm$}   |O||                    d"          |                    d#          $          \  GIHdd%l%m&}!  |!            }"	 dd&l'm(}#  |#d'd          En# tR          $ r dEY nw xY wtU          E          \  DCg Ft/          O          D ]\  }}$t          |$                    d(          p|          }%|t-          |          k     r||         nd}&|$                    d)          }'|&dd*lm+}(  |(|'|&          }'	 tY          dli d+|d|$d         d)|'d,dd"|d"         d|d-Kd.
d/|d#         d0|d1         d2|d3         d4|d5         d6|                    d7          d8|                    d9          d:|                    d;          d<|                    d=          d(|%})n5# t           $ r(}t          t#          |                    cY d}~c S d}~ww xY w|&4	 |&|)_-        n+# tR          $ r t                              d>|           Y nw xY w|t-          I          k     rI|         nd}*|*9 | t          |)d?d          |*          |)_.        t#          |*j/                  |)_0        Grtc          |)d@G           F                    ||$|)f           dAdBdCtd          dDt0          fCDEFGHIJKL
MNOPfdEB|r1ddFl%m3}+ ddGl4m5}, 	 ddHl'm6}-  |-            }.n# tR          $ r dA}.Y nw xY wd}/|.s!|"}/|/rt          7                    dI|/           dA}.|.sTt          7                    dJ            B            }0t)          |0t0                    rdK|0dL<   tq          j9        |0dM          S  |,d	          }1	 dd&l'm(}#  |#dNd          }2 |#d'd          pEE|2dOk    r$t#          t          
dPd          pd          }3|3r|3}1n# tR          $ r d}2Y nw xY w|1s$t#          t          
dPd          pd          }3|3r|3}1t          
dPd          }4dQ FD             Atu          
dR          rxt          
dSd          }5AD ]d}6	 |5r5|55  
j;        <                    |6           ddd           n# 1 swxY w Y   n
j;        <                    |6           U# t           $ r Y aw xY wBfdT}7AfdU}8AfdV}9dW OD             }: |+|:|d||d"         |1E|/|4|7|8t{                      G|9X          };|;                    dY          dZk    rt-          |:          }<|<dk    rd[n|< d\}=dZd]|<|;d^         |:|=d_}>d` AD             }?t}          da |?D                       r
|?|>db<   dc|>dd<   Hrt+          H          |>de<   df|>dg<   tq          j9        |>dM          S t          7                    dh|;                    didj                      B            }@t)          |@t0                    rdk|@dL<   tq          j9        |@dM          S tq          j9         B            dM          S )ma  
    Spawn one or more child agents to handle delegated tasks, or control
    already-running ones.

    Spawn modes (action='spawn' or omitted):
      - Single: provide goal (+ optional context and role)
      - Batch:  provide tasks array [{goal, context, role}, ...]

    Control modes (synchronous, never backgrounded):
      - action='list'  -> live children of this conversation's spawn tree
      - action='steer' -> queue course-correction text into a running child
                          (subagent_id + message)
      - action='stop'  -> interrupt a running child early (subagent_id)

    The 'role' parameter controls whether a child can further delegate:
    'leaf' (default) cannot; 'orchestrator' retains the delegation
    toolset and can spawn its own workers, bounded by
    delegation.max_spawn_depth.  Per-task role beats the top-level one.

    Returns JSON with results array, one entry per task.
    Nz.delegate_task requires a parent agent context.r   spawnr   z-'. Use spawn (default), list, steer, or stop.zzDelegation spawning is paused. Clear the pause via the TUI (`p` in /agents) or the `delegation.pause` RPC before retrying.Frc  r  r   z&Delegation depth limit reached (depth=z, max_spawn_depth=z). Raise delegation.max_spawn_depth in config.yaml if deeper nesting is required (no hard ceiling, but each level multiplies API cost).r  zidelegate_task: ignoring caller-supplied max_iterations=%s; using delegation.max_iterations=%s from configz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.)r6   r  r   r6  r%  zNo tasks provided.r*  z must be an object, got .r6   z is missing a 'goal'.)coerce_output_schemar/   z output_schema invalid: c                 .    g | ]}|d          dd         S )r6   Nr  rF   r  s     r    r   z!delegate_task.<locals>.<listcomp>  s$    555a1V9SbS>555r"   )create_live_transcriptsupdate_manifest_statuseswrap_progress_callbackr   r*  )r   r*  )_current_origin_session_idrB  rD  r   r  )append_output_contractr  r  r  r   r  r  r  r  r%  r  r/  r  rS  r  max_output_tokensr  r   r  r  z*Could not attach output schema to child %dr  rF  Thonor_parent_interruptrC  r   c                 	   *dk    rA%d         \  }}}t          ||d         |,$pd#"          }-                    |           nd}t          ,dd          }ddlm}  |)          5 }i }	%D ]N\  }
}}t          j                    }|                    |j        t           |
|d         |,$pd#"		  	        }|
|	|<   Od
 %D             }t          |	
                                          }|r| rt          ,dd          du r|D ]}|	|         }|                                rf	 |                                }n|# t          $ rC}|ddt          |          ddt          |                    |          dd          d}Y d}~n4d}~ww xY w|dddddt          |                    |          dd          d}-                    |           |dz  }ːnddlm}m}  ||d|          \  }}|D ]}	 |                                }nX# t          $ rK}|	|         }|ddt          |          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dnd}*|z
  }| d|dz    d* d | d!| d"
}|r:	 |                    |           n6# t          $ r t+          ,d#|            Y nw xY wt+          ,d#|            |r`|dk    rZ	 |                    d$| d%|dk    rd&nd' d(           # t          $ r&}t.                              d)|           Y d}~d}~ww xY w|ddd           n# 1 swxY w Y   -                    d* +           t5          -/%,           t7          t9          j                    +z
  d,          }-D ]}|                    dd-          }t=          |t>                    r%d|cxk    rt'          (          k     rn n(|         nd} | a	 |                      |           n,# t          $ r t.                              d.d/           Y nw xY w|t'          '          k     r'|         |d0<    0&-           -|d1}!'rtC          '          |!d2<   |!S )3uO  Run all built children (1 or N), join on them, aggregate results,
        fire subagent_stop hooks + cost rollup, and return the combined result
        dict. Used by BOTH the synchronous path and the background runner. In
        the background case this whole function runs on the daemon executor, so
        the parent turn isn't blocked — but the batch still JOINS on itself
        here (all children must finish) before producing ONE consolidated
        results block. That is the contract: fan-out runs in the background,
        waits on each other, and returns together.
        r/   r   r6   Nrh   r  r\  )r^  )r  r6   r  r   ri   rj   rk   c                     i | ]	\  }}}||
S rF   rF   )ry   r1  r   r  s       r    r|   zAdelegate_task.<locals>._execute_and_aggregate.<locals>.<dictcomp>j  s     "J"J"JAu1e"J"J"Jr"   rm  FTr"  rt  r  r  u9   Parent agent interrupted — child did not finish in time)r,  FIRST_COMPLETEDr~  )r2  return_whenr  r*  r  r   r  r  u   ✓u   ✗z [r  r  z  (zs)r  r  z taskr  r   z
 remainingzSpinner update_text failed: %sc                     | d         S )Nr  rF   )r   s    r    <lambda>z?delegate_task.<locals>._execute_and_aggregate.<locals>.<lambda>  s
    q r"   )r   r  r  zLive transcript finalize failedrA  r   )r  total_duration_secondslive_transcripts)"r  r   r\   r  r]  r  r  r  r  rn  r  doner   r^   r:   r)   concurrent.futuresr,  rF  rP   r  r  update_textr   r_   sortr  r   r   r  r9   r   finalizer   )1rC  _i_tr  r   completed_countspinner_refr]  executorfuturesr1  r  child_contextfuture_child_by_indexrb   fr  r!  rc   _cf_waitrF  rL  labeldurr   icon	remainingcompletion_liner  total_duration_idxr  combined_origin_owner_session_record_origin_owner_transport_origin_ui_session_idr  live_deleg_id
live_pathslive_writersmax_childrenn_tasksoverall_startr   r  task_labelsr
  r=  s1                                     r    _execute_and_aggregatez-delegate_task.<locals>._execute_and_aggregate2  sa    a<<$QKMBE&6
!6!>$ 7%A  F NN6""""  O!,0CTJJK
 CBBBBB))lCCC uRx#+ ( (KAq%$/$<$>$>M%__%))#$vY#%1)>)F$(?-I - 
 
F '(GFOO #K"J"J"J"Jgllnn-- ZR.&#L2H%PPTXXX
 ") 1 1A")!*C vvxx "!&,-HHJJEE'0 !& !& !&69293714S56<=7>,;,?,?,D,DFVX\8* 8*
-& 
-&EEEEEE!& 36.;/3-h12893:(7(;(;C(@(@BRTX4& 4&
)" 
)" $NN5111+q0OOTTTTTTTT$,H/% % %MD' #' ,R ,R$*MMOOEE(   ")&/C.1*1+/),S-.45/6$3$7$7$<$<>NPT0" 0"
% 
%EEEEEE  u---'1, $L103c+6F6F0F0FK,,MTWMM  $ii(:A>>!&8S!9!9(.+(=(=uu5$+o$=	-1*Y*YSU*Y*YW*Y*Y*Y*YRU*Y*Y*Y& W[ + 7 7 H H H H#, [ [ [ 4\CYCYCY Z Z Z Z Z[ 1?UO?U?UVVV ' R9q==R + 7 7$eI$e$e9PQ>>CCWY$e$e$e!" !" !" !" $- R R R &-Mq Q Q Q Q Q Q Q QRs  ZR7uR uR uR uR uR uR uR uR uR uR uR uR uR uR uRp LL66L777 	 HlKKKt~//-?CC  	@ 	@E99\2..D dC((-.$-J-J-J-J\9J9J-J-J-J-J-J T"" 
 ~SKK&&&&  S S SLL!BTLRRRRRS#j//))/9$/?E+,  888 &4$
 $
  	<+/
+;+;H'(s   .B9N5(D=<N5=
F
9F N5F

A*N55H
	N5

IAIN5IBN56LN5L,)N5+L,,N5$M1/N51
N!;NN5N!!N55N9<N9&Q<<&R%$R%)dispatch_async_delegation_batch)get_current_session_key)async_delivery_supportedu   delegate_task: async delivery unsupported on this session, but a session id is bound (%s) — dispatching in the background and waking the session via self-post when it completes instead of forcing synchronous execution.zkdelegate_task: async delivery unsupported on this session runtime; running the batch synchronously instead.u  background=true is not available in this session — it cannot receive a detached subagent result after the turn ends (a one-shot runner such as `hermes -z`, a cron job, a Kanban worker, or a stateless HTTP endpoint). The subagent(s) ran SYNCHRONOUSLY and the result is included above.r   r   HERMES_SESSION_SOURCEtuir   c                     g | ]\  }}}|	S rF   rF   )ry   r   r  s      r    r   z!delegate_task.<locals>.<listcomp>T  s    555y1a555r"   rY  rZ  c                        d          S )NFrB  rF   )rn  s   r    _batch_runnerz$delegate_task.<locals>._batch_runnere  s     *)GGGGr"   c                      D ]<} 	 t          | d          }|st          | d          rd| _        -# t          $ r Y 9w xY wd S )NzAsync delegation cancelledrm  T)r   rg  rm  r^   )_cr  _child_agentss     r    _batch_interruptz'delegate_task.<locals>._batch_interruptj  st    #  "8=Y"Z"ZK& 7727M+N+N 726/    D s   )1
>>c                  v   g } d}D ]}	 |                                 }|                    d          }|                     |                    dd          ||                    d          f           |pt          |          }}# t          $ r |                     d            Y w xY wt          |           |fS )NFr(  r)  r   r*  )r  r)   r   rB   r^   ri  )r   in_toolrx  r  _toolry  s        r    _batch_progressz&delegate_task.<locals>._batch_progresss  s     EG# ' ''!6688H$LL88ELL$LL)91==!$LL);<<   &4eGG  ' ' 'LL&&&&&'<<((s   A9BB'&B'c                     g | ]
}|d          S )r6   rF   r  s     r    r   z!delegate_task.<locals>.<listcomp>  s    ///!F)///r"   )goalsr  r  r   r   session_keyorigin_ui_session_idorigin_session_idrR  runnerinterrupt_fnrK  r7   progress_fnr   
dispatchedu   Subagent is running in the background. You and the user can keep working; its full result re-enters the conversation as a new message when it finishes. Do not wait or poll — just continue.u    subagents are running in parallel in the background. You and the user can keep working; they wait on each other and their consolidated results re-enter the conversation as a single message once ALL of them finish. Do not wait or poll — just continue.r5  r7   )r   moder   r7   r  r   c                 0    g | ]}t          |d d          S )r  Nr\   )ry   rx  s     r    r   z!delegate_task.<locals>.<listcomp>  s1       68ND11  r"   c              3   D   K   | ]}t          |t                    o|V  d S rE   )r9   r:   )ry   r  s     r    r   z delegate_task.<locals>.<genexpr>  s1      ;;:a%%+!;;;;;;r"   subagent_idszWhile a child runs you can orchestrate it live with this same tool: delegate_task(action='list') to see live children, action='steer' with subagent_id + message to redirect one, action='stop' with subagent_id to end one early.control_hintrK  zEach subagent streams a human-readable transcript of its operations to the file listed above (append-only, one per task). Read or `tail -f` these paths at any time to watch a child work while it runs.live_transcripts_hintzZdelegate_task: async pool at capacity (%s); running the whole batch synchronously instead.r"  rejecteda  The background delegation pool was at capacity (delegation.max_concurrent_children), so the subagent(s) ran SYNCHRONOUSLY and the result is included above. Raise delegation.max_concurrent_children in config.yaml to allow more concurrent background delegations.rF   )?r   r`   r  _CONTROL_ACTIONSr   rG   r<  r   r\   rY  r(   r)   DEFAULT_MAX_ITERATIONSr   r_   _resolve_delegation_credentialsr   r:   rE  r(  r9   r   rP   r  r   r  r  r4  r  r:  r   r   r  tools.delegation_live_logr<  r=  r>  tools.async_delegationr?  r  rC  r^   rt   r@  r  r{  r  r   r   r  rB   ro  tools.approvalrp  rq  infor   r   rg  rY  r  rM  any)Qr6   r  r#  r  r   r5  r6  r   r8   r   r   normalized_actiontop_roler  r}  r+   default_max_itereffective_max_itercredsrc   recovered_taskstasks_errorsingle_taskr1  r  batch_errorr:  task_schemas
raw_schemacoerced_schema
schema_errr<  r>  r?  _origin_wake_sidrC  r  r  _task_schemar  r@  r  _writerro  rp  rq  	_async_ok	_wake_sid_sync_result_session_key_source_agent_session_idrE  _ac_lockrx  rv  rz  r~  _goalsdispatchnr   r   _sids_cap_resultry  rn  rd  re  rf  r  rg  rh  ri  rj  rk  rl  r  rm  r
  r=  sQ             `                                                      @@@@@@@@@@@@@@@@r    r   r     s   D JKKK
  2,,..4466,,,%{G\
 
 	
  
.'99TvTTT
 
 	
  
N
 
 	
 t$$H @J?UU;;;;[`J L"3Q77E$&&I	%U % %(% % %
 
 	
 ..Cww/1GHH !n8H&H&H=,	
 	
 	

 *$/\BB $ $ $#c((########$ 011L#B5#I#I O[ '+&&&" % u  UE4(( Uu::$$F3u:: F F.:F F F   			 U*T3'' UDJJLL U/3QY&Z&Z$+8K( M		STTT 0./// Y'' @ @4$%% 	III4::3FIII     xx##))++ 	@>a>>>?????	@ Zt44+I66 	+k*** DCCCCC35LY'' , ,4XXo..
#i..A"5"5-:S&J%9%9*%E%E"
 	OMaMMMMNNNNNN++++N$$MG)nnG559555K          /F.E7%))G"4"4uyy?T?T/ / /+M< BAAAAA1133#;;;;;; /0F K K # # # "# 	))>?? :9 H)$$ <' <'1 )v)B(CC +,c,.?.?*?*?|ATy))#MMMMMM33NLQQN	(8   1vYY '  Gnn  21 #7 *\ #(
"3"3 #(
"3"3 "'y!1!1 #(
"3"3 ,1995H+I+I+I  %*II.A$B$B$B!" &+YYy%9%9%9#$ #())F"3"3"3%& $^'EE*  	( 	( 	( c#hh''''''''''	( #N0<-- N N NI1MMMMMN &'\):):%:%:,q//+A+A7>>, ,E( +.gl*;*;E'  	<E+];;;Au&&&&AE | | |$ |$ | | | | | | | | | | | | | | | | | | | |J  o;JJJJJJ::::::	HHHHHH0022II 	 	 	III	 	 	! )I 	!!
    !	 	@KKD   2133L,-- F V$ :l????..r:::	??????%o&=rBBG   6;;T?T " %$'lB(O(O(USU$V$V!$ 5#4L 	 	 	GGG	 	1 !$GL,$K$K$Qr R R  10$\<FF55H555
 <!344 
	|-DdKKH#   A% E E(9@@DDDE E E E E E E E E E E E E E E %5<<R@@@!   D	H 	H 	H 	H 	H
	 	 	 	 		) 	) 	) 	) 	)@ 0/Y///22 .$!6'0 )688 ('%
 
 
* <<!!\11FA 66	 
  & & &  '$!)/!: G <I  E ;;U;;;;; */' '  .2:.>.>*+2 /0 :gE::::
 	+LL*--	
 	
 	

 -,..k4(( 	:  z+E:::: :,,..UCCCCs   E 
F(F	F	FQ1 1R ?R B-W
W7W2*W72W7=X%X-,X-*[; ;\
	\
A
_   _/._/b-b:b-b
	
b-b
	b--
b:9b:r  r  c                    | st          |dd          S t          |dd          pd}t          |dd          }| dk    r	 ddlm}m}  ||          }|dS  |t          |dd                    }||dk    r
|||k    r|S  ||          }	|	|	                                r|	S n3# t
          $ r&}
t                              d	||
           Y d}
~
nd}
~
ww xY wdS || |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 )a  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.

    Custom endpoints are a special case: every direct ``delegation.base_url``
    runtime collapses to ``provider="custom"``, so bare provider equality would
    treat two *different* custom endpoints as interchangeable and let the child
    inherit the parent's pool. Leasing from that pool then overwrites the
    child's delegated ``base_url`` with the parent's endpoint (issue #7833).
    We therefore resolve custom runtimes by endpoint identity (the
    ``custom:<name>`` pool key derived from the base_url) and only share the
    parent's pool when both resolve to the *same* custom endpoint.
    rz  Nr*  r   r   r   )get_custom_provider_pool_key	load_poolr  zDCould not resolve custom credential pool for child endpoint '%s': %s)r  z:Could not load credential pool for child provider '%s': %s)r\   agent.credential_poolr  r  has_credentialsr^   r   r_   )r  r   r  parent_providerparent_poolr  r  	child_key
parent_keypoolrc   s              r    ry  ry    s   .  ?|%7>>>lJ==CO,(:DAAK
 X%%	UUUUUUUU445GHHI 
 t 65j$77 J '#x//*)++""9Y''DD$8$8$:$: 	 	 	LLV"       	 t#5#H#H
333333y+,, 4 4 6 6K 
 
 
H	
 	
 	
 	
 	
 	
 	
 	

 4s;   B& +B& "B& &
C0CC&(D 
E D;;E r+   c                    t          |                     d          pd                                          pd}t          |                     d          pd                                          pd}t          |                     d          pd                                          pd}t          |                     d          pd                                          pd}t          |                     d          pd                                                                          pd}h d}|pd                                                                }||v }	|rw|	su|}
d	d
lm} |                                }d} ||          pd}t          |          dk    r	d|v rd}d}n t          |          dk    rd}d}nd|v rd}d}|dv r|}||||
|dS |s
|dd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          }|r/d	dl
}|                    |          st          d| d | d!          |p|                    d          pd|                    d          t          k    r|n|                    d          |                    d          |
|                    d          t          |                    d"          pi           |                    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. ``delegation.api_key`` overrides the key; when
    omitted, ``api_key`` is returned as ``None`` so ``_build_child_agent``
    inherits the parent agent's key (``effective_api_key = override_api_key or
    parent_api_key``). This lets providers that store their key outside
    ``OPENAI_API_KEY`` (e.g. ``MINIMAX_API_KEY``, ``DASHSCOPE_API_KEY``) work
    without a duplicate config entry.

    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   r   Nr*  r  r%  r/  >   google-genaigooglevertexbedrockr   )_detect_api_mode_for_urlr   r2  zchatgpt.comz/backend-api/codexzopenai-codexcodex_responseszapi.anthropic.com	anthropicanthropic_messageszapi.kimi.com/coding>   r  r2  r  )r   r*  r  r%  r/  )r   r*  r  r%  r/  rS  rA  )resolve_runtime_provider)	requestedtarget_modelz$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   z' is pinned to the 'z]' command, which was not found on PATH. Install it or choose a different delegation provider.rS  rA  r  )	r   r*  r  r%  r/  rS  rA  r   r  )r:   r)   r`   r  hermes_cli.runtime_providerr  r   r  r^   r   rl  rm  _RUNTIME_PROVIDER_CUSTOMr   r   )r+   r   configured_modelconfigured_providerconfigured_base_urlconfigured_api_keyconfigured_api_mode_NATIVE_SDK_PROVIDERS_provider_lower_is_native_sdk_providerr%  r  
base_lowerr*  r/  r  r  rc   pinned_commandr  s                       r    r  r  A  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$cggj117R88>>@@FFHHPD LKK*0b7799??AAO-1FF ,
#: ,
 % 	IHHHHH(..00
++,?@@VDV122mCC$
22%H(HH2337JJJ"H+HH"j00H+H "___*H & + 
 
 	
  

 &!%!%
 
 	

HHHHHH**5HWghhh   Q3F Q Q3 Q Q Q
 

 	 kk)R((G 
N$7 N N N
 
 	
 [[++N     }}^,, 	I(; I I"I I I   "AW[[%9%9AT+2;;z+B+BF^+^+^''dkdodopzd{d{KK
++KK
++!'++.A"B"B"HbII$[[)<==;;y))W[[((.B//
 
 
s   !G5 5
H?HHc                  ~   t           j                            d          dk    } | sP	 ddlm}  |            }|                    d          pi }t          |t                    r|S n# t          $ r Y nw xY w	 ddlm	} |                    d          pi }t          |t                    r|ni S # t          $ r i cY S w xY w)a  Load delegation config from the active Hermes config.

    Prefer the shared persistent loader because it follows the active
    HERMES_HOME/profile. ``cli.CLI_CONFIG`` is a legacy fallback for entry
    points that cannot import the shared loader; importing it first can return
    an old default ``delegation`` block and hide user-set keys such as
    ``max_concurrent_children``.

    Uses ``load_config_readonly()``: every consumer of this dict is read-only
    (``.get()`` lookups), and this runs on each ``get_definitions()`` schema
    rebuild via ``_get_max_concurrent_children``, so skipping the defensive
    deepcopy matters. Do NOT mutate the returned dict.

    ``HERMES_IGNORE_USER_CONFIG=1`` (``hermes chat --ignore-user-config``) is
    only honored by the legacy ``cli`` loader, not the shared one, so when the
    flag is set we keep ``cli.CLI_CONFIG`` authoritative to preserve the
    flag's contract of suppressing user config.yaml settings.
    HERMES_IGNORE_USER_CONFIGr\  r   )load_config_readonlyr  )
CLI_CONFIG)
rB  environr)   hermes_cli.configr  r9   r   r^   clir  )prefer_legacyr  fullr+   r  s        r    r(   r(     s   & JNN#>??3FM 		>>>>>>''))D((<((.BC#t$$ 
 	 	 	D	""""""nn\**0b d++3ss3   			s#   =A& &
A32A375B- -B<;B<c                      	 dS )a  Compose the delegate_task tool description.

    Deliberately carries ONLY guidance that exists nowhere else in the
    schema. Batch/concurrency limits live in the 'tasks' parameter
    description and the nesting clause lives in the 'role' parameter
    description (both rebuilt per get_definitions() call with the user's
    actual delegation.max_concurrent_children / max_spawn_depth), so the
    top-level text stays static and duplication-free. If you add text
    here, check it is not already stated in a parameter description.
    u  Spawn subagents in isolated contexts; each gets its own conversation, terminal session, and toolset, and only its final summary returns to you. Provide 'goal' for a single task or 'tasks' for a parallel batch (limits and nesting rules are in the parameter descriptions).

Runs in the background: dispatch returns immediately with live transcript paths, and the completed result (one consolidated message for a batch) re-enters the conversation on its own. Do NOT wait or poll; continue other work.

LIVE ORCHESTRATION: while children run, this tool also controls them — action='list' (live children + ids), action='steer' (subagent_id + message, redirect without stopping), action='stop' (subagent_id, end early; partial result still returns). Steer when a live transcript shows a child drifting.

USE FOR: reasoning-heavy subtasks, work that would flood your context with intermediate data, or independent parallel workstreams.
DO NOT USE FOR (use these instead):
- Mechanical multi-step work with no reasoning needed -> execute_code
- A single tool call -> call the tool directly
- Tasks needing user interaction -> subagents cannot ask questions
- Durable work that must survive this session -> cronjob or terminal(background=True, notify_on_complete=True); /stop, /new, or process exit discards running subagents.

RULES:
- Children know nothing of this conversation: pass everything needed via 'context', including any required output language, tone, or style (e.g. "respond in Chinese").
- Child summaries are SELF-REPORTS, not verified facts: a child claiming "uploaded successfully" or "file written" may be wrong. For external side effects (uploads, remote writes, publishing), require a verifiable handle (URL, ID, absolute path) and verify it yourself — fetch the URL, stat the file, read back the content — before telling the user the operation succeeded.
- Leaf children (the default) cannot call delegate_task, clarify, memory, send_message, or cronjob; orchestrators regain only delegate_task.
- Children inherit the parent model and fallback chain unless pinned globally via delegation.provider / delegation.model in config.yaml. Results are returned as an array, one entry per task.rF   rF   r"   r    _build_top_level_descriptionr    s    %	@' 'r"   c                  \    	 t                      } n# t          $ r
 t          } Y nw xY wd|  dS )zICompose the 'tasks' parameter description with current concurrency limit.z,Batch mode: tasks to run in parallel (up to z for this user, set via delegation.max_concurrent_children). Each gets its own subagent with isolated context and terminal session. When provided, top-level goal/context/role are ignored.)rE  r^   rA  )rj  s    r    _build_tasks_param_descriptionr  0  sW    8355 8 8 878	B| 	B 	B 	Bs    %%c                      	 t                      } n# t          $ r
 t          } Y nw xY w	 t                      }n# t          $ r d}Y nw xY w| dk    r|rd|  d| dz
   d}n| dk    r|sd}nd|  d	}d
| S )zHCompose the 'role' parameter description with current spawn-depth limit.Tr  z2Nesting IS enabled for this user (max_spawn_depth=z7): orchestrator children can themselves delegate up to r/   z more level(s) deep.zsNesting is currently disabled (delegation.orchestrator_enabled=false); 'orchestrator' is silently forced to 'leaf'.z.Nesting is OFF for this user (max_spawn_depth=zj); 'orchestrator' is silently forced to 'leaf'. Raise delegation.max_spawn_depth in config.yaml to enable.zRole of the child agent. 'leaf' (default) = focused worker, cannot delegate further. 'orchestrator' = can use delegate_task to spawn its own workers. )rY  r^   rU  r`  )	max_depthorchestrator_onnesting_notes      r    _build_role_param_descriptionr  >  s    (**		   			355    A~~/~" " "CLq=" " " 	
 
a) 	CY C C C 		F7C	F 	Fs    %%8 AAc                     i t           d         } d t           d         d                                         D             | d<   t                      | d         d         d<   t                      | d         d         d<   t	                      | dS )zReturn per-call schema overrides reflecting current config.

    Plugged into ToolEntry.dynamic_schema_overrides so every
    get_definitions() pass rewrites the description fields to the user's
    actual limits.
    
parametersc                 4    i | ]\  }}|t          |          S rF   )r   rx   s      r    r|   z3_build_dynamic_schema_overrides.<locals>.<dictcomp>n  s1     & & &q!477& & &r"   
propertiesr#  r   r   )r   r  )DELEGATE_TASK_SCHEMAr}   r  r  r  )overrides_paramss    r    _build_dynamic_schema_overridesr  c  s    
|
,& &3LA,OUUWW& & &\" >\=]=]\"7+M:<Y<[<[\"6*=9 455&  r"   r   zSpawn one or more subagents in isolated contexts. Description is rebuilt at every get_definitions() call to reflect the user's current delegation limits.objectstringzWhat the subagent should accomplish. Be specific and self-contained -- the subagent knows nothing about your conversation history.)r  r   zBackground information the subagent needs: file paths, error messages, project structure, constraints. The more specific you are, the better the subagent performs.arrayz	Task goalzTask-specific contextr:  z;Per-task role override. See top-level 'role' for semantics.)r  enumr   aM  Optional JSON Schema the subagent's final answer must validate against. The child is told the contract up front; the parent validates the final answer and allows one bounded correction retry. The result entry gains schema_valid (and schema_errors on final failure). Keep schemas forgiving: require only fields you will actually read.)r6   r  r   r6  )r  r  requiredz#(rebuilt at get_definitions() time))r  r}   r   u   Optional JSON Schema for the single-goal form — the subagent's final answer must validate against it (same semantics as tasks[].output_schema).booleanum  DEPRECATED / IGNORED. Top-level single and batch delegations run in the background automatically — you do not need to (and cannot) opt in or out. A single result or consolidated batch result re-enters the conversation when the work finishes; just continue working in the meantime. Setting this has no effect; the parameter remains only for backward compatibility.)r8  r   rn   r   u  Default 'spawn' (omit for normal delegation). Live orchestration of running subagents: 'list' shows this conversation's live children (ids, goals, status, transcript paths); 'steer' queues course-correction text into one child (requires subagent_id + message) without stopping it; 'stop' ends one child early (requires subagent_id) — its partial result still returns as a completion message. Control actions return immediately; goal/tasks are ignored when action is not 'spawn'.zvTarget for action='steer'/'stop'. Ids are returned in the spawn dispatch response (subagent_ids) and by action='list'.u   For action='steer': the course correction. Be directive and specific — the child sees it appended to its next tool result mid-run (e.g. "Stop exploring X; focus on Y and return early results").)	r6   r  r#  r   r6  r5  r   r8   r   )r   r   r  )rf  r   r  c                 2    t          |dd          dk    }| S )u  Background flag for the MODEL-facing dispatch path (registry fallback).

    Delegations from the top-level agent always run in the background — the
    model does not choose. This applies to both a single task and a fan-out
    batch (the whole batch is one async unit that joins on all children and
    returns one consolidated result). The one
    exception is a delegation from an orchestrator subagent (depth > 0), which
    needs its workers' results within its own turn. The live path is
    ``run_agent._dispatch_delegate_task``; this lambda mirrors it for the rare
    case the intercept is bypassed. Direct Python callers of ``delegate_task``
    keep the historical synchronous default.
    r  r   r  )r  r   is_subagents      r    _model_background_valuer    s#     ,(91==AK?r"   r0  r1  c                 N   t          | t                    s| S g }d}| D ]}t          |t                    s|                    |           -d |                                D             }|pt          |          t          |          k    }|                    |           |r|n| S )NFc                 ,    i | ]\  }}|t           v||S rF   )_MODEL_HIDDEN_TASK_FIELDS)ry   r   r   s      r    r|   z3_strip_model_hidden_task_fields.<locals>.<dictcomp>   s4     
 
 
U333 333r"   )r9   r   r   r   r}   rP   )r#  stripped_taskschangedr  strippeds        r    _strip_model_hidden_task_fieldsr    s    eT"" NG 
( 
($%% 	!!$'''
 
"jjll
 
 

 7S]]c$ii7h''''$/>>%/r"   r  c                    t          |                     d          |                     d          t          |                     d                    |                     d          |                     d          t          | |                    d                    |                     d          |                     d          |                     d	          |                     d
          |                    d                    S )Nr6   r  r#  r  r   r   r6  r   r8   r   )r6   r  r#  r  r   r5  r6  r   r8   r   r   )r   r)   r  r  )r  r  s     r    rI  rI  .  s    }XXf##-dhhw.?.?@@xx 011XXf*41G1GHHhh//xx!!HH]++##VVN++      r"   u   🔀)r   toolsetschemahandlercheck_fnr  dynamic_schema_overrides)r   rE   )r/   )	NNNNNNNNr9  rq   )NNNNNNNNNNN)r  r  r  r   r  re	getLoggerr  r   rB  r  r   rx  rM  r   r  typingr   r   r   r   urllib.parser   r	   r  r
   agent.interrupt_compatr   r  rm  r   r  r   r  utilsr   r   r  r  r:   r!   r%   r-   rA  r@  rU  rV  LockrA   r0   rB   __annotations__r;   r1   rQ   r3   r>   rC   rG   rM   rU   rY   rd   rg   ro   ri  rt   r   r   r   r  r   r   r   r   r   r  r   r   r  r  r-  r   r<  rE  rI  rL  rM  r   rR  rY  r`  rd  rj  rn  rw  r|  r  r  r  r  rQ  r-  r/  r.  rh  Enumr  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(  compile
IGNORECASEr+  r-  r0  r4  r   ry  r   r  r(   r  r  r  r  r  rg  rf  r   r  r  r  registerrF   r"   r    <module>r     s    $        						8	$	$ 				            - , , , , , , , , , , , - - - - - - - -       9 9 9 9 9 9
 $        R R R R R R 4 4 4 4 4 4 4 4 #    8 3 S    
C 
c 
 
 
 
 
  " $&   ! 	   #IN$$ t   '))  02 4T#s(^+, 1 1 1  /1 4T#s(^+, 1 1 1hsm c3h8P    :	T 	d 	 	 	 	    
(tCH~ ($ ( ( ( (CDcN Ct C C C C <@ , , ,c ,S ,D , , , ,Q# Qc Qhsm Q Q Q Q0C D    8 '+ $- - --
- sm	-
 - - 
- - - -`sm
38_   $
tDcN3 
 
 
 
0 3 c S QU    . 966677 # c c    (%$sCx. % % % % % %PtVtV#tV c]tV 	tV
 	tV tV tV tVt 	4 4 4cN4 4 	4
 
$sCx.4 4 4 4nS S    8 $) % % %     !y!<!<!<== s 3 3    >7 7c3h 7 7 7 7.A# A$sCx. A A A A, d38n9M    <!c !d ! ! ! !Hx}     "&,c &, &, &, &,R6 6 6 6 6 ! * * * * *6'!HUO '! '! '! '!T$c $ $ $ $N4    "J4 J J J J;s ;t ; ; ; ;S S    >I03C	#Y      " 
 !    *. x - - -   " "$ ... 4 4 4 4 4C 4 4 40 ,(6!3#7&4/ / 4]*+   T     "K %)K K K
Kc]K SM	K
 K K K 	K K K K\Xc]    6C49 Cc C C C C*S T#Y    *S T    , 	G "&#$(,0G G GG
G 	G #G }G C=G C=G tCy!G $sCx.)G hG G G GT03 03 0 0 0 0%hsm %PXY\P] % % % %X (,'+&*'+;?)-*.-1 -i ii
i c]i tCy!	i
 C=i i i  }i  }i smi  }i !)c3h 8i "#i" #3-#i$  S	*%i, -i i i iXmm m 	m
 m I,-m m c]m m m m`s S Xc]    <4"4"4"(+4"
34" 4" 4" 4"n%3 %8C= % % % %P4
4S#X#7 4
$ 4
 4
 4
 4
t 	iQ '+ $iQ iQ iQiQ
iQ smiQ iQ iQ 
#s(^iQ iQ iQ iQX #1)."2"2 %4Y_%6%6 "*9?,,   y    $UK$sCx.!UKDcN#UK 5d38nc123UK
 
UK UK UK UKv 	 

 
#s(^   &
8Dc3h()8C=89   B "rz"8"-HH  bj7    +T$sCx.%9 +hsm + + + +^ !,0$(!%.2 !%!\D \D
3-\Dc]\D Dc3h()\D SM	\D
 3-\D \D DcN+\D SM\D #\D c]\D 	\D \D \D \DD )-R R R !R R R RjK K K K K K\$d $ $ $ $X2c 2 2 2 2j    "s " " " "J    0 	0
  !,  !J   $)1+ N N$,+B$ $
 %-%+^$<+h! ! %-!N* *# #2 "(7 @  EE# #J !0D  !A  ".  !:::I	   !%  !3 Kn
 n
^ cr rB B L 0 / / / / / / / $ d    " +J7 03 03 0 0 0 0&  	  )
<'     r"   