
    ީ^jU                      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mZ ddlmZmZmZmZmZmZmZ ddlmZ ddlm Z m!Z!m"Z"m#Z#m$Z$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          Z3dJdZ4dKdZ5dZ6dZ7dLdZ8dMdZ9dNd"Z:d# Z;dOd'Z<dddddd(dPd3Z=dQdRd6Z>d4d7dd8dSd;Z?dTd=Z@dUd?ZAdVdAZBdWdBdCdXdFZCdWdBdCdXdGZDdYdZdHZEg dIZFdS )[u  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)AnyOptional)KawaiiSpinnerbuild_tool_previewbuild_tool_labelget_cute_tool_messageget_tool_emojiredact_tool_args_for_display_detect_tool_failure)ToolGuardrailDecision)_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           5/home/ice/.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_argumentsrK   e   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_timeoutrY   x   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stagec                   	 |                      |           dS # t          $ r'}t                              d||           Y d}~dS d}~ww xY w)a`  Best-effort incremental SessionDB flush for tool-call progress.

    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.
    z5Incremental tool-call persistence failed after %s: %sN)_flush_messages_to_session_dbr9   rU   rV   )r-   rZ   r\   excs       r1   %_flush_session_db_after_tool_progressr`      sp    \++H55555 \ \ \NPUWZ[[[[[[[[[\s    
A
AA
c                     ddl } | S )zRLazy reference to ``run_agent`` so patches like ``run_agent._set_interrupt`` work.r   N	run_agentrb   s    r1   _rard      s    r3   r_   RuntimeErrorboolc                $    dt          |           v S )Nz6cannot schedule new futures after interpreter shutdown)r   )r_   s    r1   %_is_interpreter_shutdown_submit_errorrh      s    Cs3xxOOr3   )duration_msstatus
error_typeerror_messagemiddleware_traceresulttool_call_idri   r8   rj   
str | Nonerk   rl   rm   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   rn   task_idrt   ro   turn_idapi_request_idri   rj   rk   rl   rm   )model_toolsrs   r7   r[   r9   )r-   r   r   rn   r    ro   ri   rj   rk   rl   rm   rs   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)r@   rj   FrB   )rD   rI   )r}   s    r1   _cancelled_tool_resultr      s8    :<F<<!	
 	
    r3   keyboard_interrupt)r}   rk   rm   
start_timerS   c                   t          |          }	t          | |||	||t          t          j                    |z
  dz            d|d| t	          |pg                      |	S )N  r   r   )
r   r   rn   r    ro   ri   rj   rk   rl   rm   )r   r{   r8   timer[   )
r-   r   r   r    ro   r   r}   rk   rm   rn   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_cache   T)r   r   
quiet_modeskip_tool_search_assembly)rz   toolsr   tools.registryr   r9   r   r7   get_tool_definitionsscoped_deferrable_namesr   )
r-   rz   _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!tuple[dict, 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          |j        t
                    r|j        n|}|t          |j                  fS # t          $ r)}t          
                    d|           |g fcY d }~S d }~ww xY w)	Nr   )apply_tool_request_middlewarer%   rt   ru   rv   )rw   rt   ro   rx   ry   z!tool_request middleware error: %s)hermes_cli.middlewarer   r7   rH   payloadr   r[   tracer9   rU   debug)	r-   r   r   r    ro   r   rn   r   r_   s	            r1   (_apply_tool_request_middleware_for_agentr   "  s   !GGGGGG..%+ulB77=2%+E#5r::@b"5*CRHHNB
 
 
 %/v~t$D$DW&..-V\**** ! ! !8#>>>b       !s   BB
 

B=B82B=8B=tuple[Any, dict]c                  	 	d	fd}ddl m}  ||||pdt          | d	d          pd|pdt          | d
d          pdt          | dd          pd	  	        }|	fS )N	next_argsr   r!   r   c                L    t          | t                    r| n           S N)rH   r   )r   executer   observed_argss    r1   _executez6_run_agent_tool_execution_middleware.<locals>._executeH  s+    %/	4%@%@S		mw}%%%r3   r   )run_tool_execution_middlewarer%   rt   ru   rv   )original_argsrw   rt   ro   rx   ry   r   r   r!   r   )r   r   r7   )
r-   r   r   r    ro   r   r   r   rn   r   s
     `  `   @r1   $_run_agent_tool_execution_middlewarer   =  s     "M& & & & & & & &
 DCCCCC**#!'R5,339r!'R1266<"u&?DDJ
 
 
F =  r3   Tfinalizeapi_call_countr   c               $   WXY |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 X|D ]}
|
j        j	        }t          |
j        j                  \  }}|X                    |
||g |d
f           I|dk    rd _        n|dk    rd _        d	}	 ddlm} ||j        k    rO|                    |          \  }}}|s4|r2|t)                     v r|}|}nt+          j        dd| did
          }n# t.          $ r Y nw xY wt1           ||t3          |
dd          pd          \  }}d	}d
}|;|}t5           |||t3          |
dd          pddd|t7          |          
  
         nS	 ddlm}  |||pdt3           dd          pdt3          |
dd          pdt3           dd          pdt3           dd          pdt7          |                    }n# t.          $ r d	}Y nw xY w|Pt+          j        d|id
          }t5           |||t3          |
dd          pddd|t7          |          
  
         n j                            ||          }|j         s_ !                    |          }d}t5           |||t3          |
dd          pddd t3          |d!d	          pd"t7          |          
  
         ||d#v r0 j"        j#        r$	 tI           ||           n# t.          $ r Y nw xY w|d$k    r j"        j#        r	 |%                    d%d          }tM          |          ra|%                    d&          p%tO          j(        d'tO          j)                              } j"        *                    |d(|d	d)                     n# t.          $ r Y nw xY wX                    |
|||||f           d*+                    d+ XD                       } j,        sPt3           d,d-          d.k    r:t	          d/| d0|            t[          Xd1          D ]\  }\  }	}}}}}t]          ||          p|}t+          j        |d
          }  j/        rqt	          d2| d3| d4t7          |0                                           d5           t	           1                    d6t+          j        |d7d
8                               t          |            j2        k    r| d	 j2                 d9z   n| }!t	          d2| d3| d4t7          |0                                           d:|!            XD ]}\  }	}}}}}| j3        rj	 t]          ||          p|}ti          ||          }" 3                    d;||"|           O# t.          $ r!}#tk          j6        d<|#            Y d	}#~#ud	}#~#ww xY w~XD ]q\  }	}}}}}| j7        r^	 t]          ||          p|} 7                    |	j
        ||           C# t.          $ r!}#tk          j6        d=|#            Y d	}#~#id	}#~#ww xY wrd	g|z  Yt[          X          D ]\  }\  }	}}}}}||||d>dd|fY|<   | _8         9                    d?| d@|             YfdA}$d	}% :                                rj ;                                rVty          j=        t}          j?                              }&t}          |& dB| dCdD j@        E          }%|%A                                 	 dF t[          X          D             }'g }(i Wt                      })t                      }*|*t          jE                    |*z   nd	}+|'rt          t          |'          t                    },ddGlHmI}-  |-|,H          }.d
}/	 t[          |'          D ]\  }0\  }}	}}	 |.J                    t          |$          ||	||X|         dI                   }1n# t          $ r}2t          |2          s |'|0d	         }3t          O                    dJt          |3                     |3D ]/\  }4}5}6}7Y|4          X|4         dI         }dK|6 dL}8|6|7|8d>dd
|fY|4<   0Y d	}2~2 n#d	}2~2ww xY w|(                    |1           |W|1<   t          jD                    }9d
}:	 dM};|+l|+t          jE                    z
  }<|<dk    rt                      dN |(D             }>}=nYt          |;|<          };t          jQ        R                    |(|;O          \  }=}>n$t          jQ        R                    |(|;O          \  }=}>|>sn|+ t          jE                    |+k    rd}/WfdP|>D             })XfdQ|)D             }?t          O                    dR|*t          |)          d*+                    |?d	dS                              |>D ]}1|1S                                  jT        5  t7           jU                  }@d	d	d	           n# 1 swxY w Y   |@D ]5}A	 t                      W                    d|A           &# t.          $ r Y 2w xY wn j        rpd}/|:s1d}: X                     j         dTt          |>           dUdV           |>D ]}1|1S                                 t          jQ        R                    |>dWO           nt          t          jD                    |9z
            }B|Bdk    r_|BdXz  dYk     rVWXfdZ|>D             }? 9                    d[|B d\t          |>           d]d*+                    |?d	dI                    d5           |.Z                    |/ |/^           n# |.Z                    |/ |/^           w xY w|%rRt          d_ YD                       }Ct          d` YD                       }D|%\                    da|C db| dc|Dddde           nZ# |%rSt          d_ YD                       }Ct          d` YD                       }D|%\                    da|C db| dc|Dddde           w w xY wt[          X          D ]R\  }\  }	}}}}}Y|         }Ed
}Fd	}G||)v r`|E^|*|*dddfndg}HdK| dh|H }Idi}Gt5           |||It3          |	dd          pddjdk|It7          |          
  
         t          |*pd>          }Jn|E j        r>d| d}It5           |||It3          |	dd          pddldmdnt7          |          
  
         n=dK| do}It5           |||It3          |	dd          pdddp|It7          |          
  
         d>}Jn]|E\  }}}I}J}K}F}|Frd}G|Fs ^                    |||I|Kq          }I|KrKt          |I          }Lt          |L          drk    r
|Ld	dr         n|L}Mt          O                    ds||J|M           |FsF	  `                    |||I|K           n,# t.          $ r}Ntk          j6        dt|N           Y d	}N~Nnd	}N~Nww xY w|FsS j3        rL	  3                    du|d	d	|J|K|Iv           n.# t.          $ r!}#tk          j6        d<|#            Y d	}#~#nd	}#~#ww xY w j/        rCtk          j6        dw| dx|Jdydf           tk          j6        dzt          |I           d{|I             :                                r,t          |||J|I|          }O b                    d}|O            n j,        st3           d,d-          d.k    rt          |I          }P j/        r>t	          d~|d1z    dx|Jdydf           t	           1                    d|P                     nHt          |P           j2        k    r|Pd	 j2                 d9z   n|P}Qt	          d~|d1z    dx|Jdyd|Q            d	 _8         9                    d| d|Jddd           |Fsf jc        r_	 t]          ||          p|} c                    |	j
        |||I           n.# t.          $ r!}#tk          j6        d|#            Y d	}#~#nd	}#~#ww xY wt          |I          s&t          |I||	j
        t                    |          n|I}I jg        h                    ||          }R|Rr%t          |I          rt          |I|R           n|I|Rz  }I j                    ||I          }St          ||S|	j
        |G          }T                    |T           |T%                    d          }U|Un|U%                    d          dk    rU j3        rN	  3                    d|d	d	|	j
        |U           n,# t.          $ r}#tk          j6        d|#           Y d	}#~#nd	}#~#ww xY wt           d|             k                    d1           Tt          X          }|r0|dk    r*| d	         }Vt          |Vt                    |           |r|dk    r k                    |           d	S d	S d	S )u  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\   NFmemoryr   skill_manager   r@   'O' is not available in this session. Use tool_search to find tools you can call.rB   idr%   r   r   r    ro   blockedtool_scope_block	r   r   rn   r    ro   rj   rk   rl   rm   resolve_pre_tool_blockrt   ru   rv   rw   rt   ro   rx   ry   rm   plugin_blockTguardrail_blockrA    Tool blocked by guardrail policy>   patch
write_fileterminalcommandworkdirTERMINAL_CWDbefore terminal: <   z, c              3  (   K   | ]\  }}}}}}|V  d S r    ).0_names      r1   	<genexpr>z0execute_tool_calls_concurrent.<locals>.<genexpr>'  s/      LL(;4Aq!tLLLLLLr3   tool_progress_modealloffu     ⚡ Concurrent: u    tool calls — r        📞 Tool : ()Args:    indentrC   ...) - tool.startedTool progress callback error: Tool start callback error:         z
executing z tools concurrently: c                f   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                    }	 	                     |||j        ddt!          |                    }nP# t"          $ r
 	                     d           n# t          $ r Y nw xY wt'          ||t)          |dd          pd|t!          |          	          }t          j                    |z
  }	t*                              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|
 }t*                              d||
d           Y d}
~
nd}
~
ww xY wt          j                    |z
  }	t3          ||          \  }}|r&t*                              d||	|dd                    n*t*                              d||	t5          |                     ||||	|d|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   set_activity_callback)rZ   pre_tool_block_checkedskip_tool_request_middlewaretool_request_middleware_tracekeyboard interruptr   r%   r   r   r    ro   r   rm   ztool %s cancelled (%.2fs)FError executing tool '': z_invoke_tool raised for %s: %sexc_infoztool %s failed (%.2fs): %s   #tool %s completed (%.2fs, %d chars))	threadingcurrent_threadident_tool_worker_threads_lock_tool_worker_threadsadd_interrupt_requestedrd   _set_interruptr9   tools.environments.baser   _touch_activityr   _invoke_toolr   r[   KeyboardInterrupt	interruptr   r7   rU   infodiscardr@   r   len)index	tool_callr   r   rm   _worker_tidr   startrn   duration
tool_erroris_errorr   r-   r    rZ   resultss                r1   	_run_toolz0execute_tool_calls_concurrent.<locals>._run_toolU  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	
 	4	i++!!%L%+/15267G2H2H , 	 	 %   OO$89999    D@"/"/&7!(D"!=!=!C$%)*:%;%;    9;;.7QQQ"/RVX]_o!p$ 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+]FHhX]_opGEN 0 @ @*22;???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$$UK88888   	 0 @ @*22;???@ @ @ @ @ @ @ @ @ @ @ @ @ @ @$$UK8888   s'  AAA"A> >
B
BB& &
B32B3/C< :M <I	DI	
D+(I	*D++A5I	 M (GGG"G? ?
HH	I	&I?M I		B
M LLL"L1 1
L?>L?N0
M1%N01M55N08M59N0="N N0 
N-*N0,N--N0u    ⚡ running z tools concurrentlydotsspinner_typeprint_fnc                2    g | ]\  }\  }}}}}}|||||fS r   r   )r   itcr   argsrm   block_resultblocked_by_guardrails           r1   
<listcomp>z1execute_tool_calls_concurrent.<locals>.<listcomp>  sD     
 
 
YYBd$4lDX# D$###r3   )DaemonThreadPoolExecutor)max_workers   zWinterpreter shutdown while scheduling concurrent tools; skipping %d unsubmitted tool(s)r   z<': Python interpreter is shutting down; tool was not startedg      @c                :    h | ]}|                                 |S r   )done)r   fs     r1   	<setcomp>z0execute_tool_calls_concurrent.<locals>.<setcomp>  s5     5 5 5&'!&&((5 !5 5 5r3   )timeoutc                (    h | ]}|v |         S r   r   )r   r'  future_to_indexs     r1   r(  z0execute_tool_calls_concurrent.<locals>.<setcomp>  s3     - - - ! O33 ,A.333r3   c                ,    g | ]}|         d          S r   r   )r   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   )r   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: )waitcancel_futuresc              3     K   | ]}|dV  	d S )Nr   r   r   rs     r1   r   z0execute_tool_calls_concurrent.<locals>.<genexpr>Q  s"      @@!!-A----@@r3   c              3  *   K   | ]}||d         V  d S )Nr$  r   r8  s     r1   r   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 unknownr)  tool_timeoutr   r   z*Tool execution cancelled by user interruptz!': thread did not return a resultthread_missing_resultfailedr   "Tool %s returned error (%.2fs): %s(file-mutation verifier record failed: %stool.completedr  r  rn   Tool  completed in .2fTool result (	 chars): rn          ✅ Tool Result: s - tool completed:  (s)Tool complete callback error: content	tool_nametool_use_idenvconfig_tool_output_riskrisklowtool.output_riskro   risk_metadata#Tool output risk callback error: %stool result rY  rZ  )m
tool_callsr  r;   r  print
log_prefixappendr   functionr   r   r`   rK   rJ   _turns_since_memory_iters_since_skillr   r   TOOL_CALL_NAMEresolve_underlying_callr   rD   rI   r9   r   r7   r{   r[   hermes_cli.pluginsr   _tool_guardrailsbefore_callallows_execution_guardrail_block_resultr*   r   r2   r(   r   rO   rP   getcwdr,   joinr   	enumerate_redact_tool_args_for_displayverbose_loggingkeys_wrap_verboselog_prefix_charstool_progress_callback_build_tool_previewloggingr   tool_start_callback_current_toolr   _should_emit_quiet_tool_messages_should_start_quiet_spinnerrandomchoicer   get_waiting_faces	_print_fnr  setrY   r   	monotonicmin_MAX_TOOL_WORKERStools.daemon_poolr"  submitr   re   rh   rU   rV   
concurrentfuturesr5  cancelr  r  rd   r  _vprintr8   shutdownsumstoprS   _append_guardrail_observationr   _record_file_mutation_result_get_cute_tool_message_impl_safe_printtool_complete_callbackr   r   r   _subdirectory_hintscheck_tool_callr   %_tool_result_content_for_active_model$_apply_pending_steer_to_tool_resultsr   )Zr-   assistant_messagerZ   r    r   r   rd  	num_tools_tool_budgetr  r  r   r   malformed_args_result_ts_scope_blockr   _underlying_underlying_args_errrm   r  r   r   block_messageguardrail_decisioncmdcwdtool_names_strr  r   r  display_argsargs_strargs_previewpreviewcb_errr  spinnerfacerunnable_callsr  timed_out_indices	timeout_sdeadliner#  r"  executorabandon_executorsubmit_indexr'  submit_errorskipped_calls	skipped_i_tcskipped_nameskipped_argsrn   _conc_start_interrupt_loggedwait_timeout	remainingr&  not_done_still_runningworker_tidstid_conc_elapsed	completed	total_durr9  r   r   suffixfunction_resulttool_durationr  	_err_textresult_preview_ver_errcute_msg_preview_strresponse_previewsubdir_hints_tool_contenttool_messager`  turn_tool_msgsr+  r.  r  sZ   ` ``                                                                                   @@@r1   execute_tool_calls_concurrentr  ]  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 c} c}	!*//D(0
 0
,, !,!!)	 	 	  H$$()E%%n,,'(E$$ 	000000 222696Q6QR_6`6`3-t 
/ 
/"&?&F&FFF(3(8*.*#!NK !N !N !N6
 ).+/ +/ +/  	 	 	D	 +S''/ D"55;+
 +
 +
'' $&*L)++#"3$Yb99?R --!%&6!7!7    %EEEEEE 6 6!!-3&ulB??E2!(D"!=!=!C#E+=rBBHb#*52KR#P#P#VTV%)*:%;%;	! 	! 	!  % % % $% (#z7M*BQVWWW-"/"/'&7!(D"!=!=!C$-"/%)*:%;%;     &+%;%G%GWd%e%e"): #(#@#@AS#T#TL+/(1&3&3+*;%,Yb%A%A%GR(#4&-.@)T&R&R&xVx)-.>)?)?     777E<Q<Y7+%%)	    !   D 
**u/D/L*'++Ir::C.s33 +//	::dbiXZXaXcXc>d>d-??!?S"X!?!?   !   D 	Y}FVXdfz{|||| YYLL|LLLLLN 
X/CU K Ku T TN9NNnNNOOOYbcoqrYsYs 	X 	XUAUD$ 0,@T8tDDLLz,UCCCH$ XMQMM$MMl6G6G6I6I1J1JMMMNNNe))(DJ|TUdi4j4j4jkkllllLOPXMM\a\rLrLrx(?)?(?@5HH  yAVQVV$VVdiikk1B1BVVVVWWWWP\ 	I 	ILD$(,8L#' 	II<T4HHPD-dLAA,,^T7LYYYY I I IGvGGHHHHHHHHI	I Q] F FLD$(,8L#$ 	FF<T4HHPD))"%|DDDD F F FDFDDEEEEEEEEF		F fy GU^_kUlUl W WQQBd,l<P#lCtEUVGAJ )E	WyWW~WWXXXR R R R R R R Rj G--// E4U4U4W4W }]<>>??4 T Ti T T Tcity  uD  E  E  Ecc
 
]fgs]t]t
 
 

 &)ee466	3<3H4>##i//d R	c.113DEEK CBBBBB//KHHHH$H9B>9R9R #+ #+5L"51b$$OO7	BBAr4QUWcdeWfghWi  (   D\RR "!(6|}}(E>..  
 KX " "FIsL,&y193?	3J13M 0%`\ %` %` %` !'
 %1$0$*$'$($)$46"	 2 34 NN1%%%)*OA&& #ikk$)!Q#&L+$,t~/?/?$?	$>>-0UU 5 5+25 5 5(DD ,/|Y+G+GL-7-?-D-D ' .E . .ND(( *4);)@)@#\ *A * *h $ +0@0@H0L0L+/(- - - -%-- - -)
* * * *%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[ [ [  ]Qp !!--#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 V__kUlUl u@ u@QQBd,l<P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 ,%+" "'"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  Mu; MM00(-t!.. 1    
 ! M M MM"K6"K"KLLLLLLLLM $ `WmWW=WWWWXXX^c/.B.B^^_^^___ 1133 
	b24}UdeeeHo8oo....! 	bge5I5&Q&QUZ&Z&Z3ODDL$ 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"NNNNNNNOOO 	I57 	II<T4HHPD,,RUD,XXXX I I IGvGGHHHHHHHHI ,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	
 
 
 	%%%$(()<==%!!&))U22, 3
M,,&!#"/ -      M M MCVLLLLLLLLM-'''	
 	
 	
 	
 	228Q???? 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 F
FF<A,I))I87I8!M44
N NBP
P+*P+:X
X>X99X>.Z
Z2Z--Z2Bq o 83a,+o ,
c56A4c0*o 0c55E)o i?3o ?jo jo "j21o 2
j?<o >j??Do q o88q Ar'7y
y9y44y9z##
{-{		{A/AA1A1
ABA;ABBABF AF4F4
AGF>AGGAGc               5   AB t                     }t          |j        d          D ]\  }B j        r|j        |dz
  d         }|r/                      j         dt          |           dd           |D ]R}	|	j        j        }
	                    t          |
d|
 d|	j        d	
                     t           d|
            S nSBj        j        At          Bj        j                  \  }}|V	                    t          A|Bj                             t           dA                                 d           (d}	 ddlm} A|j        k    r9|                    |          \  }}}|s|r|t)                     v r|A|}nd| d}n# t*          $ r Y nw xY wt-           A|t/          Bdd          pd          \  }}d}d}||}d}n~	 ddlm}  |A|pdt/           dd          pdt/          Bdd          pdt/           dd          pdt/           dd          pdt5          |                    }n# t*          $ r Y nw xY wd}|$ j                            A|          }|j        s|}|dup|du}|rnAdk    rd _        nAdk    rd _         j         st/           dd          d k    rtC          A|          p|}tE          j#        |d!"          } j$        rqtK          d#| d$A d%t5          |&                                           d&           tK           '                    d'tE          j#        |d(d!)                               nft          |           j(        k    r|d j(                 d*z   n|}tK          d#| d$A d%t5          |&                                           d+|            |sA _)         *                    d,A            |s(	 dd-l+m,}  | j*                   n# t*          $ r Y nw xY w|sq j-        rj	 tC          A|          p|}t]          A|          } -                    d.A||           n.# t*          $ r!}t_          j0        d/|            Y d}~nd}~ww xY w|se j1        r^	 tC          A|          p|} 1                    Bj        A|           n.# t*          $ r!}t_          j0        d0|            Y d}~nd}~ww xY w|s4Ad1v r0 j2        j3        r$	 ti           A|           n# t*          $ r Y nw xY w|sAd2k    r j2        j3        r	 |5                    d3d          }tm          |          ra|5                    d4          p%to          j8        d5to          j9                              }  j2        :                    | d6|dd7                     n# t*          $ r Y nw xY wtw          j;                    }!|StE          j#        d8|id!"          }"d9}#ty           A||"t/          Bdd          pdd:||t5          |          ;
  
         n|a =                    |          }"d9}#ty           A||"t/          Bdd          pdd:d<t/          |d=d          pd>t5          |          ;
  
         nwAd?k    rd fdD}$t}           A|t/          Bdd          pd|$E          \  }"}tw          j;                    |!z
  }# ?                                r)                     dFt          d?||#|"G                      nAdHk    rd fdI}$t}           A|t/          Bdd          pd|$E          \  }"}tw          j;                    |!z
  }# ?                                r)                     dFt          dH||#|"G                      ncAdk    rd BfdJ}$t}           A|t/          Bdd          pd|$E          \  }"}tw          j;                    |!z
  }# ?                                r)                     dFt          d||#|"G                      n׉AdKk    rd fdL}$t}           A|t/          Bdd          pd|$E          \  }"}tw          j;                    |!z
  }# ?                                r)                     dFt          dK||#|"G                      nMAdMk    rd fdN}$t}           A|t/          Bdd          pd|$E          \  }"}tw          j;                    |!z
  }# ?                                r)                     dFt          dM||#|"G                      
nÉAdOk    r|5                    dP          }%|%r)t          |%t4                    rdQt          |%           dR}&n)|5                    dS          pdddT         }'|'rdU|' dVndW}&d}( ?                                ri B                                rUt          jD        t          jF                              })t          |) dX|& dY jG        Z          }(|(H                                 |( _I        d}*	 d fd[}$t}           A|t/          Bdd          pd|$E          \  }"}|"}*d _I        tw          j;                    |!z
  }#t          dO||#|*G          }+|(r|(J                    |+           	nP ?                                r                     dF|+            	n"# d _I        tw          j;                    |!z
  }#t          dO||#|*G          }+|(r|(J                    |+           w  ?                                r                     dF|+            w w xY w jK        rA jK        v rd}( ?                                rt          jD        t          jF                              })t          A          },tC          A|          p|}t          A|          pA}t          |) dX|, dX| dY jG        Z          }(|(H                                 d}-	 d Afd\}$t}           A|t/          Bdd          pd|$E          \  }"}|"}-nQ# t*          $ rD}.tE          j#        d8d]A d^|. i          }"t          O                    d_A|.d`           Y d}.~.nd}.~.ww xY wtw          j;                    |!z
  }#t          A||#|-G          }+|(r|(J                    |+           n+ ?                                r                     dF|+            n# tw          j;                    |!z
  }#t          A||#|-G          }+|(r|(J                    |+           w  ?                                r                     dF|+            w w xY w jP        r: jP        Q                    A          rd}( ?                                r B                                rt          jD        t          jF                              })t          A          },tC          A|          p|}t          A|          pA}t          |) dX|, dX| dY jG        Z          }(|(H                                 d}/	 d Afda}$t}           A|t/          Bdd          pd|$E          \  }"}|"}/nQ# t*          $ rD}.tE          j#        d8dbA d^|. i          }"t          O                    dcA|.d`           Y d}.~.nd}.~.ww xY wtw          j;                    |!z
  }#t          A||#|/G          }+|(r|(J                    |+           n ?                                r                     dF|+            n# tw          j;                    |!z
  }#t          A||#|/G          }+|(r|(J                    |+           w  ?                                r                     dF|+            w w xY w j         rd}( ?                                r B                                rt          jD        t          jF                              })t          A          },tC          A|          p|}t          A|          pA}t          |) dX|, dX| dY jG        Z          }(|(H                                 d}0	 t                      S                    A|Bj         jT        pdt/           dd          pdt/           dd          pd jU        rt5           jU                  ndddt/           ddd          t/           ded          t5          |          f          }"|"}0n# t          $ r_ t           A|t/          Bdd          pd|!t5          |          g          }"|"}0	  X                    dh           n# t*          $ r Y nw xY w t*          $ r0}.diA dj|. }"t          O                    dkA|.d`           Y d}.~.nd}.~.ww xY wtw          j;                    |!z
  }#t          A||#|0G          }+|(r|(J                    |+           n ?                                r                     dF|+            n# tw          j;                    |!z
  }#t          A||#|0G          }+|(r|(J                    |+           w  ?                                r                     dF|+            w w xY w	 t                      S                    A|Bj         jT        pdt/           dd          pdt/           dd          pd jU        rt5           jU                  ndddt/           ddd          t/           ded          t5          |          f          }"n# t          $ r] t           A|t/          Bdd          pd|!t5          |          g           	  X                    dh           n# t*          $ r Y nw xY w t*          $ r0}.diA dj|. }"t          O                    dkA|.d`           Y d}.~.nd}.~.ww xY wtw          j;                    |!z
  }#t          |"t                    r8 j$        r|"nt          |"          dlk    r
|"ddl         n|"}1t          |"          }2n|"}1t          t          |"                    }2t          A|"          \  }3}4ddml[m\}5 | o |5 A          }6|6rEty           A||"t/          Bdd          pdt          |#dnz            t5          |          o           |sA ^                    A||"|3p          }" j$        r|"nt          |"          dlk    r
|"ddl         n|"}1|3rt          _                    dqA|#|1           nt          `                    drA|#|2           |sF	  a                    A||"|3           n,# t*          $ r}7t_          j0        ds|7           Y d}7~7nd}7~7ww xY w|sS j-        rL	  -                    dtAdd|#|3|"u           n.# t*          $ r!}t_          j0        d/|            Y d}~nd}~ww xY wd _)         *                    dvA dw|#dxdy            j$        rRt_          j0        dzA d{|#d|d}           t          |"          }8t_          j0        d~t          |8           d|8            |sf jc        r_	 tC          A|          p|} c                    Bj        A||"           n.# t*          $ r!}t_          j0        d|            Y d}~nd}~ww xY wt          |"          s&t          |"ABj        t                    |          n|"}" jg        h                    A|          }9|9r%t          |"          rt          |"|9           n|"|9z  }" j                    A|"          }:t          A|:Bj                  };	                    |;           |;5                    d          }<|<n|<5                    d          dk    rU j-        rN	  -                    dAddBj        |<           n,# t*          $ r}t_          j0        d|           Y d}~nd}~ww xY wt           dA                                 d            j         st/           dd          d k    r j$        r;tK          d| d{|#d|d}           tK           '                    d|"                     nkt          |"t                    r|"nt          |"          }=t          |=           j(        k    r|=d j(                 d*z   n|=}>tK          d| d{|#d|d|>             j        r|t          |j                  k     rt          |j                  |z
  }?                      j         d|? dd           |j        |d         D ]R}	|	j        j        }
	                    t          |
d|
 d|	j        d	
                     t           d|
            S n> jk        dk    r1|t          |j                  k     rtw          jl         jk                   t          |j                  }@|r.|@dk    r(t          |@ d         t                    |           |r|@dk    r                     |@           dS dS dS )uB  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.
    r   Nr   r   Tr0  r   r   r   r   r   r   zinvalid tool arguments r   r   r   r   r   r%   r   r   r   r   rt   ru   rv   r   r   r   r   r   r   FrB   r   r   r   r   r   r   r   r   r   zexecuting tool: r   r   r   r   >   r   r   r   r   r   r   r   r   r@   r   r   r   r   rA   r   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   r   z/execute_tool_calls_sequential.<locals>._execute  sT    CCCCCC!z#--00#--77+   r3   )r   r   r    ro   r   rM  rL  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)successr@   )r  queryr%   role_filterlimitr$  rt   around_message_idwindowr/  sort)	r  r  r  rt   r  r  r  dbcurrent_session_id)	_get_session_db_for_recallhermes_stater  rD   rI   tools.session_search_toolr  r(   rt   )r   
session_dbr  _session_searchr-   s       r1   r   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   c                Z   |                      dd          }|                      d          }ddlm}  ||                      d          ||                      d          |                      d          |j        	          }j        r"j                            || fd
           |S )Ntargetr   
operationsr   )memory_toolactionrV  old_text)r  r  rV  r  r  r  c                 P                          t          dd                     S )Nr   )rw   ro   )_build_memory_write_metadatar7   )r-   r    r  s   r1   <lambda>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_toolr  _memory_store_memory_managernotify_memory_tool_write)r   r  r  _memory_toolrn   r-   r    r  s        r1   r   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          j                  S )Nr   )clarify_toolquestionr%   choices)r  r  callback)tools.clarify_toolr  r(   clarify_callback)r   _clarify_toolr-   s     r1   r   z/execute_tool_calls_sequential.<locals>._executeM  sT    LLLLLL$}&]]:r::%MM)44"3   r3   read_terminalc           	         ddl m}  ||                     d          |                     d          t          dd                     S )Nr   )read_terminal_tool
start_linecountread_terminal_callback)r  r  r  )tools.read_terminal_toolr
  r(   r7   )r   _read_terminal_toolr-   s     r1   r   z/execute_tool_calls_sequential.<locals>._execute`  s]    ^^^^^^**(}}\::#--00$U,DdKK   r3   delegate_tasktasksu   🔀 delegating u    tasks · (/agents to monitor)goalr2  u   🔀 u    · (/agents to monitor)u'   🔀 delegating · (/agents to monitor) r  r  c                .                         |           S r   )_dispatch_delegate_task)r   r-   s    r1   r   z/execute_tool_calls_sequential.<locals>._execute  s     88CCCr3   c                >    j                             |           S )N)rZ   )r5   handle_tool_call)r   r-   r   rZ   s    r1   r   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: %sr   c                :    j                             |           S r   )r  r  )r   r-   r   s    r1   r   z/execute_tool_calls_sequential.<locals>._execute  s     0AA-QZ[[[r3   zMemory tool 'z1memory_manager.handle_tool_call raised for %s: %sr   r   )
ro   rt   rx   ry   enabled_toolsskip_pre_tool_call_hookr   r   r   r   r   r   r   r   z&handle_function_call raised for %s: %sr   )!agent_runtime_owns_post_tool_hookr   )r   r   rn   r    ro   ri   rm   rA  rC  r   rD  rE  rF  rQ  rR  r<  rS  rG  rH  rI  r=  rJ  rK  rT  rU  r[  r\  r]  r^  r_  ra  rb  rN  rO  rP  z remaining tool call(s)u   [Tool execution skipped — z* was not started. User sent a new message]zskipped tool result rc  r   )nr;   rt  rd  r  r  rf  r  rh  r   rg  r   r   r`   rK   rJ   r  r   r   rk  rl  r   r9   r   r7   rm  r   r[   rn  ro  rp  ri  rj  r   ru  rD   rI   rv  re  rw  rx  ry  r~  r  r  r   rz  r{  r|  r   r}  r*   r   r2   r(   r   rO   rP   rr  r,   r   r{   rq  r   r  r  rH   r  r  r  r   r  r  r  _delegate_spinnerr  _context_engine_tool_names_get_tool_emoji_build_tool_labelrU   r@   r  has_toolrd   handle_function_callrt   valid_tool_namesr	  r   r
  r   r   agent.agent_runtime_helpersr  r8   r  rV   r  r  r   r  r   r   r   r  r  r   r  
tool_delaysleepr   )Cr-   r  rZ   r    r   r   r  r  remaining_calls
skipped_tcr  r   r  r  r   r  r  r  rm   
_block_msg_block_error_typer   _guardrail_block_decisionr  _execution_blockedr  r  r  r   r  r  r  r  tool_start_timer  r  r   	tasks_argspinner_labelgoal_previewr  r  _delegate_resultr  emoji
_ce_resultr  _mem_result_spinner_resultr  _result_len_is_error_resultr   r  _executor_must_emit_post_hookr  _log_resultr  r  r  r`  _fr_strr  r  num_tools_seqr   r  sC   ` ``                                                             @@r1   execute_tool_calls_sequentialr;    s#    %U++L!"3">BB q
) q
)9 % 	/:1Q344@O |!1nn3K_K_nnnvz{{{-  
)27 8 f\fffM'-	! ! !    6A<AA    
 E!*//D(0
 0
,, !,OO(!)L    2???   
 66xCCC
 *.	000000 222696Q6QR_6`6`3-t  "&?&F&FFF(3(8J J J J (  	 	 	D	 +S''/ D"55;+
 +
 +
'' %)
*&(J 2EEEEEE33!!-3&ulB??E2!(D"!=!=!C#E+=rBBHb#*52KR#P#P#VTV%)*:%;%;	 	 	

     CG!!&!7!C!CMS`!a!a%6 ?,>)'t3\7PX\7\ 	) h&&()E%%n,,'(E$ 	jGE3G$O$OSX$X$X8VVgZgLz,UCCCH$ jVQVV-VV$|?P?P?R?R:S:SVVVWWWe))(DJ|TUdi4j4j4jkkllllLOPXMM\a\rLrLrx(?)?(?@5HH  yAhQhh-hh$}?Q?Q?S?S:T:ThhZfhhiii! 	F"/E!!"D]"D"DEEE
 " 	IIIIII%%e&;<<<<    " 	Ie&B 	II<]MZZk^k-m\JJ,,^]GUabbbb I I IGvGGHHHHHHHHI " 	Fe&? 	FF<]MZZk^k))),|TTTT F F FDFDDEEEEEEEEF " 		m7N&N&NSXShSp&N'!!%	        " 		mz&A&AeF[Fc&A#''	266*3// '++I66`")NTVT]T_T_:`:`C);;;SbS;;       )++!"j':)>USSSOM)++&"3$Yb99?R ,(!%&6!7!7     '2 $;;<UVVOM)++&"3$Yb99?R ,%&?DQQwUw!%&6!7!7     f$$      .R++"3$Yb99?R . . .*O] !IKK/9M5577 @~#>v}Vcl{#|#|#|~~...     " .R++"3$Yb99?R . . .*O] !IKK/9M5577 J  I#>?OQ^`m  wF  $G  $G  $G  I  I  J  J  Jh&&       2 .R++"3$Yb99?R . . .*O] !IKK/9M5577 B  A#>xXen}#~#~#~  A  A  B  B  Bi''      .R++"3$Yb99?R . . .*O] !IKK/9M5577 C  B#>y-Yfo~###  B  B  C  C  Co--      .R++"3$Yb99?R . . .*O] !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1U"/"/&7!(D"!=!=!C$2 2 2. $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- W	:-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1U"/"/&7!(D"!=!=!C$2 2 2. -

 | | |"&*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" v	:u'<'E'Em'T'T v	: 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\ \ \ \ \ \ \1U"/"/&7!(D"!=!=!C$2 2 2. . | | |"&*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 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"O(3"%%%"<"<!=2C!*$/52#E+=rBBHb#*52KR#P#P#VTVBGBX"b$u'=">">">^b,015%,U4F%M%M&-e5H$&O&O267G2H2H #= # # #2$   "I"/"/&7!(D"!=!=!C.%)*:%;%;# # # #2OO$89999    D 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q"%%%"<"<!=2C!*$/52#E+=rBBHb#*52KR#P#P#VTVBGBX"b$u'=">">">^b,015%,U4F%M%M&-e5H$&O&O267G2H2H #= # # %   7"/"/&7!(D"!=!=!C.%)*:%;%;   OO$89999    D 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 " 	Ie&B 	II,,$mT4*5E* -    
  I I IGvGGHHHHHHHHI #WWW-WWWWXXX  	TMS-SS}SSSSTTT2?CCKMR#k*:*:RR[RRSSS! 	Ie&B 	II<]MZZk^k,,Y\=,Xghhhh I I IGvGGHHHHHHHHI ,O<<R3##!011
 
 
 
 CR 	 0@@P]^^ 	0)/:: 01/<PPPP</ CCMSbcc/}il[[%%%$(()<==%!!&))U22, 3
M,,&!!*"/ -      M M MCVLLLLLLLLM-000	
 	
 	
 	
 	228Q??? 	`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'-	! ! !    6???    
 EaA,=,H(I(I$I$IJu'((( )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
F  
F-,F-$A,I
II7P
PP(:Q##
R-R		R.S


S5S00S5T
T+*T+BW


WW1k::A7m1*3qt
r,(:r'"t'r,,tA0v-2z }! 
{.*:{)$}!){..}!!A0BB$AD9D8AID9A AGE:AFFAGF
AFFAGFAFFAGF*&AGGAIGAGGAIIA0AJ=KB"AM$M$>APN#AN9N8APN9
AOOAPOAOOAPO&AO>O>APU9AVV
AV;VAV6V6AV;WAW%W%
AXW/AXXAXZ/A[
[

A[5[A[0[0A[5_* A``
A`4`A`/`/A`4c           	        ddl m} |Dt          |          }||j        rt	          |j                  nd}t          |j        |          }|D ]O\  }	}
 |t          |
                    }|	dk    rt          | ||||d           :t          | ||||d           Pt          |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_cwd)rd  parallelFr   rc  )typesr=  r   r  r   r   rd  r[   r  r;  r  r;   r   r  )r-   r  rZ   r    r   segmentsr=  _active_env	_exec_cwdkindcallssegment_messagetotal_toolsr  s                 r1   execute_tool_calls_segmentedrH    sr   . &%%%%%$%677-8-D-DD)))^b	,->-IYbccc  e)/T%[[AAA:)2C^    
 *2C^     '233KQ(//k\]]#011	
 	
 	
 	

 	228[IIIII r3   )r  r;  rH  )r   r   r   r   r    r   r!   r"   )r!   r   )r=   r   r!   r>   )r!   rL   )rZ   r[   r\   r   r!   r"   )r_   re   r!   rf   )r   r   r   r   rn   r   r    r   ro   r   ri   r8   rj   rp   rk   rp   rl   rp   rm   rq   r!   r"   )r|   )r}   r   r!   r   )r   r   r   r   r    r   ro   r   r   rS   r}   r   rk   r   rm   rq   r!   r   )r!   r   )
r   r   r   r   r    r   ro   r   r!   r   )
r   r   r   r   r    r   ro   r   r!   r   )r   )
rZ   r[   r    r   r   r8   r   rf   r!   r"   )r   N)rZ   r[   r    r   r   r8   r!   r"   )G__doc__
__future__r   concurrent.futuresr  rD   pathlibr   r|  rO   r  r   r   typingr   r   agent.displayr   r   r{  r	   r  r
   r  r   r  r   ru  r   agent.tool_guardrailsr   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   	getLogger__name__rU   r2   r;   r  rR   rK   rY   r`   rd   rh   r{   r   r   r   r   r   r  r;  rH  __all__r   r3   r1   <module>rX     s  
 
 # " " " " "             				                                        8 7 7 7 7 7                     = < < < < <        X W W W W W W W W W		8	$	$Q Q Q Q,   "   &+ "   &   $\ \ \ \&  P P P P ! $7;           F    $ #*7;     :. . . .b! ! ! !6! ! ! !@{
H  RV {
H {
H {
H {
H {
H {
H~EL  RV EL EL EL EL EL ELT4J 4J 4J 4J 4Jn  r3   