
    epjBu                   F   d Z ddlmZ ddlZddlZddlmZ ddlZddl	Z	ddl
Z
ddlZddlZddlmZ ddlmZmZ ddlmZmZmZmZmZmZmZ ddlm Z m!Z!m"Z"m#Z#m$Z$m%Z% dd	l&m'Z' dd
l(m)Z) ddl*m+Z+m,Z, ddl-m.Z.m/Z/m0Z0  ej1        e2          Z3d[dZ4d\dZ5dZ6dZ7dZ8d]dZ9d^dZ:d_d$Z;d`d&Z<d`d'Z=d( Z>dad+Z?dddddd,dbd6Z@dcddd9ZAd7d:dd;ded>ZBdfd@ZCe G dA dB                      ZD G dC dD          ZEdgdGZFddddddHdhdOZGdidQZHdjdRdSdkdVZIdldWZJdjdRdSdkdXZKdmdndYZLg dZZMdS )ou  Tool-call execution — sequential and concurrent dispatch.

Both AIAgent methods (``_execute_tool_calls_sequential`` and
``_execute_tool_calls_concurrent``) live here as module-level
functions that take the parent ``AIAgent`` as their first argument.

``run_agent`` keeps thin wrappers so existing call sites work; tests
that patch ``run_agent._set_interrupt`` are honored because the
extracted functions reach back through the ``run_agent`` module via
``_ra()`` for that symbol.
    )annotationsN)Path)	dataclass)AnyOptional)KawaiiSpinnerbuild_tool_previewbuild_tool_labelget_cute_tool_messageget_tool_emojiredact_tool_args_for_display_detect_tool_failure)_is_destructive_command_is_multimodal_tool_result_multimodal_text_summary!_append_subdir_hint_to_multimodal_plan_tool_batch_segmentsmake_tool_result_message)get_active_env)propagate_context_to_thread)maybe_persist_tool_resultenforce_turn_budget)BudgetConfigDEFAULT_BUDGETbudget_for_context_windowfunction_namestrfunction_argsdicteffective_task_idreturnNonec                    |                     dd          }|sdS ddlm}  |||pd          }| j                            t          |                    }| j                            |d|            dS )zBCheckpoint the same workspace path that the file tool will mutate.path Nr   )_resolve_path_for_taskdefaultzbefore )gettools.file_toolsr&   _checkpoint_mgrget_working_dir_for_pathr   ensure_checkpoint)agentr   r   r    	file_pathr&   resolved_pathwork_dirs           9/home/thesage/.hermes/hermes-agent/agent/tool_executor.py_ensure_file_checkpointr2   8   s     !!&"--I  877777**96G6T9UUM$==c->P>PQQH	++H6O6O6OPPPPP    r   c                    	 t          t          | dd          dd          }|rt          t          |                    nt          S # t          $ r
 t          cY S w xY w)a  Resolve a tool-result BudgetConfig scaled to the agent's context window.

    Large-context models keep the historical 100K/200K char defaults; small
    models (e.g. a 65K-token local model switched into mid-session) get a budget
    proportional to their window so a single large tool result can't push the
    request past the model's limit (#23767). Falls back to the default budget
    when the context length isn't resolvable.
    context_compressorNcontext_length)getattrr   intr   	Exception)r-   ctxs     r1   _budget_for_agentr;   N   sm    ge%94@@BRTXYY69M(S222~M   s   AA AA      g     @z@raw_argumentsr   tuple[dict, Optional[str]]c                    	 t          j        |           }n# t           j        t          f$ r d}Y nw xY wt	          |t
                    r|dfS i t          j        dddd          fS )zAParse model-emitted arguments without repairing or coercing them.NzInvalid tool argumentszBTool arguments must be a valid JSON object; tool was not executed.)errormessageFensure_ascii)jsonloadsJSONDecodeError	TypeError
isinstancer   dumps)r>   	argumentss     r1   _parse_tool_argumentsrL   f   s    J}--		 ),   			)T"" $tz-T	
 	
     s    22float | Nonec                    t          j        dd                                          } | st          S 	 t	          |           }n8# t
          $ r+ t                              d| t                     t          cY S w xY w|dk    rd S |S )N HERMES_CONCURRENT_TOOL_TIMEOUT_Sr%   z8invalid HERMES_CONCURRENT_TOOL_TIMEOUT_S=%r; using %.0fsr   )osgetenvstrip"_DEFAULT_CONCURRENT_TOOL_TIMEOUT_Sfloat
ValueErrorloggerwarning)rawvalues     r1    _resolve_concurrent_tool_timeoutrZ   y   s    
)6
;
;
A
A
C
CC 2112c

 2 2 2F.	
 	
 	

 21112 zztLs   A 2A76A7messagesliststageboolc                   	 |                      |          du}|sd| _        |S # t          $ r.}d| _        t                              d||           Y d}~dS d}~ww xY w)aa  Flush tool-call progress before projecting it to any UI surface.

    Tool execution can perform side effects that terminate or restart the
    current Hermes process before the normal turn-end persistence path runs.
    Flush the already-appended assistant/tool messages immediately so the
    transcript survives destructive-but-valid tool calls.
    FTz5Incremental tool-call persistence failed after %s: %sN)_flush_messages_to_session_db_incremental_persistence_failedr9   rV   rW   )r-   r[   r]   	persistedexcs        r1   %_flush_session_db_after_tool_progressrd      s    77AAN	 	948E1   04-NPUWZ[[[uuuuus   !$ 
A#AAr8   c                    	 ddl m}   |             pi }t          |t                    r|                    d          nd}t          |t                    r|                    d          nd}n# t
          $ r d}Y nw xY w	 t          |          }n# t          t          f$ r
 t          }Y nw xY wt          dt          |t                              S )a&  Return the configured image-generation parallelism cap.

    Image-generation calls are slow enough that concurrent execution is useful,
    but backend bursts can hit TTFB or rate-limit failures. Keep the default
    intentionally conservative while allowing users to tune it per install.
    r   )load_config	image_genNmax_parallel_requests   )hermes_cli.configrf   rI   r   r(   r9   r8   rH   rU    _DEFAULT_IMAGE_PARALLEL_REQUESTSmaxmin_MAX_TOOL_WORKERS)rf   cfgrg   rY   limits        r1   _image_generate_parallel_limitrq      s    111111kmm!r,6sD,A,AKCGGK(((t	 )T**IMM1222 	
    1E

z" 1 1 101q#e.//000s$   A*A- -A<;A< B B+*B+c                    | sdS t           }t          d | D                       rt          |t                                }t          t	          |           |          S )z2Return the worker cap for a concurrent tool batch.r   c              3  X   K   | ]%}t          |          d k    r|d         nddk    V  &dS )      Nimage_generate)len).0calls     r1   	<genexpr>z._max_workers_for_tool_batch.<locals>.<genexpr>   sR         IINNa1AA     r3   )rn   anyrm   rq   rw   )runnable_callsmax_workerss     r1   _max_workers_for_tool_batchr~      ss     q#K
  "     I +'E'G'GHHs>""K000r3   c                     ddl } | S )zRLazy reference to ``run_agent`` so patches like ``run_agent._set_interrupt`` work.r   N	run_agentr   s    r1   _rar      s    r3   rc   RuntimeErrorc                $    dt          |           v S )Nz6cannot schedule new futures after interpreter shutdown)r   )rc   s    r1   %_is_interpreter_shutdown_submit_errorr      s    Cs3xxOOr3   )duration_msstatus
error_typeerror_messagemiddleware_traceresulttool_call_idr   r   
str | Noner   r   r   Optional[list[dict[str, Any]]]c       
            	 ddl m}  |||||pdt          | dd          pd|pdt          | dd          pdt          | dd          pd||||	t          |
pg                      d S # t          $ r Y d S w xY w)Nr   )_emit_post_tool_call_hookr%   
session_id_current_turn_id_current_api_request_id)r   r   r   task_idr   r   turn_idapi_request_idr   r   r   r   r   )model_toolsr   r7   r\   r9   )r-   r   r   r   r    r   r   r   r   r   r   r   s               r1   _emit_terminal_post_tool_callr      s    999999!!''%+ulB77=2%+E#5r::@b"5*CRHHNB#!'!"2"8b99	
 	
 	
 	
 	
 	
    s   A$A( (
A65A6user interruptreasonc                :    t          j        d|  ddd          S )NTool execution cancelled by 	cancelled)rA   r   FrC   )rE   rJ   r   s    r1   _cancelled_tool_resultr      s8    :<F<<!	
 	
    r3   keyboard_interrupt)r   r   r   
start_timerT   c                   t          |          }	t          | |||	||t          t          j                    |z
  dz            d|d| t	          |pg                      |	S )N  r   r   )
r   r   r   r    r   r   r   r   r   r   )r   r   r8   timer\   )
r-   r   r   r    r   r   r   r   r   r   s
             r1   '_emit_cancelled_terminal_post_tool_callr     s~     $F++F!##+!z1T9::=V==.4"55    Mr3   	frozensetc                :   	 ddl }ddlm} ddlm} n# t
          $ r t                      cY S w xY wt          | dd          }t          | dd          }t          |dd          |t          |          nd|t          |          ndf}t          | dd          }||d         |k    r|d	         S 	 |                    ||d
d
          pg }|	                    |          }	n# t
          $ r t                      }	Y nw xY w	 ||	f| _
        n# t
          $ r Y nw xY w|	S )a  Return the deferrable tool names the session may invoke via tool_call.

    The Tool Search unwrap dispatches the underlying tool directly, bypassing
    the bridge branch (and its scope check) in
    ``model_tools.handle_function_call``. To keep a restricted-toolset session
    (subagent, kanban worker, curated gateway session) from reaching tools it
    was never granted, the unwrap validates the underlying name against this
    set: the deferrable subset of the session's own enabled/disabled toolset
    scope.

    Result is cached on the agent and refreshed when the tool registry's
    generation changes (e.g. an MCP server reconnects), so the common case is
    a dict lookup, not a full tool-defs rebuild on every tool call.
    r   Ntool_search)registryenabled_toolsetsdisabled_toolsets_generation_tool_search_scope_cacheri   T)r   r   
quiet_modeskip_tool_search_assembly)r   toolsr   tools.registryr   r9   r   r7   get_tool_definitionsscoped_deferrable_namesr   )
r-   r   _ts	_registryenableddisabled	cache_keycachedscoped_defsnamess
             r1   _tool_search_scoped_namesr     s   ,,,,,,8888888   {{ e/66Gu1488H	=!,,%1	't'3	(I
 U6==FfQi944ay	!66$&&*	 7 
 
 
  	 ++K88   *3U);&&   Ls0    ..10C" "C=<C=	D 
DDc                  8    e Zd ZU ded<   ded<   ded<   ded<   d	S )
_ManagedToolResultr   r   dict[str, Any]argszlist[dict[str, Any]]r   r^   blockedN)__name__
__module____qualname____annotations__ r3   r1   r   r   P  s:         KKK****MMMMMr3   r   c                  (    e Zd ZdZd	dZd Zd
dZdS ) _ConcurrentToolAuthorizationGatezFSerialize policy prompts and exclude their queue from batch deadlines.r!   r"   c                    t          j                    | _        t          j                    | _        d| _        d | _        d| _        d S )Nr           )	threadingLock_serialization_lock_state_lock_pending_window_started_excluded_seconds)selfs    r1   __init__z)_ConcurrentToolAuthorizationGate.__init__[  s?    #,>#3#3 $>++-1!$r3   c           
        t          j                    }| j        5  | j        dk    r|| _        | xj        dz  c_        d d d            n# 1 swxY w Y   	 | j        5   |            cd d d            t          j                    }| j        5  | xj        dz  c_        | j        dk    r4| j        &| xj        t          d|| j        z
            z  c_        d | _        d d d            S # 1 swxY w Y   S # 1 swxY w Y   	 t          j                    }| j        5  | xj        dz  c_        | j        dk    r4| j        &| xj        t          d|| j        z
            z  c_        d | _        d d d            d S # 1 swxY w Y   d S # t          j                    }| j        5  | xj        dz  c_        | j        dk    r4| j        &| xj        t          d|| j        z
            z  c_        d | _        d d d            w # 1 swxY w Y   w xY w)Nr   ri   r   )r   	monotonicr   r   r   r   r   rl   )r   callbacknows      r1   runz$_ConcurrentToolAuthorizationGate.runb  s~   n 	 	}!!'*$MMQMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 		0) " "xzz" " " " " " " .""C! 0 0"=A%%+7..#t';!;3 3 .. ,0D(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0	" " " " " " " " " .""C! 0 0"=A%%+7..#t';!;3 3 .. ,0D(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .""C! 0 0"=A%%+7..#t';!;3 3 .. ,0D(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0s   #A

AAF 
C5'F AC))C-	0C-	5C99F <C9=F AE88E<?E<H AG<0H<H  HH HrT   c                    t          j                    }| j        5  | j        }| j        |t          d|| j        z
            z  }|cddd           S # 1 swxY w Y   dS )z?Return completed plus currently active authorization wait time.Nr   )r   r   r   r   r   rl   )r   r   excludeds      r1   excluded_secondsz1_ConcurrentToolAuthorizationGate.excluded_secondsv  s    n 	 	-H#/CS4+?%?@@@		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   +AAANr!   r"   )r!   rT   )r   r   r   __doc__r   r   r   r   r3   r1   r   r   X  sQ        PP% % % %0 0 0(     r3   r   outcome6tuple[Any, dict[str, Any], list[dict[str, Any]], bool]c                6    | j         | j        | j        | j        fS Nr   r   r   r   )r   s    r1   _managed_valuesr     s#     	 	 r3   )scope_blockdisplay_indexr   begin_executionauthorization_gater   r   
int | Nonelist[dict[str, Any]] | Noner   '_ConcurrentToolAuthorizationGate | Nonec       
           	
 ddl m} ddlmm ||ng dddt          j                    d 
	fdd f	d}|                    |t          t           dd          pd          pdt           dd          pdt           dd          pdpdd          \  }}t          |d         d         t          d                             S )zBRun Relay rewrites before Hermes policy and dispatch exactly once.r   )relay_tools)apply_tool_request_middlewarerun_tool_execution_middlewareNF)r   r   r   
dispatched
final_argsr   r!   r   c                    5  d         rt          d          dd<   dd<    d<   d d d            n# 1 swxY w Y   d
 fd	}ddfd
}}d}|-d}
 fd}
 |            n                    |          }d }|$
j                                       }|j        rd }|| |             dd<   |t          j        d|id          }|}|}	n*
                    |          }d}t          |dd           pd}	t          
 |d||	t          d                   
  
         |S dk    rd
_        ndk    rd
_         ||                       S )Nr   z5Hermes tool execution callback invoked more than onceTFr   r   r!   r"   c                 2    t                      d S )N)r   r   r    r   r   )_begin_tool_execution)r-   r   r    r   r   r   s   r1   _beginzR_run_agent_tool_execution_middleware.<locals>._authorized_dispatch.<locals>._begin  s6    !+("3)+     r3   c                >    | 
 |              d S  |            d S r   r   )r   r   s    r1   _advance_start_orderz`_run_agent_tool_execution_middleware.<locals>._authorized_dispatch.<locals>._advance_start_order  s5    &'HJJJOH%%%%%r3   tool_scope_blockplugin_blockc                     	 ddl m}   | pdt          dd          pdpdt          dd          pdt          dd          pdt          d                             S # t          $ r Y d S w xY w)	Nr   )resolve_pre_tool_blockr%   r   r   r   r   )r   r   r   r   r   r   )hermes_cli.pluginsr   r7   r\   r9   )r   r-   r    r   r   stater   s    r1   _resolve_pre_tool_blockzc_run_agent_tool_execution_middleware.<locals>._authorized_dispatch.<locals>._resolve_pre_tool_block  s     IIIIII11%" 1 7R#*5,#C#C#Ir%1%7R '/A2 F F L"'.u6OQS'T'T ()-e4F.G)H)H
 
 
 
 !      44 s   A"A& &
A43A4rA   rC   guardrail_blockrB   z Tool blocked by guardrail policyr   	r   r   r   r    r   r   r   r   r   memoryr   skill_manager   r   )r   r   _tool_guardrailsbefore_callallows_executionrE   rJ   _guardrail_block_resultr7   r   r\   _turns_since_memory_iters_since_skill)r   r   r   block_messageblock_error_typer   guardrail_decisionr   r   r   r-   r   r   dispatch_lockr   r    executer   r   r   r   s   `         r1   _authorized_dispatchzB_run_agent_tool_execution_middleware.<locals>._authorized_dispatch  s    	' 	'\" "K   #'E,$E)&E&M	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	'	 	 	 	 	 	 	 	 	 	 		& 	& 	& 	& 	& 	& 	& $- -                   ( &- (')))'++,CDD  " !&!7!C!Cz" " "2 *%)"$(:(F  """#E)(Wm$<5QQQ-
 -667IJJ.
.	4@@ :9  *+("3) %+!%e,>&?!@!@    MH$$()E%%n,,'(E$V$$$wz"""s   '8<<
relay_argsc                  	  | dpdt          dd          pd
pdt          dd          pdt          dd          pd          }t          |j        t                    r|j        n|                                                      |j                    	fdpdt          dd          pd
pdt          dd          pdt          dd          pd	  	        S )	NTr%   r   r   r   )
skip_relayr   r   r   r   r   c                H     t          | t                    r| n          S r   )rI   r   )	next_argsr  request_argss    r1   <lambda>zP_run_agent_tool_execution_middleware.<locals>._hermes_pipeline.<locals>.<lambda>"  s+    22'	488J		l  r3   )original_argsr   r   r   r   r   )r7   rI   payloadr   clearextendtrace)r  request_resultr  r  r-   r   r    r   r   r   r   r  s     @r1   _hermes_pipelinez>_run_agent_tool_execution_middleware.<locals>._hermes_pipeline  sI   66%+ulB77=2%+E#5r::@b"5*CRHHNB	
 	
 	
 .0$77N"" 	
 	^)***,,     (%+ulB77=2%+E#5r::@b"5*CRHHNB
 
 
 	
r3   r   r%   r   r   )r   r   r   r   )r   metadatar   r   r   r   )r   r   r!   r   )r  r   r!   r   )r-   r   hermes_cli.middlewarer   r   r   r   r  r   r7   r   r^   )r-   r   r   r    r   r  r   r   r   r   r   r   r  r   _relay_argsr  r   r  r   r   r  s   ```````` ``    @@@@@@r1   $_run_agent_tool_execution_middlewarer     s    "!!!!!       
 !1 <"E!	 E N$$Mb# b# b# b# b# b# b# b# b# b# b# b# b# b# b# b#H
 
 
 
 
 
 
 
 
 
 
 
 
 
@ &--wulB77=2>>(.Bu&8"==C%e-FKKQr(.B	
 
 .  FK 6]12U9%&&	   r3   r   c               P   | j         s%t          | dd          dk    rt          ||          p|}t          j        |d          }|d| nd}| j        rqt          d	| d
| dt          |                                           d           t          | 	                    dt          j        |dd                               nft          |          | j        k    r|d| j                 dz   n|}	t          d	| d
| dt          |                                           d|	            || _        |                     d|            	 ddlm}
  |
| j                   n# t           $ r Y nw xY w| j        rh	 t          ||          p|}t%          ||          }|                     d|||           n,# t           $ r}t'          j        d|           Y d}~nd}~ww xY w| j        rW	 t          ||          p|}|                     |||           n,# t           $ r}t'          j        d|           Y d}~nd}~ww xY w|dv r0| j        j        r$	 t1          | |||           n# t           $ r Y nw xY w|dk    r| j        j        r	 |                    dd          }t5          |          rc|                    d          p%t7          j        dt7          j                              }| j                            |d|dd                     dS dS # t           $ r Y dS w xY wdS dS ) zBRun user-visible and checkpoint preflight on final tool arguments.tool_progress_modealloffFrC   NzTool Toolu     📞 z: ()zArgs: ru   )indentrD   ...z) - zexecuting tool: r   set_activity_callbackztool.started Tool progress callback error: %szTool start callback error: %s>   patch
write_fileterminalcommandr%   workdirTERMINAL_CWDzbefore terminal: <   )r   r7   _redact_tool_args_for_displayrE   rJ   verbose_loggingprintr\   keys_wrap_verboserw   log_prefix_chars_current_tool_touch_activitytools.environments.baser+  r9   tool_progress_callback_build_tool_previewloggingdebugtool_start_callbackr*   r   r2   r(   r   rP   rQ   getcwdr,   )r-   r   r   r    r   r   display_argsargs_strprefixargs_previewr+  previewcallback_errorr0  cwds                  r1   r   r   A  s     /CU K Ku T T)-GGX= 	 :l???,9,E((((6  	RFRRmRRd<;L;L;N;N6O6ORRRSSS##djaeTTT     x==5#999 15112U:: 
 "& " "M " "D9K9K9M9M4N4N " "" "  
 (E	<]<<===AAAAAAe34444    # N
	N-m]KK !   *-FFG((w     	N 	N 	NM<nMMMMMMMM	N   
K		K-m]KK !   %%m\     	K 	K 	KM9>JJJJJJJJ	K ///E4I4Q/	#!	     	 	 	D	 
""u'<'D"
	#''	266G&w// #''	22 bi"BIKK7 7 %77;WSbS\;;    	   	 	 	DD	 #"""sg   E% %
E21E2=:F8 8
G!GG!,)H 
H? H::H?I& &
I32I3	BL 
L! L!Tfinalizeapi_call_countrK  c                  VWXYZ[\ |j         }t          |          }t                     } j        rt	           j         d| d           |D ]d}	                    t          |	j        j	        d|	j        j	         d|	j
        d                     t           d|	j        j	                    ed	S g Z|D ]}
|
j        j	        }t          |
j        j                  \  }}|Z                    |
||g |d	f           Hd	}	 d
dlm} ||j        k    rT|                    |          \  }}}|s9|r7|t%                     v r |                    ||          }||}n|}|}nd| d}n# t(          $ r Y nw xY wZ                    |
||g d	|f           d                    d ZD                       } j        s*t/           dd          dk    rt	          d| d|            d	g|z  [t1          Z          D ]\  }\  }	}}}}}||||ddd|f[|<   t3          j                    \d
Yt7                      WdtduY\fdV| _                             d| d|            V W[fd}d	}                                 rj                                 rVtA          j!        tE          j#                              }tE          | d| d d! j$        "          }|%                                 	 d# t1          Z          D             }g }i XtM                      } tO                      }!|!tQ          j)                    |!z   nd	}"|r1tU          |          }#d
d$l+m,}$  |$|#%          }%d&}&	 t1          |          D ]\  }'\  }}	}}}(	 |%-                    t]          |          ||	||Z|         d'         |(|'          })n# t^          $ r}*ta          |*          s ||'d	         }+tb          2                    d(t          |+                     |+D ]0\  },}-}.}/}[|,          Z|,         d'         }d)|. d*}0|.|/|0ddd&|f[|,<   1Y d	}*~* n#d	}*~*ww xY w|                    |)           |X|)<   tQ          j(                    }1d&}2	 d+}3|"|"W3                                z   }4|4tQ          j)                    z
  }5|5d
k    rtM                      d, |D             }7}6nYti          |3|5          }3tj          j6        7                    ||3-          \  }6}7n$tj          j6        7                    ||3-          \  }6}7|7sn|"tQ          j)                    |"W3                                z   k    rd}&Xfd.|7D             } Zfd/| D             }8tb          2                    d0|!t          |           d                    |8d	d1                              |7D ]})|)8                                  j9        5  tu           j;                  }9d	d	d	           n# 1 swxY w Y   |9D ]5}:	 ty                      =                    d|:           &# t(          $ r Y 2w xY wn j        rpd}&|2s1d}2 >                     j         d2t          |7           d3d4           |7D ]})|)8                                 tj          j6        7                    |7d5-           nt          tQ          j(                    |1z
            };|;d
k    r_|;d6z  d7k     rVXZfd8|7D             }8                     d9|; d:t          |7           d;d                    |8d	d'                    d<           |%@                    |& |&=           n# |%@                    |& |&=           w xY w|rRt          d> [D                       }<t          d? [D                       }=|B                    d@|< dA| dB|=dCdD           nZ# |rSt          d> [D                       }<t          d? [D                       }=|B                    d@|< dA| dB|=dCdD           w w xY wt1          Z          D ]G\  }\  }	}}}}>}[|         }?d&}@d}A|}Bd	}C|| v r`|?^|!|!dCdEndF}Dd)| dG|D }EdH}Ct           |||Et/          |	dIdJ          pdJdKdL|Etu          |          M
  
         t          |!pd          }Fn|? j        r>d| d}Et           |||Et/          |	dIdJ          pdJdNdOdPtu          |          M
  
         n=d)| dQ}Et           |||Et/          |	dIdJ          pdJdRdS|Etu          |          M
  
         d}Fn|?\  }}}E}F}A}@}|}|}|}B|@rd}C|@s E                    |||E|AT          }E|ArKt          |E          }Gt          |G          dUk    r
|Gd	dU         n|G}Htb          2                    dV||F|H           |@sF	  G                    |||E|A           n,# t(          $ r}It          jI        dW|I           Y d	}I~Ind	}I~Iww xY w jJ        r9t          jI        dX||F           t          jI        dYt          |E          |E           d	 _        |ArdZndJ}J                     d[| d\|FdCd]|J            |E}Kt          |E          s&t          |E||	j
        t                    |^          n|E}E jN        O                    ||          }L|Lr%t          |E          rt          |E|L           n|E|Lz  }E Q                    ||E          }Mt          ||M|	j
        |C          }N                    |N           |NR                    d_          }Ot           d`|           s d	S |@sQ jS        rJ	  S                    da|Bd	d	|F|A|Kb           n,# t(          $ r}Pt          jI        dc|P           Y d	}P~Pnd	}P~Pww xY w                                 r,t          |||F|Kd          }Q U                    de|Q            n j        st/           dd          dk    rt          |K          }R jJ        r>t	          df|dgz    dh|FdidE           t	           V                    dj|R                     nHt          |R           jW        k    r|Rd	 jW                 dkz   n|R}St	          df|dgz    dh|Fdidl|S            |@sd jX        r]	 t          ||          p|}T X                    |	j
        ||T|K           n,# t(          $ r}Pt          jI        dm|P           Y d	}P~Pnd	}P~Pww xY w|Op|OR                    dn          dok    rW jS        rP	  S                    dp|d	d	|	j
        |Oq           # t(          $ r }Pt          jI        dr|P           Y d	}P~P?d	}P~Pww xY wIt          Z          }|r0|d
k    r*| d	         }Ut          |Ut                    |s           |r|d
k    r [                    |           d	S d	S d	S )vu  Execute multiple tool calls concurrently using a thread pool.

    Results are collected in the original tool-call order and appended to
    messages so the API sees them in the expected sequence.

    ``finalize=False`` skips the end-of-batch aggregate budget enforcement
    and /steer injection — used when this call is one segment of a larger
    mixed batch and the segmented dispatcher owns the turn-end work.
       ⚡ Interrupt: skipping  tool call(s)   [Tool execution cancelled — # was skipped due to user interrupt]noneeffect_dispositioncancelled tool result r]   Nr   r   'O' is not available in this session. Use tool_search to find tools you can call.z, c              3  (   K   | ]\  }}}}}}|V  d S r   r   )rx   _names      r1   rz   z0execute_tool_calls_concurrent.<locals>.<genexpr>  s/      LL(;4Aq!tLLLLLLr3   r"  r#  r$  u     ⚡ Concurrent: u    tool calls — r   Torderr8   r!   r"   c                     5                        fd           	 |
 |             dz                                   n# dz                                   w xY w	 d d d            d S # 1 swxY w Y   d S )Nc                      k    S r   r   )next_start_orderr\  s   r1   r  zHexecute_tool_calls_concurrent.<locals>._begin_in_order.<locals>.<lambda>  s    U6F-F r3   ri   )wait_for
notify_all)r\  r   r_  start_conditions   ` r1   _begin_in_orderz6execute_tool_calls_concurrent.<locals>._begin_in_order  s     	- 	-$$%F%F%F%F%FGGG-'HJJJ A% **,,,, !A% **,,,,,	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-s'   A2AA2A!!A22A69A6z
executing z tools concurrently: c                   t          j                    j        }j        5  j                            |           ddd           n# 1 swxY w Y   j        r4	 t                                          d|           n# t          $ r Y nw xY w	 ddl
m}  |j                   n# t          $ r Y nw xY wt          j                    }	d}
dddfd}	 	 dfd}t          |t          dd          pd||| dz   |          }|j        }|j        }|j        |j        }
nZ# t(          $ r 	                     d           n# t          $ r Y nw xY wt-          |t          dd          pd|	t/                              }t          j                    |	z
  }t0                              d|           |||ddf| <   Y  |             j        5  j                            |           ddd           n# 1 swxY w Y   	 t                                          d|           dS # t          $ r Y dS w xY wt          $ r0}d d| }t0                              d|d           Y d}~nd}~ww xY wt          j                    |	z
  }t9          |          \  }}|r&t0                              d||dd                    n*t0                              d|t;          |                     |||||
f| <    |             j        5  j                            |           ddd           n# 1 swxY w Y   	 t                                          d|           dS # t          $ r Y dS w xY w#  |             j        5  j                            |           ddd           n# 1 swxY w Y   	 t                                          d|           w # t          $ r Y w w xY wxY w)z%Worker function executed in a thread.NTr   r*  Fr!   r"   c                <    rd S 	  |            dd S # dw xY w)NTr   )r   rc  start_advancedstart_orders    r1   _advance_startzHexecute_tool_calls_concurrent.<locals>._run_tool.<locals>._advance_startM  sA     &X666!%%%%%s    r  r   r   c                d                         | j        dddt                    	  	        S )NT)r[   pre_tool_block_checkedskip_tool_request_middlewareskip_tool_execution_middlewaretool_request_middleware_trace)_invoke_toolidr\   )r  r-   r    r   r[   r   	tool_calls    r1   _executezBexecute_tool_calls_concurrent.<locals>._run_tool.<locals>._executeX  sF     --%!)!!)/3597;6:;K6L6L . 
 
 
r3   ro  r%   ri   )
r   r   r    r   r  r   r   r   r   r   keyboard interruptr   r   r    r   r   r   ztool %s cancelled (%.2fs)Error executing tool '': z_invoke_tool raised for %s: %sexc_infoztool %s failed (%.2fs): %s   #tool %s completed (%.2fs, %d chars)r   r   )r  r   r!   r   )r   current_threadident_tool_worker_threads_lock_tool_worker_threadsadd_interrupt_requestedr   _set_interruptr9   r<  r+  r;  r   r   r7   r   r   r   r   KeyboardInterrupt	interruptr   r\   rV   infodiscardrA   r   rw   )indexrp  r   r   r   r   rg  _worker_tidr+  startr   rh  rq  managedr   duration
tool_erroris_errorrZ  rf  rc  r-   r   r    r[   resultss    `` ` `            @r1   	_run_toolz0execute_tool_calls_concurrent.<locals>._run_tool$  s     .006, 	8 	8&**;777	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 	8 % 	$$T;7777   	EEEEEE!!%"78888 	 	 	D	
 		& 	& 	& 	& 	& 	& 	& 	& 	&Y	;i           ?"/"/&7!(D"!=!=!C$ +"'!)%5$2'9   ! '#*#; !/$   OO$89999    D@"/"/&7!(D"!=!=!C$%)*:%;%;    9;;.7QQQ!!$" ( N 0 @ @*22;???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$$UK88888   =  i i iP-PPJPP=}jcghhhhhhhhi y{{U*H.}fEEKHa i8-SYZ^[^Z^S_````A=RZ\_`f\g\ghhh GEN N 0 @ @*22;???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$$UK88888    N 0 @ @*22;???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$$UK8888   s(  AAA "B 
BBB+ +
B87B8AD4 2N 4J EJ
E# J"E##A5JN *HHH"I 
II	J&JN JB
N &MMM"M= =
N
NP O;POPOP"O65P6
P PPPu    ⚡ running z tools concurrentlydotsspinner_typeprint_fnc                4    g | ]\  }\  }}}}}}||||||fS r   r   )rx   itcr[  r   _traceparse_errorr   s           r1   
<listcomp>z1execute_tool_calls_concurrent.<locals>.<listcomp>  sH     
 
 
EEBdFK "	 D$, #""r3   )DaemonThreadPoolExecutor)r}   Frt   zWinterpreter shutdown while scheduling concurrent tools; skipping %d unsubmitted tool(s)rt  z<': Python interpreter is shutting down; tool was not startedg      @c                :    h | ]}|                                 |S r   )done)rx   fs     r1   	<setcomp>z0execute_tool_calls_concurrent.<locals>.<setcomp>  s5     5 5 5&'!&&((5 !5 5 5r3   )timeoutc                (    h | ]}|v |         S r   r   )rx   r  future_to_indexs     r1   r  z0execute_tool_calls_concurrent.<locals>.<setcomp>(  s3     - - - ! O33 ,A.333r3   c                ,    g | ]}|         d          S ri   r   )rx   r  parsed_callss     r1   r  z1execute_tool_calls_concurrent.<locals>.<listcomp>-  s2     * * * ! )OA.* * *r3   zIconcurrent tool batch timed out after %.1fs; %d tool(s) still running: %s   u   ⚡ Interrupt: cancelling z pending concurrent tool(s)forceg      @      c                @    g | ]}|v |                  d          S r  r   )rx   r  r  r  s     r1   r  z1execute_tool_calls_concurrent.<locals>.<listcomp>[  s=     * * * ! O33 ));<Q?333r3   zconcurrent tools running (zs, z remaining: r'  )waitcancel_futuresc              3     K   | ]}|dV  	d S )Nri   r   rx   rs     r1   rz   z0execute_tool_calls_concurrent.<locals>.<genexpr>q  s"      @@!!-A----@@r3   c              3  *   K   | ]}||d         V  d S )Nrt   r   r  s     r1   rz   z0execute_tool_calls_concurrent.<locals>.<genexpr>r  s&      CCQQ]AaD]]]]CCr3   u   ⚡ /z tools completed in .1fzs totalszthe configured timeoutz': timed out after unknownro  r%   r  tool_timeoutr   r   r   z*Tool execution cancelled by user interruptz!': thread did not return a resultrA   thread_missing_resultfailedrx  "Tool %s returned error (%.2fs): %s(file-mutation verifier record failed: %sTool %s completed in %.2fsTool result (%d chars): %s (error)tool completed:  (s)content	tool_nametool_use_idenvconfig_tool_output_risktool result tool.completedr  r  r   r,  r          ✅ Tool ri    completed in .2fResult: r)  s -  Tool complete callback error: %srisklowtool.output_riskr   risk_metadata#Tool output risk callback error: %sr  r  r   )r\  r8   r!   r"   )\
tool_callsrw   r;   r  r6  
log_prefixappendr   functionr[  ro  rd   rL   rK   r   r   TOOL_CALL_NAMEresolve_underlying_callr   validate_deferred_call_argsr9   joinr   r7   	enumerater   	Conditionr   r:  r;   _should_emit_quiet_tool_messages_should_start_quiet_spinnerrandomchoicer   get_waiting_faces	_print_fnr  setrZ   r   r   r~   tools.daemon_poolr  submitr   r   r   rV   rW   r   rm   
concurrentfuturesr  cancelr|  r\   r}  r   r  _vprintr8   shutdownsumstopr   rT   _append_guardrail_observationr   _record_file_mutation_resultr?  r@  r5  r   r   r   _subdirectory_hintscheck_tool_callr   %_tool_result_content_for_active_modelr(   r=  _get_cute_tool_message_impl_safe_printr8  r9  tool_complete_callbackr4  r   $_apply_pending_steer_to_tool_results)]r-   assistant_messager[   r    rL  rK  r  	num_tools_tool_budgetr  rp  r   r   malformed_args_result_ts_scope_blockr   _underlying_underlying_args_err
_probe_errtool_names_strr  r[  r   r   block_result_scope_blockr  spinnerfacer|   r  timed_out_indices	timeout_sdeadliner}   r  executorabandon_executorsubmit_indexr   r  submit_errorskipped_calls	skipped_i_tcskipped_nameskipped_argsr   _conc_start_interrupt_loggedwait_timeouteffective_deadline	remainingr  not_done_still_runningworker_tidstid_conc_elapsed	completed	total_dur_parse_errorr  r   r  progress_function_namerT  suffixfunction_resulttool_duration	_err_textresult_preview_ver_err_status_suffixdisplay_function_resultsubdir_hints_tool_contenttool_messager  cb_errcute_msg_preview_strresponse_previewrC  turn_tool_msgsrc  r   r  r_  r  r  rb  s]   ` ``                                                                                  @@@@@@@r1   execute_tool_calls_concurrentr3    s    #-JJI %U++L ! !SS9SSSTTT 	 	BOO4 f1Afff#)	      2Ar{/?AA    
 	
 L >
 >
	!*//D(0
 0
,, !,!!)	 	 	 $ 	000000 222696Q6QR_6`6`3-t  "&?&F&FFF &)%D%D[Rb%c%c
%1.8OO,7M,<MMJ J J J (  	 	 	D	 	}b$P	
 	
 	
 	

 YYLL|LLLLLN P/CU K Ku T TN9NNnNNOOO fy GMVWcMdMd W WIIBd,lL#lCtEUVGAJ)++O9;;	- 	- 	- 	- 	- 	- 	- 	- )E	WyWW~WWXXXK K K K K K K K K K\ G--// E4U4U4W4W }]<>>??4 T Ti T T Tcity  uD  E  E  E{c
 
IRJ J
 
 
 &)ee466	3<3H4>##i//d h	5nEEK CBBBBB//KHHHH$^FO"G G 2+ 2+BL"B1b$k*$OO7	BB  (OA.'(	 	 (   D\RR "!(6|}}(E>..   +" " %(((&y193?	3J13M 0%`\ %` %` %` !'
 %1$0$*$'$($)$46"	 2 ?@ NN1%%%)*OA&& #ikk$)!X#&L+$'9'J'J'L'LL + %79I9I$I	$>>-0UU 5 5+25 5 5(DD ,/|Y+G+GL-7-?-D-D ' .E . .ND(( *4);)@)@#\ *A * *h $  !, N,,#&8&I&I&K&KKL L ,0(- - - -%-- - -)
* * * *%6* * * ;% 122 IInRaR&899   "* ' 'AHHJJJJ"< K K*.u/I*J*JKK K K K K K K K K K K K K K K#. % %C% # 4 4T3 ? ? ? ?#, % % % $% 1 +/(0 04-!MM#(#3 !N !N#&x==!N !N !N&* *   
 "* ' 'AHHJJJJ #*//#/FFF$'	k(A$B$BM$q((]R-?!-C-C* * * * *%-* * *
 --[ [ ["8}}[ [:>))NSUTUSUDV:W:W[ [ [  kX~ !!--#3 "    !!--#3 "    
  	c@@w@@@@@ICC'CCCCCILLa	aaIaa9aaaabbb	  	c@@w@@@@@ICC'CCCCCILLa	aaIaa9aaaabbbb		c NWN N BM BMIIBd,lL AJ!%
 "!!!ai,5,A	(((((G_FXtXXPVXXO!*)""&"3$Rr228b )-!%&6!7!7    ")"2s33MMY) "l4"l"l"l-"&"&*&7!(T2!6!6!<"&3"N%)*:%;%;     #c4"b"b"b-"&"&*&7!(T2!6!6!<""6"1%)*:%;%;     MMpqmM=/=(T[]m D D%2" ,%+" "'"E"E!!##	 #F # #  s4_EE	47	NNS4H4H4C4iC]Tacqrrr
  XX66%}ox    ! X X XM"LhWWWWWWWWX $ c:M=YYY:C<P<PRabbb"'/7R^^^^^^n^^___"1 ,O<<R3#011
 
 
 
 CR 	 0@@tLL 	0)/:: 0 2/<PPPP</ CCD/ZZ/E1	
 
 
 	%%%$(()<==4'''
 
 
 	
 FF
  	J57 	JJ,,$&<dD*X2 -    
  J J J@&IIIIIIIIJ 1133 	b2dM2I  H o8oo....! 	bge5I5&Q&QUZ&Z&Z34KLLL$ bKAaCKK}KKKKLLLe))*lCCDDDDTWXdTeTehmh~T~T~<0G1G0G#H5#P#P  EQ `AaC``}```N^``aaa 	J57 	JJ<T4HHPD,,E4/F     J J J@&IIIIIIIIJ %!!&))U22, 3
M,,&!#"/ -      M M MCVLLLLLLLLM L!!I hIMM!9*++.N?P0Q0QZfgggg  HIMM228YGGGGGH HMMs  	A%E//
E<;E<3A9_ -] 5N>=] >
QA5Q=] QF] W>2] >X] X] "X10] 1
X>;] =X>>D] _ ]77_ A`& g
h#g==h&n
n,n''n,1/s!!
t
+tt
0 u
u<u77u<c                   |D ]b}t          t          |dd          dd          pd}|                     t          |d| d| dt          |d	d          pdd
                     cdS )u  Append a cancelled ``tool`` result for each call in ``tool_calls``.

    Used when a hard interrupt (KeyboardInterrupt / BaseException) aborts the
    sequential executor mid-batch. Without this, the loop re-raises leaving the
    assistant tool-call turn with no matching tool results — a message-role
    alternation violation that malforms the next provider request. Mirrors the
    cooperative-interrupt skip block and the concurrent path, both of which
    already emit a result for every call_id.
    r  Nr[  r%   toolrP  z was skipped due to ]ro  rR  rS  )r7   r  r   )r[   r  r   r  r[  s        r1   _append_cancelled_tool_resultsr7  L  s       wr:t44fbAAKV0PTPPvPPPBb!!'R%	
 
 
 	 	 	 	 r3   c               H,   :;< t                     }t          |j        d          D ]\  }<t           dd          r dS  j        r|j        |dz
  d         }|r/                      j         dt          |           dd           |D ]V}	|	j        j	        }

                    t          |
d	|
 d
|	j        d                     t           d|
           s  dS W nщ<j        j	        :t          <j        j                  \  }}|C
                    t          :|<j                             t           d:           s dS -d}	 ddlm} :|j        k    r|                    |          \  }}}|s|r|t)                     v r|                    ||          }|	 t-          j        |          }|                    dd           dt-          j        |                    di           d           d|                    dd                                           }n# t6          $ r |}Y nw xY w|:|}nd| d}n# t6          $ r Y nw xY wg ;d}t9          j                    }:dk    rdu fd }t;          t=           :|t          <d!d          pd|||"                    \  }};}t9          j                    |z
  }                                 r)                     d#tA          d|||$                      n:d%k    rdu fd&}t;          t=           :|t          <d!d          pd|||"                    \  }};}t9          j                    |z
  }                                 r)                     d#tA          d%|||$                      nS:d'k    rdu <fd(}t;          t=           :|t          <d!d          pd|||"                    \  }};}t9          j                    |z
  }                                 r)                     d#tA          d'|||$                      n:d)k    rdu fd*}t;          t=           :|t          <d!d          pd|||"                    \  }};}t9          j                    |z
  }                                 r)                     d#tA          d)|||$                      n:d+k    rdu fd,}t;          t=           :|t          <d!d          pd|||"                    \  }};}t9          j                    |z
  }                                 r)                     d#tA          d+|||$                      
n:d-k    r%|                    d.          }|r)tC          |tD                    rd/t          |           d0}n)|                    d1          pddd2         }|rd3| d4nd5}d}                                 ri #                                rUtI          j%        tM          j'                              }tM          | d6| d7 j(        8          }|)                                 | _*        d}	 du fd9}t;          t=           :|t          <d!d          pd|||"                    \  }};}|}d _*        t9          j                    |z
  }tA          d-|||$          }|r|+                    |           n                                 r                     d#|            n# d _*        t9          j                    |z
  }tA          d-|||$          }|r|+                    |           w                                  r                     d#|            w w xY w j,        r': j,        v rd}                                 rtI          j%        tM          j'                              }t[          :          } t]          :|          p|}!t_          :|!          p:}"tM          | d6|  d6|" d7 j(        8          }|)                                 d}#	 du :fd:}t;          t=           :|t          <d!d          pd|||"                    \  }};}|}#nQ# t6          $ rD}$t-          j        dd;: d<|$ i          }t`          1                    d=:|$d>           Y d}$~$nd}$~$ww xY wt9          j                    |z
  }tA          :|||#$          }|r|+                    |           nƉ                                 r                     d#|            n# t9          j                    |z
  }tA          :|||#$          }|r|+                    |           w                                  r                     d#|            w w xY w j2        rK j2        3                    :          r0d}                                 r #                                rtI          j%        tM          j'                              }t[          :          } t]          :|          p|}!t_          :|!          p:}"tM          | d6|  d6|" d7 j(        8          }|)                                 d}%	 du :fd?}t;          t=           :|t          <d!d          pd|||"                    \  }};}|}%nQ# t6          $ rD}$t-          j        dd@: d<|$ i          }t`          1                    dA:|$d>           Y d}$~$nd}$~$ww xY wt9          j                    |z
  }tA          :|||%$          }|r|+                    |           ns                                 r                     d#|            nE# t9          j                    |z
  }tA          :|||%$          }|r|+                    |           w                                  r                     d#|            w w xY w j4        rd}                                 r #                                rtI          j%        tM          j'                              }t[          :          } t]          :|          p|}!t_          :|!          p:}"tM          | d6|  d6|" d7 j(        8          }|)                                 d}&	 du :;<fdB}t;          t=           :|t          <d!d          pd|||;C	  	                  \  }};}|}&n# tj          $ r tm           :|t          <d!d          pd|tE          ;          D          }|}&	  7                    dE           n# t6          $ r Y nw xY wtq          |j        |dz
  d         dEF            t6          $ r0}$dG: dH|$ }t`          1                    dI:|$d>           Y d}$~$nd}$~$ww xY wt9          j                    |z
  }tA          :|||&$          }|r|+                    |           n                                 r                     d#|            n# t9          j                    |z
  }tA          :|||&$          }|r|+                    |           w                                  r                     d#|            w w xY w	 du :;<fdJ}t;          t=           :|t          <d!d          pd|||;C	  	                  \  }};}n# tj          $ r tm           :|t          <d!d          pd|tE          ;          D           	  7                    dE           n# t6          $ r Y nw xY wtq          |j        |dz
  d         dEF            t6          $ r0}$dG: dH|$ }t`          1                    dI:|$d>           Y d}$~$nd}$~$ww xY wt9          j                    |z
  }tC          |tr                    r8 j:        r|nt          |          dKk    r
|ddK         n|}'t          |          }(n|}'t          ts          |                    }(tw          :|          \  })}*ddLl<m=}+ | o |+ :          },|,rEt}           :||t          <d!d          pdt          |dMz            tE          ;          N           |sA @                    :|||)O          } j:        r|nt          |          dKk    r
|ddK         n|}'|)rt`          A                    dP:||'           nt`          B                    dQ:||(           |sF	  C                    :|||)           n,# t6          $ r}-t          jE        dR|-           Y d}-~-nd}-~-ww xY wd _F        |)rdSnd}. G                    dT: dU|dVdW|.             j:        rHt          jE        dX:|           t          |          }/t          jE        dYt          |/          |/           |}0t          |          s&t          |:<j        t                    |Z          n|} jL        M                    :|          }1|1r%t          |          rt          ||1           n||1z  } O                    :|          }2t          :|2<j                  }3
                    |3           |3                    d[          }4t           d\:           s dS |sQ jP        rJ	  P                    d]:dd||)|0^           n,# t6          $ r}5t          jE        d_|5           Y d}5~5nd}5~5ww xY w|sd jQ        r]	 t]          :|          p|}! Q                    <j        :|!|0           n,# t6          $ r}5t          jE        d`|5           Y d}5~5nd}5~5ww xY w|4n|4                    da          dbk    rU jP        rN	  P                    dc:dd<j        |4d           n,# t6          $ r}5t          jE        de|5           Y d}5~5nd}5~5ww xY w j4        st           dfdg          dhk    r j:        r;t          di| dj|dkdl           t           S                    dm|                     nktC          |tr                    r|nts          |          }6t          |6           jT        k    r|6d jT                 dnz   n|6}7t          di| dj|dkdo|7             j        r|t          |j                  k     rt          |j                  |z
  }8                      j         d|8 dpd           |j        |d         D ]V}	|	j        j	        }

                    t          |
dq|
 dr|	j        d                     t           ds|
           s  dS W nt          |j                  }9|r.|9dk    r(t          |9 d         t                    |t           |r|9dk    r V                    |9           dS dS dS )vuB  Execute tool calls sequentially (original behavior). Used for single calls or interactive tools.

    ``finalize=False`` skips the end-of-batch aggregate budget enforcement
    and /steer injection — used when this call is one segment of a larger
    mixed batch and the segmented dispatcher owns the turn-end work.
    ri   ra   FNrN  rO  Tr  rP  rQ  rR  rS  rU  rV  zinvalid tool arguments r   r   rA   r%   z Parameters schema: 
parametersrC   z. hintrW  rX  todor  r   r!   r   c                    ddl m}  ||                     d          |                     dd          j                  S )Nr   )	todo_tooltodosmergeF)r>  r?  store)tools.todo_toolr=  r(   _todo_store)r  
_todo_toolr-   s     r1   rq  z/execute_tool_calls_sequential.<locals>._execute  sT    CCCCCC!z#--00#--77+   r3   ro  )r   r   r    r   r  r   r   r  r  session_searchc                                                    }|s%ddlm} t          j        d |            d          S ddlm}  ||                     dd          |                     d          |                     d	d
          |                     d          |                     d          |                     dd          |                     d          |j        	  	        S )Nr   )format_session_db_unavailableF)successrA   )rD  queryr%   role_filterrp   rt   r   around_message_idwindowr  sort)	rH  rI  rp   r   rJ  rK  rL  dbcurrent_session_id)	_get_session_db_for_recallhermes_staterF  rE   rJ   tools.session_search_toolrD  r(   r   )r  
session_dbrF  _session_searchr-   s       r1   rq  z/execute_tool_calls_sequential.<locals>._execute  s    "==??
! dJJJJJJ:%B_B_BaBa&b&bcccWWWWWW&#--44 )m < <#--33(}}\::&/mm4G&H&H$==155"v..!','7
 
 
 
r3   r  c                Z   |                      dd          }|                      d          }ddlm}  ||                      d          ||                      d          |                      d          |j        	          }j        r"j                            || fd
           |S )Ntargetr  
operationsr   )memory_toolactionr  old_text)rX  rU  r  rY  rV  r@  c                 P                          t          dd                     S )Nro  )r   r   )_build_memory_write_metadatar7   )r-   r    rp  s   r1   r  zAexecute_tool_calls_sequential.<locals>._execute.<locals>.<lambda>
  s/    u/Q/Q$5)0D$)G)G 0R 0 0 r3   )build_metadata)r(   tools.memory_toolrW  _memory_store_memory_managernotify_memory_tool_write)r  rU  rV  _memory_toolr   r-   r    rp  s        r1   rq  z/execute_tool_calls_sequential.<locals>._execute  s    "x::&]]<88
IIIIII%$==22!%MM)44&]]:66)-   ( )BB!( ( ( ( ( ( C    r3   clarifyc                    ddl m}  ||                     dd          |                     d          |                     dd          j                  S )	Nr   )clarify_toolquestionr%   choicesmulti_selectF)re  rf  rg  r   )tools.clarify_toolrd  r(   clarify_callback)r  _clarify_toolr-   s     r1   rq  z/execute_tool_calls_sequential.<locals>._execute  se    LLLLLL$}&]]:r::%MM)44!*~u!E!E"3	   r3   read_terminalc           	         ddl m}  ||                     d          |                     d          t          dd                     S )Nr   )read_terminal_tool
start_linecountread_terminal_callback)rn  ro  r   )tools.read_terminal_toolrm  r(   r7   )r  _read_terminal_toolr-   s     r1   rq  z/execute_tool_calls_sequential.<locals>._execute4  s]    ^^^^^^**(}}\::#--00$U,DdKK   r3   delegate_tasktasksu   🔀 delegating u    tasks · (/agents to monitor)goalr  u   🔀 u    · (/agents to monitor)u'   🔀 delegating · (/agents to monitor) r  r  c                .                         |           S r   )_dispatch_delegate_task)r  r-   s    r1   rq  z/execute_tool_calls_sequential.<locals>._execute[  s     88CCCr3   c                >    j                             |           S )N)r[   )r5   handle_tool_call)r  r-   r   r[   s    r1   rq  z/execute_tool_calls_sequential.<locals>._execute|  s#     3DD]T]hpDqqqr3   zContext engine tool 'z
' failed: z1context_engine.handle_tool_call raised for %s: %srv  c                :    j                             |           S r   )r_  rz  )r  r-   r   s    r1   rq  z/execute_tool_calls_sequential.<locals>._execute  s     0AA-QZ[[[r3   zMemory tool 'z1memory_manager.handle_tool_call raised for %s: %sc                J   t                                          | j        j        pdt	          dd          pdt	          dd          pdj        rt          j                  nd dddt                    t	          dd           t	          dd                     S Nr%   r   r   Tr   r   )r   r   r   r   enabled_toolsskip_pre_tool_call_hookrk  rl  rm  r   r   r   handle_function_callro  r   r7   valid_tool_namesr\   r  r-   r    r   r   rp  s    r1   rq  z/execute_tool_calls_sequential.<locals>._execute      5555%!)%.\#(#3#9r '/A2 F F L"'.u6OQS'T'T (  %5&D!7888!%04597;6:;K6L6L)08JD)Q)Q*1%9Ld*S*S' 6   r3   )r   r   r    r   r  r   r   r   rs  rr  r   rt  ru  z&handle_function_call raised for %s: %sc                J   t                                          | j        j        pdt	          dd          pdt	          dd          pdj        rt          j                  nd dddt                    t	          dd           t	          dd                     S r}  r  r  s    r1   rq  z/execute_tool_calls_sequential.<locals>._execute  r  r3   rx  )!agent_runtime_owns_post_tool_hookr   )r   r   r   r    r   r   r   r  r  ry  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  z remaining tool call(s)u   [Tool execution skipped — z* was not started. User sent a new message]zskipped tool result r  )r  r   r!   r   )Wr;   r  r  r7   r  r  r  rw   r  r[  r  r   ro  rd   rL   rK   r   r   r  r  r   r  rE   rF   r(   rJ   rR   r9   r   r   r   r  r  rI   r\   r  r  r  r   r  r  r  _delegate_spinnerr  _context_engine_tool_names_get_tool_emojir4  _build_tool_labelrV   rA   r_  has_toolr   r  r   r  r7  r   r5  r   agent.agent_runtime_helpersr  r   r8   r  rW   r  r  r?  r@  r:  r;  r   r   r   r   r  r  r   r  r=  r  r6  r8  r9  r   r  )=r-   r  r[   r    rL  rK  r  r  remaining_calls
skipped_tcr  r   r  r  r   r   r  r  r  _probe_execution_blockedtool_start_timerq  r$  r%  	tasks_argspinner_labelgoal_previewr  r  _delegate_resultr/  emojirC  rG  
_ce_resultr  _mem_result_spinner_resultr'  _result_len_is_error_resultrZ  r  _executor_must_emit_post_hookr(  r)  _log_resultr*  r+  r,  r-  r  r.  _fr_strr1  r  num_tools_seqr   r   rp  s=   ` ``                                                      @@@r1   execute_tool_calls_sequentialr  `  s    %U++L!"3">BB V
 V
95;UCC 	FF % 	/:1Q344@O |!1nn3K_K_nnnvz{{{-  
)27 8 f\fffM'-	! ! !    =A<AA   
 FFF E!*//D(0
 0
,, !,OO(!)L    9???   
 
 *.	000000 222696Q6QR_6`6`3-t  "&?&F&FFF &)%D%D[Rb%c%c
%1=)-J)?)?'-zz'2'>'> %@ %@'+z&**\22N2N]b'c'c'c%@ %@'-zz&"'='=%@ %@ #(%''	 !0
 $- = = =2<= -8M,<MMJ J J J (  	 	 	D	 24")++F""      Tc  dH++"3$Yb99?R +	d 	d 	d 	T 	TPO],<>P !IKK/9M5577 @~#>v}Vcl{#|#|#|~~...     " Tc  dH++"3$Yb99?R +	d 	d 	d 	T 	TPO],<>P !IKK/9M5577 J  I#>?OQ^`m  wF  $G  $G  $G  I  I  J  J  Jh&&       2 Tc  dH++"3$Yb99?R +	d 	d 	d 	T 	TPO],<>P !IKK/9M5577 B  A#>xXen}#~#~#~  A  A  B  B  Bi''      Tc  dH++"3$Yb99?R +	d 	d 	d 	T 	TPO],<>P !IKK/9M5577 C  B#>y-Yfo~###  B  B  C  C  Co--      Tc  dH++"3$Yb99?R +	d 	d 	d 	T 	TPO],<>P !IKK/9M5577 I  H#>P]_l  vE  $F  $F  $F  H  H  I  I  Io--%))'22I Z	488  a3y>> a a a - 1 1& 9 9 ?R"E $CBLBBBBB 
 G5577  E<]<]<_<_  }]%D%F%FGG'4(A(A-(A(APVafapqqq&-E##3D D D D D DWf  hL"/"/&7!(D"!=!=!C$ /"#	h 	h 	h 	X 	XT0@BT $3 *.' $	o =6Wdm}~~~ 3LL****;;== 3MM/x//222 +/' $	o =6Wdm}~~~ 3LL****;;== 3MM/x//22223- b	:-5Cc2c2cG5577  }]%D%F%FGG'66<]MZZk^k+M<HHYM'4(C(C%(C(C'(C(CRXchcrsssJ3r r r r r r r rWf  hL"/"/&7!(D"!=!=!C$ /"#	h 	h 	h 	X 	XT0@BT -

 | | |"&*g7t}7t7thr7t7t-u"v"vPR_akvz{{{{{{{{| !%	o =6}mUbkuvvv 3LL****;;== 3MM/x//222 !%	o =6}mUbkuvvv 3LL****;;== 3MM/x//22223" 	:u'<'E'Em'T'T 	: G5577  E<]<]<_<_  }]%D%F%FGG'66<]MZZk^k+M<HHYM'4(C(C%(C(C'(C(CRXchcrsssK3\ \ \ \ \ \ \Wf  hL"/"/&7!(D"!=!=!C$ /"#	h 	h 	h 	X 	XT0@BT . | | |"&*g7l}7l7l`j7l7l-m"n"nPR_akvz{{{{{{{{| !%	o =6}mUbkvwww 3LL****;;== 3MM/x//222 !%	o =6}mUbkvwww 3LL****;;== 3MM/x//22223 [	:G5577  E<]<]<_<_  }]%D%F%FGG'66<]MZZk^k+M<HHYM'4(C(C%(C(C'(C(CRXchcrsss"OL3         8 $8&3&3*;%,Yb%A%A%GR ($3&')9
 
 
 #!$& #2$   "I"/"/&7!(D"!=!=!C.%)*:%;%;# # # #2OO$89999    D
 /%0Q8/   
  q q q"Y="Y"YZ"Y"YE}V`koppppppppq !%	o =6}mUbkz{{{ 3LL****;;== 3MM/x//222 !%	o =6}mUbkz{{{ 3LL****;;== 3MM/x//22223Bq         8 $8&3&3*;%,Yb%A%A%GR ($3&')9
 
 
 #!$&& %   7"/"/&7!(D"!=!=!C.%)*:%;%;   OO$89999    D /%0Q8/   
  q q q"Y="Y"YZ"Y"YE}V`koppppppppq !IKK/9Mos++ 	4050E __),_)=)=)C)C%%  o..KK -Nc/2233K 3=/RR! 	RQQQQQ"" H11%GG 	& ) 
	)++&"3$Yb99?R 455!%&6!7!7	 	 	 	 " 		#AA'	 B  O 160E __),_)=)=)C)C%%   	jNN?P]_mnnnnKK=}m]hiii " 	TT22!=/CS     T T TH(SSSSSSSST #'7?Rggg-gggWegghhh  	WM6}UUU2?CCKM6K8H8H+VVV"1 ,O<<R3##!011
 
 
 
 CR 	 0@@P]^^ 	0)/:: 01/<PPPP</ CCMSbcc/}il[[%%%$(()<==4000
 
 
 	
 FF " 	Je&B 	JJ,,$mT4*5E2 -    
  J J J@&IIIIIIIIJ " 	Je&B 	JJ1-OO %$  ,,L! +	     J J J@&IIIIIIIIJ %!!&))U22, 3
M,,&!!*"/ -      M M MCVLLLLLLLLM  	`GE3G$O$OSX$X$X$ `IAII]IIIIJJJe))*oFFGGGG-7-M-Mg//SVWfSgSgORSZ||^c^tOtOt7+BE,B+B#Ce#K#K  {B ^A^^]^^^L\^^___% 	!c2C2N.O.O*O*O-899A=IMMU-iiyiiiquMvvv/:122>  
)27 8 k<kkkM'-	! ! !    =???   
 FFF E )455M sMA%%Hm^__5>J[;\;\eqrrrr
  LMA%%228]KKKKKL L%%s  AI3B H43I4I III
II;A\44A7^+$Ab)(e*)
c73:c2-e*2c77e**A0g8Ak<;n=<
m
:m n=m

n==A0p-0At87y.8A w;9vw;
vw;v/w;&w61y.6w;;y..A0{"A|((>)'}=<)=
~
)	~

/)9&$$)EAE8E8
AF!FAFFAF!LAL/L/
AML9AMMAMM%/ANN
AN>NAN9N9AN>O$ APP
AP.PAP)P)AP.c           	     d   ddl m} |Dt          |          }||j        rt	          |j                  nd}t          |j        |          }|D ]w\  }	}
t          | dd          r dS  |t          |
                    }|	dk    rt          | ||||d	           nt          | ||||d	           t          | dd          r dS xt          |j                  }|dk    rOt          |           }t          || d         t          |          |
           |                     ||           dS dS )u  Execute a mixed tool-call batch as ordered parallel/sequential segments.

    ``segments`` is the ``(kind, calls)`` plan from
    ``_plan_tool_batch_segments``: maximal contiguous runs of parallel-safe
    calls execute on the concurrent path, barrier calls on the sequential
    path, strictly in the model's original call order. Because segments are
    contiguous, every tool result is still appended one-per-call in emission
    order and no call ever starts before an earlier barrier finishes —
    identical ordering and side-effect boundaries to fully-sequential
    execution, with I/O parallelism recovered inside the safe runs.

    Turn-end work (aggregate budget enforcement + /steer injection) is done
    once here for the WHOLE batch; the per-segment executor calls run with
    ``finalize=False`` so a multi-segment turn cannot multiply the budget or
    truncate a steer marker.

    Interrupt semantics: each segment executor already checks
    ``agent._interrupt_requested`` up front and appends a cancelled/skipped
    result per call, so an interrupt during segment *k* drains segments
    *k+1..n* without executing them while preserving one result per
    tool_call_id.
    r   )SimpleNamespaceN)execution_cwdra   F)r  parallelrJ  r  )typesr  r   rI  r   r   r  r7   r\   r3  r  rw   r;   r   r  )r-   r  r[   r    rL  segmentsr  _active_env	_exec_cwdkindcallssegment_messagetotal_toolsr  s                 r1   execute_tool_calls_segmentedr    s   . &%%%%%$%677-8-D-DD)))^b	,->-IYbccc  e5;UCC 	FF)/T%[[AAA:)2C^    
 *2C^   
 5;UCC 	FF	 '233KQ(//k\]]#011	
 	
 	
 	

 	228[IIIII r3   )r3  r  r  )r   r   r   r   r    r   r!   r"   )r!   r   )r>   r   r!   r?   )r!   rM   )r[   r\   r]   r   r!   r^   )r!   r8   )rc   r   r!   r^   )r   r   r   r   r   r   r    r   r   r   r   r8   r   r   r   r   r   r   r   r   r!   r"   )r   )r   r   r!   r   )r   r   r   r   r    r   r   r   r   rT   r   r   r   r   r   r   r!   r   )r!   r   )r   r   r!   r   )r   r   r   r   r    r   r   r   r   r   r   r   r   r   r   r   r!   r   )r   r   r   r   r    r   r   r   r   r   r!   r"   )r   )
r[   r\   r    r   rL  r8   rK  r^   r!   r"   )r[   r\   r   r   r!   r"   )r   N)r[   r\   r    r   rL  r8   r!   r"   )Nr   
__future__r   concurrent.futuresr  rE   pathlibr   r?  rP   r  r   r   dataclassesr   typingr   r   agent.displayr   r	   r>  r
   r  r   r  r   r  r   r4  r   agent.tool_dispatch_helpersr   r   r   r   r   r   tools.terminal_toolr   tools.thread_contextr   tools.tool_result_storager   r   tools.budget_configr   r   r   	getLoggerr   rV   r2   r;   rn   rk   rS   rL   rZ   rd   rq   r~   r   r   r   r   r   r   r   r   r   r   r   r3  r7  r  r  __all__r   r3   r1   <module>r     s  
 
 # " " " " "             				       ! ! ! ! ! !                                                      = < < < < <        X W W W W W W W W W		8	$	$Q Q Q Q,   "  #$   &+ "   &   $   01 1 1 16
1 
1 
1 
1  P P P P ! $7;           F    $ #*7;     :. . . .b        % % % % % % % %P   & # $48BFs s s s s slZ Z Z Zzj
H  RV j
H j
H j
H j
H j
H j
H\   (m
L  RV m
L m
L m
L m
L m
L m
Ld9J 9J 9J 9J 9Jx  r3   